@opensourcekd/ng-common-libs 2.0.10 → 2.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.
package/dist/index.d.ts CHANGED
@@ -413,6 +413,7 @@ declare function buildUserData(userInfo: UserInfo): UserData;
413
413
  declare class AuthService {
414
414
  private auth0Client;
415
415
  private initializationPromise;
416
+ /** Remains false if callback processing fails, allowing the callback to be retried. */
416
417
  private callbackHandled;
417
418
  private callbackPromise;
418
419
  private userSubject;
@@ -447,6 +448,13 @@ declare class AuthService {
447
448
  * @throws {Error} When required config fields (domain, clientId) are missing
448
449
  */
449
450
  private initializeAuth0;
451
+ /**
452
+ * Ensure the Auth0 client instance is created, without triggering callback detection.
453
+ * Used internally by {@link handleCallback} to avoid a circular async dependency:
454
+ * `ensureInitialized` → `checkAndHandleCallback` → `handleCallback` → `ensureInitialized`.
455
+ * @throws {Error} When the Auth0 client fails to initialize
456
+ */
457
+ private ensureAuth0Client;
450
458
  /**
451
459
  * Ensure the Auth0 client is initialized before use
452
460
  * Lazy-initializes on the first call and auto-handles OAuth callbacks when detected
@@ -459,6 +467,10 @@ declare class AuthService {
459
467
  * The Auth0 SDK's `handleRedirectCallback` validates the `state` parameter
460
468
  * to prevent CSRF attacks. This method only detects presence of callback
461
469
  * params before delegating securely to the SDK.
470
+ *
471
+ * Uses an async IIFE to store the in-flight promise for concurrency deduplication
472
+ * (concurrent callers await the same promise) while still using async/await
473
+ * internally instead of `.then()/.catch()` chains.
462
474
  */
463
475
  private checkAndHandleCallback;
464
476
  /**
@@ -474,11 +486,20 @@ declare class AuthService {
474
486
  /**
475
487
  * Handle the OAuth2 redirect callback after successful authorization
476
488
  * Stores the user info and access token, then cleans up the callback URL
489
+ *
490
+ * Uses {@link ensureAuth0Client} (not {@link ensureInitialized}) to avoid a circular
491
+ * async dependency: `ensureInitialized` → `checkAndHandleCallback` → `handleCallback`
492
+ * → `ensureInitialized`. Only the Auth0 client instance is needed here.
477
493
  * @returns {@link CallbackResult} with `success` flag and optional `appState`
478
494
  */
479
495
  handleCallback(): Promise<CallbackResult>;
480
496
  /**
481
497
  * Log the user out, clear all stored auth data, and redirect to the logout URI
498
+ *
499
+ * Uses {@link ensureAuth0Client} (not {@link ensureInitialized}) to avoid triggering
500
+ * callback detection during logout. Calling `ensureInitialized` here would invoke
501
+ * `checkAndHandleCallback`, which re-authenticates the user if callback URL params
502
+ * are present, causing them to be sent back to Auth0 instead of the logout URI.
482
503
  */
483
504
  logout(): Promise<void>;
484
505
  /**
@@ -773,5 +794,197 @@ declare class Logger {
773
794
  }): void;
774
795
  }
775
796
 
776
- export { APP_CONFIG, AUTH0_CONFIG, AuthService, EventBus, LogSeverity, Logger, STANDARD_JWT_CLAIMS, STORAGE_CONFIG, STORAGE_KEYS, buildUserData, configureAuth0, createAuthService, decodeAndStoreToken, extractClaimValue, getCustomClaims, getDecodedToken, getStorageItem, isNamespacedClaim, removeStorageItem, resetAuth0Config, setStorageItem };
777
- export type { AppState, Auth0Config, Auth0ConfigOptions, AuthServiceOptions, AuthorizationParams, CallbackResult, EventBusOptions, EventPayload, LogAttributes, LogRecord, LoggerOptions, StorageConfig, StorageKeys, TokenPayload, UserData, UserInfo };
797
+ /**
798
+ * Configuration for a {@link BearerTokenInterceptor} instance.
799
+ *
800
+ * @example
801
+ * ```typescript
802
+ * const config: BearerTokenInterceptorConfig = {
803
+ * apiUrl: 'https://api.example.com',
804
+ * getToken: () => authService.getTokenSync(),
805
+ * };
806
+ * ```
807
+ */
808
+ interface BearerTokenInterceptorConfig {
809
+ /**
810
+ * API base URL to match against — only requests whose URL begins with this
811
+ * string will receive the `Authorization` header.
812
+ * Defaults to {@link APP_CONFIG}.apiUrl when not provided.
813
+ */
814
+ apiUrl?: string;
815
+ /**
816
+ * Synchronous function that returns the current bearer token string,
817
+ * or `null` when no token is available (e.g. before login).
818
+ */
819
+ getToken: () => string | null;
820
+ }
821
+ /**
822
+ * BearerTokenInterceptor
823
+ *
824
+ * A per-identifier singleton that patches the global `window.fetch` to
825
+ * automatically attach an `Authorization: Bearer <token>` header to every
826
+ * request whose URL begins with the configured API base URL.
827
+ *
828
+ * **Singleton behaviour**: the first call to {@link BearerTokenInterceptor.getInstance}
829
+ * for a given `id` creates the instance; subsequent calls with the same `id`
830
+ * return the previously created instance, regardless of the `config` argument.
831
+ *
832
+ * Designed for Module Federation micro-frontend environments where both the
833
+ * fetch wrapper and the XHR prototype must be shared across the shell and all
834
+ * remote applications.
835
+ *
836
+ * @example
837
+ * ```typescript
838
+ * import { BearerTokenInterceptor, APP_CONFIG } from '@opensourcekd/ng-common-libs';
839
+ *
840
+ * // In the shell app — creates the instance
841
+ * const interceptor = BearerTokenInterceptor.getInstance('shell', {
842
+ * apiUrl: APP_CONFIG.apiUrl,
843
+ * getToken: () => authService.getTokenSync(),
844
+ * });
845
+ * interceptor.activate();
846
+ *
847
+ * // In any MFE — same instance is returned
848
+ * const same = BearerTokenInterceptor.getInstance('shell', { getToken: () => null });
849
+ * console.log(same === interceptor); // true
850
+ * ```
851
+ */
852
+ declare class BearerTokenInterceptor {
853
+ private static readonly instances;
854
+ private static originalFetch;
855
+ private static originalXhrOpen;
856
+ private static originalXhrSend;
857
+ private readonly id;
858
+ private readonly apiUrl;
859
+ private readonly tokenFn;
860
+ private active;
861
+ private constructor();
862
+ /**
863
+ * Get or create the singleton interceptor for the given identifier.
864
+ *
865
+ * The first invocation with a given `id` creates the instance using the
866
+ * supplied `config`. Subsequent calls with the same `id` return the existing
867
+ * instance — the `config` argument is ignored on subsequent calls.
868
+ *
869
+ * @param id - Unique identifier for this interceptor (e.g. `'shell'`, `'mfe-orders'`)
870
+ * @param config - Configuration used only when creating a new instance
871
+ * @returns The singleton {@link BearerTokenInterceptor} for the given `id`
872
+ *
873
+ * @example
874
+ * ```typescript
875
+ * const interceptor = BearerTokenInterceptor.getInstance('shell', {
876
+ * apiUrl: 'https://api.example.com',
877
+ * getToken: () => authService.getTokenSync(),
878
+ * });
879
+ * ```
880
+ */
881
+ static getInstance(id: string, config: BearerTokenInterceptorConfig): BearerTokenInterceptor;
882
+ /**
883
+ * Get the identifier of this interceptor instance.
884
+ * @returns The `id` string supplied when the instance was created
885
+ */
886
+ getId(): string;
887
+ /**
888
+ * Get the API base URL that this interceptor matches against.
889
+ * @returns The configured API URL string
890
+ */
891
+ getApiUrl(): string;
892
+ /**
893
+ * Check whether this interceptor is currently active.
894
+ * @returns `true` if the interceptor has been activated and not yet deactivated
895
+ */
896
+ isActive(): boolean;
897
+ /**
898
+ * Activate the interceptor.
899
+ *
900
+ * Patches `window.fetch` and `XMLHttpRequest` once (on the first active
901
+ * interceptor) so that matching requests receive the bearer token.
902
+ * Subsequent calls are no-ops. No-op in non-browser environments.
903
+ */
904
+ activate(): void;
905
+ /**
906
+ * Deactivate the interceptor.
907
+ *
908
+ * Stops attaching the bearer token for this interceptor's URL pattern.
909
+ * Both the global fetch wrapper and the XHR prototype patches are removed
910
+ * automatically once all registered interceptors have been deactivated.
911
+ * No-op when already inactive.
912
+ */
913
+ deactivate(): void;
914
+ /**
915
+ * Return the effective bearer token for a given request URL, or `null` if
916
+ * this interceptor should not modify the request.
917
+ *
918
+ * Returns `null` when the interceptor is inactive, the URL does not begin
919
+ * with the configured API base URL, or the token getter returns `null`.
920
+ *
921
+ * @param url - The absolute URL of the outgoing request
922
+ * @returns Bearer token string or `null`
923
+ */
924
+ private getEffectiveToken;
925
+ /**
926
+ * Extract headers from a `RequestInit` object into a plain key-value map.
927
+ * Handles `Headers` instances, `[key, value]` arrays, and plain objects.
928
+ *
929
+ * @param init - Optional `RequestInit` whose headers to extract
930
+ * @returns A plain `Record<string, string>` copy of the headers
931
+ */
932
+ private static extractHeaders;
933
+ /**
934
+ * Find the bearer token for a given URL by consulting all active interceptors.
935
+ * Uses first-match semantics to avoid ambiguity when multiple interceptors
936
+ * share the same API URL prefix.
937
+ *
938
+ * @param url - Absolute URL of the outgoing request
939
+ * @returns The first matching bearer token string, or `null`
940
+ */
941
+ private static findToken;
942
+ /**
943
+ * Apply the `Authorization: Bearer` header from the first active interceptor
944
+ * that matches the given URL. Uses first-match semantics to avoid ambiguity
945
+ * when multiple interceptors share the same API URL prefix.
946
+ *
947
+ * @param url - Absolute URL of the outgoing fetch request
948
+ * @param init - Original `RequestInit` options
949
+ * @returns Modified `RequestInit` with the `Authorization` header added when applicable
950
+ */
951
+ private static applyBearerToken;
952
+ /**
953
+ * Install the global fetch wrapper exactly once.
954
+ * The wrapper delegates to {@link applyBearerToken} for every outgoing request.
955
+ * No-op when already patched or in a non-browser environment.
956
+ */
957
+ private static patchFetch;
958
+ /**
959
+ * Restore the original `window.fetch` if no interceptors remain active.
960
+ * No-op when the fetch has not been patched or some interceptors are still active.
961
+ */
962
+ private static maybeRestoreFetch;
963
+ /**
964
+ * Install a global `XMLHttpRequest` prototype patch exactly once.
965
+ *
966
+ * Overrides `XMLHttpRequest.prototype.open` to capture the request URL on
967
+ * the XHR instance, and `XMLHttpRequest.prototype.send` to inject the
968
+ * `Authorization: Bearer` header (via `setRequestHeader`) before dispatching
969
+ * the request. Supports Angular's default XHR-based `HttpClient` backend.
970
+ *
971
+ * No-op when already patched or in a non-browser environment.
972
+ */
973
+ private static patchXhr;
974
+ /**
975
+ * Restore `XMLHttpRequest.prototype.open` and `.send` to their original
976
+ * values if no interceptors remain active.
977
+ * No-op when XHR has not been patched or some interceptors are still active.
978
+ */
979
+ private static maybeRestoreXhr;
980
+ /**
981
+ * Remove all registered instances and restore `window.fetch` and
982
+ * `XMLHttpRequest` prototype methods to their original values.
983
+ * Intended for use in test teardown only.
984
+ * @internal
985
+ */
986
+ static _reset(): void;
987
+ }
988
+
989
+ export { APP_CONFIG, AUTH0_CONFIG, AuthService, BearerTokenInterceptor, EventBus, LogSeverity, Logger, STANDARD_JWT_CLAIMS, STORAGE_CONFIG, STORAGE_KEYS, buildUserData, configureAuth0, createAuthService, decodeAndStoreToken, extractClaimValue, getCustomClaims, getDecodedToken, getStorageItem, isNamespacedClaim, removeStorageItem, resetAuth0Config, setStorageItem };
990
+ export type { AppState, Auth0Config, Auth0ConfigOptions, AuthServiceOptions, AuthorizationParams, BearerTokenInterceptorConfig, CallbackResult, EventBusOptions, EventPayload, LogAttributes, LogRecord, LoggerOptions, StorageConfig, StorageKeys, TokenPayload, UserData, UserInfo };