@authrim/core 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2090 @@
1
+ /**
2
+ * HTTP Client Provider Interface
3
+ *
4
+ * Platform-agnostic HTTP client abstraction.
5
+ * Implementations must be injected - @authrim/core does not use fetch directly.
6
+ */
7
+ /**
8
+ * HTTP request options
9
+ */
10
+ interface HttpOptions {
11
+ method?: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH';
12
+ headers?: Record<string, string>;
13
+ body?: string | FormData | URLSearchParams;
14
+ /** Request timeout in milliseconds */
15
+ timeout?: number;
16
+ /** Signal for request cancellation */
17
+ signal?: AbortSignal;
18
+ }
19
+ /**
20
+ * HTTP response wrapper
21
+ */
22
+ interface HttpResponse<T = unknown> {
23
+ /** HTTP status code */
24
+ status: number;
25
+ /** HTTP status text */
26
+ statusText: string;
27
+ /** Response headers */
28
+ headers: Record<string, string>;
29
+ /** Parsed response body */
30
+ data: T;
31
+ /** Whether the response was successful (2xx) */
32
+ ok: boolean;
33
+ }
34
+ /**
35
+ * HTTP Client interface
36
+ *
37
+ * Implementations should:
38
+ * - Handle JSON parsing automatically when Content-Type is application/json
39
+ * - Handle form data submissions
40
+ * - Implement timeout handling
41
+ * - Propagate network errors appropriately
42
+ */
43
+ interface HttpClient {
44
+ /**
45
+ * Make an HTTP request
46
+ *
47
+ * @param url - Full URL to request
48
+ * @param options - Request options
49
+ * @returns Promise resolving to the response
50
+ * @throws Error on network failure or timeout
51
+ */
52
+ fetch<T = unknown>(url: string, options?: HttpOptions): Promise<HttpResponse<T>>;
53
+ }
54
+
55
+ /**
56
+ * Crypto Provider Interface
57
+ *
58
+ * Platform-agnostic cryptographic operations abstraction.
59
+ * Implementations must be injected - @authrim/core does not use crypto.subtle directly.
60
+ */
61
+ /**
62
+ * Crypto Provider interface
63
+ *
64
+ * Implementations should:
65
+ * - Use cryptographically secure random number generation
66
+ * - Implement SHA-256 using platform-native crypto APIs
67
+ * - Generate PKCE code verifiers and challenges per RFC 7636
68
+ */
69
+ interface CryptoProvider {
70
+ /**
71
+ * Generate cryptographically secure random bytes
72
+ *
73
+ * @param length - Number of bytes to generate
74
+ * @returns Promise resolving to random bytes
75
+ */
76
+ randomBytes(length: number): Promise<Uint8Array>;
77
+ /**
78
+ * Compute SHA-256 hash of a string
79
+ *
80
+ * @param data - String to hash (UTF-8 encoded)
81
+ * @returns Promise resolving to hash bytes
82
+ */
83
+ sha256(data: string): Promise<Uint8Array>;
84
+ /**
85
+ * Generate a PKCE code verifier (RFC 7636)
86
+ *
87
+ * Requirements:
88
+ * - 43-128 characters
89
+ * - URL-safe characters only: [A-Z] / [a-z] / [0-9] / "-" / "." / "_" / "~"
90
+ * - Recommended: 43 characters of base64url-encoded random bytes
91
+ *
92
+ * @returns Promise resolving to code verifier string
93
+ */
94
+ generateCodeVerifier(): Promise<string>;
95
+ /**
96
+ * Generate a PKCE code challenge from a code verifier (RFC 7636)
97
+ *
98
+ * Computes: BASE64URL(SHA256(code_verifier))
99
+ *
100
+ * @param verifier - Code verifier string
101
+ * @returns Promise resolving to code challenge string
102
+ */
103
+ generateCodeChallenge(verifier: string): Promise<string>;
104
+ }
105
+
106
+ /**
107
+ * Storage Provider Interface
108
+ *
109
+ * Platform-agnostic storage abstraction.
110
+ * Implementations must be injected - @authrim/core does not use localStorage directly.
111
+ */
112
+ /**
113
+ * Storage Provider interface
114
+ *
115
+ * Implementations:
116
+ * - Browser: localStorage, sessionStorage, IndexedDB
117
+ * - React Native: AsyncStorage
118
+ * - Node.js: Memory, Redis, Database
119
+ * - Cookie-based: Server-side session storage
120
+ *
121
+ * Note: getAll() and clear() are optional. The SDK functions correctly without them,
122
+ * but providing them enables automatic cleanup of expired state entries.
123
+ */
124
+ interface AuthrimStorage {
125
+ /**
126
+ * Get a value from storage
127
+ *
128
+ * @param key - Storage key
129
+ * @returns Promise resolving to the value, or null if not found
130
+ */
131
+ get(key: string): Promise<string | null>;
132
+ /**
133
+ * Set a value in storage
134
+ *
135
+ * @param key - Storage key
136
+ * @param value - Value to store
137
+ * @returns Promise resolving when complete
138
+ */
139
+ set(key: string, value: string): Promise<void>;
140
+ /**
141
+ * Remove a value from storage
142
+ *
143
+ * @param key - Storage key
144
+ * @returns Promise resolving when complete
145
+ */
146
+ remove(key: string): Promise<void>;
147
+ /**
148
+ * Get all key-value pairs from storage (optional)
149
+ *
150
+ * Used for cleanup of expired state entries.
151
+ * If not implemented, cleanup operations are skipped (security is not affected).
152
+ *
153
+ * @returns Promise resolving to all stored values
154
+ */
155
+ getAll?(): Promise<Record<string, string>>;
156
+ /**
157
+ * Clear all values from storage (optional)
158
+ *
159
+ * Use with caution - clears ALL stored data including tokens.
160
+ *
161
+ * @returns Promise resolving when complete
162
+ */
163
+ clear?(): Promise<void>;
164
+ }
165
+
166
+ /**
167
+ * Client Configuration
168
+ */
169
+
170
+ /**
171
+ * Endpoint overrides
172
+ */
173
+ interface EndpointOverrides {
174
+ /** Authorization endpoint */
175
+ authorization?: string;
176
+ /** Token endpoint */
177
+ token?: string;
178
+ /** UserInfo endpoint */
179
+ userinfo?: string;
180
+ /** Revocation endpoint */
181
+ revocation?: string;
182
+ /** End session endpoint (null to disable) */
183
+ endSession?: string | null;
184
+ }
185
+ /**
186
+ * Hash options for storage key generation
187
+ */
188
+ interface HashOptions {
189
+ /**
190
+ * Hash length for storage keys
191
+ *
192
+ * Default: 16 characters (96 bits)
193
+ * Alternative: 22 characters (132 bits) for lower collision risk
194
+ */
195
+ hashLength?: number;
196
+ }
197
+ /**
198
+ * Authrim Client Configuration
199
+ */
200
+ interface AuthrimClientConfig {
201
+ /**
202
+ * OpenID Connect issuer URL
203
+ *
204
+ * This is used to fetch the discovery document and validate tokens.
205
+ * Trailing slashes are automatically normalized.
206
+ */
207
+ issuer: string;
208
+ /**
209
+ * OAuth 2.0 client ID
210
+ */
211
+ clientId: string;
212
+ /**
213
+ * HTTP client implementation
214
+ *
215
+ * Required for @authrim/core.
216
+ * @authrim/web provides a default browser implementation.
217
+ */
218
+ http: HttpClient;
219
+ /**
220
+ * Crypto provider implementation
221
+ *
222
+ * Required for @authrim/core.
223
+ * @authrim/web provides a default browser implementation.
224
+ */
225
+ crypto: CryptoProvider;
226
+ /**
227
+ * Storage provider implementation
228
+ *
229
+ * Required for @authrim/core.
230
+ * @authrim/web provides localStorage/sessionStorage implementations.
231
+ */
232
+ storage: AuthrimStorage;
233
+ /**
234
+ * Default redirect URI for authorization requests
235
+ */
236
+ redirectUri?: string;
237
+ /**
238
+ * Default scopes to request
239
+ *
240
+ * Default: ['openid', 'profile']
241
+ */
242
+ scopes?: string[];
243
+ /**
244
+ * Manual endpoint overrides
245
+ *
246
+ * Use these to override discovery document endpoints.
247
+ * Set endSession to null to disable logout redirect.
248
+ */
249
+ endpoints?: EndpointOverrides;
250
+ /**
251
+ * Enable Flow Engine (server-driven UI)
252
+ *
253
+ * Default: false
254
+ * Set to true to enable server-driven UI flows.
255
+ * Note: Both SDK and server must have Flow Engine enabled for it to work.
256
+ */
257
+ flowEngine?: boolean;
258
+ /**
259
+ * Discovery cache TTL in milliseconds
260
+ *
261
+ * Default: 3600000 (1 hour)
262
+ */
263
+ discoveryCacheTtlMs?: number;
264
+ /**
265
+ * Token refresh skew in seconds
266
+ *
267
+ * Refresh tokens this many seconds before expiration.
268
+ * Default: 30
269
+ */
270
+ refreshSkewSeconds?: number;
271
+ /**
272
+ * State/nonce TTL in seconds
273
+ *
274
+ * Default: 600 (10 minutes)
275
+ */
276
+ stateTtlSeconds?: number;
277
+ /**
278
+ * Hash options for storage key generation
279
+ */
280
+ hashOptions?: HashOptions;
281
+ }
282
+ /**
283
+ * Resolved configuration with defaults applied
284
+ */
285
+ interface ResolvedConfig extends Required<Omit<AuthrimClientConfig, 'endpoints' | 'redirectUri' | 'hashOptions'>> {
286
+ endpoints?: EndpointOverrides;
287
+ redirectUri?: string;
288
+ hashOptions: Required<HashOptions>;
289
+ }
290
+ /**
291
+ * Apply defaults to configuration
292
+ */
293
+ declare function resolveConfig(config: AuthrimClientConfig): ResolvedConfig;
294
+
295
+ /**
296
+ * OIDC / OAuth 2.0 Types
297
+ */
298
+ /**
299
+ * OIDC Discovery Document
300
+ * https://openid.net/specs/openid-connect-discovery-1_0.html
301
+ */
302
+ interface OIDCDiscoveryDocument {
303
+ /** Issuer identifier (REQUIRED) */
304
+ issuer: string;
305
+ /** Authorization endpoint URL (REQUIRED) */
306
+ authorization_endpoint: string;
307
+ /** Token endpoint URL (REQUIRED unless only implicit flow is used) */
308
+ token_endpoint: string;
309
+ /** UserInfo endpoint URL (RECOMMENDED) */
310
+ userinfo_endpoint?: string;
311
+ /** JWKS URI (REQUIRED) */
312
+ jwks_uri: string;
313
+ /** Registration endpoint URL (RECOMMENDED) */
314
+ registration_endpoint?: string;
315
+ /** Scopes supported (RECOMMENDED) */
316
+ scopes_supported?: string[];
317
+ /** Response types supported (REQUIRED) */
318
+ response_types_supported: string[];
319
+ /** Response modes supported (OPTIONAL) */
320
+ response_modes_supported?: string[];
321
+ /** Grant types supported (OPTIONAL) */
322
+ grant_types_supported?: string[];
323
+ /** ACR values supported (OPTIONAL) */
324
+ acr_values_supported?: string[];
325
+ /** Subject types supported (REQUIRED) */
326
+ subject_types_supported: string[];
327
+ /** ID Token signing algs supported (REQUIRED) */
328
+ id_token_signing_alg_values_supported: string[];
329
+ /** ID Token encryption algs supported (OPTIONAL) */
330
+ id_token_encryption_alg_values_supported?: string[];
331
+ /** ID Token encryption enc supported (OPTIONAL) */
332
+ id_token_encryption_enc_values_supported?: string[];
333
+ /** UserInfo signing algs supported (OPTIONAL) */
334
+ userinfo_signing_alg_values_supported?: string[];
335
+ /** UserInfo encryption algs supported (OPTIONAL) */
336
+ userinfo_encryption_alg_values_supported?: string[];
337
+ /** UserInfo encryption enc supported (OPTIONAL) */
338
+ userinfo_encryption_enc_values_supported?: string[];
339
+ /** Request object signing algs supported (OPTIONAL) */
340
+ request_object_signing_alg_values_supported?: string[];
341
+ /** Request object encryption algs supported (OPTIONAL) */
342
+ request_object_encryption_alg_values_supported?: string[];
343
+ /** Request object encryption enc supported (OPTIONAL) */
344
+ request_object_encryption_enc_values_supported?: string[];
345
+ /** Token endpoint auth methods supported (OPTIONAL) */
346
+ token_endpoint_auth_methods_supported?: string[];
347
+ /** Token endpoint auth signing algs supported (OPTIONAL) */
348
+ token_endpoint_auth_signing_alg_values_supported?: string[];
349
+ /** Display values supported (OPTIONAL) */
350
+ display_values_supported?: string[];
351
+ /** Claim types supported (OPTIONAL) */
352
+ claim_types_supported?: string[];
353
+ /** Claims supported (RECOMMENDED) */
354
+ claims_supported?: string[];
355
+ /** Service documentation URL (OPTIONAL) */
356
+ service_documentation?: string;
357
+ /** Claims locales supported (OPTIONAL) */
358
+ claims_locales_supported?: string[];
359
+ /** UI locales supported (OPTIONAL) */
360
+ ui_locales_supported?: string[];
361
+ /** Claims parameter supported (OPTIONAL) */
362
+ claims_parameter_supported?: boolean;
363
+ /** Request parameter supported (OPTIONAL) */
364
+ request_parameter_supported?: boolean;
365
+ /** Request URI parameter supported (OPTIONAL) */
366
+ request_uri_parameter_supported?: boolean;
367
+ /** Require request URI registration (OPTIONAL) */
368
+ require_request_uri_registration?: boolean;
369
+ /** OP policy URI (OPTIONAL) */
370
+ op_policy_uri?: string;
371
+ /** OP ToS URI (OPTIONAL) */
372
+ op_tos_uri?: string;
373
+ /** End session endpoint (OPTIONAL) */
374
+ end_session_endpoint?: string;
375
+ /** Revocation endpoint (OPTIONAL) */
376
+ revocation_endpoint?: string;
377
+ /** Revocation endpoint auth methods supported (OPTIONAL) */
378
+ revocation_endpoint_auth_methods_supported?: string[];
379
+ /** Revocation endpoint auth signing algs supported (OPTIONAL) */
380
+ revocation_endpoint_auth_signing_alg_values_supported?: string[];
381
+ /** Introspection endpoint (OPTIONAL) */
382
+ introspection_endpoint?: string;
383
+ /** Introspection endpoint auth methods supported (OPTIONAL) */
384
+ introspection_endpoint_auth_methods_supported?: string[];
385
+ /** Introspection endpoint auth signing algs supported (OPTIONAL) */
386
+ introspection_endpoint_auth_signing_alg_values_supported?: string[];
387
+ /** Code challenge methods supported (OPTIONAL) */
388
+ code_challenge_methods_supported?: string[];
389
+ /** Flow Engine support indicator (OPTIONAL, Authrim-specific) */
390
+ flow_engine_supported?: boolean;
391
+ [key: string]: unknown;
392
+ }
393
+ /**
394
+ * Standard OIDC claims in ID Token
395
+ */
396
+ interface IdTokenClaims {
397
+ /** Issuer Identifier */
398
+ iss: string;
399
+ /** Subject Identifier */
400
+ sub: string;
401
+ /** Audience */
402
+ aud: string | string[];
403
+ /** Expiration time */
404
+ exp: number;
405
+ /** Issued at time */
406
+ iat: number;
407
+ /** Authentication time */
408
+ auth_time?: number;
409
+ /** Nonce */
410
+ nonce?: string;
411
+ /** ACR - Authentication Context Class Reference */
412
+ acr?: string;
413
+ /** AMR - Authentication Methods References */
414
+ amr?: string[];
415
+ /** Authorized party */
416
+ azp?: string;
417
+ /** Access token hash */
418
+ at_hash?: string;
419
+ /** Code hash */
420
+ c_hash?: string;
421
+ /** Session ID */
422
+ sid?: string;
423
+ name?: string;
424
+ given_name?: string;
425
+ family_name?: string;
426
+ middle_name?: string;
427
+ nickname?: string;
428
+ preferred_username?: string;
429
+ profile?: string;
430
+ picture?: string;
431
+ website?: string;
432
+ email?: string;
433
+ email_verified?: boolean;
434
+ gender?: string;
435
+ birthdate?: string;
436
+ zoneinfo?: string;
437
+ locale?: string;
438
+ phone_number?: string;
439
+ phone_number_verified?: boolean;
440
+ address?: {
441
+ formatted?: string;
442
+ street_address?: string;
443
+ locality?: string;
444
+ region?: string;
445
+ postal_code?: string;
446
+ country?: string;
447
+ };
448
+ updated_at?: number;
449
+ [key: string]: unknown;
450
+ }
451
+ /**
452
+ * Address claim
453
+ */
454
+ interface AddressClaim {
455
+ formatted?: string;
456
+ street_address?: string;
457
+ locality?: string;
458
+ region?: string;
459
+ postal_code?: string;
460
+ country?: string;
461
+ }
462
+ /**
463
+ * Standard OIDC claims (profile, email, phone, address)
464
+ */
465
+ interface StandardClaims {
466
+ name?: string;
467
+ given_name?: string;
468
+ family_name?: string;
469
+ middle_name?: string;
470
+ nickname?: string;
471
+ preferred_username?: string;
472
+ profile?: string;
473
+ picture?: string;
474
+ website?: string;
475
+ email?: string;
476
+ email_verified?: boolean;
477
+ gender?: string;
478
+ birthdate?: string;
479
+ zoneinfo?: string;
480
+ locale?: string;
481
+ phone_number?: string;
482
+ phone_number_verified?: boolean;
483
+ address?: AddressClaim;
484
+ updated_at?: number;
485
+ }
486
+ /**
487
+ * UserInfo response
488
+ */
489
+ interface UserInfo extends StandardClaims {
490
+ sub: string;
491
+ [key: string]: unknown;
492
+ }
493
+
494
+ /**
495
+ * Token Types
496
+ */
497
+ /**
498
+ * Token set returned from token endpoint
499
+ *
500
+ * Note: expiresAt is epoch seconds (not milliseconds)
501
+ */
502
+ interface TokenSet {
503
+ /** Access token */
504
+ accessToken: string;
505
+ /** Refresh token (if provided) */
506
+ refreshToken?: string;
507
+ /** ID token (if openid scope was requested) */
508
+ idToken?: string;
509
+ /** Token type (always 'Bearer' for OAuth 2.0) */
510
+ tokenType: 'Bearer';
511
+ /**
512
+ * Token expiration time as epoch seconds
513
+ *
514
+ * Calculated from expires_in at token exchange time:
515
+ * expiresAt = Math.floor(Date.now() / 1000) + expires_in
516
+ */
517
+ expiresAt: number;
518
+ /** Scope granted (may differ from requested scope) */
519
+ scope?: string;
520
+ }
521
+ /**
522
+ * Token endpoint response (raw)
523
+ */
524
+ interface TokenEndpointResponse {
525
+ access_token: string;
526
+ token_type: string;
527
+ expires_in?: number;
528
+ refresh_token?: string;
529
+ id_token?: string;
530
+ scope?: string;
531
+ }
532
+ /**
533
+ * Alias for TokenEndpointResponse
534
+ */
535
+ type TokenResponse = TokenEndpointResponse;
536
+ /**
537
+ * Token exchange request (RFC 8693)
538
+ */
539
+ interface TokenExchangeRequest {
540
+ /** The subject token to exchange */
541
+ subjectToken: string;
542
+ /** Subject token type (default: access_token) */
543
+ subjectTokenType?: 'access_token' | 'refresh_token' | 'id_token';
544
+ /** Target audience for the new token */
545
+ audience?: string;
546
+ /** Requested scope for the new token */
547
+ scope?: string;
548
+ /** Requested token type (default: access_token) */
549
+ requestedTokenType?: 'access_token' | 'refresh_token' | 'id_token';
550
+ /** Actor token (for delegation) */
551
+ actorToken?: string;
552
+ /** Actor token type */
553
+ actorTokenType?: 'access_token' | 'id_token';
554
+ }
555
+ /**
556
+ * Token exchange response (RFC 8693)
557
+ *
558
+ * Extends standard token response with issued_token_type
559
+ */
560
+ interface TokenExchangeResponse extends TokenEndpointResponse {
561
+ /** URI of the issued token type */
562
+ issued_token_type: string;
563
+ }
564
+ /**
565
+ * Token type URIs (RFC 8693)
566
+ */
567
+ declare const TOKEN_TYPE_URIS: {
568
+ readonly access_token: "urn:ietf:params:oauth:token-type:access_token";
569
+ readonly refresh_token: "urn:ietf:params:oauth:token-type:refresh_token";
570
+ readonly id_token: "urn:ietf:params:oauth:token-type:id_token";
571
+ };
572
+ /**
573
+ * Token type URI type
574
+ */
575
+ type TokenTypeUri = (typeof TOKEN_TYPE_URIS)[keyof typeof TOKEN_TYPE_URIS];
576
+ /**
577
+ * Token exchange result
578
+ */
579
+ interface TokenExchangeResult {
580
+ /** Token set from exchange */
581
+ tokens: TokenSet;
582
+ /** Issued token type URI */
583
+ issuedTokenType: TokenTypeUri | string;
584
+ }
585
+
586
+ /**
587
+ * Authrim SDK Error Types
588
+ */
589
+ /**
590
+ * User action recommended for error recovery
591
+ */
592
+ type AuthrimErrorUserAction = 'retry' | 'reauthenticate' | 'contact_support' | 'check_network' | 'none';
593
+ /**
594
+ * Error severity level
595
+ */
596
+ type AuthrimErrorSeverity = 'fatal' | 'error' | 'warning';
597
+ /**
598
+ * Error metadata for recovery information
599
+ */
600
+ interface AuthrimErrorMeta {
601
+ /** Whether this is a transient error */
602
+ transient: boolean;
603
+ /** Whether automatic retry is possible */
604
+ retryable: boolean;
605
+ /** Suggested retry wait time in milliseconds */
606
+ retryAfterMs?: number;
607
+ /** Maximum number of retry attempts */
608
+ maxRetries?: number;
609
+ /** Recommended user action */
610
+ userAction: AuthrimErrorUserAction;
611
+ /** Error severity level */
612
+ severity: AuthrimErrorSeverity;
613
+ }
614
+ /**
615
+ * Error codes used by the SDK
616
+ */
617
+ type AuthrimErrorCode = 'invalid_request' | 'unauthorized_client' | 'access_denied' | 'unsupported_response_type' | 'invalid_scope' | 'server_error' | 'temporarily_unavailable' | 'invalid_grant' | 'invalid_token' | 'invalid_state' | 'expired_state' | 'invalid_nonce' | 'nonce_mismatch' | 'session_expired' | 'session_check_failed' | 'network_error' | 'timeout_error' | 'discovery_error' | 'discovery_mismatch' | 'configuration_error' | 'storage_error' | 'flow_engine_error' | 'no_tokens' | 'token_expired' | 'token_error' | 'refresh_error' | 'token_exchange_error' | 'oauth_error' | 'missing_code' | 'missing_state' | 'not_initialized' | 'no_discovery' | 'no_userinfo_endpoint' | 'userinfo_error' | 'introspection_error' | 'revocation_error' | 'no_introspection_endpoint' | 'no_revocation_endpoint' | 'login_required' | 'interaction_required' | 'consent_required' | 'account_selection_required';
618
+ /**
619
+ * Options for creating an AuthrimError
620
+ */
621
+ interface AuthrimErrorOptions {
622
+ details?: Record<string, unknown>;
623
+ errorUri?: string;
624
+ cause?: Error;
625
+ }
626
+ /**
627
+ * Authrim SDK Error class
628
+ */
629
+ declare class AuthrimError extends Error {
630
+ /** Error code for programmatic handling */
631
+ readonly code: AuthrimErrorCode;
632
+ /** Additional error details */
633
+ readonly details?: Record<string, unknown>;
634
+ /** OAuth error_uri if provided */
635
+ readonly errorUri?: string;
636
+ /** Underlying cause */
637
+ readonly cause?: Error;
638
+ constructor(code: AuthrimErrorCode, message: string, options?: AuthrimErrorOptions);
639
+ /**
640
+ * Create an AuthrimError from an OAuth error response
641
+ */
642
+ static fromOAuthError(error: {
643
+ error: string;
644
+ error_description?: string;
645
+ error_uri?: string;
646
+ }): AuthrimError;
647
+ /**
648
+ * Check if an error is retryable (e.g., network errors)
649
+ */
650
+ isRetryable(): boolean;
651
+ /**
652
+ * Get error metadata for recovery guidance
653
+ */
654
+ get meta(): AuthrimErrorMeta;
655
+ }
656
+ /**
657
+ * Get error metadata for a given error code
658
+ */
659
+ declare function getErrorMeta(code: AuthrimErrorCode): AuthrimErrorMeta;
660
+
661
+ /**
662
+ * Event Types
663
+ */
664
+
665
+ /**
666
+ * Token refresh event data
667
+ */
668
+ interface TokenRefreshedEvent {
669
+ tokens: TokenSet;
670
+ }
671
+ /**
672
+ * Token expired event data
673
+ */
674
+ interface TokenExpiredEvent {
675
+ accessToken: string;
676
+ }
677
+ /**
678
+ * Token error event data
679
+ */
680
+ interface TokenErrorEvent {
681
+ error: AuthrimError;
682
+ }
683
+ /**
684
+ * Token exchanged event data (RFC 8693)
685
+ */
686
+ interface TokenExchangedEvent {
687
+ tokens: TokenSet;
688
+ issuedTokenType: string;
689
+ }
690
+ /**
691
+ * Session started event data
692
+ */
693
+ interface SessionStartedEvent {
694
+ user: UserInfo;
695
+ }
696
+ /**
697
+ * Session ended event data
698
+ */
699
+ interface SessionEndedEvent {
700
+ reason: 'logout' | 'expired' | 'revoked';
701
+ }
702
+ /**
703
+ * Auth redirecting event data
704
+ */
705
+ interface AuthRedirectingEvent {
706
+ url: string;
707
+ }
708
+ /**
709
+ * Auth callback event data
710
+ */
711
+ interface AuthCallbackEvent {
712
+ code: string;
713
+ state: string;
714
+ }
715
+ /**
716
+ * Error event data
717
+ */
718
+ interface ErrorEvent {
719
+ error: AuthrimError;
720
+ context: string;
721
+ }
722
+ /**
723
+ * All Authrim events
724
+ */
725
+ interface AuthrimEvents {
726
+ 'token:refreshed': TokenRefreshedEvent;
727
+ 'token:expired': TokenExpiredEvent;
728
+ 'token:error': TokenErrorEvent;
729
+ 'token:exchanged': TokenExchangedEvent;
730
+ 'session:started': SessionStartedEvent;
731
+ 'session:ended': SessionEndedEvent;
732
+ 'auth:redirecting': AuthRedirectingEvent;
733
+ 'auth:callback': AuthCallbackEvent;
734
+ error: ErrorEvent;
735
+ }
736
+ /**
737
+ * Event names
738
+ */
739
+ type AuthrimEventName = keyof AuthrimEvents;
740
+ /**
741
+ * Event handler type
742
+ */
743
+ type AuthrimEventHandler<T extends AuthrimEventName> = (event: AuthrimEvents[T]) => void;
744
+
745
+ /**
746
+ * State/Nonce Manager
747
+ *
748
+ * Manages CSRF protection (state) and replay attack prevention (nonce)
749
+ * for Authorization Code Flow.
750
+ */
751
+
752
+ /**
753
+ * Auth state stored in storage
754
+ */
755
+ interface AuthState {
756
+ /** State parameter (CSRF protection) */
757
+ state: string;
758
+ /** Nonce parameter (replay attack prevention) */
759
+ nonce: string;
760
+ /** PKCE code verifier */
761
+ codeVerifier: string;
762
+ /** Redirect URI used for this auth request */
763
+ redirectUri: string;
764
+ /** Timestamp when state was created */
765
+ createdAt: number;
766
+ /** Timestamp when state expires */
767
+ expiresAt: number;
768
+ }
769
+ /**
770
+ * Options for generating auth state
771
+ */
772
+ interface GenerateAuthStateOptions {
773
+ /** Redirect URI for this auth request */
774
+ redirectUri: string;
775
+ /** Code verifier for PKCE */
776
+ codeVerifier: string;
777
+ /** TTL in seconds (default: 600 = 10 minutes) */
778
+ ttlSeconds?: number;
779
+ }
780
+ /**
781
+ * Storage keys factory
782
+ */
783
+ declare const STORAGE_KEYS: {
784
+ /**
785
+ * Auth state key (state-specific)
786
+ */
787
+ readonly authState: (issuerHash: string, clientIdHash: string, state: string) => string;
788
+ /**
789
+ * Token storage key
790
+ */
791
+ readonly tokens: (issuerHash: string, clientIdHash: string) => string;
792
+ /**
793
+ * ID token storage key
794
+ */
795
+ readonly idToken: (issuerHash: string, clientIdHash: string) => string;
796
+ /**
797
+ * Auth state prefix for cleanup
798
+ */
799
+ readonly authStatePrefix: (issuerHash: string, clientIdHash: string) => string;
800
+ };
801
+ /**
802
+ * State Manager
803
+ */
804
+ declare class StateManager {
805
+ private readonly crypto;
806
+ private readonly storage;
807
+ private readonly issuerHash;
808
+ private readonly clientIdHash;
809
+ /** Default TTL: 10 minutes */
810
+ private static readonly DEFAULT_TTL_SECONDS;
811
+ constructor(crypto: CryptoProvider, storage: AuthrimStorage, issuerHash: string, clientIdHash: string);
812
+ /**
813
+ * Generate and store auth state
814
+ *
815
+ * Creates state, nonce, stores them with the code verifier.
816
+ *
817
+ * @param options - Generation options
818
+ * @returns Generated state string
819
+ */
820
+ generateAuthState(options: GenerateAuthStateOptions): Promise<AuthState>;
821
+ /**
822
+ * Validate and consume state
823
+ *
824
+ * Retrieves, validates, and ALWAYS deletes the state (success or failure).
825
+ * This ensures replay attack prevention and GC.
826
+ *
827
+ * @param state - State parameter from callback
828
+ * @returns Auth state if valid
829
+ * @throws AuthrimError if state is invalid or expired
830
+ */
831
+ validateAndConsumeState(state: string): Promise<AuthState>;
832
+ /**
833
+ * Clean up expired states
834
+ *
835
+ * This is a best-effort cleanup. Only works if storage.getAll() is available.
836
+ * The primary GC mechanism is validateAndConsumeState()'s finally delete.
837
+ *
838
+ * Safe to call at startup or periodically.
839
+ */
840
+ cleanupExpiredStates(): Promise<void>;
841
+ }
842
+
843
+ /**
844
+ * PKCE (Proof Key for Code Exchange) Helper
845
+ *
846
+ * Implements RFC 7636 for Authorization Code Flow security.
847
+ * https://tools.ietf.org/html/rfc7636
848
+ */
849
+
850
+ /**
851
+ * PKCE challenge method
852
+ */
853
+ type CodeChallengeMethod = 'S256' | 'plain';
854
+ /**
855
+ * PKCE pair (verifier and challenge)
856
+ */
857
+ interface PKCEPair {
858
+ /** Code verifier (high-entropy random string) */
859
+ codeVerifier: string;
860
+ /** Code challenge (derived from verifier) */
861
+ codeChallenge: string;
862
+ /** Challenge method used */
863
+ codeChallengeMethod: CodeChallengeMethod;
864
+ }
865
+ /**
866
+ * PKCE Helper class
867
+ */
868
+ declare class PKCEHelper {
869
+ private readonly crypto;
870
+ constructor(crypto: CryptoProvider);
871
+ /**
872
+ * Generate a PKCE pair (verifier + challenge)
873
+ *
874
+ * Uses S256 method (SHA-256 hash, base64url-encoded).
875
+ *
876
+ * @returns PKCE pair
877
+ */
878
+ generatePKCE(): Promise<PKCEPair>;
879
+ /**
880
+ * Generate only the code verifier
881
+ *
882
+ * @returns Code verifier string
883
+ */
884
+ generateCodeVerifier(): Promise<string>;
885
+ /**
886
+ * Generate a code challenge from a verifier
887
+ *
888
+ * @param verifier - Code verifier
889
+ * @returns Code challenge (base64url-encoded SHA-256 hash)
890
+ */
891
+ generateCodeChallenge(verifier: string): Promise<string>;
892
+ }
893
+
894
+ /**
895
+ * Authorization Code Flow
896
+ *
897
+ * Implements OAuth 2.0 Authorization Code Flow with PKCE.
898
+ * Uses 2-step pattern: buildAuthorizationUrl() + handleCallback()
899
+ */
900
+
901
+ /**
902
+ * Options for building authorization URL
903
+ */
904
+ interface BuildAuthorizationUrlOptions {
905
+ /** Redirect URI (required) */
906
+ redirectUri: string;
907
+ /** Scopes to request (default: 'openid profile') */
908
+ scope?: string;
909
+ /** Prompt behavior */
910
+ prompt?: 'none' | 'login' | 'consent' | 'select_account';
911
+ /** Hint about the login identifier */
912
+ loginHint?: string;
913
+ /** Requested Authentication Context Class Reference values */
914
+ acrValues?: string;
915
+ /** Additional custom parameters */
916
+ extraParams?: Record<string, string>;
917
+ /**
918
+ * Expose state/nonce in result (for SSR/external storage)
919
+ *
920
+ * Default: false (security: state/nonce stay internal)
921
+ * Set to true only when you need to store state externally
922
+ * (e.g., cookie, server-side session)
923
+ */
924
+ exposeState?: boolean;
925
+ }
926
+ /**
927
+ * Result of buildAuthorizationUrl
928
+ */
929
+ interface AuthorizationUrlResult {
930
+ /** Authorization URL to redirect to */
931
+ url: string;
932
+ /** State parameter (only if exposeState: true) */
933
+ state?: string;
934
+ /** Nonce parameter (only if exposeState: true) */
935
+ nonce?: string;
936
+ }
937
+ /**
938
+ * Internal authorization context (stored by StateManager)
939
+ */
940
+ interface AuthorizationContext {
941
+ /** Auth state object */
942
+ authState: AuthState;
943
+ /** PKCE pair */
944
+ pkce: PKCEPair;
945
+ }
946
+ /**
947
+ * Options for exchanging authorization code
948
+ */
949
+ interface ExchangeCodeOptions {
950
+ /** Authorization code */
951
+ code: string;
952
+ /** State parameter (for validation) */
953
+ state: string;
954
+ /** Redirect URI used in authorization request */
955
+ redirectUri: string;
956
+ /** Code verifier for PKCE */
957
+ codeVerifier: string;
958
+ /** Nonce to validate in ID token */
959
+ nonce: string;
960
+ }
961
+ /**
962
+ * Authorization Code Flow helper
963
+ */
964
+ declare class AuthorizationCodeFlow {
965
+ private readonly http;
966
+ private readonly clientId;
967
+ constructor(http: HttpClient, clientId: string);
968
+ /**
969
+ * Build authorization URL
970
+ *
971
+ * @param discovery - OIDC discovery document
972
+ * @param authState - Auth state from StateManager
973
+ * @param pkce - PKCE pair
974
+ * @param options - Authorization options
975
+ * @returns Authorization URL result
976
+ */
977
+ buildAuthorizationUrl(discovery: OIDCDiscoveryDocument, authState: AuthState, pkce: PKCEPair, options: BuildAuthorizationUrlOptions): AuthorizationUrlResult;
978
+ /**
979
+ * Parse callback URL and extract code/state
980
+ *
981
+ * @param callbackUrl - Callback URL or query string
982
+ * @returns Parsed code and state
983
+ * @throws AuthrimError if code or state is missing, or if error is present
984
+ */
985
+ parseCallback(callbackUrl: string): {
986
+ code: string;
987
+ state: string;
988
+ };
989
+ /**
990
+ * Exchange authorization code for tokens
991
+ *
992
+ * @param discovery - OIDC discovery document
993
+ * @param options - Exchange options
994
+ * @returns Token set
995
+ * @throws AuthrimError if exchange fails or nonce validation fails
996
+ */
997
+ exchangeCode(discovery: OIDCDiscoveryDocument, options: ExchangeCodeOptions): Promise<TokenSet>;
998
+ }
999
+
1000
+ /**
1001
+ * Token Introspection (RFC 7662)
1002
+ *
1003
+ * Implements OAuth 2.0 Token Introspection to validate tokens server-side.
1004
+ * https://datatracker.ietf.org/doc/html/rfc7662
1005
+ */
1006
+
1007
+ /**
1008
+ * Token type hint for introspection
1009
+ */
1010
+ type IntrospectionTokenTypeHint = 'access_token' | 'refresh_token';
1011
+ /**
1012
+ * Token introspection response (RFC 7662)
1013
+ */
1014
+ interface IntrospectionResponse {
1015
+ /** Whether the token is active */
1016
+ active: boolean;
1017
+ /** Space-separated list of scopes (if active) */
1018
+ scope?: string;
1019
+ /** Client identifier (if active) */
1020
+ client_id?: string;
1021
+ /** Human-readable username (if active) */
1022
+ username?: string;
1023
+ /** Token type (e.g., "Bearer") */
1024
+ token_type?: string;
1025
+ /** Expiration time (Unix timestamp) */
1026
+ exp?: number;
1027
+ /** Issued at time (Unix timestamp) */
1028
+ iat?: number;
1029
+ /** Not before time (Unix timestamp) */
1030
+ nbf?: number;
1031
+ /** Subject identifier */
1032
+ sub?: string;
1033
+ /** Audience (single string or array) */
1034
+ aud?: string | string[];
1035
+ /** Issuer identifier */
1036
+ iss?: string;
1037
+ /** JWT ID */
1038
+ jti?: string;
1039
+ /** Additional claims */
1040
+ [key: string]: unknown;
1041
+ }
1042
+ /**
1043
+ * Token introspection options
1044
+ */
1045
+ interface IntrospectTokenOptions {
1046
+ /** Token to introspect */
1047
+ token: string;
1048
+ /** Hint about the token type (optional, helps server optimize lookup) */
1049
+ tokenTypeHint?: IntrospectionTokenTypeHint;
1050
+ }
1051
+ /**
1052
+ * Token introspector options
1053
+ */
1054
+ interface TokenIntrospectorOptions {
1055
+ /** HTTP client */
1056
+ http: HttpClient;
1057
+ /** Client ID */
1058
+ clientId: string;
1059
+ }
1060
+ /**
1061
+ * Token Introspector
1062
+ *
1063
+ * Handles token introspection requests to the authorization server.
1064
+ */
1065
+ declare class TokenIntrospector {
1066
+ private readonly http;
1067
+ private readonly clientId;
1068
+ constructor(options: TokenIntrospectorOptions);
1069
+ /**
1070
+ * Introspect a token
1071
+ *
1072
+ * Per RFC 7662, the introspection endpoint returns:
1073
+ * - { active: true, ... } for valid tokens with additional metadata
1074
+ * - { active: false } for invalid, expired, or revoked tokens
1075
+ *
1076
+ * @param discovery - OIDC discovery document
1077
+ * @param options - Introspection options
1078
+ * @returns Introspection response
1079
+ * @throws AuthrimError if introspection endpoint is not available or request fails
1080
+ */
1081
+ introspect(discovery: OIDCDiscoveryDocument, options: IntrospectTokenOptions): Promise<IntrospectionResponse>;
1082
+ /**
1083
+ * Introspect a token directly using the endpoint URL
1084
+ *
1085
+ * Use this when you have the endpoint URL but not the full discovery document.
1086
+ *
1087
+ * @param endpoint - Introspection endpoint URL
1088
+ * @param options - Introspection options
1089
+ * @returns Introspection response
1090
+ * @throws AuthrimError if request fails
1091
+ */
1092
+ introspectWithEndpoint(endpoint: string, options: IntrospectTokenOptions): Promise<IntrospectionResponse>;
1093
+ /**
1094
+ * Check if a token is active
1095
+ *
1096
+ * Convenience method that returns only the active status.
1097
+ *
1098
+ * @param discovery - OIDC discovery document
1099
+ * @param token - Token to check
1100
+ * @returns True if token is active
1101
+ */
1102
+ isActive(discovery: OIDCDiscoveryDocument, token: string): Promise<boolean>;
1103
+ }
1104
+
1105
+ /**
1106
+ * Token Revocation (RFC 7009)
1107
+ *
1108
+ * Implements OAuth 2.0 Token Revocation to explicitly invalidate tokens.
1109
+ * https://datatracker.ietf.org/doc/html/rfc7009
1110
+ */
1111
+
1112
+ /**
1113
+ * Token type hint for revocation
1114
+ */
1115
+ type TokenTypeHint = 'access_token' | 'refresh_token';
1116
+ /**
1117
+ * Token revocation options
1118
+ */
1119
+ interface RevokeTokenOptions {
1120
+ /** Token to revoke */
1121
+ token: string;
1122
+ /** Hint about the token type (optional, helps server optimize lookup) */
1123
+ tokenTypeHint?: TokenTypeHint;
1124
+ }
1125
+ /**
1126
+ * Token revoker options
1127
+ */
1128
+ interface TokenRevokerOptions {
1129
+ /** HTTP client */
1130
+ http: HttpClient;
1131
+ /** Client ID */
1132
+ clientId: string;
1133
+ }
1134
+ /**
1135
+ * Token Revoker
1136
+ *
1137
+ * Handles token revocation requests to the authorization server.
1138
+ */
1139
+ declare class TokenRevoker {
1140
+ private readonly http;
1141
+ private readonly clientId;
1142
+ constructor(options: TokenRevokerOptions);
1143
+ /**
1144
+ * Revoke a token
1145
+ *
1146
+ * Per RFC 7009, the revocation endpoint:
1147
+ * - Returns 200 OK on success (even if token was already invalid)
1148
+ * - Returns 400 for invalid requests
1149
+ * - Returns 503 if temporarily unavailable
1150
+ *
1151
+ * @param discovery - OIDC discovery document
1152
+ * @param options - Revocation options
1153
+ * @throws AuthrimError if revocation endpoint is not available or request fails
1154
+ */
1155
+ revoke(discovery: OIDCDiscoveryDocument, options: RevokeTokenOptions): Promise<void>;
1156
+ /**
1157
+ * Revoke a token directly using the endpoint URL
1158
+ *
1159
+ * Use this when you have the endpoint URL but not the full discovery document.
1160
+ *
1161
+ * @param endpoint - Revocation endpoint URL
1162
+ * @param options - Revocation options
1163
+ * @throws AuthrimError if request fails
1164
+ */
1165
+ revokeWithEndpoint(endpoint: string, options: RevokeTokenOptions): Promise<void>;
1166
+ }
1167
+
1168
+ /**
1169
+ * Event Emitter
1170
+ *
1171
+ * Simple typed event emitter for SDK events.
1172
+ */
1173
+
1174
+ /**
1175
+ * Typed Event Emitter
1176
+ */
1177
+ declare class EventEmitter {
1178
+ private listeners;
1179
+ /**
1180
+ * Subscribe to an event
1181
+ *
1182
+ * @param event - Event name
1183
+ * @param handler - Event handler
1184
+ * @returns Unsubscribe function
1185
+ */
1186
+ on<T extends AuthrimEventName>(event: T, handler: AuthrimEventHandler<T>): () => void;
1187
+ /**
1188
+ * Subscribe to an event (one-time)
1189
+ *
1190
+ * @param event - Event name
1191
+ * @param handler - Event handler
1192
+ * @returns Unsubscribe function
1193
+ */
1194
+ once<T extends AuthrimEventName>(event: T, handler: AuthrimEventHandler<T>): () => void;
1195
+ /**
1196
+ * Unsubscribe from an event
1197
+ *
1198
+ * @param event - Event name
1199
+ * @param handler - Event handler to remove
1200
+ */
1201
+ off<T extends AuthrimEventName>(event: T, handler: AuthrimEventHandler<T>): void;
1202
+ /**
1203
+ * Emit an event
1204
+ *
1205
+ * @param event - Event name
1206
+ * @param data - Event data
1207
+ */
1208
+ emit<T extends AuthrimEventName>(event: T, data: AuthrimEvents[T]): void;
1209
+ /**
1210
+ * Remove all listeners for an event (or all events)
1211
+ *
1212
+ * @param event - Event name (optional, removes all if not specified)
1213
+ */
1214
+ removeAllListeners(event?: AuthrimEventName): void;
1215
+ /**
1216
+ * Get the number of listeners for an event
1217
+ *
1218
+ * @param event - Event name
1219
+ * @returns Number of listeners
1220
+ */
1221
+ listenerCount(event: AuthrimEventName): number;
1222
+ }
1223
+
1224
+ /**
1225
+ * Logout Handler
1226
+ *
1227
+ * Implements RP-Initiated Logout (OpenID Connect RP-Initiated Logout 1.0)
1228
+ * https://openid.net/specs/openid-connect-rpinitiated-1_0.html
1229
+ */
1230
+
1231
+ /**
1232
+ * Logout options
1233
+ */
1234
+ interface LogoutOptions {
1235
+ /** URI to redirect to after logout */
1236
+ postLogoutRedirectUri?: string;
1237
+ /** ID token hint (optional, uses stored ID token if not provided) */
1238
+ idTokenHint?: string;
1239
+ /** State parameter for post-logout redirect */
1240
+ state?: string;
1241
+ /** Whether to revoke tokens before logout (requires revocation_endpoint) */
1242
+ revokeTokens?: boolean;
1243
+ }
1244
+ /**
1245
+ * Logout result
1246
+ */
1247
+ interface LogoutResult {
1248
+ /** Logout URL to redirect to (if IdP supports end_session_endpoint) */
1249
+ logoutUrl?: string;
1250
+ /** True if only local logout was performed (IdP doesn't support RP-Initiated Logout) */
1251
+ localOnly: boolean;
1252
+ /** Token revocation result (if revokeTokens was true) */
1253
+ revocation?: {
1254
+ /** Whether revocation was attempted */
1255
+ attempted: boolean;
1256
+ /** Whether access token revocation succeeded */
1257
+ accessTokenRevoked?: boolean;
1258
+ /** Whether refresh token revocation succeeded */
1259
+ refreshTokenRevoked?: boolean;
1260
+ /** Error if revocation failed (logout still proceeds) */
1261
+ error?: Error;
1262
+ };
1263
+ }
1264
+ /**
1265
+ * Logout handler options
1266
+ */
1267
+ interface LogoutHandlerOptions {
1268
+ /** Storage provider */
1269
+ storage: AuthrimStorage;
1270
+ /** HTTP client (for token revocation) */
1271
+ http: HttpClient;
1272
+ /** Client ID */
1273
+ clientId: string;
1274
+ /** Issuer hash for storage keys */
1275
+ issuerHash: string;
1276
+ /** Client ID hash for storage keys */
1277
+ clientIdHash: string;
1278
+ /** Event emitter */
1279
+ eventEmitter?: EventEmitter;
1280
+ /** Endpoint overrides */
1281
+ endpoints?: EndpointOverrides;
1282
+ }
1283
+ /**
1284
+ * Logout Handler
1285
+ */
1286
+ declare class LogoutHandler {
1287
+ private readonly storage;
1288
+ private readonly clientId;
1289
+ private readonly issuerHash;
1290
+ private readonly clientIdHash;
1291
+ private readonly eventEmitter?;
1292
+ private readonly endpoints?;
1293
+ private readonly tokenRevoker;
1294
+ constructor(options: LogoutHandlerOptions);
1295
+ /**
1296
+ * Perform logout
1297
+ *
1298
+ * 1. Optionally revokes tokens at the authorization server (if revokeTokens=true)
1299
+ * 2. Clears local tokens (always)
1300
+ * 3. Emits session:ended event
1301
+ * 4. Builds logout URL if IdP supports end_session_endpoint
1302
+ *
1303
+ * @param discovery - OIDC discovery document
1304
+ * @param options - Logout options
1305
+ * @returns Logout result
1306
+ */
1307
+ logout(discovery: OIDCDiscoveryDocument | null, options?: LogoutOptions): Promise<LogoutResult>;
1308
+ /**
1309
+ * Revoke tokens at the authorization server
1310
+ *
1311
+ * Best-effort: if revocation fails, logout still proceeds
1312
+ *
1313
+ * @param discovery - OIDC discovery document
1314
+ * @param tokens - Tokens to revoke
1315
+ * @returns Revocation result
1316
+ */
1317
+ private revokeTokens;
1318
+ /**
1319
+ * Clear all tokens from storage
1320
+ */
1321
+ private clearTokens;
1322
+ /**
1323
+ * Get stored ID token
1324
+ */
1325
+ private getStoredIdToken;
1326
+ /**
1327
+ * Get stored tokens
1328
+ */
1329
+ private getStoredTokens;
1330
+ }
1331
+
1332
+ /**
1333
+ * Authrim Client
1334
+ */
1335
+ declare class AuthrimClient {
1336
+ /** Resolved configuration */
1337
+ private readonly config;
1338
+ /** Event emitter */
1339
+ private readonly events;
1340
+ /** Discovery client */
1341
+ private readonly discoveryClient;
1342
+ /** PKCE helper */
1343
+ private readonly pkce;
1344
+ /** State manager (initialized in initialize()) */
1345
+ private stateManager;
1346
+ /** Authorization code flow helper */
1347
+ private readonly authCodeFlow;
1348
+ /** Token manager (initialized in initialize()) */
1349
+ private tokenManager;
1350
+ /** Logout handler (initialized in initialize()) */
1351
+ private logoutHandler;
1352
+ /** Session manager (initialized in initialize()) */
1353
+ private sessionManager;
1354
+ /** Token introspector */
1355
+ private tokenIntrospector;
1356
+ /** Token revoker */
1357
+ private tokenRevoker;
1358
+ /** Issuer hash for storage keys */
1359
+ private issuerHash;
1360
+ /** Client ID hash for storage keys */
1361
+ private clientIdHash;
1362
+ /** Normalized issuer URL */
1363
+ private readonly normalizedIssuer;
1364
+ /** Whether the client has been initialized */
1365
+ private initialized;
1366
+ /**
1367
+ * Create a new Authrim client
1368
+ *
1369
+ * @internal Use createAuthrimClient() instead
1370
+ */
1371
+ constructor(config: AuthrimClientConfig);
1372
+ /**
1373
+ * Initialize the client
1374
+ *
1375
+ * @internal Called by createAuthrimClient()
1376
+ */
1377
+ initialize(): Promise<void>;
1378
+ /**
1379
+ * Ensure client is initialized
1380
+ */
1381
+ private ensureInitialized;
1382
+ /**
1383
+ * Get OIDC discovery document
1384
+ *
1385
+ * @returns Discovery document
1386
+ */
1387
+ discover(): Promise<OIDCDiscoveryDocument>;
1388
+ /**
1389
+ * Build authorization URL
1390
+ *
1391
+ * Generates the URL to redirect the user to for authentication.
1392
+ * Stores state, nonce, and code_verifier in storage.
1393
+ *
1394
+ * @param options - Authorization options
1395
+ * @returns Authorization URL result
1396
+ */
1397
+ buildAuthorizationUrl(options: BuildAuthorizationUrlOptions): Promise<AuthorizationUrlResult>;
1398
+ /**
1399
+ * Handle authorization callback
1400
+ *
1401
+ * Processes the callback URL, validates state/nonce, and exchanges
1402
+ * the authorization code for tokens.
1403
+ *
1404
+ * @param callbackUrl - Callback URL or query string
1405
+ * @returns Token set
1406
+ */
1407
+ handleCallback(callbackUrl: string): Promise<TokenSet>;
1408
+ /**
1409
+ * Token API accessor
1410
+ */
1411
+ get token(): {
1412
+ /**
1413
+ * Get access token (refreshes if needed)
1414
+ */
1415
+ getAccessToken: () => Promise<string>;
1416
+ /**
1417
+ * Get current tokens
1418
+ */
1419
+ getTokens: () => Promise<TokenSet | null>;
1420
+ /**
1421
+ * Get ID token
1422
+ */
1423
+ getIdToken: () => Promise<string | null>;
1424
+ /**
1425
+ * Check if authenticated
1426
+ */
1427
+ isAuthenticated: () => Promise<boolean>;
1428
+ /**
1429
+ * Exchange token (RFC 8693)
1430
+ *
1431
+ * Exchanges a token for a new token with different audience, scope,
1432
+ * or delegation. Useful for:
1433
+ * - Cross-service token acquisition
1434
+ * - Delegation (actor token)
1435
+ * - Scope reduction
1436
+ *
1437
+ * @param request - Token exchange request parameters
1438
+ * @returns Token exchange result
1439
+ */
1440
+ exchange: (request: TokenExchangeRequest) => Promise<TokenExchangeResult>;
1441
+ /**
1442
+ * Introspect a token (RFC 7662)
1443
+ *
1444
+ * Validates a token server-side and returns its metadata.
1445
+ * Useful for resource servers to validate access tokens.
1446
+ *
1447
+ * @param options - Introspection options (token and optional type hint)
1448
+ * @returns Introspection response with token metadata
1449
+ * @throws AuthrimError if introspection endpoint not available or request fails
1450
+ */
1451
+ introspect: (options: IntrospectTokenOptions) => Promise<IntrospectionResponse>;
1452
+ /**
1453
+ * Revoke a token (RFC 7009)
1454
+ *
1455
+ * Explicitly invalidates a token at the authorization server.
1456
+ * Use this when you want to ensure a token can no longer be used.
1457
+ *
1458
+ * @param options - Revocation options (token and optional type hint)
1459
+ * @throws AuthrimError if revocation endpoint not available or request fails
1460
+ */
1461
+ revoke: (options: RevokeTokenOptions) => Promise<void>;
1462
+ };
1463
+ /**
1464
+ * Session API accessor
1465
+ */
1466
+ get session(): {
1467
+ /**
1468
+ * Check if authenticated locally
1469
+ */
1470
+ isAuthenticated: () => Promise<boolean>;
1471
+ /**
1472
+ * Check session with authorization server
1473
+ */
1474
+ check: () => Promise<SessionCheckResult>;
1475
+ };
1476
+ /**
1477
+ * Check if user is authenticated
1478
+ *
1479
+ * @returns True if tokens exist
1480
+ */
1481
+ isAuthenticated(): Promise<boolean>;
1482
+ /**
1483
+ * Get user information
1484
+ *
1485
+ * @returns User info
1486
+ */
1487
+ getUser(): Promise<UserInfo>;
1488
+ /**
1489
+ * Log out the user
1490
+ *
1491
+ * Clears local tokens and optionally redirects to IdP for logout.
1492
+ *
1493
+ * @param options - Logout options
1494
+ * @returns Logout result
1495
+ */
1496
+ logout(options?: LogoutOptions): Promise<LogoutResult>;
1497
+ /**
1498
+ * Subscribe to an event
1499
+ *
1500
+ * @param event - Event name
1501
+ * @param handler - Event handler
1502
+ * @returns Unsubscribe function
1503
+ */
1504
+ on<T extends AuthrimEventName>(event: T, handler: AuthrimEventHandler<T>): () => void;
1505
+ /**
1506
+ * Subscribe to an event (one-time)
1507
+ *
1508
+ * @param event - Event name
1509
+ * @param handler - Event handler
1510
+ * @returns Unsubscribe function
1511
+ */
1512
+ once<T extends AuthrimEventName>(event: T, handler: AuthrimEventHandler<T>): () => void;
1513
+ /**
1514
+ * Unsubscribe from an event
1515
+ *
1516
+ * @param event - Event name
1517
+ * @param handler - Event handler
1518
+ */
1519
+ off<T extends AuthrimEventName>(event: T, handler: AuthrimEventHandler<T>): void;
1520
+ }
1521
+ /**
1522
+ * Create an Authrim client
1523
+ *
1524
+ * This is the main entry point for creating a client.
1525
+ * The client is fully initialized when returned.
1526
+ *
1527
+ * @param config - Client configuration
1528
+ * @returns Initialized Authrim client
1529
+ */
1530
+ declare function createAuthrimClient(config: AuthrimClientConfig): Promise<AuthrimClient>;
1531
+
1532
+ /**
1533
+ * OIDC Discovery Client
1534
+ *
1535
+ * Fetches and caches OIDC Discovery documents from the authorization server.
1536
+ * https://openid.net/specs/openid-connect-discovery-1_0.html
1537
+ */
1538
+
1539
+ /**
1540
+ * Discovery client options
1541
+ */
1542
+ interface DiscoveryClientOptions {
1543
+ /** HTTP client for making requests */
1544
+ http: HttpClient;
1545
+ /** Cache TTL in milliseconds (default: 1 hour) */
1546
+ cacheTtlMs?: number;
1547
+ }
1548
+ /**
1549
+ * Normalize issuer URL
1550
+ *
1551
+ * Removes trailing slashes to ensure consistent comparison.
1552
+ *
1553
+ * @param issuer - Issuer URL
1554
+ * @returns Normalized issuer URL
1555
+ */
1556
+ declare function normalizeIssuer(issuer: string): string;
1557
+ /**
1558
+ * OIDC Discovery Client
1559
+ */
1560
+ declare class DiscoveryClient {
1561
+ private readonly http;
1562
+ private readonly cacheTtlMs;
1563
+ private readonly cache;
1564
+ /** Default cache TTL: 1 hour */
1565
+ private static readonly DEFAULT_CACHE_TTL_MS;
1566
+ constructor(options: DiscoveryClientOptions);
1567
+ /**
1568
+ * Fetch the OIDC Discovery document for an issuer
1569
+ *
1570
+ * @param issuer - Issuer URL
1571
+ * @returns Discovery document
1572
+ * @throws AuthrimError if discovery fails or issuer mismatch
1573
+ */
1574
+ discover(issuer: string): Promise<OIDCDiscoveryDocument>;
1575
+ /**
1576
+ * Check if a cached document has expired
1577
+ */
1578
+ private isExpired;
1579
+ /**
1580
+ * Clear the discovery cache (useful for testing)
1581
+ */
1582
+ clearCache(): void;
1583
+ /**
1584
+ * Clear a specific issuer from the cache
1585
+ *
1586
+ * @param issuer - Issuer URL to clear
1587
+ */
1588
+ clearIssuer(issuer: string): void;
1589
+ }
1590
+
1591
+ /**
1592
+ * Silent Authentication (prompt=none)
1593
+ *
1594
+ * Foundation for silent authentication using OIDC prompt=none.
1595
+ * This module provides the core logic for building silent auth requests
1596
+ * and parsing responses. The actual iframe/hidden frame implementation
1597
+ * is platform-specific and should be implemented in @authrim/web or similar.
1598
+ *
1599
+ * Silent authentication allows checking if a user has an active session
1600
+ * with the authorization server without user interaction.
1601
+ */
1602
+
1603
+ /**
1604
+ * Silent authentication options
1605
+ */
1606
+ interface SilentAuthOptions {
1607
+ /** Redirect URI for silent auth response (often an iframe callback page) */
1608
+ redirectUri: string;
1609
+ /** Scopes to request (default: 'openid') */
1610
+ scope?: string;
1611
+ /** Hint about the login identifier */
1612
+ loginHint?: string;
1613
+ /** ID token hint (helps IdP identify the user) */
1614
+ idTokenHint?: string;
1615
+ /** Additional custom parameters */
1616
+ extraParams?: Record<string, string>;
1617
+ /**
1618
+ * Expose state/nonce in result (for SSR/external storage)
1619
+ *
1620
+ * Default: false (security: state/nonce stay internal)
1621
+ */
1622
+ exposeState?: boolean;
1623
+ }
1624
+ /**
1625
+ * Result of building silent auth URL
1626
+ */
1627
+ interface SilentAuthUrlResult {
1628
+ /** Authorization URL with prompt=none */
1629
+ url: string;
1630
+ /** State parameter (only if exposeState: true) */
1631
+ state?: string;
1632
+ /** Nonce parameter (only if exposeState: true) */
1633
+ nonce?: string;
1634
+ }
1635
+ /**
1636
+ * Silent authentication result
1637
+ */
1638
+ interface SilentAuthResult {
1639
+ /** Whether silent auth succeeded */
1640
+ success: boolean;
1641
+ /** Tokens if successful */
1642
+ tokens?: TokenSet;
1643
+ /** Error if failed (e.g., login_required) */
1644
+ error?: AuthrimError;
1645
+ }
1646
+ /**
1647
+ * Silent Authentication Handler
1648
+ *
1649
+ * Provides core logic for silent authentication. Platform-specific
1650
+ * implementations (iframe, hidden frame, etc.) should use this class.
1651
+ */
1652
+ declare class SilentAuthHandler {
1653
+ private readonly clientId;
1654
+ constructor(clientId: string);
1655
+ /**
1656
+ * Build silent authentication URL
1657
+ *
1658
+ * Creates an authorization URL with prompt=none for silent authentication.
1659
+ *
1660
+ * @param discovery - OIDC discovery document
1661
+ * @param authState - Auth state from StateManager
1662
+ * @param pkce - PKCE pair
1663
+ * @param options - Silent auth options
1664
+ * @returns Silent auth URL result
1665
+ */
1666
+ buildSilentAuthUrl(discovery: OIDCDiscoveryDocument, authState: AuthState, pkce: PKCEPair, options: SilentAuthOptions): SilentAuthUrlResult;
1667
+ /**
1668
+ * Parse silent authentication response URL
1669
+ *
1670
+ * Parses the callback URL from silent authentication and returns
1671
+ * either the authorization code (for token exchange) or an error.
1672
+ *
1673
+ * @param responseUrl - Response URL from silent auth (iframe callback)
1674
+ * @returns Parsed result with code/state or error
1675
+ */
1676
+ parseSilentAuthResponse(responseUrl: string): {
1677
+ success: true;
1678
+ code: string;
1679
+ state: string;
1680
+ } | {
1681
+ success: false;
1682
+ error: AuthrimError;
1683
+ };
1684
+ /**
1685
+ * Check if an error indicates interactive login is required
1686
+ *
1687
+ * @param error - Error to check
1688
+ * @returns True if interactive login is needed
1689
+ */
1690
+ isInteractiveLoginRequired(error: AuthrimError): boolean;
1691
+ /**
1692
+ * Map OAuth error to AuthrimErrorCode
1693
+ */
1694
+ private mapSilentAuthError;
1695
+ /**
1696
+ * Get default error message for silent auth errors
1697
+ */
1698
+ private getDefaultErrorMessage;
1699
+ }
1700
+
1701
+ /**
1702
+ * Token Manager
1703
+ *
1704
+ * Manages token storage, retrieval, and automatic refresh.
1705
+ * Implements in-flight request coalescing for concurrent refresh requests.
1706
+ */
1707
+
1708
+ /**
1709
+ * Token manager options
1710
+ */
1711
+ interface TokenManagerOptions {
1712
+ /** HTTP client */
1713
+ http: HttpClient;
1714
+ /** Storage provider */
1715
+ storage: AuthrimStorage;
1716
+ /** Client ID */
1717
+ clientId: string;
1718
+ /** Issuer hash for storage keys */
1719
+ issuerHash: string;
1720
+ /** Client ID hash for storage keys */
1721
+ clientIdHash: string;
1722
+ /** Refresh skew in seconds (default: 30) */
1723
+ refreshSkewSeconds?: number;
1724
+ /** Event emitter for token events */
1725
+ eventEmitter?: EventEmitter;
1726
+ }
1727
+ /**
1728
+ * Token Manager
1729
+ *
1730
+ * Handles token storage, retrieval, and automatic refresh with
1731
+ * concurrent request coalescing.
1732
+ */
1733
+ declare class TokenManager {
1734
+ private readonly http;
1735
+ private readonly storage;
1736
+ private readonly clientId;
1737
+ private readonly issuerHash;
1738
+ private readonly clientIdHash;
1739
+ private readonly refreshSkewSeconds;
1740
+ private readonly eventEmitter?;
1741
+ /** In-flight refresh promise for request coalescing */
1742
+ private refreshPromise;
1743
+ /** Discovery document (set externally) */
1744
+ private discovery;
1745
+ /** Default refresh skew: 30 seconds */
1746
+ private static readonly DEFAULT_REFRESH_SKEW_SECONDS;
1747
+ constructor(options: TokenManagerOptions);
1748
+ /**
1749
+ * Set discovery document
1750
+ */
1751
+ setDiscovery(discovery: OIDCDiscoveryDocument): void;
1752
+ /**
1753
+ * Get storage key for tokens
1754
+ */
1755
+ private get tokenKey();
1756
+ /**
1757
+ * Get storage key for ID token
1758
+ */
1759
+ private get idTokenKey();
1760
+ /**
1761
+ * Get current tokens from storage
1762
+ *
1763
+ * @returns Token set or null if not found
1764
+ */
1765
+ getTokens(): Promise<TokenSet | null>;
1766
+ /**
1767
+ * Save tokens to storage
1768
+ *
1769
+ * @param tokens - Token set to save
1770
+ */
1771
+ saveTokens(tokens: TokenSet): Promise<void>;
1772
+ /**
1773
+ * Clear all tokens from storage
1774
+ */
1775
+ clearTokens(): Promise<void>;
1776
+ /**
1777
+ * Get access token, refreshing if necessary
1778
+ *
1779
+ * This method coalesces concurrent refresh requests - if multiple
1780
+ * calls are made while a refresh is in-flight, they all share the
1781
+ * same refresh operation.
1782
+ *
1783
+ * @returns Access token
1784
+ * @throws AuthrimError if no tokens available or refresh fails
1785
+ */
1786
+ getAccessToken(): Promise<string>;
1787
+ /**
1788
+ * Get ID token
1789
+ *
1790
+ * @returns ID token or null
1791
+ */
1792
+ getIdToken(): Promise<string | null>;
1793
+ /**
1794
+ * Check if token needs refresh
1795
+ *
1796
+ * @param tokens - Token set to check
1797
+ * @returns True if token should be refreshed
1798
+ */
1799
+ private shouldRefresh;
1800
+ /**
1801
+ * Refresh token with in-flight request coalescing
1802
+ *
1803
+ * If a refresh is already in progress, wait for it instead of
1804
+ * starting a new one.
1805
+ *
1806
+ * @param refreshToken - Refresh token to use
1807
+ * @returns Access token from new token set
1808
+ */
1809
+ private refreshWithLock;
1810
+ /**
1811
+ * Perform refresh with single retry for network errors
1812
+ *
1813
+ * @param refreshToken - Refresh token to use
1814
+ * @param attemptedRetry - Whether retry has been attempted (stack-local)
1815
+ * @returns New token set
1816
+ */
1817
+ private doRefreshWithRetry;
1818
+ /**
1819
+ * Perform the actual token refresh
1820
+ *
1821
+ * @param refreshToken - Refresh token to use
1822
+ * @returns New token set
1823
+ */
1824
+ private doRefresh;
1825
+ /**
1826
+ * Check if error is retryable (network errors only)
1827
+ */
1828
+ private isRetryableError;
1829
+ /**
1830
+ * Check if user is authenticated
1831
+ *
1832
+ * @returns True if valid tokens exist
1833
+ */
1834
+ isAuthenticated(): Promise<boolean>;
1835
+ /**
1836
+ * Exchange a token using RFC 8693 Token Exchange
1837
+ *
1838
+ * This allows exchanging tokens for different audiences or scopes,
1839
+ * delegation scenarios, and cross-service token acquisition.
1840
+ *
1841
+ * @param request - Token exchange request parameters
1842
+ * @returns Token exchange result with new tokens and issued token type
1843
+ * @throws AuthrimError if exchange fails
1844
+ */
1845
+ exchangeToken(request: TokenExchangeRequest): Promise<TokenExchangeResult>;
1846
+ /**
1847
+ * Map short token type to URI (RFC 8693)
1848
+ */
1849
+ private mapTokenTypeToUri;
1850
+ }
1851
+
1852
+ /**
1853
+ * Token API Client
1854
+ *
1855
+ * Provides session verification against the authorization server.
1856
+ * Uses the UserInfo endpoint or custom session check endpoint.
1857
+ */
1858
+
1859
+ /**
1860
+ * Session check result
1861
+ */
1862
+ interface SessionCheckResult {
1863
+ /** Whether session is valid */
1864
+ valid: boolean;
1865
+ /** User info if session is valid */
1866
+ user?: UserInfo;
1867
+ /** Error if session is invalid */
1868
+ error?: AuthrimError;
1869
+ }
1870
+ /**
1871
+ * Token API client options
1872
+ */
1873
+ interface TokenApiClientOptions {
1874
+ /** HTTP client */
1875
+ http: HttpClient;
1876
+ }
1877
+ /**
1878
+ * Token API Client
1879
+ *
1880
+ * Verifies session status with the authorization server.
1881
+ */
1882
+ declare class TokenApiClient {
1883
+ private readonly http;
1884
+ constructor(options: TokenApiClientOptions);
1885
+ /**
1886
+ * Check session validity by calling UserInfo endpoint
1887
+ *
1888
+ * @param discovery - OIDC discovery document
1889
+ * @param accessToken - Access token to verify
1890
+ * @returns Session check result
1891
+ */
1892
+ checkSession(discovery: OIDCDiscoveryDocument, accessToken: string): Promise<SessionCheckResult>;
1893
+ /**
1894
+ * Get user info from the authorization server
1895
+ *
1896
+ * @param discovery - OIDC discovery document
1897
+ * @param accessToken - Access token
1898
+ * @returns User info
1899
+ * @throws AuthrimError if request fails
1900
+ */
1901
+ getUserInfo(discovery: OIDCDiscoveryDocument, accessToken: string): Promise<UserInfo>;
1902
+ }
1903
+
1904
+ /**
1905
+ * Session Manager
1906
+ *
1907
+ * Coordinates session-related operations including checking
1908
+ * session status and retrieving user information.
1909
+ */
1910
+
1911
+ /**
1912
+ * Session manager options
1913
+ */
1914
+ interface SessionManagerOptions {
1915
+ /** Token manager */
1916
+ tokenManager: TokenManager;
1917
+ /** Token API client */
1918
+ tokenApiClient: TokenApiClient;
1919
+ }
1920
+ /**
1921
+ * Session Manager
1922
+ */
1923
+ declare class SessionManager {
1924
+ private readonly tokenManager;
1925
+ private readonly tokenApiClient;
1926
+ /** Discovery document */
1927
+ private discovery;
1928
+ constructor(options: SessionManagerOptions);
1929
+ /**
1930
+ * Set discovery document
1931
+ */
1932
+ setDiscovery(discovery: OIDCDiscoveryDocument): void;
1933
+ /**
1934
+ * Check if user is authenticated locally
1935
+ *
1936
+ * This checks if valid tokens exist in storage.
1937
+ * Does not verify with the authorization server.
1938
+ *
1939
+ * @returns True if tokens exist
1940
+ */
1941
+ isAuthenticated(): Promise<boolean>;
1942
+ /**
1943
+ * Check session validity with authorization server
1944
+ *
1945
+ * Calls the UserInfo endpoint to verify the session is still valid.
1946
+ *
1947
+ * @returns Session check result
1948
+ */
1949
+ checkSession(): Promise<SessionCheckResult>;
1950
+ /**
1951
+ * Get user information
1952
+ *
1953
+ * Fetches user info from the UserInfo endpoint.
1954
+ *
1955
+ * @returns User info
1956
+ * @throws AuthrimError if not authenticated or request fails
1957
+ */
1958
+ getUser(): Promise<UserInfo>;
1959
+ }
1960
+
1961
+ /**
1962
+ * Base64URL Encoding/Decoding Utilities
1963
+ *
1964
+ * Implements RFC 4648 Section 5 (Base64 URL and Filename Safe Alphabet)
1965
+ */
1966
+ /**
1967
+ * Encode a Uint8Array to base64url string
1968
+ *
1969
+ * @param data - Bytes to encode
1970
+ * @returns Base64URL encoded string (no padding)
1971
+ */
1972
+ declare function base64urlEncode(data: Uint8Array): string;
1973
+ /**
1974
+ * Decode a base64url string to Uint8Array
1975
+ *
1976
+ * @param str - Base64URL encoded string
1977
+ * @returns Decoded bytes
1978
+ */
1979
+ declare function base64urlDecode(str: string): Uint8Array;
1980
+ /**
1981
+ * Encode a string to base64url
1982
+ *
1983
+ * @param str - String to encode (UTF-8)
1984
+ * @returns Base64URL encoded string
1985
+ */
1986
+ declare function stringToBase64url(str: string): string;
1987
+ /**
1988
+ * Decode a base64url string to string
1989
+ *
1990
+ * @param base64url - Base64URL encoded string
1991
+ * @returns Decoded string (UTF-8)
1992
+ */
1993
+ declare function base64urlToString(base64url: string): string;
1994
+
1995
+ /**
1996
+ * JWT Utilities
1997
+ *
1998
+ * Note: This module only provides decoding (parsing) functionality.
1999
+ * JWT signature verification MUST be performed by the server.
2000
+ * Never trust decoded JWT claims without server-side verification.
2001
+ */
2002
+
2003
+ /**
2004
+ * JWT Header
2005
+ */
2006
+ interface JwtHeader {
2007
+ alg: string;
2008
+ typ?: string;
2009
+ kid?: string;
2010
+ [key: string]: unknown;
2011
+ }
2012
+ /**
2013
+ * Decoded JWT structure
2014
+ */
2015
+ interface DecodedJwt<T = Record<string, unknown>> {
2016
+ header: JwtHeader;
2017
+ payload: T;
2018
+ signature: string;
2019
+ }
2020
+ /**
2021
+ * Decode a JWT without verifying the signature
2022
+ *
2023
+ * WARNING: This function does NOT verify the JWT signature.
2024
+ * Use this only for reading claims after the token has been
2025
+ * validated by the authorization server.
2026
+ *
2027
+ * @param jwt - JWT string to decode
2028
+ * @returns Decoded JWT parts
2029
+ * @throws Error if the JWT format is invalid
2030
+ */
2031
+ declare function decodeJwt<T = Record<string, unknown>>(jwt: string): DecodedJwt<T>;
2032
+ /**
2033
+ * Decode an ID token and extract claims
2034
+ *
2035
+ * WARNING: This function does NOT verify the ID token.
2036
+ * The token MUST be verified by the authorization server before use.
2037
+ *
2038
+ * @param idToken - ID token string
2039
+ * @returns ID token claims
2040
+ */
2041
+ declare function decodeIdToken(idToken: string): IdTokenClaims;
2042
+ /**
2043
+ * Check if a JWT is expired
2044
+ *
2045
+ * @param jwt - Decoded JWT payload with exp claim
2046
+ * @param skewSeconds - Clock skew tolerance in seconds (default: 0)
2047
+ * @returns true if expired
2048
+ */
2049
+ declare function isJwtExpired(payload: {
2050
+ exp?: number;
2051
+ }, skewSeconds?: number): boolean;
2052
+ /**
2053
+ * Get the nonce claim from an ID token
2054
+ *
2055
+ * @param idToken - ID token string
2056
+ * @returns nonce value or undefined
2057
+ */
2058
+ declare function getIdTokenNonce(idToken: string): string | undefined;
2059
+
2060
+ /**
2061
+ * Hash Utilities
2062
+ *
2063
+ * Provides hash calculation utilities for OIDC specifications.
2064
+ */
2065
+
2066
+ /**
2067
+ * Calculate ds_hash for Native SSO device_secret verification
2068
+ *
2069
+ * Algorithm: BASE64URL(left half of SHA-256(device_secret))
2070
+ * Reference: OIDC Native SSO 1.0 specification
2071
+ *
2072
+ * This is the same algorithm used for at_hash and c_hash in OIDC Core,
2073
+ * applied to the device_secret value.
2074
+ *
2075
+ * @param deviceSecret - The device_secret value to hash
2076
+ * @param crypto - Platform-specific crypto provider
2077
+ * @returns ds_hash value (BASE64URL encoded)
2078
+ *
2079
+ * @example
2080
+ * ```typescript
2081
+ * const dsHash = await calculateDsHash(deviceSecret, cryptoProvider);
2082
+ * // Compare with id_token.ds_hash claim
2083
+ * if (idToken.ds_hash === dsHash) {
2084
+ * // device_secret is valid
2085
+ * }
2086
+ * ```
2087
+ */
2088
+ declare function calculateDsHash(deviceSecret: string, crypto: CryptoProvider): Promise<string>;
2089
+
2090
+ export { type AddressClaim, type AuthCallbackEvent, type AuthRedirectingEvent, type AuthState, AuthorizationCodeFlow, type AuthorizationContext, type AuthorizationUrlResult, AuthrimClient, type AuthrimClientConfig, AuthrimError, type AuthrimErrorCode, type AuthrimErrorMeta, type AuthrimErrorOptions, type AuthrimErrorSeverity, type AuthrimErrorUserAction, type AuthrimEventHandler, type AuthrimEventName, type AuthrimEvents, type AuthrimStorage, type BuildAuthorizationUrlOptions, type CodeChallengeMethod, type CryptoProvider, type DecodedJwt, DiscoveryClient, type EndpointOverrides, type ErrorEvent, EventEmitter, type ExchangeCodeOptions, type GenerateAuthStateOptions, type HashOptions, type HttpClient, type HttpOptions, type HttpResponse, type IntrospectTokenOptions, type IntrospectionResponse, type IntrospectionTokenTypeHint, type JwtHeader, LogoutHandler, type LogoutHandlerOptions, type LogoutOptions, type LogoutResult, type OIDCDiscoveryDocument, PKCEHelper, type PKCEPair, type ResolvedConfig, type RevokeTokenOptions, STORAGE_KEYS, type SessionCheckResult, type SessionEndedEvent, SessionManager, type SessionManagerOptions, type SessionStartedEvent, SilentAuthHandler, type SilentAuthOptions, type SilentAuthResult, type SilentAuthUrlResult, type StandardClaims, StateManager, TOKEN_TYPE_URIS, TokenApiClient, type TokenApiClientOptions, type TokenErrorEvent, type TokenExchangeRequest, type TokenExchangeResponse, type TokenExchangeResult, type TokenExchangedEvent, type TokenExpiredEvent, TokenIntrospector, type TokenIntrospectorOptions, TokenManager, type TokenManagerOptions, type TokenRefreshedEvent, type TokenResponse, TokenRevoker, type TokenRevokerOptions, type TokenSet, type TokenTypeHint, type TokenTypeUri, type UserInfo, base64urlDecode, base64urlEncode, base64urlToString, calculateDsHash, createAuthrimClient, decodeIdToken, decodeJwt, getErrorMeta, getIdTokenNonce, isJwtExpired, normalizeIssuer, resolveConfig, stringToBase64url };