antaeus.keycloak.react 1.0.6 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -86,6 +86,33 @@ interface SilentRenewConfig {
86
86
  * @default 300 (5 minutes)
87
87
  */
88
88
  thresholdSeconds?: number;
89
+ /**
90
+ * When to check and refresh tokens
91
+ * - 'startup': Check immediately on app startup (proactive)
92
+ * - 'on-demand': Only refresh when API calls fail with 401 (reactive)
93
+ * - 'both': Check on startup AND retry on 401 (recommended)
94
+ * @default 'both'
95
+ */
96
+ refreshStrategy?: 'startup' | 'on-demand' | 'both';
97
+ /**
98
+ * Maximum lifetime for refresh token in seconds
99
+ * After this duration, user must re-authenticate
100
+ * Set to 0 or undefined for no limit
101
+ * @default 2592000 (30 days)
102
+ * @example 86400 (24 hours), 604800 (7 days)
103
+ */
104
+ maxRefreshTokenLifetime?: number;
105
+ /**
106
+ * Show loading indicator during automatic token refresh
107
+ * @default false
108
+ */
109
+ showLoadingIndicator?: boolean;
110
+ /**
111
+ * Custom loading message to display during refresh
112
+ * Only used if showLoadingIndicator is true
113
+ * @default 'Refreshing session...'
114
+ */
115
+ loadingMessage?: string;
89
116
  }
90
117
  /**
91
118
  * Event callbacks for authentication lifecycle
@@ -138,9 +165,89 @@ interface AdvancedOidcOptions {
138
165
  automaticSilentSignIn?: boolean;
139
166
  }
140
167
 
141
- interface KeycloakProviderProps {
168
+ /**
169
+ * Configuration preset types
170
+ */
171
+ type ConfigPreset = 'default' | 'mobile' | 'high-security' | 'long-running' | 'development';
172
+ /**
173
+ * Configuration presets for common use cases
174
+ *
175
+ * These presets provide optimized configurations for different application types
176
+ * and security requirements. All presets can be further customized by overriding
177
+ * specific properties.
178
+ */
179
+ declare const CONFIG_PRESETS: Record<ConfigPreset, Partial<KeycloakConfig>>;
180
+ /**
181
+ * Get a configuration preset by name
182
+ *
183
+ * @param preset - The preset name
184
+ * @returns Partial Keycloak configuration for the preset
185
+ *
186
+ * @example
187
+ * ```typescript
188
+ * const config = getConfigPreset('mobile');
189
+ * ```
190
+ */
191
+ declare function getConfigPreset(preset: ConfigPreset): Partial<KeycloakConfig>;
192
+ /**
193
+ * Merge a preset with custom configuration
194
+ *
195
+ * Custom configuration takes precedence over preset values.
196
+ * Use this to start with a preset and override specific properties.
197
+ *
198
+ * @param preset - The preset name
199
+ * @param customConfig - Custom configuration to merge
200
+ * @returns Merged configuration
201
+ *
202
+ * @example
203
+ * ```typescript
204
+ * const config = mergeWithPreset('mobile', {
205
+ * silentRenew: {
206
+ * maxRefreshTokenLifetime: 604800, // Override to 7 days
207
+ * }
208
+ * });
209
+ * ```
210
+ */
211
+ declare function mergeWithPreset(preset: ConfigPreset, customConfig: Partial<KeycloakConfig>): Partial<KeycloakConfig>;
212
+
213
+ /**
214
+ * Props for zero-config mode (simplified setup)
215
+ */
216
+ interface KeycloakProviderZeroConfigProps {
142
217
  /**
143
- * Keycloak configuration
218
+ * Keycloak realm authority URL (e.g., https://sso.example.com/realms/myrealm)
219
+ */
220
+ authority: string;
221
+ /**
222
+ * Client ID registered in Keycloak
223
+ */
224
+ clientId: string;
225
+ /**
226
+ * Configuration preset to use
227
+ * @default 'default'
228
+ */
229
+ preset?: ConfigPreset;
230
+ /**
231
+ * Child components to render
232
+ */
233
+ children: React.ReactNode;
234
+ /**
235
+ * Enable debug logging to console
236
+ * @default false
237
+ */
238
+ debug?: boolean;
239
+ /**
240
+ * Override specific configuration properties
241
+ * Use this to customize preset or zero-config defaults
242
+ */
243
+ config?: Partial<Omit<KeycloakConfig, 'authority' | 'clientId'>>;
244
+ }
245
+ /**
246
+ * Props for full-config mode (advanced setup)
247
+ */
248
+ interface KeycloakProviderFullConfigProps {
249
+ /**
250
+ * Full Keycloak configuration object
144
251
  */
145
252
  config: KeycloakConfig;
146
253
  /**
@@ -153,30 +260,110 @@ interface KeycloakProviderProps {
153
260
  */
154
261
  debug?: boolean;
155
262
  }
