@memberjunction/ng-auth-services 6.2.0-edge.0 → 6.2.0-edge.2
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/lib/AngularAuthProviderFactory.d.ts +12 -0
- package/dist/lib/AngularAuthProviderFactory.d.ts.map +1 -1
- package/dist/lib/AngularAuthProviderFactory.js +31 -7
- package/dist/lib/AngularAuthProviderFactory.js.map +1 -1
- package/dist/lib/IAuthProvider.js.map +1 -1
- package/dist/lib/auth-services.module.d.ts +2 -0
- package/dist/lib/auth-services.module.d.ts.map +1 -1
- package/dist/lib/auth-services.module.js +7 -3
- package/dist/lib/auth-services.module.js.map +1 -1
- package/dist/lib/catalog-environment.d.ts +4 -0
- package/dist/lib/catalog-environment.d.ts.map +1 -1
- package/dist/lib/catalog-environment.js +11 -3
- package/dist/lib/catalog-environment.js.map +1 -1
- package/dist/lib/providers/mjexplorer-auth0-provider.service.d.ts +11 -3
- package/dist/lib/providers/mjexplorer-auth0-provider.service.d.ts.map +1 -1
- package/dist/lib/providers/mjexplorer-auth0-provider.service.js +32 -16
- package/dist/lib/providers/mjexplorer-auth0-provider.service.js.map +1 -1
- package/dist/lib/providers/mjexplorer-cognito-provider.service.d.ts +11 -1
- package/dist/lib/providers/mjexplorer-cognito-provider.service.d.ts.map +1 -1
- package/dist/lib/providers/mjexplorer-cognito-provider.service.js +9 -1
- package/dist/lib/providers/mjexplorer-cognito-provider.service.js.map +1 -1
- package/dist/lib/providers/mjexplorer-magic-link-provider.service.d.ts +2 -0
- package/dist/lib/providers/mjexplorer-magic-link-provider.service.d.ts.map +1 -1
- package/dist/lib/providers/mjexplorer-magic-link-provider.service.js +5 -1
- package/dist/lib/providers/mjexplorer-magic-link-provider.service.js.map +1 -1
- package/dist/lib/providers/mjexplorer-msal-provider.service.d.ts +49 -3
- package/dist/lib/providers/mjexplorer-msal-provider.service.d.ts.map +1 -1
- package/dist/lib/providers/mjexplorer-msal-provider.service.js +41 -25
- package/dist/lib/providers/mjexplorer-msal-provider.service.js.map +1 -1
- package/dist/lib/providers/mjexplorer-okta-provider.service.d.ts +23 -1
- package/dist/lib/providers/mjexplorer-okta-provider.service.d.ts.map +1 -1
- package/dist/lib/providers/mjexplorer-okta-provider.service.js +9 -1
- package/dist/lib/providers/mjexplorer-okta-provider.service.js.map +1 -1
- package/dist/lib/providers/mjexplorer-workos-provider.service.d.ts +21 -1
- package/dist/lib/providers/mjexplorer-workos-provider.service.d.ts.map +1 -1
- package/dist/lib/providers/mjexplorer-workos-provider.service.js +9 -1
- package/dist/lib/providers/mjexplorer-workos-provider.service.js.map +1 -1
- package/dist/lib/redirect.component.d.ts +5 -1
- package/dist/lib/redirect.component.d.ts.map +1 -1
- package/dist/lib/redirect.component.js +11 -3
- package/dist/lib/redirect.component.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mjexplorer-auth0-provider.service.js","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-auth0-provider.service.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAE,UAAU,EAAY,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAAE,WAAW,EAAiB,SAAS,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,sBAAsB,CAAC;AAC1J,OAAO,EAAkB,cAAc,EAAE,MAAM,MAAM,CAAC;AACtD,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAE9C,OAAO,EAIL,aAAa,EAEd,MAAM,eAAe,CAAC;;;AACvB;;;;;;GAMG;AAKI,IAAM,eAAe,GAArB,MAAM,eAAgB,SAAQ,UAAU;;IA+C1B;IA9CnB,MAAM,CAAU,aAAa,GAAG,OAAO,CAAC;IA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Y,eAAe;cAJ3B,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable, Provider } from '@angular/core';\nimport { RegisterClass } from '@memberjunction/global';\nimport { MJAuthBase } from '../mjexplorer-auth-base.service';\nimport { AuthService, IdToken, User, AuthGuard, AuthConfigService, Auth0ClientService, Auth0ClientFactory, AuthClientConfig } from '@auth0/auth0-angular';\nimport { Observable, of, firstValueFrom } from 'rxjs';\nimport { take, filter } from 'rxjs/operators';\nimport { AngularAuthProviderConfig } from '../IAuthProvider';\nimport {\n StandardUserInfo,\n StandardAuthToken,\n StandardAuthError,\n AuthErrorType,\n TokenRefreshResult\n} from '../auth-types';\n/**\n * Auth0 authentication provider implementation - v3.0.0\n *\n * Implements the abstract methods from MJAuthBase to hide Auth0-specific details.\n * The key abstraction is that Auth0 stores the JWT in `idTokenClaims.__raw`,\n * but consumers never need to know this detail.\n */\n@Injectable({\n providedIn: 'root'\n})\n@RegisterClass(MJAuthBase, 'auth0')\nexport class MJAuth0Provider extends MJAuthBase {\n static readonly PROVIDER_TYPE = 'auth0';\n readonly type = MJAuth0Provider.PROVIDER_TYPE;\n private _initialized = false;\n\n /**\n * Factory function to provide Angular dependencies required by Auth0\n * Stored as a static property for the factory to access without instantiation\n */\n static angularProviderFactory = (environment: Record<string, unknown>): Provider[] => {\n // Check if we're on the MCP OAuth callback path\n const isMCPOAuthCallback = window.location.pathname.startsWith('/oauth/callback');\n\n return [\n AuthService,\n AuthGuard,\n {\n provide: AuthConfigService,\n useValue: {\n domain: environment['AUTH0_DOMAIN'],\n clientId: environment['AUTH0_CLIENTID'],\n authorizationParams: {\n redirect_uri: window.location.origin,\n scope: 'openid profile email offline_access',\n // No audience parameter - uses ID tokens (matches pre-refactor behavior)\n // ID tokens have aud=clientId by default and contain user claims\n },\n cacheLocation: 'localstorage',\n // Enable refresh tokens so we can refresh without relying on Auth0 session cookies\n useRefreshTokens: true,\n // Use rotating refresh tokens for better security\n useRefreshTokensFallback: true,\n // CRITICAL: Skip Auth0's redirect callback handling for MCP OAuth callbacks\n // The /oauth/callback path is used by MCP OAuth, not Auth0. If we don't skip,\n // Auth0 will consume the code parameter and redirect to /, preventing the\n // OAuthCallbackComponent from processing the MCP OAuth flow.\n skipRedirectCallback: isMCPOAuthCallback,\n },\n },\n {\n provide: Auth0ClientService,\n useFactory: Auth0ClientFactory.createClient,\n deps: [AuthClientConfig],\n }\n ];\n };\n\n constructor(public auth: AuthService) {\n const config: AngularAuthProviderConfig = {\n name: MJAuth0Provider.PROVIDER_TYPE,\n type: MJAuth0Provider.PROVIDER_TYPE\n };\n super(config);\n }\n\n // ============================================================================\n // LIFECYCLE METHODS\n // ============================================================================\n\n async initialize(): Promise<void> {\n if (this._initialized) {\n return;\n }\n\n // CRITICAL: Wait for Auth0 SDK to process any redirect callback\n // The SDK handles this internally and updates isLoading$ when done\n await firstValueFrom(this.auth.isLoading$.pipe(\n filter(loading => !loading),\n take(1)\n ));\n\n // Get current authentication state\n const isAuthenticated = await firstValueFrom(this.auth.isAuthenticated$);\n\n // CRITICAL: Get current user BEFORE setting up subscriptions\n // This ensures userInfo$ has a value before app.component.ts subscribes\n if (isAuthenticated) {\n const user = await firstValueFrom(this.auth.user$);\n if (user) {\n const userInfo = this.mapAuth0UserToStandard(user);\n this.updateUserInfo(userInfo);\n }\n }\n\n // Subscribe to authentication state and user info for future changes\n this.auth.isAuthenticated$.subscribe((loggedIn) => {\n this.updateAuthState(loggedIn);\n });\n\n this.auth.user$.subscribe((user) => {\n if (user) {\n const userInfo = this.mapAuth0UserToStandard(user);\n this.updateUserInfo(userInfo);\n } else {\n this.updateUserInfo(null);\n }\n });\n\n this._initialized = true;\n }\n\n protected async loginInternal(options?: Record<string, unknown>): Promise<void> {\n await this.ensureInitialized();\n this.auth.loginWithRedirect(options);\n }\n\n protected async logoutInternal(): Promise<void> {\n // Subscribe to the Observable so Auth0 Angular SDK v2's authState.refresh() fires.\n try {\n await firstValueFrom(\n this.auth.logout({ logoutParams: { returnTo: document.location.origin } })\n );\n } catch {\n // Expected when Auth0 redirects the browser before the Observable completes.\n }\n }\n\n async handleCallback(): Promise<void> {\n // Auth0 Angular SDK handles callbacks internally via interceptors\n // This method exists for interface compatibility\n }\n\n // ============================================================================\n // ABSTRACT METHOD IMPLEMENTATIONS (v3.0.0)\n // ============================================================================\n\n /**\n * Extract ID token from Auth0's storage\n *\n * Auth0 stores the JWT string in idTokenClaims.__raw\n * This is the key abstraction - consumers never need to know about __raw!\n */\n protected async extractIdTokenInternal(): Promise<string | null> {\n try {\n const claims = await firstValueFrom(this.auth.idTokenClaims$);\n // Auth0-specific detail: JWT is in __raw property\n return claims?.__raw || null;\n } catch (error) {\n console.error('[Auth0] Error extracting ID token:', error);\n return null;\n }\n }\n\n /**\n * Extract complete token info from Auth0\n *\n * Maps Auth0's token structure to StandardAuthToken\n */\n protected async extractTokenInfoInternal(): Promise<StandardAuthToken | null> {\n try {\n const claims = await firstValueFrom(this.auth.idTokenClaims$);\n if (!claims) {\n return null;\n }\n\n const idToken = claims.__raw;\n if (!idToken) {\n return null;\n }\n\n return {\n idToken,\n expiresAt: claims.exp ? claims.exp * 1000 : 0, // Convert to milliseconds\n scopes: claims.scope ? claims.scope.split(' ') : undefined\n };\n } catch (error) {\n console.error('[Auth0] Error extracting token info:', error);\n return null;\n }\n }\n\n /**\n * Extract user info from Auth0 claims\n *\n * Maps Auth0's user object structure to StandardUserInfo\n */\n protected async extractUserInfoInternal(): Promise<StandardUserInfo | null> {\n try {\n const user = await firstValueFrom(this.auth.user$);\n if (!user) {\n return null;\n }\n\n return this.mapAuth0UserToStandard(user);\n } catch (error) {\n console.error('[Auth0] Error extracting user info:', error);\n return null;\n }\n }\n\n /**\n * Refresh token using Auth0's silent authentication\n *\n * Uses cacheMode: 'off' to bypass cache and force token refresh\n * With useRefreshTokens: true and offline_access scope, this will use refresh tokens\n */\n protected async refreshTokenInternal(): Promise<TokenRefreshResult> {\n try {\n console.log('[Auth0] Attempting to refresh token...');\n\n // Force token refresh by bypassing cache\n // With useRefreshTokens: true and offline_access scope, this will use refresh tokens\n await firstValueFrom(this.auth.getAccessTokenSilently({\n cacheMode: 'off'\n }));\n\n // Small delay to ensure Auth0 SDK has updated observables\n await new Promise(resolve => setTimeout(resolve, 100));\n\n // Extract fresh token info from updated observables\n const token = await this.extractTokenInfoInternal();\n\n if (!token) {\n return {\n success: false,\n error: {\n type: AuthErrorType.NO_ACTIVE_SESSION,\n message: 'Token refresh succeeded but could not extract token info',\n userMessage: 'Session refresh failed. Please log in again.'\n }\n };\n }\n\n console.log('[Auth0] Token refresh successful', {\n expiresAt: new Date(token.expiresAt).toISOString()\n });\n\n return {\n success: true,\n token\n };\n } catch (error) {\n console.error('[Auth0] Token refresh failed:', error);\n\n return {\n success: false,\n error: this.classifyErrorInternal(error)\n };\n }\n }\n\n /**\n * Classify Auth0-specific errors into semantic types\n *\n * Maps Auth0 error patterns to AuthErrorType enum\n */\n protected classifyErrorInternal(error: unknown): StandardAuthError {\n const errorObj = error as Record<string, unknown>;\n const message = errorObj?.['message'] as string || 'Unknown error';\n const errorType = errorObj?.['error'] as string || '';\n\n // Check for specific Auth0 error patterns\n if (message.includes('jwt expired') || message.includes('token expired')) {\n return {\n type: AuthErrorType.TOKEN_EXPIRED,\n message,\n originalError: error,\n userMessage: 'Your session has expired. Please log in again.'\n };\n }\n\n if (errorType === 'login_required' || message.includes('login_required')) {\n return {\n type: AuthErrorType.NO_ACTIVE_SESSION,\n message,\n originalError: error,\n userMessage: 'You need to log in to continue.'\n };\n }\n\n if (errorType === 'consent_required' || message.includes('consent_required')) {\n return {\n type: AuthErrorType.INTERACTION_REQUIRED,\n message,\n originalError: error,\n userMessage: 'Additional permissions are required. Please log in again.'\n };\n }\n\n if (message.includes('user closed') || message.includes('cancelled')) {\n return {\n type: AuthErrorType.USER_CANCELLED,\n message,\n originalError: error,\n userMessage: 'Login was cancelled.'\n };\n }\n\n if (message.includes('network') || message.includes('fetch')) {\n return {\n type: AuthErrorType.NETWORK_ERROR,\n message,\n originalError: error,\n userMessage: 'Network error. Please check your connection and try again.'\n };\n }\n\n // Default to unknown error\n return {\n type: AuthErrorType.UNKNOWN_ERROR,\n message,\n originalError: error,\n userMessage: 'An unexpected error occurred. Please try again.'\n };\n }\n\n // ============================================================================\n // HELPER METHODS\n // ============================================================================\n\n private async ensureInitialized(): Promise<void> {\n if (!this._initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Map Auth0 User object to StandardUserInfo\n */\n private mapAuth0UserToStandard(user: User): StandardUserInfo {\n return {\n id: user.sub || '',\n email: user.email || '',\n name: user.name || '',\n givenName: user.given_name,\n familyName: user.family_name,\n preferredUsername: user.nickname,\n pictureUrl: user.picture,\n locale: user.locale,\n emailVerified: user.email_verified\n };\n }\n\n /**\n * Get profile picture URL from Auth0\n *\n * Auth0 includes the picture URL directly in user claims.\n * No additional API call needed.\n */\n protected async getProfilePictureUrlInternal(): Promise<string | null> {\n try {\n const user = await firstValueFrom(this.auth.user$);\n return user?.picture || null;\n } catch (error) {\n console.error('[Auth0] Error getting profile picture:', error);\n return null;\n }\n }\n\n /**\n * Handle session expiry - no-op for Auth0\n *\n * Auth0 uses refresh tokens (offline_access scope), so it doesn't need\n * interactive re-authentication when tokens expire. If refresh fails,\n * the base class will throw an error and the user must log out/in manually.\n */\n protected async handleSessionExpiryInternal(): Promise<void> {\n // No-op - Auth0 doesn't need interactive re-auth\n return;\n }\n\n // ============================================================================\n // CONFIGURATION\n // ============================================================================\n\n override getRequiredConfig(): string[] {\n return ['clientId', 'domain'];\n }\n\n override validateConfig(_config: Record<string, unknown>): boolean {\n // Auth0 configuration is handled by Angular module providers\n return true;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mjexplorer-auth0-provider.service.js","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-auth0-provider.service.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAE,UAAU,EAAY,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE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AAE,IAAI,CAAC,OAAO;YACxB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,aAAa,EAAE,IAAI,CAAC,cAAc;SACnC,CAAC;IACJ,CAAC;IAED;;;;;OAKG;IACO,KAAK,CAAC,4BAA4B;QAC1C,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,MAAM,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;YACnD,OAAO,IAAI,EAAE,OAAO,IAAI,IAAI,CAAC;QAC/B,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,OAAO,CAAC,KAAK,CAAC,wCAAwC,EAAE,KAAK,CAAC,CAAC;YAC/D,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAED;;;;;;OAMG;IACO,KAAK,CAAC,2BAA2B;QACzC,iDAAiD;QACjD,OAAO;IACT,CAAC;IAED,+EAA+E;IAC/E,gBAAgB;IAChB,+EAA+E;IAEtE,iBAAiB;QACxB,OAAO,CAAC,UAAU,EAAE,QAAQ,CAAC,CAAC;IAChC,CAAC;IAEQ,cAAc,CAAC,OAAgC;QACtD,6DAA6D;QAC7D,OAAO,IAAI,CAAC;IACd,CAAC;yGAtYU,eAAe;gEAAf,eAAe,WAAf,eAAe,mBAHd,MAAM;;AAGP,eAAe;IAD3B,aAAa,CAAC,UAAU,EAAE,OAAO,CAAC;GACtB,eAAe,CAuY3B;;iFAvYY,eAAe;cAJ3B,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB","sourcesContent":["import { Injectable, Provider } from '@angular/core';\nimport { RegisterClass } from '@memberjunction/global';\nimport { MJAuthBase } from '../mjexplorer-auth-base.service';\nimport { AuthService, IdToken, User, AuthGuard, AuthConfigService, Auth0ClientService, Auth0ClientFactory, AuthClientConfig } from '@auth0/auth0-angular';\nimport { Observable, of, firstValueFrom } from 'rxjs';\nimport { take, filter } from 'rxjs/operators';\nimport { AngularAuthProviderConfig } from '../IAuthProvider';\nimport {\n StandardUserInfo,\n StandardAuthToken,\n StandardAuthError,\n AuthErrorType,\n TokenRefreshResult\n} from '../auth-types';\n/**\n * Auth0 authentication provider implementation - v3.0.0\n *\n * Implements the abstract methods from MJAuthBase to hide Auth0-specific details.\n * The key abstraction is that Auth0 stores the JWT in `idTokenClaims.__raw`,\n * but consumers never need to know this detail.\n */\n@Injectable({\n providedIn: 'root'\n})\n@RegisterClass(MJAuthBase, 'auth0')\nexport class MJAuth0Provider extends MJAuthBase {\n static readonly PROVIDER_TYPE = 'auth0';\n readonly type = MJAuth0Provider.PROVIDER_TYPE;\n private _initialized = false;\n\n /**\n * Factory function to provide Angular dependencies required by Auth0\n * Stored as a static property for the factory to access without instantiation\n */\n static AngularProviderFactory = (environment: Record<string, unknown>): Provider[] => {\n // Check if we're on the MCP OAuth callback path\n const isMCPOAuthCallback = window.location.pathname.startsWith('/oauth/callback');\n\n return [\n AuthService,\n AuthGuard,\n {\n provide: AuthConfigService,\n useValue: {\n domain: environment['AUTH0_DOMAIN'],\n clientId: environment['AUTH0_CLIENTID'],\n authorizationParams: {\n redirect_uri: window.location.origin,\n scope: 'openid profile email offline_access',\n // No audience parameter - uses ID tokens (matches pre-refactor behavior)\n // ID tokens have aud=clientId by default and contain user claims\n },\n cacheLocation: 'localstorage',\n // Enable refresh tokens so we can refresh without relying on Auth0 session cookies\n useRefreshTokens: true,\n // Use rotating refresh tokens for better security\n useRefreshTokensFallback: true,\n // CRITICAL: Skip Auth0's redirect callback handling for MCP OAuth callbacks\n // The /oauth/callback path is used by MCP OAuth, not Auth0. If we don't skip,\n // Auth0 will consume the code parameter and redirect to /, preventing the\n // OAuthCallbackComponent from processing the MCP OAuth flow.\n skipRedirectCallback: isMCPOAuthCallback,\n },\n },\n {\n provide: Auth0ClientService,\n useFactory: Auth0ClientFactory.createClient,\n deps: [AuthClientConfig],\n }\n ];\n };\n\n /** @deprecated Use {@link AngularProviderFactory}. */\n static get angularProviderFactory() {\n return this.AngularProviderFactory;\n }\n /** @deprecated Use {@link AngularProviderFactory}. */\n static set angularProviderFactory(value) {\n this.AngularProviderFactory = value;\n }\n\n constructor(public Auth: AuthService) {\n const config: AngularAuthProviderConfig = {\n name: MJAuth0Provider.PROVIDER_TYPE,\n type: MJAuth0Provider.PROVIDER_TYPE\n };\n super(config);\n }\n\n /** @deprecated Use {@link Auth}. */\n public get auth(): AuthService {\n return this.Auth;\n }\n /** @deprecated Use {@link Auth}. */\n public set auth(value: AuthService) {\n this.Auth = value;\n }\n\n // ============================================================================\n // LIFECYCLE METHODS\n // ============================================================================\n\n async initialize(): Promise<void> {\n if (this._initialized) {\n return;\n }\n\n // CRITICAL: Wait for Auth0 SDK to process any redirect callback\n // The SDK handles this internally and updates isLoading$ when done\n await firstValueFrom(this.Auth.isLoading$.pipe(\n filter(loading => !loading),\n take(1)\n ));\n\n // Get current authentication state\n const isAuthenticated = await firstValueFrom(this.Auth.isAuthenticated$);\n\n // CRITICAL: Get current user BEFORE setting up subscriptions\n // This ensures userInfo$ has a value before app.component.ts subscribes\n if (isAuthenticated) {\n const user = await firstValueFrom(this.Auth.user$);\n if (user) {\n const userInfo = this.mapAuth0UserToStandard(user);\n this.updateUserInfo(userInfo);\n }\n }\n\n // Subscribe to authentication state and user info for future changes\n this.Auth.isAuthenticated$.subscribe((loggedIn) => {\n this.updateAuthState(loggedIn);\n });\n\n this.Auth.user$.subscribe((user) => {\n if (user) {\n const userInfo = this.mapAuth0UserToStandard(user);\n this.updateUserInfo(userInfo);\n } else {\n this.updateUserInfo(null);\n }\n });\n\n this._initialized = true;\n }\n\n protected async loginInternal(options?: Record<string, unknown>): Promise<void> {\n await this.ensureInitialized();\n this.Auth.loginWithRedirect(options);\n }\n\n protected async logoutInternal(): Promise<void> {\n // Subscribe to the Observable so Auth0 Angular SDK v2's authState.refresh() fires.\n try {\n await firstValueFrom(\n this.Auth.logout({ logoutParams: { returnTo: document.location.origin } })\n );\n } catch {\n // Expected when Auth0 redirects the browser before the Observable completes.\n }\n }\n\n async handleCallback(): Promise<void> {\n // Auth0 Angular SDK handles callbacks internally via interceptors\n // This method exists for interface compatibility\n }\n\n // ============================================================================\n // ABSTRACT METHOD IMPLEMENTATIONS (v3.0.0)\n // ============================================================================\n\n /**\n * Extract ID token from Auth0's storage\n *\n * Auth0 stores the JWT string in idTokenClaims.__raw\n * This is the key abstraction - consumers never need to know about __raw!\n */\n protected async extractIdTokenInternal(): Promise<string | null> {\n try {\n const claims = await firstValueFrom(this.Auth.idTokenClaims$);\n // Auth0-specific detail: JWT is in __raw property\n return claims?.__raw || null;\n } catch (error) {\n console.error('[Auth0] Error extracting ID token:', error);\n return null;\n }\n }\n\n /**\n * Extract complete token info from Auth0\n *\n * Maps Auth0's token structure to StandardAuthToken\n */\n protected async extractTokenInfoInternal(): Promise<StandardAuthToken | null> {\n try {\n const claims = await firstValueFrom(this.Auth.idTokenClaims$);\n if (!claims) {\n return null;\n }\n\n const idToken = claims.__raw;\n if (!idToken) {\n return null;\n }\n\n return {\n idToken,\n expiresAt: claims.exp ? claims.exp * 1000 : 0, // Convert to milliseconds\n scopes: claims.scope ? claims.scope.split(' ') : undefined\n };\n } catch (error) {\n console.error('[Auth0] Error extracting token info:', error);\n return null;\n }\n }\n\n /**\n * Extract user info from Auth0 claims\n *\n * Maps Auth0's user object structure to StandardUserInfo\n */\n protected async extractUserInfoInternal(): Promise<StandardUserInfo | null> {\n try {\n const user = await firstValueFrom(this.Auth.user$);\n if (!user) {\n return null;\n }\n\n return this.mapAuth0UserToStandard(user);\n } catch (error) {\n console.error('[Auth0] Error extracting user info:', error);\n return null;\n }\n }\n\n /**\n * Refresh token using Auth0's silent authentication\n *\n * Uses cacheMode: 'off' to bypass cache and force token refresh\n * With useRefreshTokens: true and offline_access scope, this will use refresh tokens\n */\n protected async refreshTokenInternal(): Promise<TokenRefreshResult> {\n try {\n console.log('[Auth0] Attempting to refresh token...');\n\n // Force token refresh by bypassing cache\n // With useRefreshTokens: true and offline_access scope, this will use refresh tokens\n await firstValueFrom(this.Auth.getAccessTokenSilently({\n cacheMode: 'off'\n }));\n\n // Small delay to ensure Auth0 SDK has updated observables\n await new Promise(resolve => setTimeout(resolve, 100));\n\n // Extract fresh token info from updated observables\n const token = await this.extractTokenInfoInternal();\n\n if (!token) {\n return {\n success: false,\n error: {\n type: AuthErrorType.NO_ACTIVE_SESSION,\n message: 'Token refresh succeeded but could not extract token info',\n userMessage: 'Session refresh failed. Please log in again.'\n }\n };\n }\n\n console.log('[Auth0] Token refresh successful', {\n expiresAt: new Date(token.expiresAt).toISOString()\n });\n\n return {\n success: true,\n token\n };\n } catch (error) {\n console.error('[Auth0] Token refresh failed:', error);\n\n return {\n success: false,\n error: this.classifyErrorInternal(error)\n };\n }\n }\n\n /**\n * Classify Auth0-specific errors into semantic types\n *\n * Maps Auth0 error patterns to AuthErrorType enum\n */\n protected classifyErrorInternal(error: unknown): StandardAuthError {\n const errorObj = error as Record<string, unknown>;\n const message = errorObj?.['message'] as string || 'Unknown error';\n const errorType = errorObj?.['error'] as string || '';\n\n // Check for specific Auth0 error patterns\n if (message.includes('jwt expired') || message.includes('token expired')) {\n return {\n type: AuthErrorType.TOKEN_EXPIRED,\n message,\n originalError: error,\n userMessage: 'Your session has expired. Please log in again.'\n };\n }\n\n if (errorType === 'login_required' || message.includes('login_required')) {\n return {\n type: AuthErrorType.NO_ACTIVE_SESSION,\n message,\n originalError: error,\n userMessage: 'You need to log in to continue.'\n };\n }\n\n if (errorType === 'consent_required' || message.includes('consent_required')) {\n return {\n type: AuthErrorType.INTERACTION_REQUIRED,\n message,\n originalError: error,\n userMessage: 'Additional permissions are required. Please log in again.'\n };\n }\n\n if (message.includes('user closed') || message.includes('cancelled')) {\n return {\n type: AuthErrorType.USER_CANCELLED,\n message,\n originalError: error,\n userMessage: 'Login was cancelled.'\n };\n }\n\n if (message.includes('network') || message.includes('fetch')) {\n return {\n type: AuthErrorType.NETWORK_ERROR,\n message,\n originalError: error,\n userMessage: 'Network error. Please check your connection and try again.'\n };\n }\n\n // Default to unknown error\n return {\n type: AuthErrorType.UNKNOWN_ERROR,\n message,\n originalError: error,\n userMessage: 'An unexpected error occurred. Please try again.'\n };\n }\n\n // ============================================================================\n // HELPER METHODS\n // ============================================================================\n\n private async ensureInitialized(): Promise<void> {\n if (!this._initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Map Auth0 User object to StandardUserInfo\n */\n private mapAuth0UserToStandard(user: User): StandardUserInfo {\n return {\n id: user.sub || '',\n email: user.email || '',\n name: user.name || '',\n givenName: user.given_name,\n familyName: user.family_name,\n preferredUsername: user.nickname,\n pictureUrl: user.picture,\n locale: user.locale,\n emailVerified: user.email_verified\n };\n }\n\n /**\n * Get profile picture URL from Auth0\n *\n * Auth0 includes the picture URL directly in user claims.\n * No additional API call needed.\n */\n protected async getProfilePictureUrlInternal(): Promise<string | null> {\n try {\n const user = await firstValueFrom(this.Auth.user$);\n return user?.picture || null;\n } catch (error) {\n console.error('[Auth0] Error getting profile picture:', error);\n return null;\n }\n }\n\n /**\n * Handle session expiry - no-op for Auth0\n *\n * Auth0 uses refresh tokens (offline_access scope), so it doesn't need\n * interactive re-authentication when tokens expire. If refresh fails,\n * the base class will throw an error and the user must log out/in manually.\n */\n protected async handleSessionExpiryInternal(): Promise<void> {\n // No-op - Auth0 doesn't need interactive re-auth\n return;\n }\n\n // ============================================================================\n // CONFIGURATION\n // ============================================================================\n\n override getRequiredConfig(): string[] {\n return ['clientId', 'domain'];\n }\n\n override validateConfig(_config: Record<string, unknown>): boolean {\n // Auth0 configuration is handled by Angular module providers\n return true;\n }\n}\n"]}
|
|
@@ -43,10 +43,20 @@ export declare class MJCognitoProvider extends MJAuthBase {
|
|
|
43
43
|
* Factory function to provide Angular dependencies required by the Cognito provider.
|
|
44
44
|
* Returns a config injection token following the Okta provider pattern.
|
|
45
45
|
*/
|
|
46
|
-
static
|
|
46
|
+
static AngularProviderFactory: (environment: Record<string, unknown>) => {
|
|
47
47
|
provide: string;
|
|
48
48
|
useValue: CognitoConfig;
|
|
49
49
|
}[];
|
|
50
|
+
/** @deprecated Use {@link AngularProviderFactory}. */
|
|
51
|
+
static get angularProviderFactory(): (environment: Record<string, unknown>) => {
|
|
52
|
+
provide: string;
|
|
53
|
+
useValue: CognitoConfig;
|
|
54
|
+
}[];
|
|
55
|
+
/** @deprecated Use {@link AngularProviderFactory}. */
|
|
56
|
+
static set angularProviderFactory(value: (environment: Record<string, unknown>) => {
|
|
57
|
+
provide: string;
|
|
58
|
+
useValue: CognitoConfig;
|
|
59
|
+
}[]);
|
|
50
60
|
constructor(cognitoConfig: CognitoConfig);
|
|
51
61
|
initialize(): Promise<void>;
|
|
52
62
|
protected loginInternal(_options?: Record<string, unknown>): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mjexplorer-cognito-provider.service.d.ts","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-cognito-provider.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAW7D,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAEjB,kBAAkB,EACnB,MAAM,eAAe,CAAC;;AAEvB;;;GAGG;AACH,UAAU,aAAa;IACrB,UAAU,EAAE,MAAM,CAAC;IACnB,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,8EAA8E;IAC9E,MAAM,EAAE,MAAM,CAAC;IACf,6DAA6D;IAC7D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,+DAA+D;IAC/D,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;IAClB,kFAAkF;IAClF,oBAAoB,CAAC,EAAE,OAAO,CAAC;CAChC;AAED;;;;;;;;;;;;;;GAcG;AACH,qBAIa,iBAAkB,SAAQ,UAAU;
|
|
1
|
+
{"version":3,"file":"mjexplorer-cognito-provider.service.d.ts","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-cognito-provider.service.ts"],"names":[],"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O,CAAC,IAAI,CAAC;cAMhE,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAYzC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAoBrC;;;;;OAKG;cACa,sBAAsB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAUhE;;;OAGG;cACa,wBAAwB,IAAI,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;IAuB7E;;;OAGG;cACa,uBAAuB,IAAI,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;IAY3E;;;;;;OAMG;cACa,oBAAoB,IAAI,OAAO,CAAC,kBAAkB,CAAC;IA2CnE;;;;OAIG;IACH,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB;IA2ElE;;;;;OAKG;cACa,4BAA4B,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IAUtE;;;;;;OAMG;cACa,2BAA2B,IAAI,OAAO,CAAC,IAAI,CAAC;YAU9C,iBAAiB;IAM/B;;OAEG;YACW,eAAe;IAW7B;;;;;OAKG;IACH,OAAO,CAAC,8BAA8B;IAsBtC;;OAEG;IACH,OAAO,CAAC,aAAa;IAQrB;;OAEG;IACH,OAAO,CAAC,iBAAiB;IAWhB,iBAAiB,IAAI,MAAM,EAAE;IAI7B,cAAc,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO;yCAhdtD,iBAAiB;6CAAjB,iBAAiB;CAmd7B"}
|
|
@@ -39,7 +39,7 @@ let MJCognitoProvider = class MJCognitoProvider extends MJAuthBase {
|
|
|
39
39
|
* Factory function to provide Angular dependencies required by the Cognito provider.
|
|
40
40
|
* Returns a config injection token following the Okta provider pattern.
|
|
41
41
|
*/
|
|
42
|
-
static
|
|
42
|
+
static AngularProviderFactory = (environment) => {
|
|
43
43
|
const isMCPOAuthCallback = window.location.pathname.startsWith('/oauth/callback');
|
|
44
44
|
return [
|
|
45
45
|
{
|
|
@@ -59,6 +59,14 @@ let MJCognitoProvider = class MJCognitoProvider extends MJAuthBase {
|
|
|
59
59
|
}
|
|
60
60
|
];
|
|
61
61
|
};
|
|
62
|
+
/** @deprecated Use {@link AngularProviderFactory}. */
|
|
63
|
+
static get angularProviderFactory() {
|
|
64
|
+
return this.AngularProviderFactory;
|
|
65
|
+
}
|
|
66
|
+
/** @deprecated Use {@link AngularProviderFactory}. */
|
|
67
|
+
static set angularProviderFactory(value) {
|
|
68
|
+
this.AngularProviderFactory = value;
|
|
69
|
+
}
|
|
62
70
|
constructor(cognitoConfig) {
|
|
63
71
|
const config = {
|
|
64
72
|
name: MJCognitoProvider_1.PROVIDER_TYPE,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mjexplorer-cognito-provider.service.js","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-cognito-provider.service.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7D,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,kBAAkB,EAClB,OAAO,EACP,gBAAgB,EAChB,cAAc,EACd,mBAAmB,EACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACxC,OAAO,EAIL,aAAa,EAEd,MAAM,eAAe,CAAC;;AAoBvB;;;;;;;;;;;;;;GAcG;AAKI,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,UAAU;;IAgCF;IA/B7C,MAAM,CAAU,aAAa,GAAG,SAAS,CAAC;IACjC,IAAI,GAAG,mBAAiB,CAAC,aAAa,CAAC;IACxC,YAAY,GAAG,KAAK,CAAC;IACrB,kBAAkB,GAAwB,IAAI,CAAC;IAEv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CAAC,CAAC;IACtD,CAAC;IAEQ,cAAc,CAAC,MAA+B;QACrD,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,MAAM,CAAC,kBAAkB,CAAC,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC;IACpF,CAAC;2GAzcU,iBAAiB,cAgCR,eAAe;gEAhCxB,iBAAiB,WAAjB,iBAAiB,mBAHhB,MAAM;;AAGP,iBAAiB;IAD7B,aAAa,CAAC,UAAU,EAAE,SAAS,CAAC;GACxB,iBAAiB,CA0c7B;;iFA1cY,iBAAiB;cAJ7B,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB;;sBAkCc,MAAM;uBAAC,eAAe","sourcesContent":["import { Injectable, Inject } from '@angular/core';\nimport { RegisterClass } from '@memberjunction/global';\nimport { MJAuthBase } from '../mjexplorer-auth-base.service';\nimport { AngularAuthProviderConfig } from '../IAuthProvider';\nimport { Amplify } from 'aws-amplify';\nimport {\n signInWithRedirect,\n signOut,\n fetchAuthSession,\n getCurrentUser,\n fetchUserAttributes\n} from 'aws-amplify/auth';\nimport { Hub } from 'aws-amplify/utils';\nimport {\n StandardUserInfo,\n StandardAuthToken,\n StandardAuthError,\n AuthErrorType,\n TokenRefreshResult\n} from '../auth-types';\n\n/**\n * Configuration interface for the Cognito provider.\n * Populated from environment config via the `angularProviderFactory`.\n */\ninterface CognitoConfig {\n userPoolId: string;\n userPoolClientId: string;\n region?: string;\n /** Cognito Hosted UI domain, e.g. 'myapp.auth.us-east-1.amazoncognito.com' */\n domain: string;\n /** OAuth redirect URI. Defaults to window.location.origin */\n redirectUri?: string;\n /** OAuth scopes. Defaults to ['openid', 'profile', 'email'] */\n scopes?: string[];\n /** When true, skips redirect callback processing (for MCP OAuth callback path) */\n skipRedirectCallback?: boolean;\n}\n\n/**\n * AWS Cognito authentication provider implementation - v3.0.0\n *\n * Implements the abstract methods from MJAuthBase to hide Cognito-specific details.\n * Uses AWS Amplify v6 (tree-shakeable subpath imports) for authentication.\n *\n * Key abstraction: Cognito stores tokens in Amplify's internal storage, accessed\n * via `fetchAuthSession().tokens?.idToken?.toString()`. Consumers never need to\n * know this detail.\n *\n * ## Cognito Hosted UI Flow\n * This provider uses the Cognito Hosted UI for login via `signInWithRedirect()`.\n * The flow is: redirect to Hosted UI -> user authenticates -> redirect back with\n * authorization code -> Amplify exchanges code for tokens (PKCE).\n */\n@Injectable({\n providedIn: 'root'\n})\n@RegisterClass(MJAuthBase, 'cognito')\nexport class MJCognitoProvider extends MJAuthBase {\n static readonly PROVIDER_TYPE = 'cognito';\n readonly type = MJCognitoProvider.PROVIDER_TYPE;\n private _initialized = false;\n private _hubListenerCancel: (() => void) | null = null;\n\n /**\n * Factory function to provide Angular dependencies required by the Cognito provider.\n * Returns a config injection token following the Okta provider pattern.\n */\n static angularProviderFactory = (environment: Record<string, unknown>) => {\n const isMCPOAuthCallback = window.location.pathname.startsWith('/oauth/callback');\n\n return [\n {\n provide: 'cognitoConfig',\n useValue: {\n userPoolId: environment['COGNITO_USER_POOL_ID'],\n // COGNITO_CLIENTID first: it is the key the catalog overlay emits for a metadata-configured\n // row, and it must beat the compiled environment's canonical COGNITO_CLIENT_ID spelling —\n // otherwise a catalog row's ClientID is silently ignored in favour of the compiled value.\n userPoolClientId: environment['COGNITO_CLIENTID'] || environment['COGNITO_CLIENT_ID'],\n region: environment['COGNITO_REGION'] || environment['AWS_REGION'],\n domain: environment['COGNITO_DOMAIN'],\n redirectUri: environment['COGNITO_REDIRECT_URI'] || window.location.origin,\n scopes: environment['COGNITO_SCOPES'] || ['openid', 'profile', 'email', 'aws.cognito.signin.user.admin'],\n skipRedirectCallback: isMCPOAuthCallback,\n } as CognitoConfig\n }\n ];\n };\n\n constructor(@Inject('cognitoConfig') private cognitoConfig: CognitoConfig) {\n const config: AngularAuthProviderConfig = {\n name: MJCognitoProvider.PROVIDER_TYPE,\n type: MJCognitoProvider.PROVIDER_TYPE\n };\n super(config);\n\n // Configure Amplify with the existing Cognito User Pool\n const redirectUri = this.cognitoConfig.redirectUri || window.location.origin;\n Amplify.configure({\n Auth: {\n Cognito: {\n userPoolId: this.cognitoConfig.userPoolId,\n userPoolClientId: this.cognitoConfig.userPoolClientId,\n loginWith: {\n oauth: {\n domain: this.cognitoConfig.domain,\n scopes: this.cognitoConfig.scopes || ['openid', 'profile', 'email', 'aws.cognito.signin.user.admin'],\n redirectSignIn: [redirectUri],\n redirectSignOut: [redirectUri],\n responseType: 'code', // Authorization code + PKCE for refresh tokens\n }\n }\n }\n }\n });\n }\n\n // ============================================================================\n // LIFECYCLE METHODS\n // ============================================================================\n\n async initialize(): Promise<void> {\n if (this._initialized) {\n return;\n }\n\n // CRITICAL: Skip Amplify's redirect handling on the MCP OAuth callback path.\n // The /oauth/callback path is used by MCP OAuth, not Cognito. If we don't skip,\n // Amplify will consume the authorization code and prevent the MCP OAuth flow.\n if (this.cognitoConfig.skipRedirectCallback) {\n this._initialized = true;\n return;\n }\n\n // Set up Hub listener for reactive auth events\n this._hubListenerCancel = Hub.listen('auth', async ({ payload }) => {\n switch (payload.event) {\n case 'signedIn':\n this.updateAuthState(true);\n await this.refreshUserInfo();\n break;\n case 'signedOut':\n this.updateAuthState(false);\n this.updateUserInfo(null);\n break;\n case 'tokenRefresh':\n console.log('[Cognito] Token refreshed successfully');\n break;\n case 'tokenRefresh_failure':\n console.warn('[Cognito] Token refresh failed');\n break;\n case 'signInWithRedirect':\n console.log('[Cognito] OAuth redirect sign-in completed');\n break;\n case 'signInWithRedirect_failure':\n console.error('[Cognito] OAuth redirect sign-in failed');\n break;\n }\n });\n\n // Check for existing session (page refresh or returning from redirect)\n try {\n const user = await getCurrentUser();\n if (user) {\n this.updateAuthState(true);\n await this.refreshUserInfo();\n }\n } catch {\n // Not authenticated — this is expected on fresh visits\n this.updateAuthState(false);\n }\n\n this._initialized = true;\n }\n\n protected async loginInternal(_options?: Record<string, unknown>): Promise<void> {\n await this.ensureInitialized();\n // Redirect to Cognito Hosted UI. This navigates the browser and never returns.\n await signInWithRedirect();\n }\n\n protected async logoutInternal(): Promise<void> {\n this.updateAuthState(false);\n this.updateUserInfo(null);\n\n // Cancel Hub listener before sign-out to avoid race conditions\n this.cancelHubListener();\n\n await signOut();\n // signOut() clears local tokens. With Hosted UI, it also redirects to the\n // Cognito logout endpoint to clear the Hosted UI session cookie.\n }\n\n async handleCallback(): Promise<void> {\n // Amplify v6 handles OAuth code exchange automatically when it detects\n // ?code= and ?state= in the URL during initialization. The Hub listener\n // catches 'signInWithRedirect' events. This method exists for interface\n // compatibility.\n try {\n const user = await getCurrentUser();\n if (user) {\n this.updateAuthState(true);\n await this.refreshUserInfo();\n }\n } catch {\n // Not authenticated after callback\n }\n }\n\n // ============================================================================\n // ABSTRACT METHOD IMPLEMENTATIONS (v3.0.0)\n // ============================================================================\n\n /**\n * Extract ID token from Cognito via Amplify's fetchAuthSession.\n *\n * Cognito stores the JWT in session.tokens.idToken. The .toString()\n * call extracts the raw JWT string. Consumers never need to know this detail.\n */\n protected async extractIdTokenInternal(): Promise<string | null> {\n try {\n const session = await fetchAuthSession();\n return session.tokens?.idToken?.toString() || null;\n } catch (error) {\n console.error('[Cognito] Error extracting ID token:', error);\n return null;\n }\n }\n\n /**\n * Extract complete token info from Cognito session.\n * Maps Amplify's token structure to StandardAuthToken.\n */\n protected async extractTokenInfoInternal(): Promise<StandardAuthToken | null> {\n try {\n const session = await fetchAuthSession();\n const idToken = session.tokens?.idToken;\n if (!idToken) {\n return null;\n }\n\n const payload = idToken.payload;\n const accessToken = session.tokens?.accessToken;\n\n return {\n idToken: idToken.toString(),\n accessToken: accessToken?.toString(),\n expiresAt: payload?.exp ? (payload.exp as number) * 1000 : 0, // Convert to ms\n scopes: this.extractScopes(accessToken)\n };\n } catch (error) {\n console.error('[Cognito] Error extracting token info:', error);\n return null;\n }\n }\n\n /**\n * Extract user info from Cognito user attributes.\n * Maps Cognito's attribute structure to StandardUserInfo.\n */\n protected async extractUserInfoInternal(): Promise<StandardUserInfo | null> {\n try {\n const user = await getCurrentUser();\n const attributes = await fetchUserAttributes();\n\n return this.mapCognitoAttributesToStandard(user, attributes);\n } catch (error) {\n console.error('[Cognito] Error extracting user info:', error);\n return null;\n }\n }\n\n /**\n * Refresh token using Amplify's fetchAuthSession with forceRefresh.\n *\n * Amplify v6 handles the entire refresh token exchange internally:\n * fetchAuthSession({ forceRefresh: true }) uses the stored refresh token\n * to obtain new ID and access tokens from Cognito.\n */\n protected async refreshTokenInternal(): Promise<TokenRefreshResult> {\n try {\n console.log('[Cognito] Attempting to refresh token...');\n\n const session = await fetchAuthSession({ forceRefresh: true });\n const idToken = session.tokens?.idToken;\n\n if (!idToken) {\n return {\n success: false,\n error: {\n type: AuthErrorType.NO_ACTIVE_SESSION,\n message: 'Token refresh succeeded but no ID token returned',\n userMessage: 'Session refresh failed. Please log in again.'\n }\n };\n }\n\n const payload = idToken.payload;\n const accessToken = session.tokens?.accessToken;\n\n console.log('[Cognito] Token refresh successful', {\n expiresAt: payload?.exp ? new Date((payload.exp as number) * 1000).toISOString() : 'N/A'\n });\n\n return {\n success: true,\n token: {\n idToken: idToken.toString(),\n accessToken: accessToken?.toString(),\n expiresAt: payload?.exp ? (payload.exp as number) * 1000 : 0,\n scopes: this.extractScopes(accessToken)\n }\n };\n } catch (error) {\n console.error('[Cognito] Token refresh failed:', error);\n return {\n success: false,\n error: this.classifyErrorInternal(error)\n };\n }\n }\n\n /**\n * Classify Cognito/Amplify-specific errors into semantic types.\n *\n * Maps Amplify v6 error names and messages to AuthErrorType enum.\n */\n protected classifyErrorInternal(error: unknown): StandardAuthError {\n const errorObj = error as Record<string, unknown>;\n const message = (errorObj?.['message'] as string) || 'Unknown error';\n const name = (errorObj?.['name'] as string) || '';\n\n // Not authenticated / no session\n if (name === 'UserUnAuthenticatedException' ||\n message.includes('not authenticated') ||\n message.includes('No current user') ||\n name === 'UserNotFoundException') {\n return {\n type: AuthErrorType.NO_ACTIVE_SESSION,\n message,\n originalError: error,\n userMessage: 'You need to log in to continue.'\n };\n }\n\n // Token expired / invalid refresh token\n if (name === 'NotAuthorizedException' ||\n message.includes('not authorized') ||\n message.includes('Invalid Refresh Token') ||\n message.includes('expired') ||\n message.includes('invalid_grant')) {\n return {\n type: AuthErrorType.TOKEN_EXPIRED,\n message,\n originalError: error,\n userMessage: 'Your session has expired. Please log in again.'\n };\n }\n\n // User cancelled login\n if (message.includes('cancelled') || message.includes('canceled') ||\n message.includes('user denied')) {\n return {\n type: AuthErrorType.USER_CANCELLED,\n message,\n originalError: error,\n userMessage: 'Login was cancelled.'\n };\n }\n\n // Network errors\n if (message.includes('network') || message.includes('fetch') ||\n message.includes('Network') || message.includes('Load failed')) {\n return {\n type: AuthErrorType.NETWORK_ERROR,\n message,\n originalError: error,\n userMessage: 'Network error. Please check your connection and try again.'\n };\n }\n\n // OAuth configuration errors\n if (name === 'OAuthNotConfigureException' ||\n name === 'AuthTokenConfigException' ||\n message.includes('OAuth') || message.includes('configuration')) {\n return {\n type: AuthErrorType.CONFIGURATION_ERROR,\n message,\n originalError: error,\n userMessage: 'Authentication configuration error. Please contact support.'\n };\n }\n\n // Default to unknown\n return {\n type: AuthErrorType.UNKNOWN_ERROR,\n message,\n originalError: error,\n userMessage: 'An unexpected error occurred. Please try again.'\n };\n }\n\n /**\n * Get profile picture URL from Cognito user attributes.\n *\n * Cognito can store a `picture` attribute if configured in the user pool.\n * Returns null if the attribute is not set.\n */\n protected async getProfilePictureUrlInternal(): Promise<string | null> {\n try {\n const attributes = await fetchUserAttributes();\n return attributes.picture || null;\n } catch (error) {\n console.error('[Cognito] Error getting profile picture:', error);\n return null;\n }\n }\n\n /**\n * Handle session expiry by redirecting to Cognito Hosted UI.\n *\n * Cognito uses refresh tokens (responseType: 'code'), so silent refresh\n * usually works. If it fails, we redirect to the Hosted UI for\n * re-authentication. This will navigate the browser and may never return.\n */\n protected async handleSessionExpiryInternal(): Promise<void> {\n console.log('[Cognito] Session expired, redirecting to Hosted UI for re-authentication');\n await signInWithRedirect();\n // This redirects the page and never returns\n }\n\n // ============================================================================\n // HELPER METHODS\n // ============================================================================\n\n private async ensureInitialized(): Promise<void> {\n if (!this._initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Refresh user info from Cognito and update the reactive state.\n */\n private async refreshUserInfo(): Promise<void> {\n try {\n const userInfo = await this.extractUserInfoInternal();\n if (userInfo) {\n this.updateUserInfo(userInfo);\n }\n } catch (error) {\n console.warn('[Cognito] Failed to refresh user info:', error);\n }\n }\n\n /**\n * Map Cognito user attributes to StandardUserInfo.\n *\n * Cognito attributes use snake_case keys (email, given_name, family_name, etc.)\n * and all values are strings (including booleans like email_verified = 'true').\n */\n private mapCognitoAttributesToStandard(\n user: { userId: string; username: string; signInDetails?: { loginId?: string } },\n attributes: Partial<Record<string, string>>\n ): StandardUserInfo {\n const givenName = attributes['given_name'];\n const familyName = attributes['family_name'];\n const fullName = attributes['name'] ||\n (givenName && familyName ? `${givenName} ${familyName}` : givenName || familyName || '');\n\n return {\n id: user.userId || user.username,\n email: attributes['email'] || '',\n name: fullName,\n givenName,\n familyName,\n preferredUsername: attributes['preferred_username'] || user.username,\n pictureUrl: attributes['picture'],\n emailVerified: attributes['email_verified'] === 'true',\n locale: attributes['locale'],\n };\n }\n\n /**\n * Extract OAuth scopes from an access token's payload.\n */\n private extractScopes(accessToken: { payload?: Record<string, unknown> } | undefined): string[] | undefined {\n const scope = accessToken?.payload?.['scope'];\n if (typeof scope === 'string') {\n return scope.split(' ');\n }\n return undefined;\n }\n\n /**\n * Cancel the Hub event listener if active.\n */\n private cancelHubListener(): void {\n if (this._hubListenerCancel) {\n this._hubListenerCancel();\n this._hubListenerCancel = null;\n }\n }\n\n // ============================================================================\n // CONFIGURATION\n // ============================================================================\n\n override getRequiredConfig(): string[] {\n return ['userPoolId', 'userPoolClientId', 'domain'];\n }\n\n override validateConfig(config: Record<string, unknown>): boolean {\n return !!(config['userPoolId'] && config['userPoolClientId'] && config['domain']);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mjexplorer-cognito-provider.service.js","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-cognito-provider.service.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7D,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EACL,kBAAkB,EAClB,OAAO,EACP,gBAAgB,EAChB,cAAc,EACd,mBAAmB,EACpB,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACxC,OAAO,EAIL,aAAa,EAEd,MAAM,eAAe,CAAC;;AAoBvB;;;;;;;;;;;;;;GAcG;AAKI,IAAM,iBAAiB,GAAvB,MAAM,iBAAkB,SAAQ,UAAU;;IAyCF;IAxC7C,MAAM,CAAU,aAAa,GAAG,SAAS,CAAC;IACjC,IAAI,GAAG,mBAAiB,CAAC,aAAa,CAAC;IACxC,YAAY,GAAG,KAAK,CAAC;IACrB,kBAAkB,GAAwB,IAAI,CAAC;IAEvD;;;OAGG;IACH,MAAM,CAAC,sBAAsB,GAAG,CAAC,WAAoC,EAAE,EAAE;QACvE,MAAM,kBAAkB,GAAG,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,UAAU,CAAC,iBAAiB,CAAC,CAAC;QAElF,OAAO;YACL;gBACE,OAAO,EAAE,eAAe;gBACxB,QAAQ,EAAE;oBACR,UAAU,EAAE,WAAW,CAAC,sBAAsB,CAAC;oBAC/C,4FAA4F;oBAC5F,0FAA0F;oBAC1F,0FAA0F;oBAC1F,gBAAgB,EAAE,WAAW,CAAC,kBAAkB,CAAC,IAAI,WAAW,CAAC,mBAAmB,CAAC;oBACrF,MAAM,EAAE,WAAW,CAAC,gBAAgB,CAA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iBAAiB,mBAHhB,MAAM;;AAGP,iBAAiB;IAD7B,aAAa,CAAC,UAAU,EAAE,SAAS,CAAC;GACxB,iBAAiB,CAmd7B;;iFAndY,iBAAiB;cAJ7B,UAAU;eAAC;gBACV,UAAU,EAAE,MAAM;aACnB;;sBA2Cc,MAAM;uBAAC,eAAe","sourcesContent":["import { Injectable, Inject } from '@angular/core';\nimport { RegisterClass } from '@memberjunction/global';\nimport { MJAuthBase } from '../mjexplorer-auth-base.service';\nimport { AngularAuthProviderConfig } from '../IAuthProvider';\nimport { Amplify } from 'aws-amplify';\nimport {\n signInWithRedirect,\n signOut,\n fetchAuthSession,\n getCurrentUser,\n fetchUserAttributes\n} from 'aws-amplify/auth';\nimport { Hub } from 'aws-amplify/utils';\nimport {\n StandardUserInfo,\n StandardAuthToken,\n StandardAuthError,\n AuthErrorType,\n TokenRefreshResult\n} from '../auth-types';\n\n/**\n * Configuration interface for the Cognito provider.\n * Populated from environment config via the `angularProviderFactory`.\n */\ninterface CognitoConfig {\n userPoolId: string;\n userPoolClientId: string;\n region?: string;\n /** Cognito Hosted UI domain, e.g. 'myapp.auth.us-east-1.amazoncognito.com' */\n domain: string;\n /** OAuth redirect URI. Defaults to window.location.origin */\n redirectUri?: string;\n /** OAuth scopes. Defaults to ['openid', 'profile', 'email'] */\n scopes?: string[];\n /** When true, skips redirect callback processing (for MCP OAuth callback path) */\n skipRedirectCallback?: boolean;\n}\n\n/**\n * AWS Cognito authentication provider implementation - v3.0.0\n *\n * Implements the abstract methods from MJAuthBase to hide Cognito-specific details.\n * Uses AWS Amplify v6 (tree-shakeable subpath imports) for authentication.\n *\n * Key abstraction: Cognito stores tokens in Amplify's internal storage, accessed\n * via `fetchAuthSession().tokens?.idToken?.toString()`. Consumers never need to\n * know this detail.\n *\n * ## Cognito Hosted UI Flow\n * This provider uses the Cognito Hosted UI for login via `signInWithRedirect()`.\n * The flow is: redirect to Hosted UI -> user authenticates -> redirect back with\n * authorization code -> Amplify exchanges code for tokens (PKCE).\n */\n@Injectable({\n providedIn: 'root'\n})\n@RegisterClass(MJAuthBase, 'cognito')\nexport class MJCognitoProvider extends MJAuthBase {\n static readonly PROVIDER_TYPE = 'cognito';\n readonly type = MJCognitoProvider.PROVIDER_TYPE;\n private _initialized = false;\n private _hubListenerCancel: (() => void) | null = null;\n\n /**\n * Factory function to provide Angular dependencies required by the Cognito provider.\n * Returns a config injection token following the Okta provider pattern.\n */\n static AngularProviderFactory = (environment: Record<string, unknown>) => {\n const isMCPOAuthCallback = window.location.pathname.startsWith('/oauth/callback');\n\n return [\n {\n provide: 'cognitoConfig',\n useValue: {\n userPoolId: environment['COGNITO_USER_POOL_ID'],\n // COGNITO_CLIENTID first: it is the key the catalog overlay emits for a metadata-configured\n // row, and it must beat the compiled environment's canonical COGNITO_CLIENT_ID spelling —\n // otherwise a catalog row's ClientID is silently ignored in favour of the compiled value.\n userPoolClientId: environment['COGNITO_CLIENTID'] || environment['COGNITO_CLIENT_ID'],\n region: environment['COGNITO_REGION'] || environment['AWS_REGION'],\n domain: environment['COGNITO_DOMAIN'],\n redirectUri: environment['COGNITO_REDIRECT_URI'] || window.location.origin,\n scopes: environment['COGNITO_SCOPES'] || ['openid', 'profile', 'email', 'aws.cognito.signin.user.admin'],\n skipRedirectCallback: isMCPOAuthCallback,\n } as CognitoConfig\n }\n ];\n };\n\n /** @deprecated Use {@link AngularProviderFactory}. */\n static get angularProviderFactory() {\n return this.AngularProviderFactory;\n }\n /** @deprecated Use {@link AngularProviderFactory}. */\n static set angularProviderFactory(value) {\n this.AngularProviderFactory = value;\n }\n\n constructor(@Inject('cognitoConfig') private cognitoConfig: CognitoConfig) {\n const config: AngularAuthProviderConfig = {\n name: MJCognitoProvider.PROVIDER_TYPE,\n type: MJCognitoProvider.PROVIDER_TYPE\n };\n super(config);\n\n // Configure Amplify with the existing Cognito User Pool\n const redirectUri = this.cognitoConfig.redirectUri || window.location.origin;\n Amplify.configure({\n Auth: {\n Cognito: {\n userPoolId: this.cognitoConfig.userPoolId,\n userPoolClientId: this.cognitoConfig.userPoolClientId,\n loginWith: {\n oauth: {\n domain: this.cognitoConfig.domain,\n scopes: this.cognitoConfig.scopes || ['openid', 'profile', 'email', 'aws.cognito.signin.user.admin'],\n redirectSignIn: [redirectUri],\n redirectSignOut: [redirectUri],\n responseType: 'code', // Authorization code + PKCE for refresh tokens\n }\n }\n }\n }\n });\n }\n\n // ============================================================================\n // LIFECYCLE METHODS\n // ============================================================================\n\n async initialize(): Promise<void> {\n if (this._initialized) {\n return;\n }\n\n // CRITICAL: Skip Amplify's redirect handling on the MCP OAuth callback path.\n // The /oauth/callback path is used by MCP OAuth, not Cognito. If we don't skip,\n // Amplify will consume the authorization code and prevent the MCP OAuth flow.\n if (this.cognitoConfig.skipRedirectCallback) {\n this._initialized = true;\n return;\n }\n\n // Set up Hub listener for reactive auth events\n this._hubListenerCancel = Hub.listen('auth', async ({ payload }) => {\n switch (payload.event) {\n case 'signedIn':\n this.updateAuthState(true);\n await this.refreshUserInfo();\n break;\n case 'signedOut':\n this.updateAuthState(false);\n this.updateUserInfo(null);\n break;\n case 'tokenRefresh':\n console.log('[Cognito] Token refreshed successfully');\n break;\n case 'tokenRefresh_failure':\n console.warn('[Cognito] Token refresh failed');\n break;\n case 'signInWithRedirect':\n console.log('[Cognito] OAuth redirect sign-in completed');\n break;\n case 'signInWithRedirect_failure':\n console.error('[Cognito] OAuth redirect sign-in failed');\n break;\n }\n });\n\n // Check for existing session (page refresh or returning from redirect)\n try {\n const user = await getCurrentUser();\n if (user) {\n this.updateAuthState(true);\n await this.refreshUserInfo();\n }\n } catch {\n // Not authenticated — this is expected on fresh visits\n this.updateAuthState(false);\n }\n\n this._initialized = true;\n }\n\n protected async loginInternal(_options?: Record<string, unknown>): Promise<void> {\n await this.ensureInitialized();\n // Redirect to Cognito Hosted UI. This navigates the browser and never returns.\n await signInWithRedirect();\n }\n\n protected async logoutInternal(): Promise<void> {\n this.updateAuthState(false);\n this.updateUserInfo(null);\n\n // Cancel Hub listener before sign-out to avoid race conditions\n this.cancelHubListener();\n\n await signOut();\n // signOut() clears local tokens. With Hosted UI, it also redirects to the\n // Cognito logout endpoint to clear the Hosted UI session cookie.\n }\n\n async handleCallback(): Promise<void> {\n // Amplify v6 handles OAuth code exchange automatically when it detects\n // ?code= and ?state= in the URL during initialization. The Hub listener\n // catches 'signInWithRedirect' events. This method exists for interface\n // compatibility.\n try {\n const user = await getCurrentUser();\n if (user) {\n this.updateAuthState(true);\n await this.refreshUserInfo();\n }\n } catch {\n // Not authenticated after callback\n }\n }\n\n // ============================================================================\n // ABSTRACT METHOD IMPLEMENTATIONS (v3.0.0)\n // ============================================================================\n\n /**\n * Extract ID token from Cognito via Amplify's fetchAuthSession.\n *\n * Cognito stores the JWT in session.tokens.idToken. The .toString()\n * call extracts the raw JWT string. Consumers never need to know this detail.\n */\n protected async extractIdTokenInternal(): Promise<string | null> {\n try {\n const session = await fetchAuthSession();\n return session.tokens?.idToken?.toString() || null;\n } catch (error) {\n console.error('[Cognito] Error extracting ID token:', error);\n return null;\n }\n }\n\n /**\n * Extract complete token info from Cognito session.\n * Maps Amplify's token structure to StandardAuthToken.\n */\n protected async extractTokenInfoInternal(): Promise<StandardAuthToken | null> {\n try {\n const session = await fetchAuthSession();\n const idToken = session.tokens?.idToken;\n if (!idToken) {\n return null;\n }\n\n const payload = idToken.payload;\n const accessToken = session.tokens?.accessToken;\n\n return {\n idToken: idToken.toString(),\n accessToken: accessToken?.toString(),\n expiresAt: payload?.exp ? (payload.exp as number) * 1000 : 0, // Convert to ms\n scopes: this.extractScopes(accessToken)\n };\n } catch (error) {\n console.error('[Cognito] Error extracting token info:', error);\n return null;\n }\n }\n\n /**\n * Extract user info from Cognito user attributes.\n * Maps Cognito's attribute structure to StandardUserInfo.\n */\n protected async extractUserInfoInternal(): Promise<StandardUserInfo | null> {\n try {\n const user = await getCurrentUser();\n const attributes = await fetchUserAttributes();\n\n return this.mapCognitoAttributesToStandard(user, attributes);\n } catch (error) {\n console.error('[Cognito] Error extracting user info:', error);\n return null;\n }\n }\n\n /**\n * Refresh token using Amplify's fetchAuthSession with forceRefresh.\n *\n * Amplify v6 handles the entire refresh token exchange internally:\n * fetchAuthSession({ forceRefresh: true }) uses the stored refresh token\n * to obtain new ID and access tokens from Cognito.\n */\n protected async refreshTokenInternal(): Promise<TokenRefreshResult> {\n try {\n console.log('[Cognito] Attempting to refresh token...');\n\n const session = await fetchAuthSession({ forceRefresh: true });\n const idToken = session.tokens?.idToken;\n\n if (!idToken) {\n return {\n success: false,\n error: {\n type: AuthErrorType.NO_ACTIVE_SESSION,\n message: 'Token refresh succeeded but no ID token returned',\n userMessage: 'Session refresh failed. Please log in again.'\n }\n };\n }\n\n const payload = idToken.payload;\n const accessToken = session.tokens?.accessToken;\n\n console.log('[Cognito] Token refresh successful', {\n expiresAt: payload?.exp ? new Date((payload.exp as number) * 1000).toISOString() : 'N/A'\n });\n\n return {\n success: true,\n token: {\n idToken: idToken.toString(),\n accessToken: accessToken?.toString(),\n expiresAt: payload?.exp ? (payload.exp as number) * 1000 : 0,\n scopes: this.extractScopes(accessToken)\n }\n };\n } catch (error) {\n console.error('[Cognito] Token refresh failed:', error);\n return {\n success: false,\n error: this.classifyErrorInternal(error)\n };\n }\n }\n\n /**\n * Classify Cognito/Amplify-specific errors into semantic types.\n *\n * Maps Amplify v6 error names and messages to AuthErrorType enum.\n */\n protected classifyErrorInternal(error: unknown): StandardAuthError {\n const errorObj = error as Record<string, unknown>;\n const message = (errorObj?.['message'] as string) || 'Unknown error';\n const name = (errorObj?.['name'] as string) || '';\n\n // Not authenticated / no session\n if (name === 'UserUnAuthenticatedException' ||\n message.includes('not authenticated') ||\n message.includes('No current user') ||\n name === 'UserNotFoundException') {\n return {\n type: AuthErrorType.NO_ACTIVE_SESSION,\n message,\n originalError: error,\n userMessage: 'You need to log in to continue.'\n };\n }\n\n // Token expired / invalid refresh token\n if (name === 'NotAuthorizedException' ||\n message.includes('not authorized') ||\n message.includes('Invalid Refresh Token') ||\n message.includes('expired') ||\n message.includes('invalid_grant')) {\n return {\n type: AuthErrorType.TOKEN_EXPIRED,\n message,\n originalError: error,\n userMessage: 'Your session has expired. Please log in again.'\n };\n }\n\n // User cancelled login\n if (message.includes('cancelled') || message.includes('canceled') ||\n message.includes('user denied')) {\n return {\n type: AuthErrorType.USER_CANCELLED,\n message,\n originalError: error,\n userMessage: 'Login was cancelled.'\n };\n }\n\n // Network errors\n if (message.includes('network') || message.includes('fetch') ||\n message.includes('Network') || message.includes('Load failed')) {\n return {\n type: AuthErrorType.NETWORK_ERROR,\n message,\n originalError: error,\n userMessage: 'Network error. Please check your connection and try again.'\n };\n }\n\n // OAuth configuration errors\n if (name === 'OAuthNotConfigureException' ||\n name === 'AuthTokenConfigException' ||\n message.includes('OAuth') || message.includes('configuration')) {\n return {\n type: AuthErrorType.CONFIGURATION_ERROR,\n message,\n originalError: error,\n userMessage: 'Authentication configuration error. Please contact support.'\n };\n }\n\n // Default to unknown\n return {\n type: AuthErrorType.UNKNOWN_ERROR,\n message,\n originalError: error,\n userMessage: 'An unexpected error occurred. Please try again.'\n };\n }\n\n /**\n * Get profile picture URL from Cognito user attributes.\n *\n * Cognito can store a `picture` attribute if configured in the user pool.\n * Returns null if the attribute is not set.\n */\n protected async getProfilePictureUrlInternal(): Promise<string | null> {\n try {\n const attributes = await fetchUserAttributes();\n return attributes.picture || null;\n } catch (error) {\n console.error('[Cognito] Error getting profile picture:', error);\n return null;\n }\n }\n\n /**\n * Handle session expiry by redirecting to Cognito Hosted UI.\n *\n * Cognito uses refresh tokens (responseType: 'code'), so silent refresh\n * usually works. If it fails, we redirect to the Hosted UI for\n * re-authentication. This will navigate the browser and may never return.\n */\n protected async handleSessionExpiryInternal(): Promise<void> {\n console.log('[Cognito] Session expired, redirecting to Hosted UI for re-authentication');\n await signInWithRedirect();\n // This redirects the page and never returns\n }\n\n // ============================================================================\n // HELPER METHODS\n // ============================================================================\n\n private async ensureInitialized(): Promise<void> {\n if (!this._initialized) {\n await this.initialize();\n }\n }\n\n /**\n * Refresh user info from Cognito and update the reactive state.\n */\n private async refreshUserInfo(): Promise<void> {\n try {\n const userInfo = await this.extractUserInfoInternal();\n if (userInfo) {\n this.updateUserInfo(userInfo);\n }\n } catch (error) {\n console.warn('[Cognito] Failed to refresh user info:', error);\n }\n }\n\n /**\n * Map Cognito user attributes to StandardUserInfo.\n *\n * Cognito attributes use snake_case keys (email, given_name, family_name, etc.)\n * and all values are strings (including booleans like email_verified = 'true').\n */\n private mapCognitoAttributesToStandard(\n user: { userId: string; username: string; signInDetails?: { loginId?: string } },\n attributes: Partial<Record<string, string>>\n ): StandardUserInfo {\n const givenName = attributes['given_name'];\n const familyName = attributes['family_name'];\n const fullName = attributes['name'] ||\n (givenName && familyName ? `${givenName} ${familyName}` : givenName || familyName || '');\n\n return {\n id: user.userId || user.username,\n email: attributes['email'] || '',\n name: fullName,\n givenName,\n familyName,\n preferredUsername: attributes['preferred_username'] || user.username,\n pictureUrl: attributes['picture'],\n emailVerified: attributes['email_verified'] === 'true',\n locale: attributes['locale'],\n };\n }\n\n /**\n * Extract OAuth scopes from an access token's payload.\n */\n private extractScopes(accessToken: { payload?: Record<string, unknown> } | undefined): string[] | undefined {\n const scope = accessToken?.payload?.['scope'];\n if (typeof scope === 'string') {\n return scope.split(' ');\n }\n return undefined;\n }\n\n /**\n * Cancel the Hub event listener if active.\n */\n private cancelHubListener(): void {\n if (this._hubListenerCancel) {\n this._hubListenerCancel();\n this._hubListenerCancel = null;\n }\n }\n\n // ============================================================================\n // CONFIGURATION\n // ============================================================================\n\n override getRequiredConfig(): string[] {\n return ['userPoolId', 'userPoolClientId', 'domain'];\n }\n\n override validateConfig(config: Record<string, unknown>): boolean {\n return !!(config['userPoolId'] && config['userPoolClientId'] && config['domain']);\n }\n}\n"]}
|
|
@@ -33,6 +33,8 @@ export declare class MJMagicLinkProvider extends MJAuthBase {
|
|
|
33
33
|
* Falls back cleanly to the primary IdP when no token is present (e.g. after a
|
|
34
34
|
* guest's session expires or logs out).
|
|
35
35
|
*/
|
|
36
|
+
static HasSessionToken(): boolean;
|
|
37
|
+
/** @deprecated Use {@link HasSessionToken}. */
|
|
36
38
|
static hasSessionToken(): boolean;
|
|
37
39
|
initialize(): Promise<void>;
|
|
38
40
|
protected loginInternal(): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mjexplorer-magic-link-provider.service.d.ts","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-magic-link-provider.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAEjB,kBAAkB,EAClB,YAAY,EAEb,MAAM,eAAe,CAAC;;AAKvB;;;;;;;;;;;;;;GAcG;AACH,qBAEa,mBAAoB,SAAQ,UAAU;IACjD,MAAM,CAAC,QAAQ,CAAC,aAAa,gBAAgB;IAC7C,QAAQ,CAAC,IAAI,gBAAqC;IAElD,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,MAAM,CAAuC;;IAMrD;;;;;;;;;;OAUG;IACH,MAAM,CAAC,eAAe,IAAI,OAAO;
|
|
1
|
+
{"version":3,"file":"mjexplorer-magic-link-provider.service.d.ts","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-magic-link-provider.service.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAEjB,kBAAkB,EAClB,YAAY,EAEb,MAAM,eAAe,CAAC;;AAKvB;;;;;;;;;;;;;;GAcG;AACH,qBAEa,mBAAoB,SAAQ,UAAU;IACjD,MAAM,CAAC,QAAQ,CAAC,aAAa,gBAAgB;IAC7C,QAAQ,CAAC,IAAI,gBAAqC;IAElD,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,MAAM,CAAuC;;IAMrD;;;;;;;;;;OAUG;IACH,MAAM,CAAC,eAAe,IAAI,OAAO;IAgBjC,+CAA+C;IAC/C,MAAM,CAAC,eAAe,IAAI,OAAO;IAI3B,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;cAiCjB,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;cAK9B,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;IAQzC,cAAc,IAAI,OAAO,CAAC,IAAI,CAAC;cAIrB,sBAAsB,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;cAIhD,wBAAwB,IAAI,OAAO,CAAC,iBAAiB,GAAG,IAAI,CAAC;cAU7D,uBAAuB,IAAI,OAAO,CAAC,gBAAgB,GAAG,IAAI,CAAC;cAI3D,oBAAoB,IAAI,OAAO,CAAC,kBAAkB,CAAC;IAiBnE,SAAS,CAAC,qBAAqB,CAAC,KAAK,EAAE,OAAO,GAAG,iBAAiB;cAKlD,4BAA4B,IAAI,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;cAItD,2BAA2B,IAAI,OAAO,CAAC,IAAI,CAAC;IAI5D;;;OAGG;IACM,eAAe,IAAI,YAAY,GAAG,IAAI;IAQtC,iBAAiB,IAAI,MAAM,EAAE;IAI7B,cAAc,IAAI,OAAO;IAMlC,0DAA0D;IAC1D,OAAO,CAAC,iBAAiB;IAQzB,gEAAgE;IAChE,OAAO,CAAC,SAAS;IAIjB;;;;OAIG;IACH,OAAO,CAAC,MAAM;IAsBd,OAAO,CAAC,SAAS;IAKjB,OAAO,CAAC,UAAU;yCAjNP,mBAAmB;6CAAnB,mBAAmB;CAgO/B"}
|
|
@@ -47,7 +47,7 @@ let MJMagicLinkProvider = class MJMagicLinkProvider extends MJAuthBase {
|
|
|
47
47
|
* Falls back cleanly to the primary IdP when no token is present (e.g. after a
|
|
48
48
|
* guest's session expires or logs out).
|
|
49
49
|
*/
|
|
50
|
-
static
|
|
50
|
+
static HasSessionToken() {
|
|
51
51
|
if (typeof window === 'undefined') {
|
|
52
52
|
return false;
|
|
53
53
|
}
|
|
@@ -63,6 +63,10 @@ let MJMagicLinkProvider = class MJMagicLinkProvider extends MJAuthBase {
|
|
|
63
63
|
return false;
|
|
64
64
|
}
|
|
65
65
|
}
|
|
66
|
+
/** @deprecated Use {@link HasSessionToken}. */
|
|
67
|
+
static hasSessionToken() {
|
|
68
|
+
return this.HasSessionToken();
|
|
69
|
+
}
|
|
66
70
|
async initialize() {
|
|
67
71
|
// Token may arrive in the URL fragment from the redeem redirect, or already
|
|
68
72
|
// be stored from earlier in this tab's session.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mjexplorer-magic-link-provider.service.js","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-magic-link-provider.service.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAIL,aAAa,GAId,MAAM,eAAe,CAAC;;AAEvB,4EAA4E;AAC5E,MAAM,iBAAiB,GAAG,qBAAqB,CAAC;AAEhD;;;;;;;;;;;;;;GAcG;AAGI,IAAM,mBAAmB,GAAzB,MAAM,mBAAoB,SAAQ,UAAU;;IACjD,MAAM,CAAU,aAAa,GAAG,YAAY,CAAC;IACpC,IAAI,GAAG,qBAAmB,CAAC,aAAa,CAAC;IAE1C,KAAK,GAAkB,IAAI,CAAC;IAC5B,MAAM,GAAkC,IAAI,CAAC;IAErD;QACE,KAAK,CAAC,EAAE,IAAI,EAAE,qBAAmB,CAAC,aAAa,EAAE,IAAI,EAAE,qBAAmB,CAAC,aAAa,EAAE,CAAC,CAAC;IAC9F,CAAC;IAED;;;;;;;;;;OAUG;IACH,MAAM,CAAC,eAAe;QACpB,IAAI,OAAO,MAAM,KAAK,WAAW,E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C,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;iBAC/D,IAAI,CAAC,EAAE,CAAC,CACZ,CAAC;YACF,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAA2B,CAAC;QACpD,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,4EAA4E;YAC5E,OAAO,CAAC,KAAK,CAAC,6CAA6C,EAAE,CAAC,CAAC,CAAC;YAChE,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IAEO,SAAS;QACf,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC;QAC7B,OAAO,CAAC,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE,IAAI,GAAG,GAAG,IAAI,CAAC;IAC3C,CAAC;IAEO,UAAU,CAAC,MAAqC;QACtD,IAAI,CAAC,MAAM,EAAE,CAAC;YACZ,OAAO,IAAI,CAAC;QACd,CAAC;QACD,MAAM,KAAK,GAAG,MAAM,CAAC,KAAK,IAAI,EAAE,CAAC;QACjC,OAAO;YACL,EAAE,EAAE,MAAM,CAAC,GAAG,IAAI,KAAK;YACvB,KAAK;YACL,IAAI,EAAE,MAAM,CAAC,IAAI,IAAI,KAAK;YAC1B,SAAS,EAAE,MAAM,CAAC,UAAU;YAC5B,UAAU,EAAE,MAAM,CAAC,WAAW;YAC9B,iBAAiB,EAAE,KAAK;YACxB,aAAa,EAAE,IAAI;SACpB,CAAC;IACJ,CAAC;6GA1NU,mBAAmB;gEAAnB,mBAAmB,WAAnB,mBAAmB,mBAFN,MAAM;;AAEnB,mBAAmB;IAD/B,aAAa,CAAC,UAAU,EAAE,YAAY,CAAC;GAC3B,mBAAmB,CA2N/B;;iFA3NY,mBAAmB;cAF/B,UAAU;eAAC,EAAE,UAAU,EAAE,MAAM,EAAE","sourcesContent":["import { Injectable } from '@angular/core';\nimport { RegisterClass } from '@memberjunction/global';\nimport { MJAuthBase } from '../mjexplorer-auth-base.service';\nimport {\n StandardUserInfo,\n StandardAuthToken,\n StandardAuthError,\n AuthErrorType,\n TokenRefreshResult,\n SessionScope,\n MagicLinkSessionClaims,\n} from '../auth-types';\n\n/** sessionStorage key holding the magic-link session token for this tab. */\nconst TOKEN_STORAGE_KEY = 'mj_magic_link_token';\n\n/**\n * Client-side auth provider for MemberJunction-issued magic-link sessions.\n *\n * Unlike MSAL/Auth0, there is no interactive login and no SDK: the session\n * token (minted server-side when the user redeemed their invite) arrives in the\n * URL fragment — `#token=<jwt>` — when `/magic-link/redeem` redirects the\n * browser to Explorer. This provider extracts it, stashes it in sessionStorage\n * (per-tab, so it dies with the tab), decodes the claims for display, and hands\n * the token to the GraphQL client via `getIdToken()`. The server validates it\n * through the standard JWKS path.\n *\n * Set `AUTH_TYPE: 'magic-link'` in the Explorer environment to use this\n * provider. There are no refresh tokens — when the session expires the user\n * must redeem a fresh link.\n */\n@Injectable({ providedIn: 'root' })\n@RegisterClass(MJAuthBase, 'magic-link')\nexport class MJMagicLinkProvider extends MJAuthBase {\n static readonly PROVIDER_TYPE = 'magic-link';\n readonly type = MJMagicLinkProvider.PROVIDER_TYPE;\n\n private token: string | null = null;\n private claims: MagicLinkSessionClaims | null = null;\n\n constructor() {\n super({ name: MJMagicLinkProvider.PROVIDER_TYPE, type: MJMagicLinkProvider.PROVIDER_TYPE });\n }\n\n /**\n * True if a magic-link session token is present for this page load — either\n * arriving in the URL fragment (`#token=<jwt>`, from the redeem redirect) or\n * already stashed in sessionStorage from earlier in this tab.\n *\n * Used at module-config time (`AuthServicesModule.forRoot`) to auto-select the\n * magic-link provider even when `AUTH_TYPE` names a different primary IdP, so a\n * single Explorer deployment can serve both SSO users and magic-link guests.\n * Falls back cleanly to the primary IdP when no token is present (e.g. after a\n * guest's session expires or logs out).\n */\n static hasSessionToken(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n try {\n const hash = window.location?.hash ?? '';\n const fragment = hash.startsWith('#') ? hash.slice(1) : hash;\n if (new URLSearchParams(fragment).get('token')) {\n return true;\n }\n return !!window.sessionStorage?.getItem(TOKEN_STORAGE_KEY);\n } catch {\n return false;\n }\n }\n\n async initialize(): Promise<void> {\n // Token may arrive in the URL fragment from the redeem redirect, or already\n // be stored from earlier in this tab's session.\n const fromHash = this.readTokenFromHash();\n const stored = sessionStorage.getItem(TOKEN_STORAGE_KEY);\n const token = fromHash ?? stored;\n\n if (!token) {\n this.updateAuthState(false);\n return;\n }\n\n this.token = token;\n this.claims = this.decode(token);\n\n if (fromHash) {\n sessionStorage.setItem(TOKEN_STORAGE_KEY, token);\n this.stripHash(); // remove the token from the visible URL\n }\n\n if (this.isExpired()) {\n // Stale token — treat as logged out so the user is prompted for a fresh link.\n sessionStorage.removeItem(TOKEN_STORAGE_KEY);\n this.token = null;\n this.claims = null;\n this.updateAuthState(false);\n return;\n }\n\n this.updateUserInfo(this.toUserInfo(this.claims));\n this.updateAuthState(true);\n }\n\n protected async loginInternal(): Promise<void> {\n // No interactive login path — access is only via a magic-link redemption URL.\n this.updateAuthState(false);\n }\n\n protected async logoutInternal(): Promise<void> {\n sessionStorage.removeItem(TOKEN_STORAGE_KEY);\n this.token = null;\n this.claims = null;\n this.updateUserInfo(null);\n this.updateAuthState(false);\n }\n\n async handleCallback(): Promise<void> {\n // No OAuth callback for magic links.\n }\n\n protected async extractIdTokenInternal(): Promise<string | null> {\n return this.token ?? sessionStorage.getItem(TOKEN_STORAGE_KEY);\n }\n\n protected async extractTokenInfoInternal(): Promise<StandardAuthToken | null> {\n const idToken = await this.extractIdTokenInternal();\n if (!idToken) {\n return null;\n }\n const claims = this.claims ?? this.decode(idToken);\n const exp = claims?.exp;\n return { idToken, expiresAt: exp ? exp * 1000 : 0 };\n }\n\n protected async extractUserInfoInternal(): Promise<StandardUserInfo | null> {\n return this.toUserInfo(this.claims);\n }\n\n protected async refreshTokenInternal(): Promise<TokenRefreshResult> {\n // No refresh tokens for magic-link sessions. Hand back the current token\n // while it's valid; once expired, signal TOKEN_EXPIRED.\n const token = await this.extractTokenInfoInternal();\n if (token && !this.isExpired()) {\n return { success: true, token };\n }\n return {\n success: false,\n error: {\n type: AuthErrorType.TOKEN_EXPIRED,\n message: 'Magic-link session expired',\n userMessage: 'Your access link has expired. Please request a new one.',\n },\n };\n }\n\n protected classifyErrorInternal(error: unknown): StandardAuthError {\n const message = (error as { message?: string })?.message ?? 'Unknown error';\n return { type: AuthErrorType.UNKNOWN_ERROR, message, originalError: error };\n }\n\n protected async getProfilePictureUrlInternal(): Promise<string | null> {\n return null;\n }\n\n protected async handleSessionExpiryInternal(): Promise<void> {\n // No interactive re-auth — the user must redeem a fresh link.\n }\n\n /**\n * Magic-link sessions are locked to the single app the invite scoped to\n * (`mj_app_id`), so the shell hides app-switching and keeps the user there.\n */\n override GetSessionScope(): SessionScope | null {\n const appId = this.claims?.mj_app_id;\n if (this.claims?.mj_magic_link === true && appId) {\n return { restrictedToApplicationId: appId, magicLink: true };\n }\n return null;\n }\n\n override getRequiredConfig(): string[] {\n return [];\n }\n\n override validateConfig(): boolean {\n return true;\n }\n\n // ── helpers ────────────────────────────────────────────────────────────────\n\n /** Reads `token` from the URL fragment (`#token=...`). */\n private readTokenFromHash(): string | null {\n const hash = window.location.hash;\n if (!hash) {\n return null;\n }\n return new URLSearchParams(hash.replace(/^#/, '')).get('token');\n }\n\n /** Removes the token from the address bar without reloading. */\n private stripHash(): void {\n history.replaceState(null, '', window.location.pathname + window.location.search);\n }\n\n /**\n * Decodes a JWT payload (no verification — the server validates via JWKS).\n * UTF-8-safe: external users routinely have non-ASCII names, which a plain\n * `atob` would mangle. Also restores base64url padding `atob` needs.\n */\n private decode(token: string): MagicLinkSessionClaims | null {\n try {\n const segment = token.split('.')[1];\n if (!segment) {\n return null;\n }\n let b64 = segment.replace(/-/g, '+').replace(/_/g, '/');\n b64 += '='.repeat((4 - (b64.length % 4)) % 4);\n const json = decodeURIComponent(\n atob(b64)\n .split('')\n .map((c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))\n .join(''),\n );\n return JSON.parse(json) as MagicLinkSessionClaims;\n } catch (e) {\n // A malformed token must not be silently indistinguishable from \"no token\".\n console.error('[MagicLink] Failed to decode session token:', e);\n return null;\n }\n }\n\n private isExpired(): boolean {\n const exp = this.claims?.exp;\n return !!exp && Date.now() >= exp * 1000;\n }\n\n private toUserInfo(claims: MagicLinkSessionClaims | null): StandardUserInfo | null {\n if (!claims) {\n return null;\n }\n const email = claims.email || '';\n return {\n id: claims.sub || email,\n email,\n name: claims.name || email,\n givenName: claims.given_name,\n familyName: claims.family_name,\n preferredUsername: email,\n emailVerified: true,\n };\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"mjexplorer-magic-link-provider.service.js","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-magic-link-provider.service.ts"],"names":[],"mappings":";;;;;;;AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AACvD,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAIL,aAAa,GAId,MAAM,eAAe,CAAC;;AAEvB,4EAA4E;AAC5E,MAAM,iBAAiB,GAAG,qBAAqB,CAAC;AAEhD;;;;;;;;;;;;;;GAcG;AAGI,IAAM,mBAAmB,GAAzB,MAAM,mBAAoB,SAAQ,UAAU;;IACjD,MAAM,CAAU,aAAa,GAAG,YAAY,CAAC;IACpC,IAAI,GAAG,qBAAmB,CAAC,aAAa,CAAC;IAE1C,KAAK,GAAkB,IAAI,CAAC;IAC5B,MAAM,GAAkC,IAAI,CAAC;IAErD;QACE,KAAK,CAAC,EAAE,IAAI,EAAE,qBAAmB,CAAC,aAAa,EAAE,IAAI,EAAE,qBAAmB,CAAC,aAAa,EAAE,CAAC,CAAC;IAC9F,CAAC;IAED;;;;;;;;;;OAUG;IACH,MAAM,CAAC,eAAe;QACpB,IAAI,OAAO,MAAM,KAAK,WAAW,EAAE,CAA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":["import { Injectable } from '@angular/core';\nimport { RegisterClass } from '@memberjunction/global';\nimport { MJAuthBase } from '../mjexplorer-auth-base.service';\nimport {\n StandardUserInfo,\n StandardAuthToken,\n StandardAuthError,\n AuthErrorType,\n TokenRefreshResult,\n SessionScope,\n MagicLinkSessionClaims,\n} from '../auth-types';\n\n/** sessionStorage key holding the magic-link session token for this tab. */\nconst TOKEN_STORAGE_KEY = 'mj_magic_link_token';\n\n/**\n * Client-side auth provider for MemberJunction-issued magic-link sessions.\n *\n * Unlike MSAL/Auth0, there is no interactive login and no SDK: the session\n * token (minted server-side when the user redeemed their invite) arrives in the\n * URL fragment — `#token=<jwt>` — when `/magic-link/redeem` redirects the\n * browser to Explorer. This provider extracts it, stashes it in sessionStorage\n * (per-tab, so it dies with the tab), decodes the claims for display, and hands\n * the token to the GraphQL client via `getIdToken()`. The server validates it\n * through the standard JWKS path.\n *\n * Set `AUTH_TYPE: 'magic-link'` in the Explorer environment to use this\n * provider. There are no refresh tokens — when the session expires the user\n * must redeem a fresh link.\n */\n@Injectable({ providedIn: 'root' })\n@RegisterClass(MJAuthBase, 'magic-link')\nexport class MJMagicLinkProvider extends MJAuthBase {\n static readonly PROVIDER_TYPE = 'magic-link';\n readonly type = MJMagicLinkProvider.PROVIDER_TYPE;\n\n private token: string | null = null;\n private claims: MagicLinkSessionClaims | null = null;\n\n constructor() {\n super({ name: MJMagicLinkProvider.PROVIDER_TYPE, type: MJMagicLinkProvider.PROVIDER_TYPE });\n }\n\n /**\n * True if a magic-link session token is present for this page load — either\n * arriving in the URL fragment (`#token=<jwt>`, from the redeem redirect) or\n * already stashed in sessionStorage from earlier in this tab.\n *\n * Used at module-config time (`AuthServicesModule.forRoot`) to auto-select the\n * magic-link provider even when `AUTH_TYPE` names a different primary IdP, so a\n * single Explorer deployment can serve both SSO users and magic-link guests.\n * Falls back cleanly to the primary IdP when no token is present (e.g. after a\n * guest's session expires or logs out).\n */\n static HasSessionToken(): boolean {\n if (typeof window === 'undefined') {\n return false;\n }\n try {\n const hash = window.location?.hash ?? '';\n const fragment = hash.startsWith('#') ? hash.slice(1) : hash;\n if (new URLSearchParams(fragment).get('token')) {\n return true;\n }\n return !!window.sessionStorage?.getItem(TOKEN_STORAGE_KEY);\n } catch {\n return false;\n }\n }\n\n /** @deprecated Use {@link HasSessionToken}. */\n static hasSessionToken(): boolean {\n return this.HasSessionToken();\n }\n\n async initialize(): Promise<void> {\n // Token may arrive in the URL fragment from the redeem redirect, or already\n // be stored from earlier in this tab's session.\n const fromHash = this.readTokenFromHash();\n const stored = sessionStorage.getItem(TOKEN_STORAGE_KEY);\n const token = fromHash ?? stored;\n\n if (!token) {\n this.updateAuthState(false);\n return;\n }\n\n this.token = token;\n this.claims = this.decode(token);\n\n if (fromHash) {\n sessionStorage.setItem(TOKEN_STORAGE_KEY, token);\n this.stripHash(); // remove the token from the visible URL\n }\n\n if (this.isExpired()) {\n // Stale token — treat as logged out so the user is prompted for a fresh link.\n sessionStorage.removeItem(TOKEN_STORAGE_KEY);\n this.token = null;\n this.claims = null;\n this.updateAuthState(false);\n return;\n }\n\n this.updateUserInfo(this.toUserInfo(this.claims));\n this.updateAuthState(true);\n }\n\n protected async loginInternal(): Promise<void> {\n // No interactive login path — access is only via a magic-link redemption URL.\n this.updateAuthState(false);\n }\n\n protected async logoutInternal(): Promise<void> {\n sessionStorage.removeItem(TOKEN_STORAGE_KEY);\n this.token = null;\n this.claims = null;\n this.updateUserInfo(null);\n this.updateAuthState(false);\n }\n\n async handleCallback(): Promise<void> {\n // No OAuth callback for magic links.\n }\n\n protected async extractIdTokenInternal(): Promise<string | null> {\n return this.token ?? sessionStorage.getItem(TOKEN_STORAGE_KEY);\n }\n\n protected async extractTokenInfoInternal(): Promise<StandardAuthToken | null> {\n const idToken = await this.extractIdTokenInternal();\n if (!idToken) {\n return null;\n }\n const claims = this.claims ?? this.decode(idToken);\n const exp = claims?.exp;\n return { idToken, expiresAt: exp ? exp * 1000 : 0 };\n }\n\n protected async extractUserInfoInternal(): Promise<StandardUserInfo | null> {\n return this.toUserInfo(this.claims);\n }\n\n protected async refreshTokenInternal(): Promise<TokenRefreshResult> {\n // No refresh tokens for magic-link sessions. Hand back the current token\n // while it's valid; once expired, signal TOKEN_EXPIRED.\n const token = await this.extractTokenInfoInternal();\n if (token && !this.isExpired()) {\n return { success: true, token };\n }\n return {\n success: false,\n error: {\n type: AuthErrorType.TOKEN_EXPIRED,\n message: 'Magic-link session expired',\n userMessage: 'Your access link has expired. Please request a new one.',\n },\n };\n }\n\n protected classifyErrorInternal(error: unknown): StandardAuthError {\n const message = (error as { message?: string })?.message ?? 'Unknown error';\n return { type: AuthErrorType.UNKNOWN_ERROR, message, originalError: error };\n }\n\n protected async getProfilePictureUrlInternal(): Promise<string | null> {\n return null;\n }\n\n protected async handleSessionExpiryInternal(): Promise<void> {\n // No interactive re-auth — the user must redeem a fresh link.\n }\n\n /**\n * Magic-link sessions are locked to the single app the invite scoped to\n * (`mj_app_id`), so the shell hides app-switching and keeps the user there.\n */\n override GetSessionScope(): SessionScope | null {\n const appId = this.claims?.mj_app_id;\n if (this.claims?.mj_magic_link === true && appId) {\n return { restrictedToApplicationId: appId, magicLink: true };\n }\n return null;\n }\n\n override getRequiredConfig(): string[] {\n return [];\n }\n\n override validateConfig(): boolean {\n return true;\n }\n\n // ── helpers ────────────────────────────────────────────────────────────────\n\n /** Reads `token` from the URL fragment (`#token=...`). */\n private readTokenFromHash(): string | null {\n const hash = window.location.hash;\n if (!hash) {\n return null;\n }\n return new URLSearchParams(hash.replace(/^#/, '')).get('token');\n }\n\n /** Removes the token from the address bar without reloading. */\n private stripHash(): void {\n history.replaceState(null, '', window.location.pathname + window.location.search);\n }\n\n /**\n * Decodes a JWT payload (no verification — the server validates via JWKS).\n * UTF-8-safe: external users routinely have non-ASCII names, which a plain\n * `atob` would mangle. Also restores base64url padding `atob` needs.\n */\n private decode(token: string): MagicLinkSessionClaims | null {\n try {\n const segment = token.split('.')[1];\n if (!segment) {\n return null;\n }\n let b64 = segment.replace(/-/g, '+').replace(/_/g, '/');\n b64 += '='.repeat((4 - (b64.length % 4)) % 4);\n const json = decodeURIComponent(\n atob(b64)\n .split('')\n .map((c) => '%' + c.charCodeAt(0).toString(16).padStart(2, '0'))\n .join(''),\n );\n return JSON.parse(json) as MagicLinkSessionClaims;\n } catch (e) {\n // A malformed token must not be silently indistinguishable from \"no token\".\n console.error('[MagicLink] Failed to decode session token:', e);\n return null;\n }\n }\n\n private isExpired(): boolean {\n const exp = this.claims?.exp;\n return !!exp && Date.now() >= exp * 1000;\n }\n\n private toUserInfo(claims: MagicLinkSessionClaims | null): StandardUserInfo | null {\n if (!claims) {\n return null;\n }\n const email = claims.email || '';\n return {\n id: claims.sub || email,\n email,\n name: claims.name || email,\n givenName: claims.given_name,\n familyName: claims.family_name,\n preferredUsername: email,\n emailVerified: true,\n };\n }\n}\n"]}
|
|
@@ -13,7 +13,7 @@ import * as i0 from "@angular/core";
|
|
|
13
13
|
* but consumers never need to know this detail.
|
|
14
14
|
*/
|
|
15
15
|
export declare class MJMSALProvider extends MJAuthBase implements OnDestroy {
|
|
16
|
-
|
|
16
|
+
Auth: MsalService;
|
|
17
17
|
private msalBroadcastService;
|
|
18
18
|
static readonly PROVIDER_TYPE = "msal";
|
|
19
19
|
readonly type = "msal";
|
|
@@ -24,7 +24,7 @@ export declare class MJMSALProvider extends MJAuthBase implements OnDestroy {
|
|
|
24
24
|
* Factory function to provide Angular dependencies required by MSAL
|
|
25
25
|
* Stored as a static property for the factory to access without instantiation
|
|
26
26
|
*/
|
|
27
|
-
static
|
|
27
|
+
static AngularProviderFactory: (environment: Record<string, unknown>) => (typeof MsalService | typeof MsalGuard | typeof MsalBroadcastService | {
|
|
28
28
|
provide: import("@angular/core").InjectionToken<import("@azure/msal-browser").IPublicClientApplication>;
|
|
29
29
|
useValue: PublicClientApplication;
|
|
30
30
|
} | {
|
|
@@ -44,6 +44,48 @@ export declare class MJMSALProvider extends MJAuthBase implements OnDestroy {
|
|
|
44
44
|
authRequest?: undefined;
|
|
45
45
|
};
|
|
46
46
|
})[];
|
|
47
|
+
/** @deprecated Use {@link AngularProviderFactory}. */
|
|
48
|
+
static get angularProviderFactory(): (environment: Record<string, unknown>) => (typeof MsalService | typeof MsalGuard | typeof MsalBroadcastService | {
|
|
49
|
+
provide: import("@angular/core").InjectionToken<import("@azure/msal-browser").IPublicClientApplication>;
|
|
50
|
+
useValue: PublicClientApplication;
|
|
51
|
+
} | {
|
|
52
|
+
provide: import("@angular/core").InjectionToken<import("@azure/msal-angular").MsalGuardConfiguration>;
|
|
53
|
+
useValue: {
|
|
54
|
+
interactionType: InteractionType;
|
|
55
|
+
authRequest: {
|
|
56
|
+
scopes: string[];
|
|
57
|
+
};
|
|
58
|
+
protectedResourceMap?: undefined;
|
|
59
|
+
};
|
|
60
|
+
} | {
|
|
61
|
+
provide: import("@angular/core").InjectionToken<import("@azure/msal-angular").MsalInterceptorConfiguration>;
|
|
62
|
+
useValue: {
|
|
63
|
+
interactionType: InteractionType;
|
|
64
|
+
protectedResourceMap: Map<string, string[]>;
|
|
65
|
+
authRequest?: undefined;
|
|
66
|
+
};
|
|
67
|
+
})[];
|
|
68
|
+
/** @deprecated Use {@link AngularProviderFactory}. */
|
|
69
|
+
static set angularProviderFactory(value: (environment: Record<string, unknown>) => (typeof MsalService | typeof MsalGuard | typeof MsalBroadcastService | {
|
|
70
|
+
provide: import("@angular/core").InjectionToken<import("@azure/msal-browser").IPublicClientApplication>;
|
|
71
|
+
useValue: PublicClientApplication;
|
|
72
|
+
} | {
|
|
73
|
+
provide: import("@angular/core").InjectionToken<import("@azure/msal-angular").MsalGuardConfiguration>;
|
|
74
|
+
useValue: {
|
|
75
|
+
interactionType: InteractionType;
|
|
76
|
+
authRequest: {
|
|
77
|
+
scopes: string[];
|
|
78
|
+
};
|
|
79
|
+
protectedResourceMap?: undefined;
|
|
80
|
+
};
|
|
81
|
+
} | {
|
|
82
|
+
provide: import("@angular/core").InjectionToken<import("@azure/msal-angular").MsalInterceptorConfiguration>;
|
|
83
|
+
useValue: {
|
|
84
|
+
interactionType: InteractionType;
|
|
85
|
+
protectedResourceMap: Map<string, string[]>;
|
|
86
|
+
authRequest?: undefined;
|
|
87
|
+
};
|
|
88
|
+
})[]);
|
|
47
89
|
/**
|
|
48
90
|
* Maps a catalog row onto the unprefixed keys `angularProviderFactory` reads (`CLIENT_ID` /
|
|
49
91
|
* `CLIENT_AUTHORITY`), which predate the `<DRIVER>_*` convention the generic overlay emits —
|
|
@@ -59,7 +101,11 @@ export declare class MJMSALProvider extends MJAuthBase implements OnDestroy {
|
|
|
59
101
|
* `knownAuthorities`, which this driver does not yet plumb).
|
|
60
102
|
*/
|
|
61
103
|
static EnvironmentFromCatalog(info: PublicAuthProviderInfo): Record<string, unknown>;
|
|
62
|
-
constructor(
|
|
104
|
+
constructor(Auth: MsalService, msalBroadcastService: MsalBroadcastService);
|
|
105
|
+
/** @deprecated Use {@link Auth}. */
|
|
106
|
+
get auth(): MsalService;
|
|
107
|
+
/** @deprecated Use {@link Auth}. */
|
|
108
|
+
set auth(value: MsalService);
|
|
63
109
|
initialize(): Promise<void>;
|
|
64
110
|
private _performInitialization;
|
|
65
111
|
protected loginInternal(options?: Record<string, unknown>): Promise<void>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"mjexplorer-msal-provider.service.d.ts","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-msal-provider.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,SAAS,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7D,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAA6D,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAE9I,OAAO,EAAuF,uBAAuB,EAAE,eAAe,EAAoB,MAAM,qBAAqB,CAAC;AACtL,OAAO,EAAY,KAAK,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE7E,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAEjB,kBAAkB,EACnB,MAAM,eAAe,CAAC;;AACvB;;;;;;GAMG;AACH,qBAIa,cAAe,SAAQ,UAAW,YAAW,SAAS;
|
|
1
|
+
{"version":3,"file":"mjexplorer-msal-provider.service.d.ts","sourceRoot":"","sources":["../../../src/lib/providers/mjexplorer-msal-provider.service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAc,SAAS,EAAE,MAAM,eAAe,CAAC;AAEtD,OAAO,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAE7D,OAAO,EAAE,oBAAoB,EAAE,WAAW,EAA6D,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAE9I,OAAO,EAAuF,uBAAuB,EAAE,eAAe,EAAoB,MAAM,qBAAqB,CAAC;AACtL,OAAO,EAAY,KAAK,sBAAsB,EAAE,MAAM,sBAAsB,CAAC;AAE7E,OAAO,EACL,gBAAgB,EAChB,iBAAiB,EACjB,iBAAiB,EAEjB,kBAAkB,EACnB,MAAM,eAAe,CAAC;;AACvB;;;;;;GAMG;AACH,qBAIa,cAAe,SAAQ,UAAW,YAAW,SAAS;IAyF9C,IAAI,EAAE,WAAW;IAAE,OAAO,CAAC,oBAAoB;IAxFlE,MAAM,CAAC,QAAQ,CAAC,aAAa,UAAU;IACvC,QAAQ,CAAC,IAAI,UAAgC;IAE7C,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAuB;IACpD,OAAO,CAAC,QAAQ,CAAC,yBAAyB,CAAuC;IACjF,OAAO,CAAC,YAAY,CAA8B;IAElD;;;OAGG;IACH,MAAM,CAAC,sBAAsB,GAAI,aAAa,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;;;;;SAiCnE;IAEF,sDAAsD;IACtD,MAAM,KAAK,sBAAsB,kBApCa,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;;;;;;;;;;;;;;;;;;;SAsCpE;IACD,sDAAsD;I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