@opensourcekd/ng-common-libs 1.2.2 → 1.2.4

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.
@@ -1,6 +1,7 @@
1
- import { Observable } from 'rxjs';
1
+ import { Observable, ReplaySubject } from 'rxjs';
2
+ import { HttpClient, HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
3
+ import { EventType } from 'mitt';
2
4
  import { CanActivateFn } from '@angular/router';
3
- import { HttpInterceptorFn, HttpErrorResponse } from '@angular/common/http';
4
5
 
5
6
  /**
6
7
  * Event payload interface
@@ -494,6 +495,273 @@ declare class PermissionService {
494
495
  getUserEmail(): string | null;
495
496
  }
496
497
 
498
+ /**
499
+ * EventBusService - Angular service for cross-application event communication
500
+ * Uses mitt library for efficient event handling and RxJS ReplaySubject for observable stream
501
+ *
502
+ * This service is designed for MicroFrontend architectures where different apps need to communicate
503
+ * The ReplaySubject keeps last 100 events in memory for late subscribers
504
+ *
505
+ * @example
506
+ * ```typescript
507
+ * import { Component, inject, OnInit } from '@angular/core';
508
+ * import { EventBusService } from '@opensourcekd/ng-common-libs';
509
+ *
510
+ * @Component({
511
+ * selector: 'app-example',
512
+ * template: '...'
513
+ * })
514
+ * export class ExampleComponent implements OnInit {
515
+ * private eventBus = inject(EventBusService);
516
+ *
517
+ * ngOnInit() {
518
+ * // Subscribe to all events
519
+ * this.eventBus.onePlusNEvents.subscribe(event => {
520
+ * console.log('Event received:', event);
521
+ * });
522
+ * }
523
+ *
524
+ * sendCustomEvent() {
525
+ * // Send a custom event
526
+ * this.eventBus.sendEvent('user:action');
527
+ *
528
+ * // Or send structured event with data
529
+ * this.eventBus.sendEvent(JSON.stringify({
530
+ * type: 'user:login',
531
+ * payload: { userId: '123' },
532
+ * timestamp: new Date().toISOString()
533
+ * }));
534
+ * }
535
+ * }
536
+ * ```
537
+ */
538
+ declare class EventBusService {
539
+ /**
540
+ * ReplaySubject that buffers the last 100 events for late subscribers
541
+ * Subscribe to this observable to receive all events
542
+ */
543
+ onePlusNEvents: ReplaySubject<EventType>;
544
+ /**
545
+ * mitt event emitter instance
546
+ * Lightweight event emitter library
547
+ */
548
+ private emitter;
549
+ constructor();
550
+ /**
551
+ * Send an event through the event bus
552
+ * The event will be forwarded to all subscribers via the ReplaySubject
553
+ *
554
+ * @param s - Event string, can be a simple event name or JSON stringified structured data
555
+ *
556
+ * @example
557
+ * ```typescript
558
+ * // Simple event
559
+ * eventBus.sendEvent('user:logout');
560
+ *
561
+ * // Structured event
562
+ * eventBus.sendEvent(JSON.stringify({
563
+ * type: 'auth:token_updated',
564
+ * payload: { token: 'abc123' },
565
+ * timestamp: new Date().toISOString()
566
+ * }));
567
+ * ```
568
+ */
569
+ sendEvent(s: string): void;
570
+ }
571
+
572
+ /**
573
+ * User information from ID token
574
+ * Standard OIDC claims compatible with Auth0
575
+ */
576
+ interface UserInfo {
577
+ sub: string;
578
+ name?: string;
579
+ email?: string;
580
+ email_verified?: boolean;
581
+ preferred_username?: string;
582
+ given_name?: string;
583
+ family_name?: string;
584
+ nickname?: string;
585
+ locale?: string;
586
+ picture?: string;
587
+ phone?: string;
588
+ phone_verified?: boolean;
589
+ updated_at?: string;
590
+ role?: string;
591
+ org?: string;
592
+ organization?: string;
593
+ [key: string]: any;
594
+ }
595
+ /**
596
+ * Simplified user data extracted from token
597
+ */
598
+ interface UserData {
599
+ id: string;
600
+ name: string;
601
+ email: string;
602
+ role: string;
603
+ org: string;
604
+ }
605
+ /**
606
+ * Authentication service for Auth0 integration
607
+ * Handles login, logout, token management, and user session
608
+ * Uses sessionStorage for sensitive data and emits authentication events for MicroApps
609
+ *
610
+ * Configuration is centralized in config/auth.config.ts for easy management
611
+ *
612
+ * NOTE: All navigation logic using setTimeout is commented out as per requirements.
613
+ * To enable navigation after auth operations, uncomment the marked sections in consuming components.
614
+ */
615
+ declare class AuthService {
616
+ private http;
617
+ private eventBus;
618
+ id: string;
619
+ private readonly STANDARD_JWT_CLAIMS;
620
+ private auth0Client;
621
+ private initializationPromise;
622
+ private userSubject;
623
+ user$: Observable<UserInfo | null>;
624
+ constructor(http: HttpClient, eventBus: EventBusService);
625
+ /**
626
+ * Initialize Auth0 client
627
+ */
628
+ private initializeAuth0;
629
+ /**
630
+ * Ensure Auth0 client is initialized before use
631
+ */
632
+ private ensureInitialized;
633
+ /**
634
+ * Login with Auth0
635
+ * Redirects to Auth0 Universal Login
636
+ * Preserves current URL parameters (like invitation tokens) through the auth flow
637
+ *
638
+ * @param user - Optional user identifier for logging
639
+ * @param options - Optional login options including invitation and organization parameters
640
+ */
641
+ login(user?: string, options?: {
642
+ invitation?: string;
643
+ organization?: string;
644
+ }): Promise<void>;
645
+ /**
646
+ * Handle OAuth2 callback after successful authorization
647
+ * Processes the callback and retrieves user info
648
+ *
649
+ * NOTE: Navigation after successful/failed authentication should be handled in the calling component
650
+ * using setTimeout. See commented examples in app.component.ts
651
+ *
652
+ * @returns Promise<{ success: boolean, appState?: any }> - Success status and preserved appState
653
+ */
654
+ handleCallback(): Promise<{
655
+ success: boolean;
656
+ appState?: any;
657
+ }>;
658
+ /**
659
+ * Log all user claims for debugging
660
+ * @param user - User info from Auth0
661
+ */
662
+ private logUserClaims;
663
+ /**
664
+ * Log standard OIDC claims
665
+ * @param user - User info from Auth0
666
+ */
667
+ private logStandardClaims;
668
+ /**
669
+ * Log claims with consistent formatting
670
+ * @param header - Section header to display
671
+ * @param claims - Array of claim keys to log
672
+ * @param user - User info object
673
+ */
674
+ private logClaims;
675
+ /**
676
+ * Get custom namespaced claims from user info
677
+ * @param user - User info object
678
+ * @returns Array of custom claim keys
679
+ */
680
+ private getCustomClaims;
681
+ /**
682
+ * Get additional non-namespaced claims from user info
683
+ * @param user - User info object
684
+ * @returns Array of additional claim keys
685
+ */
686
+ private getAdditionalClaims;
687
+ /**
688
+ * Check if a claim key is namespaced
689
+ * @param key - Claim key to check
690
+ * @returns True if the key starts with http:// or https://
691
+ */
692
+ private isNamespacedClaim;
693
+ /**
694
+ * Logout user and clear authentication state
695
+ * Redirects to Auth0 logout endpoint and clears local state
696
+ */
697
+ logout(): Promise<void>;
698
+ /**
699
+ * Get current access token from storage or Auth0 client
700
+ * @returns string | null - Access token or null if not authenticated
701
+ */
702
+ getToken(): Promise<string | null>;
703
+ /**
704
+ * Get current access token synchronously from storage only
705
+ * Use this for synchronous operations like interceptors
706
+ * @returns string | null - Access token or null if not authenticated
707
+ */
708
+ getTokenSync(): string | null;
709
+ /**
710
+ * Set access token in storage and emit event for MicroApps
711
+ * @param token - Access token to store
712
+ */
713
+ private setToken;
714
+ /**
715
+ * Check if user is authenticated
716
+ * @returns boolean - True if user has valid token
717
+ */
718
+ isAuthenticated(): Promise<boolean>;
719
+ /**
720
+ * Check if user is authenticated synchronously
721
+ * Only checks storage, doesn't verify with Auth0
722
+ * @returns boolean - True if user has token in storage
723
+ */
724
+ isAuthenticatedSync(): boolean;
725
+ /**
726
+ * Get current user information
727
+ * @returns UserInfo | null - Current user or null if not authenticated
728
+ */
729
+ getUser(): UserInfo | null;
730
+ /**
731
+ * Get simplified user data from token
732
+ * Extracts user details, role, and organization from ID token claims
733
+ * Checks both top-level claims and namespaced custom claims
734
+ * @returns UserData | null - Simplified user data or null if not authenticated
735
+ */
736
+ getUserData(): UserData | null;
737
+ /**
738
+ * Extract claim value from user info, checking both direct properties and namespaced custom claims
739
+ * @param userInfo - User info object
740
+ * @param claimNames - Single claim name or array of claim names to search for
741
+ * @param defaultValue - Default value if claim is not found
742
+ * @returns Extracted claim value or default value
743
+ */
744
+ private extractClaimValue;
745
+ /**
746
+ * Get user information from storage
747
+ * @returns UserInfo | null - Stored user info or null
748
+ */
749
+ private getUserInfoFromStorage;
750
+ /**
751
+ * Set user information in storage, update observable and emit event for MicroApps
752
+ * Logs all Auth0 claims for debugging
753
+ * @param userInfo - User information to store
754
+ */
755
+ private setUserInfo;
756
+ /**
757
+ * Emit authentication event for MicroApps to consume
758
+ * Events are emitted via EventBus for cross-MFE communication
759
+ * @param eventType - Type of authentication event
760
+ * @param payload - Event payload
761
+ */
762
+ private emitAuthEvent;
763
+ }
764
+
497
765
  /**
498
766
  * Auth guard configuration
499
767
  */
@@ -687,5 +955,81 @@ declare function clearCacheEntry(url: string): void;
687
955
  */
688
956
  declare const cachingInterceptor: HttpInterceptorFn;
689
957
 
690
- export { HttpError, LogLevel, LoggerService, NgEventEmitter, PermissionService, StorageService, TokenService, authGuard, authInterceptor, cachingInterceptor, clearCache, clearCacheEntry, configureAuthInterceptor, configureCaching, configureErrorHandling, createAuthGuard, createPermissionGuard, createRoleGuard, errorHandlingInterceptor, isClientError, isNetworkError, isServerError, parseHttpError };
691
- export type { AuthGuardConfig, AuthInterceptorConfig, CacheConfig, ErrorHandlingConfig, LoggerConfig, TokenConfig };
958
+ /**
959
+ * Auth0 Configuration
960
+ * Centralized configuration for Auth0 integration
961
+ *
962
+ * Environment variables are typically set in consuming applications
963
+ * Default values are provided for development/testing
964
+ */
965
+ /**
966
+ * Auth0 client configuration
967
+ * Override these values in your consuming application by setting them before importing AuthService
968
+ */
969
+ declare const AUTH0_CONFIG: {
970
+ domain: string;
971
+ clientId: string;
972
+ redirectUri: string;
973
+ logoutUri: string;
974
+ audience: string;
975
+ scope: string;
976
+ connection: string | undefined;
977
+ };
978
+ /**
979
+ * Storage configuration
980
+ * Controls where sensitive data is stored
981
+ */
982
+ declare const STORAGE_CONFIG: {
983
+ TOKEN_STORAGE: "localStorage" | "sessionStorage";
984
+ USER_INFO_STORAGE: "localStorage" | "sessionStorage";
985
+ };
986
+ /**
987
+ * Storage keys for auth data
988
+ */
989
+ declare const STORAGE_KEYS: {
990
+ ACCESS_TOKEN: string;
991
+ USER_INFO: string;
992
+ };
993
+ /**
994
+ * Helper functions for storage operations
995
+ * These work with both localStorage and sessionStorage
996
+ */
997
+ /**
998
+ * Get item from storage
999
+ * @param key - Storage key
1000
+ * @param storageType - Type of storage to use
1001
+ * @returns Stored value or null
1002
+ */
1003
+ declare function getStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): string | null;
1004
+ /**
1005
+ * Set item in storage
1006
+ * @param key - Storage key
1007
+ * @param value - Value to store
1008
+ * @param storageType - Type of storage to use
1009
+ */
1010
+ declare function setStorageItem(key: string, value: string, storageType?: 'localStorage' | 'sessionStorage'): void;
1011
+ /**
1012
+ * Remove item from storage
1013
+ * @param key - Storage key
1014
+ * @param storageType - Type of storage to use
1015
+ */
1016
+ declare function removeStorageItem(key: string, storageType?: 'localStorage' | 'sessionStorage'): void;
1017
+ /**
1018
+ * Configure Auth0 settings
1019
+ * Call this function in your consuming application before using AuthService
1020
+ *
1021
+ * @example
1022
+ * ```typescript
1023
+ * import { configureAuth0 } from '@opensourcekd/ng-common-libs';
1024
+ *
1025
+ * configureAuth0({
1026
+ * domain: 'your-domain.auth0.com',
1027
+ * clientId: 'your-client-id',
1028
+ * audience: 'https://your-api.com'
1029
+ * });
1030
+ * ```
1031
+ */
1032
+ declare function configureAuth0(config: Partial<typeof AUTH0_CONFIG>): void;
1033
+
1034
+ export { AUTH0_CONFIG, AuthService, EventBusService, HttpError, LogLevel, LoggerService, NgEventEmitter, PermissionService, STORAGE_CONFIG, STORAGE_KEYS, StorageService, TokenService, authGuard, authInterceptor, cachingInterceptor, clearCache, clearCacheEntry, configureAuth0, configureAuthInterceptor, configureCaching, configureErrorHandling, createAuthGuard, createPermissionGuard, createRoleGuard, errorHandlingInterceptor, getStorageItem, isClientError, isNetworkError, isServerError, parseHttpError, removeStorageItem, setStorageItem };
1035
+ export type { AuthGuardConfig, AuthInterceptorConfig, CacheConfig, ErrorHandlingConfig, LoggerConfig, TokenConfig, UserData, UserInfo };