263
+ /**
264
+ * Combined props type
265
+ */
266
+ type KeycloakProviderProps = KeycloakProviderZeroConfigProps | KeycloakProviderFullConfigProps;
156
267
  /**
157
268
  * Main Keycloak authentication provider component
158
269
  *
159
- * Wraps your application to provide authentication context using Keycloak.
160
- * This component handles all OIDC flows including login, logout, token refresh,
161
- * and silent renewal.
270
+ * This component wraps your application to provide authentication context using Keycloak.
271
+ * It supports both zero-config mode (for simplicity) and full-config mode (for advanced use cases).
162
272
  *
163
- * @example
273
+ * ## Zero-Config Mode (Recommended)
274
+ *
275
+ * Minimal setup with sensible defaults and automatic feature enablement.
276
+ *
277
+ * @example Zero-config (simplest)
164
278
  * ```tsx
165
279
  * import { KeycloakProvider } from 'antaeus.keycloak.react';
166
280
  *
167
281
  * function App() {
168
282
  * return (
169
283
  * <KeycloakProvider
170
- * config={{
171
- * authority: 'https://sso.example.com/realms/myrealm',
172
- * clientId: 'my-app',
173
- * }}
284
+ * authority="https://sso.example.com/realms/myrealm"
285
+ * clientId="my-app"
174
286
  * >
175
287
  * <YourApp />
176
288
  * </KeycloakProvider>
177
289
  * );
178
290
  * }
179
291
  * ```
292
+ *
293
+ * @example Zero-config with preset
294
+ * ```tsx
295
+ * <KeycloakProvider
296
+ * authority="https://sso.example.com/realms/myrealm"
297
+ * clientId="my-app"
298
+ * preset="mobile" // or 'high-security', 'long-running', 'development'
299
+ * >
300
+ * <YourApp />
301
+ * </KeycloakProvider>
302
+ * ```
303
+ *
304
+ * @example Zero-config with overrides
305
+ * ```tsx
306
+ * <KeycloakProvider
307
+ * authority="https://sso.example.com/realms/myrealm"
308
+ * clientId="my-app"
309
+ * preset="default"
310
+ * config={{
311
+ * silentRenew: {
312
+ * maxRefreshTokenLifetime: 604800, // Override: 7 days instead of 30
313
+ * showLoadingIndicator: true,
314
+ * }
315
+ * }}
316
+ * debug={true}
317
+ * >
318
+ * <YourApp />
319
+ * </KeycloakProvider>
320
+ * ```
321
+ *
322
+ * ## Full-Config Mode (Advanced)
323
+ *
324
+ * Complete control over all configuration options.
325
+ *
326
+ * @example Full configuration
327
+ * ```tsx
328
+ * <KeycloakProvider
329
+ * config={{
330
+ * authority: 'https://sso.example.com/realms/myrealm',
331
+ * clientId: 'my-app',
332
+ * redirectUri: window.location.origin,
333
+ * scope: 'openid profile email offline_access',
334
+ * features: {
335
+ * autoRefresh: true,
336
+ * sessionMonitor: true,
337
+ * },
338
+ * silentRenew: {
339
+ * enabled: true,
340
+ * refreshStrategy: 'both',
341
+ * maxRefreshTokenLifetime: 2592000,
342
+ * },
343
+ * events: {
344
+ * onLogin: (user) => console.log('User logged in', user),
345
+ * onError: (error) => sendToSentry(error),
346
+ * }
347
+ * }}
348
+ * debug={true}
349
+ * >
350
+ * <YourApp />
351
+ * </KeycloakProvider>
352
+ * ```
353
+ *
354
+ * ## Features Automatically Enabled
355
+ *
356
+ * When using zero-config or presets, the following features are automatically enabled:
357
+ * - ✅ Automatic token refresh (before expiration)
358
+ * - ✅ Token lifecycle management (refresh on app startup)
359
+ * - ✅ Session monitoring UI (countdown timer)
360
+ * - ✅ Silent renew (background token refresh)
361
+ * - ✅ Error notifications (user-friendly messages)
362
+ * - ✅ 401 retry logic (automatic token refresh on API errors)
363
+ * - ✅ Maximum refresh token lifetime (security control)
364
+ * - ✅ PKCE (for secure public clients)
365
+ *
366
+ * All features can be disabled or customized via configuration overrides.
180
367
  */
181
368
  declare const KeycloakProvider: React.FC<KeycloakProviderProps>;
182
369
 
@@ -749,6 +936,38 @@ interface DeviceLoginProps {
749
936
  */
750
937
  declare const DeviceLogin: React.FC<DeviceLoginProps>;
751
938
 
939
+ interface TokenLifecycleManagerProps {
940
+ /**
941
+ * Keycloak configuration
942
+ */
943
+ config: KeycloakConfig;
944
+ /**
945
+ * Child components to render
946
+ */
947
+ children: React.ReactNode;
948
+ /**
949
+ * Enable debug logging
950
+ * @default false
951
+ */
952
+ debug?: boolean;
953
+ }
954
+ /**
955
+ * Component that manages token lifecycle including startup refresh and max lifetime tracking
956
+ *
957
+ * This component wraps your app and automatically:
958
+ * - Checks tokens on app startup and refreshes if needed
959
+ * - Tracks refresh token max lifetime
960
+ * - Shows optional loading indicator during refresh
961
+ *
962
+ * @example
963
+ * ```tsx
964
+ * <TokenLifecycleManager config={config} debug={true}>
965
+ * <YourApp />
966
+ * </TokenLifecycleManager>
967
+ * ```
968
+ */
969
+ declare const TokenLifecycleManager: React.FC<TokenLifecycleManagerProps>;
970
+
752
971
  /**
753
972
  * Main authentication hook for accessing Keycloak authentication state and methods
754
973
  *
@@ -1040,6 +1259,83 @@ interface UseProtectedFetchReturn {
1040
1259
  */
1041
1260
  declare function useProtectedFetch(options?: UseProtectedFetchOptions): UseProtectedFetchReturn;
1042
1261
 
1262
+ interface UseTokenLifecycleOptions {
1263
+ /**
1264
+ * Keycloak configuration for token lifecycle settings
1265
+ */
1266
+ config: KeycloakConfig;
1267
+ /**
1268
+ * Enable debug logging
1269
+ * @default false
1270
+ */
1271
+ debug?: boolean;
1272
+ /**
1273
+ * Callback when token refresh starts
1274
+ */
1275
+ onRefreshStart?: () => void;
1276
+ /**
1277
+ * Callback when token refresh succeeds
1278
+ */
1279
+ onRefreshSuccess?: () => void;
1280
+ /**
1281
+ * Callback when token refresh fails
1282
+ */
1283
+ onRefreshError?: (error: Error) => void;
1284
+ /**
1285
+ * Callback when refresh token lifetime expires
1286
+ */
1287
+ onRefreshTokenExpired?: () => void;
1288
+ }
1289
+ interface UseTokenLifecycleReturn {
1290
+ /**
1291
+ * Whether token is being refreshed
1292
+ */
1293
+ isRefreshing: boolean;
1294
+ /**
1295
+ * Whether refresh token has exceeded max lifetime
1296
+ */
1297
+ isRefreshTokenExpired: boolean;
1298
+ /**
1299
+ * Manually trigger token refresh
1300
+ */
1301
+ refreshToken: () => Promise<void>;
1302
+ /**
1303
+ * Check if tokens need refresh and do it if needed
1304
+ */
1305
+ checkAndRefreshTokens: () => Promise<boolean>;
1306
+ }
1307
+ /**
1308
+ * Hook to manage token lifecycle including startup refresh and max lifetime tracking
1309
+ *
1310
+ * This hook provides proactive token management:
1311
+ * - Checks tokens on app startup and refreshes if needed
1312
+ * - Tracks refresh token max lifetime
1313
+ * - Provides manual refresh capabilities
1314
+ *
1315
+ * @param options - Configuration options
1316
+ * @returns Token lifecycle methods and state
1317
+ *
1318
+ * @example
1319
+ * ```tsx
1320
+ * import { useTokenLifecycle } from 'antaeus.keycloak.react';
1321
+ *
1322
+ * function App() {
1323
+ * const { isRefreshing, isRefreshTokenExpired } = useTokenLifecycle({
1324
+ * config: myConfig,
1325
+ * onRefreshStart: () => console.log('Refreshing...'),
1326
+ * onRefreshSuccess: () => console.log('Refreshed!'),
1327
+ * onRefreshError: (error) => console.error('Failed:', error),
1328
+ * });
1329
+ *
1330
+ * if (isRefreshing) return <div>Loading...</div>;
1331
+ * if (isRefreshTokenExpired) return <div>Please sign in again</div>;
1332
+ *
1333
+ * return <YourApp />;
1334
+ * }
1335
+ * ```
1336
+ */
1337
+ declare function useTokenLifecycle(options: UseTokenLifecycleOptions): UseTokenLifecycleReturn;
1338
+
1043
1339
  /**
1044
1340
  * Default configuration values for Keycloak integration
1045
1341
  */
@@ -1190,4 +1486,4 @@ declare function pollForToken(apiBaseUrl: string, deviceCode: string): Promise<T
1190
1486
  */
1191
1487
  declare function fetchUserInfo(apiBaseUrl: string, accessToken: string): Promise<any>;
1192
1488
 
1193
- export { type AdvancedOidcOptions, type DeviceAuthorizationResponse, type DeviceFlowError, DeviceLogin, type DeviceLoginProps, type EventCallbacks, type FeatureFlags, type KeycloakConfig, KeycloakConfigBuilder, KeycloakProvider, type KeycloakProviderProps, LoginButton, type LoginButtonProps, LogoutButton, type LogoutButtonProps, type PolicyContext, type PolicyFunction, ProtectedRoute, type ProtectedRouteProps, SessionMonitor, type SessionMonitorProps, type SilentRenewConfig, type TokenResponse, type UseProtectedFetchOptions, type UseProtectedFetchReturn, type UseRolesReturn, type UseScopesReturn, UserProfile, type UserProfileProps, defaultConfig, fetchUserInfo, getConfigFromEnv, pollForToken, requestDeviceCode, useAuth, useProtectedFetch, useRoles, useScopes };
1489
+ export { type AdvancedOidcOptions, CONFIG_PRESETS, type ConfigPreset, type DeviceAuthorizationResponse, type DeviceFlowError, DeviceLogin, type DeviceLoginProps, type EventCallbacks, type FeatureFlags, type KeycloakConfig, KeycloakConfigBuilder, KeycloakProvider, type KeycloakProviderFullConfigProps, type KeycloakProviderProps, type KeycloakProviderZeroConfigProps, LoginButton, type LoginButtonProps, LogoutButton, type LogoutButtonProps, type PolicyContext, type PolicyFunction, ProtectedRoute, type ProtectedRouteProps, SessionMonitor, type SessionMonitorProps, type SilentRenewConfig, TokenLifecycleManager, type TokenLifecycleManagerProps, type TokenResponse, type UseProtectedFetchOptions, type UseProtectedFetchReturn, type UseRolesReturn, type UseScopesReturn, type UseTokenLifecycleOptions, type UseTokenLifecycleReturn, UserProfile, type UserProfileProps, defaultConfig, fetchUserInfo, getConfigFromEnv, getConfigPreset, mergeWithPreset, pollForToken, requestDeviceCode, useAuth, useProtectedFetch, useRoles, useScopes, useTokenLifecycle };