@civic/auth 0.6.1-beta.1 → 0.6.1-beta.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.
Files changed (85) hide show
  1. package/dist/nextjs/config.d.ts.map +1 -1
  2. package/dist/nextjs/config.js +3 -1
  3. package/dist/nextjs/config.js.map +1 -1
  4. package/dist/nextjs/hooks/useUserCookie.d.ts.map +1 -1
  5. package/dist/nextjs/hooks/useUserCookie.js.map +1 -1
  6. package/dist/nextjs/providers/NextAuthProvider.d.ts.map +1 -1
  7. package/dist/nextjs/providers/NextAuthProvider.js +1 -0
  8. package/dist/nextjs/providers/NextAuthProvider.js.map +1 -1
  9. package/dist/shared/hooks/useSignIn.d.ts +9 -4
  10. package/dist/shared/hooks/useSignIn.d.ts.map +1 -1
  11. package/dist/shared/hooks/useSignIn.js +75 -42
  12. package/dist/shared/hooks/useSignIn.js.map +1 -1
  13. package/dist/shared/providers/AuthContext.d.ts +7 -2
  14. package/dist/shared/providers/AuthContext.d.ts.map +1 -1
  15. package/dist/shared/providers/AuthContext.js.map +1 -1
  16. package/dist/shared/providers/UserProvider.d.ts +5 -1
  17. package/dist/shared/providers/UserProvider.d.ts.map +1 -1
  18. package/dist/shared/providers/UserProvider.js.map +1 -1
  19. package/dist/shared/version.d.ts +1 -1
  20. package/dist/shared/version.js +1 -1
  21. package/dist/shared/version.js.map +1 -1
  22. package/dist/vanillajs/auth/AuthenticationEvents.d.ts.map +1 -1
  23. package/dist/vanillajs/auth/AuthenticationEvents.js +2 -2
  24. package/dist/vanillajs/auth/AuthenticationEvents.js.map +1 -1
  25. package/dist/vanillajs/auth/CivicAuth.d.ts +68 -107
  26. package/dist/vanillajs/auth/CivicAuth.d.ts.map +1 -1
  27. package/dist/vanillajs/auth/CivicAuth.js +389 -412
  28. package/dist/vanillajs/auth/CivicAuth.js.map +1 -1
  29. package/dist/vanillajs/auth/SessionManager.d.ts.map +1 -1
  30. package/dist/vanillajs/auth/SessionManager.js +2 -2
  31. package/dist/vanillajs/auth/SessionManager.js.map +1 -1
  32. package/dist/vanillajs/auth/TokenRefresher.d.ts.map +1 -1
  33. package/dist/vanillajs/auth/TokenRefresher.js +2 -2
  34. package/dist/vanillajs/auth/TokenRefresher.js.map +1 -1
  35. package/dist/vanillajs/auth/config/ConfigProcessor.d.ts +6 -0
  36. package/dist/vanillajs/auth/config/ConfigProcessor.d.ts.map +1 -0
  37. package/dist/vanillajs/auth/config/ConfigProcessor.js +59 -0
  38. package/dist/vanillajs/auth/config/ConfigProcessor.js.map +1 -0
  39. package/dist/vanillajs/auth/handlers/IframeAuthHandler.d.ts +40 -0
  40. package/dist/vanillajs/auth/handlers/IframeAuthHandler.d.ts.map +1 -0
  41. package/dist/vanillajs/auth/handlers/IframeAuthHandler.js +388 -0
  42. package/dist/vanillajs/auth/handlers/IframeAuthHandler.js.map +1 -0
  43. package/dist/vanillajs/auth/handlers/MessageHandler.d.ts +170 -0
  44. package/dist/vanillajs/auth/handlers/MessageHandler.d.ts.map +1 -0
  45. package/dist/vanillajs/auth/handlers/MessageHandler.js +367 -0
  46. package/dist/vanillajs/auth/handlers/MessageHandler.js.map +1 -0
  47. package/dist/vanillajs/auth/{OAuthCallbackHandler.d.ts → handlers/OAuthCallbackHandler.d.ts} +2 -2
  48. package/dist/vanillajs/auth/handlers/OAuthCallbackHandler.d.ts.map +1 -0
  49. package/dist/vanillajs/auth/handlers/OAuthCallbackHandler.js +301 -0
  50. package/dist/vanillajs/auth/handlers/OAuthCallbackHandler.js.map +1 -0
  51. package/dist/vanillajs/auth/handlers/PopupHandler.d.ts +108 -0
  52. package/dist/vanillajs/auth/handlers/PopupHandler.d.ts.map +1 -0
  53. package/dist/vanillajs/auth/handlers/PopupHandler.js +333 -0
  54. package/dist/vanillajs/auth/handlers/PopupHandler.js.map +1 -0
  55. package/dist/vanillajs/auth/types/AuthTypes.d.ts +128 -0
  56. package/dist/vanillajs/auth/types/AuthTypes.d.ts.map +1 -0
  57. package/dist/vanillajs/auth/types/AuthTypes.js +40 -0
  58. package/dist/vanillajs/auth/types/AuthTypes.js.map +1 -0
  59. package/dist/vanillajs/iframe/IframeManager.d.ts +33 -0
  60. package/dist/vanillajs/iframe/IframeManager.d.ts.map +1 -1
  61. package/dist/vanillajs/iframe/IframeManager.js +163 -36
  62. package/dist/vanillajs/iframe/IframeManager.js.map +1 -1
  63. package/dist/vanillajs/index.d.ts +2 -2
  64. package/dist/vanillajs/index.d.ts.map +1 -1
  65. package/dist/vanillajs/index.js +2 -2
  66. package/dist/vanillajs/index.js.map +1 -1
  67. package/dist/vanillajs/services/ApiService.d.ts.map +1 -1
  68. package/dist/vanillajs/services/ApiService.js +2 -2
  69. package/dist/vanillajs/services/ApiService.js.map +1 -1
  70. package/dist/vanillajs/types/index.d.ts +15 -10
  71. package/dist/vanillajs/types/index.d.ts.map +1 -1
  72. package/dist/vanillajs/types/index.js +15 -10
  73. package/dist/vanillajs/types/index.js.map +1 -1
  74. package/dist/vanillajs/utils/auth-utils.d.ts +2 -1
  75. package/dist/vanillajs/utils/auth-utils.d.ts.map +1 -1
  76. package/dist/vanillajs/utils/auth-utils.js +6 -3
  77. package/dist/vanillajs/utils/auth-utils.js.map +1 -1
  78. package/dist/vanillajs/utils/logger.d.ts +16 -15
  79. package/dist/vanillajs/utils/logger.d.ts.map +1 -1
  80. package/dist/vanillajs/utils/logger.js +35 -19
  81. package/dist/vanillajs/utils/logger.js.map +1 -1
  82. package/package.json +1 -1
  83. package/dist/vanillajs/auth/OAuthCallbackHandler.d.ts.map +0 -1
  84. package/dist/vanillajs/auth/OAuthCallbackHandler.js +0 -143
  85. package/dist/vanillajs/auth/OAuthCallbackHandler.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"CivicAuth.js","sourceRoot":"","sources":["../../../src/vanillajs/auth/CivicAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE9C,OAAO,EAAE,mBAAmB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0B;QACpD,IAAI,CAAC,MAAM,CAAC,iBAAiB,GAAG,IAAI,CAAC;QACrC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,mCAAmC,IAAI,EAAE,CAAC,CAAC;IAC/D,CAAC;IAED;;;OAGG;IACI,oBAAoB;QACzB,OAAO,IAAI,CAAC,MAAM,CAAC,iBAAiB,CAAC;IACvC,CAAC;IAED;;OAEG;IACI,KAAK,CAAC,OAAO;QAClB,IAAI,CAAC,OAAO,EAAE,CAAC;QACf,MAAM,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAAC;QACrC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;IAC1C,CAAC;CACF","sourcesContent":["import { AuthEvent } from \"../types/index.js\";\nimport type { AuthenticationEvents } from \"./AuthenticationEvents.js\";\nimport { LocalStorageAdapter } from \"../../browser/storage.js\";\nimport { handleOAuthRedirectPage } from \"./OAuthCallbackHandler.js\";\nimport type { Endpoints, DisplayMode, AuthStorage } from \"../../types.js\";\nimport { buildAuthUrl } from \"../utils/auth-utils.js\";\nimport type { AuthResult, Session } from \"../types/index.js\";\nimport {\n createLogger,\n configureLogging,\n setCurrentLogger,\n} from \"../utils/logger.js\";\nimport { SignalObserver } from \"../iframe/SignalObserver.js\";\nimport { GenericPublicClientPKCEProducer } from \"../../services/PKCE.js\";\nimport { generateState } from \"../../lib/oauth.js\";\nimport { SessionManager } from \"./SessionManager.js\";\nimport { IframeManager } from \"../iframe/IframeManager.js\";\n\n/**\n * Error codes for CivicAuth errors\n */\nexport enum CivicAuthErrorCode {\n CONFIG_REQUIRED = \"CONFIG_REQUIRED\",\n INIT_FAILED = \"INIT_FAILED\",\n ENDPOINTS_NOT_INITIALIZED = \"ENDPOINTS_NOT_INITIALIZED\",\n CONTAINER_NOT_FOUND = \"CONTAINER_NOT_FOUND\",\n AUTH_PROCESS_TIMEOUT = \"AUTH_PROCESS_TIMEOUT\",\n IFRAME_LOAD_ERROR = \"IFRAME_LOAD_ERROR\",\n INVALID_MESSAGE = \"INVALID_MESSAGE\",\n}\n\n/**\n * Constants for the auth client\n */\nconst CONSTANTS = {\n DEFAULT_IFRAME_ID: \"civic-auth-iframe\",\n DEFAULT_AUTH_PROCESS_TIMEOUT: 60000, // 60 seconds\n SUCCESS_SIGNAL_ID: \"civic-auth-success-signal\",\n ERROR_SIGNAL_ID: \"civic-auth-error-signal\",\n} as const;\n\n/**\n * Message types for postMessage communication\n */\ntype AuthMessageType = \"auth_success\" | \"auth_error\";\n\ninterface AuthMessage {\n type: AuthMessageType;\n detail?: string;\n data?: unknown;\n error?: unknown;\n}\n\nclass CivicAuthError extends Error {\n constructor(\n message: string,\n public readonly code: CivicAuthErrorCode,\n ) {\n super(message);\n this.name = \"CivicAuthError\";\n }\n}\n\n/**\n * Configuration options for the CivicAuth client\n */\nexport interface CivicAuthClientConfig {\n /** OAuth client ID */\n clientId: string;\n /** URL to redirect to after authentication */\n redirectUrl: string;\n /** Base URL of the OAuth server */\n oauthServerBaseUrl: string;\n /** Array of OAuth scopes to request */\n scopes: string[];\n /** HTML element or element ID where the auth iframe will be mounted */\n targetContainerElement: HTMLElement | string;\n /** Text signals for success and error states */\n textSignals: {\n /** Text to display on successful authentication */\n success: string;\n /** Optional text to display on authentication error */\n error?: string;\n };\n /** Display mode for the authentication UI */\n displayMode?: DisplayMode;\n /** Display mode for iframe rendering - modal (full-screen overlay) or embedded (within container) */\n iframeDisplayMode?: \"modal\" | \"embedded\";\n /**\n * Timeout duration in milliseconds for the entire authentication process.\n * If the authentication process takes longer than this duration, it will be cancelled\n * and an error will be thrown.\n */\n authProcessTimeout?: number;\n /** Event handlers for authentication events */\n events?: AuthenticationEvents;\n /** Custom ID for the auth iframe */\n iframeId?: string;\n /** Custom storage adapter for auth state - uses shared AuthStorage interface */\n storageAdapter?: AuthStorage;\n /** OAuth prompt parameter */\n prompt?: string;\n /** Initial state for OAuth flow */\n initialState?: string;\n /** Logging configuration */\n logging?: LoggingConfig;\n}\n\nexport interface LoggingConfig {\n enabled: boolean;\n namespace?: string;\n level?: \"debug\" | \"info\" | \"warn\" | \"error\";\n}\n\n/**\n * Process the configuration with defaults\n */\nfunction processConfigWithDefaults(\n config: CivicAuthClientConfig,\n): CivicAuthClientConfig & {\n storageAdapter: AuthStorage;\n logging: LoggingConfig;\n displayMode: DisplayMode;\n authProcessTimeout: number;\n iframeId: string;\n} {\n const loggingConfig: LoggingConfig = {\n enabled: true,\n namespace: \"iframe\",\n level: \"debug\" as const,\n ...config.logging,\n };\n\n return {\n ...config,\n displayMode: config.displayMode || \"iframe\",\n authProcessTimeout:\n config.authProcessTimeout || CONSTANTS.DEFAULT_AUTH_PROCESS_TIMEOUT,\n iframeId: config.iframeId || CONSTANTS.DEFAULT_IFRAME_ID,\n logging: loggingConfig,\n storageAdapter: config.storageAdapter || new LocalStorageAdapter(),\n };\n}\n\n/**\n * CivicAuth client for handling OAuth authentication\n */\nexport class CivicAuth {\n /**\n * Internal configuration with all optional properties resolved to required ones.\n *\n * We extend CivicAuthClientConfig rather than making these properties required\n * in the public interface to maintain better DX (optional properties) while\n * ensuring type safety internally after defaults are applied.\n */\n private config: CivicAuthClientConfig & {\n storageAdapter: AuthStorage;\n logging: LoggingConfig;\n displayMode: DisplayMode;\n authProcessTimeout: number;\n iframeId: string;\n };\n private iframeElement?: HTMLIFrameElement;\n private observer?: MutationObserver;\n private authPromise?: Promise<AuthResult>;\n private authPromiseResolve?: (value: AuthResult) => void;\n private authPromiseReject?: (reason?: Error) => void;\n private authProcessTimeoutHandle?: number;\n private messageEventHandler?: (event: MessageEvent) => void;\n private storage: AuthStorage;\n private endpoints?: Endpoints;\n private logger: ReturnType<typeof createLogger>;\n private sessionManager?: SessionManager;\n private iframeManager?: IframeManager;\n\n /**\n * Private constructor for CivicAuth.\n * Use {@link CivicAuth.create} to create a new instance.\n * @param config - Configuration options for the auth client\n * @throws {CivicAuthError} If required configuration is missing\n * @private\n */\n private constructor(config: CivicAuthClientConfig) {\n // Process config with defaults\n this.config = processConfigWithDefaults(config);\n\n // Configure logging based on config\n configureLogging(this.config.logging);\n\n // Initialize logger based on config\n if (this.config.logging?.enabled) {\n const namespace = this.config.logging.namespace || \"iframe\";\n this.logger = createLogger(namespace);\n } else {\n // Create a no-op logger when logging is disabled\n this.logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n };\n }\n\n // Set this logger as the current logger\n setCurrentLogger(this.logger);\n\n // Use the storage adapter from processed config (guaranteed to be present)\n this.storage = this.config.storageAdapter;\n\n // Initialize SessionManager if events are provided\n if (config.events) {\n this.sessionManager = new SessionManager(this.storage, config.events);\n }\n\n // Validate required configuration\n const requiredConfigs = [\n { key: \"clientId\", value: config.clientId },\n { key: \"targetContainerElement\", value: config.targetContainerElement },\n { key: \"textSignals.success\", value: config.textSignals?.success },\n ];\n\n for (const { key, value } of requiredConfigs) {\n if (!value) {\n throw new CivicAuthError(\n `CivicAuth: ${key} is required.`,\n CivicAuthErrorCode.CONFIG_REQUIRED,\n );\n }\n }\n\n this.messageEventHandler = this.handleIframeMessage.bind(this);\n }\n\n /**\n * Creates and initializes a new instance of CivicAuth.\n * This is the recommended way to create a CivicAuth instance.\n *\n * @param config - Configuration options for the auth client\n * @returns A promise that resolves with the initialized CivicAuth instance\n * @throws {CivicAuthError} If initialization fails or required configuration is missing\n *\n * @example\n * ```typescript\n * const auth = await CivicAuth.create({\n * clientId: \"your-client-id\",\n * redirectUrl: \"https://your-app.com/callback\",\n * oauthServerBaseUrl: \"https://auth-server.com/\",\n * scopes: [\"openid\", \"profile\"],\n * targetContainerElement: \"auth-container\",\n * textSignals: {\n * success: \"Authentication successful!\"\n * }\n * });\n * ```\n */\n public static async create(\n config: CivicAuthClientConfig,\n ): Promise<CivicAuth> {\n const instance = new CivicAuth(config);\n await instance.init();\n return instance;\n }\n\n /**\n * Initializes the auth client and checks for callback handling\n * @throws {CivicAuthError} If initialization fails\n */\n private async init(): Promise<void> {\n try {\n // Get OAuth endpoints from well-known configuration\n this.endpoints = {\n auth: `${this.config.oauthServerBaseUrl}auth`,\n token: `${this.config.oauthServerBaseUrl}token`,\n jwks: `${this.config.oauthServerBaseUrl}jwks`,\n userinfo: `${this.config.oauthServerBaseUrl}userinfo`,\n endsession: `${this.config.oauthServerBaseUrl}endsession`,\n };\n\n // Initialize SessionManager with auth config for token refresh\n if (this.sessionManager) {\n const authConfig = {\n clientId: this.config.clientId,\n redirectUrl: this.config.redirectUrl,\n oauthServer: this.config.oauthServerBaseUrl,\n scopes: this.config.scopes,\n endpoints: this.endpoints,\n };\n await this.sessionManager.initializeWithAuthConfig(authConfig);\n }\n\n // Check if we're on the callback page\n if (window.location.href.startsWith(this.config.redirectUrl)) {\n await this.handleCallback();\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to initialize authentication\";\n this.logger.error(\"Failed to initialize CivicAuth:\", { error });\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: errorMessage,\n });\n throw new CivicAuthError(errorMessage, CivicAuthErrorCode.INIT_FAILED);\n }\n }\n\n /**\n * Gets the container element for the auth iframe\n * @returns The container element or null if not found\n */\n private getContainerElement(): HTMLElement | null {\n if (typeof this.config.targetContainerElement === \"string\") {\n const element = document.getElementById(\n this.config.targetContainerElement,\n );\n if (!element) {\n this.logger.warn(\n `Container element with ID \"${this.config.targetContainerElement}\" not found`,\n );\n }\n return element;\n }\n return this.config.targetContainerElement;\n }\n\n /**\n * Determines the appropriate iframe display mode based on container characteristics\n * @param container The HTML element that will contain the iframe\n * @returns \"modal\" for full-screen overlay or \"embedded\" for in-container display\n */\n private determineIframeDisplayMode(\n container: HTMLElement,\n ): \"modal\" | \"embedded\" {\n // Use explicit config if provided\n if (this.config.iframeDisplayMode) {\n this.logger.debug(\n `Using configured iframe display mode: ${this.config.iframeDisplayMode}`,\n );\n return this.config.iframeDisplayMode;\n }\n\n // Analyze container characteristics to determine best display mode\n const containerRect = container.getBoundingClientRect();\n const containerStyles = window.getComputedStyle(container);\n\n // Get container dimensions\n const containerWidth = containerRect.width;\n const containerHeight = containerRect.height;\n\n // Check if container is positioned in a way that suggests it's meant for modal display\n const isFullScreenContainer =\n containerStyles.position === \"fixed\" &&\n (containerWidth >= window.innerWidth * 0.9 ||\n containerHeight >= window.innerHeight * 0.9);\n\n // Modal mode thresholds - if container is too small, use modal for better UX\n const MIN_EMBEDDED_WIDTH = 320; // Same as modal content wrapper width\n const MIN_EMBEDDED_HEIGHT = 400; // Reasonable minimum for embedded auth flow\n\n // Determine mode based on container characteristics\n if (isFullScreenContainer) {\n this.logger.debug(\n \"Container appears to be full-screen positioned, using modal mode\",\n { containerWidth, containerHeight, position: containerStyles.position },\n );\n return \"modal\";\n }\n\n if (\n containerWidth < MIN_EMBEDDED_WIDTH ||\n containerHeight < MIN_EMBEDDED_HEIGHT\n ) {\n this.logger.debug(\n `Container too small for embedded mode (${containerWidth}x${containerHeight}), using modal mode`,\n {\n containerWidth,\n containerHeight,\n MIN_EMBEDDED_WIDTH,\n MIN_EMBEDDED_HEIGHT,\n },\n );\n return \"modal\";\n }\n\n // Check if container has sufficient space and is properly positioned for embedding\n const hasAdequateSpace =\n containerWidth >= MIN_EMBEDDED_WIDTH &&\n containerHeight >= MIN_EMBEDDED_HEIGHT;\n const isEmbeddablePosition =\n containerStyles.position === \"relative\" ||\n containerStyles.position === \"static\" ||\n containerStyles.position === \"\";\n\n if (hasAdequateSpace && isEmbeddablePosition) {\n this.logger.debug(\n \"Container has adequate space and positioning for embedded mode\",\n { containerWidth, containerHeight, position: containerStyles.position },\n );\n return \"embedded\";\n }\n\n // Default to modal mode if container characteristics are unclear\n this.logger.debug(\n \"Container characteristics unclear, defaulting to modal mode for better UX\",\n { containerWidth, containerHeight, position: containerStyles.position },\n );\n return \"modal\";\n }\n\n /**\n * Builds the authentication URL with PKCE challenge\n * @returns The complete authentication URL\n * @throws {CivicAuthError} If endpoints are not initialized\n */\n private async buildAuthUrl(): Promise<string> {\n if (!this.endpoints) {\n throw new CivicAuthError(\n \"OAuth endpoints not initialized. Please wait for initialization to complete.\",\n CivicAuthErrorCode.ENDPOINTS_NOT_INITIALIZED,\n );\n }\n\n // Use storage directly since it's now AuthStorage\n const pkceProducer = new GenericPublicClientPKCEProducer(this.storage);\n const codeChallenge = await pkceProducer.getCodeChallenge();\n const state =\n this.config.initialState ||\n generateState({\n displayMode: this.config.displayMode || \"iframe\",\n });\n\n return buildAuthUrl({\n endpoints: this.endpoints,\n clientId: this.config.clientId,\n redirectUrl: this.config.redirectUrl,\n scopes: this.config.scopes,\n codeChallenge,\n state,\n prompt: this.config.prompt,\n });\n }\n\n private handleIframeMessage(event: MessageEvent): void {\n const expectedOrigin = new URL(this.config.oauthServerBaseUrl).origin;\n this.logIncomingMessage(event, expectedOrigin);\n\n if (!this.isValidMessageSource(event, expectedOrigin)) {\n return;\n }\n\n this.handleValidMessage(event);\n }\n\n private logIncomingMessage(\n event: MessageEvent,\n expectedOrigin: string,\n ): void {\n this.logger.debug(\"Global window received message:\", {\n data: event.data,\n origin: event.origin,\n sourceProvided: !!event.source,\n iframeContentWindow: this.iframeElement?.contentWindow,\n expectedIframeOrigin: expectedOrigin,\n });\n }\n\n private isValidMessageSource(\n event: MessageEvent,\n expectedOrigin: string,\n ): boolean {\n const isValidOrigin = event.origin === expectedOrigin;\n const isValidSource = event.source === this.iframeElement?.contentWindow;\n\n if (!isValidOrigin) {\n this.logger.warn(\"Ignored message from unexpected origin.\", {\n receivedOrigin: event.origin,\n expectedOrigin,\n iframeSrc: this.iframeElement?.src,\n });\n }\n\n if (!isValidSource) {\n this.logger.warn(\"Ignored message from unexpected source.\", {\n isSourceProvided: !!event.source,\n isIframeContentWindowAvailable: !!this.iframeElement?.contentWindow,\n iframeSrc: this.iframeElement?.src,\n });\n }\n\n return isValidOrigin && isValidSource;\n }\n\n private handleValidMessage(event: MessageEvent): void {\n this.logger.info(\n \"Message from configured iframe source and origin received\",\n {\n data: event.data,\n iframeSrc: this.iframeElement?.src,\n },\n );\n\n const message = event.data as AuthMessage;\n const messageType = message?.type;\n\n switch (messageType) {\n case \"auth_success\":\n this.handleAuthSuccess(message);\n break;\n case \"auth_error\":\n this.handleAuthError(message);\n break;\n default:\n this.logger.debug(\n \"Message from iframe did not match expected types (auth_success, auth_error)\",\n { data: event.data },\n );\n }\n }\n\n private handleAuthSuccess(data: AuthMessage): void {\n this.config.events?.emit(AuthEvent.SIGN_IN_COMPLETE, {\n detail: \"Success signal received via postMessage\",\n data,\n });\n this.authPromiseResolve?.((data?.data as AuthResult) || {});\n this.cleanup();\n }\n\n private handleAuthError(data: AuthMessage): void {\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Error signal received via postMessage\",\n error: data,\n });\n this.authPromiseReject?.(\n new CivicAuthError(\n data?.detail || \"Error signal received via postMessage\",\n CivicAuthErrorCode.INVALID_MESSAGE,\n ),\n );\n this.cleanup();\n }\n\n private setupSignalObserver(iframeDoc: Document): void {\n const signalObserver = new SignalObserver(\n {\n textSignals: this.config.textSignals,\n events: this.config.events,\n logger: this.logger,\n },\n this.authPromiseResolve,\n this.authPromiseReject,\n () => this.cleanup(),\n );\n\n signalObserver.setup(iframeDoc);\n }\n\n private async handleNewTabAuth(\n fullAuthUrl: string,\n reject: (error: Error) => void,\n ): Promise<void> {\n const popupWindow = window.open(fullAuthUrl, \"_blank\");\n if (!popupWindow) {\n const error = new CivicAuthError(\n \"Failed to open popup window. Please check your browser's popup settings.\",\n CivicAuthErrorCode.INIT_FAILED,\n );\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: error.message,\n });\n reject(error);\n }\n }\n\n private async handleIframeAuth(\n fullAuthUrl: string,\n reject: (error: Error) => void,\n ): Promise<void> {\n const container = this.getContainerElement();\n if (!container) {\n const error = new CivicAuthError(\n \"Target container element not found.\",\n CivicAuthErrorCode.CONTAINER_NOT_FOUND,\n );\n this.logger.error(error.message);\n reject(error);\n return;\n }\n\n this.logger.debug(\"Creating iframe with modal backdrop\", {\n url: fullAuthUrl,\n containerId: container?.id,\n iframeId: this.config.iframeId,\n origin: window.location.origin,\n });\n\n // Determine the actual display mode for IframeManager\n // For iframe displayMode, we need to decide between modal and embedded based on container\n const iframeDisplayMode = this.determineIframeDisplayMode(container);\n\n this.logger.debug(\n `🎯 CivicAuth: Creating IframeManager with display mode: ${iframeDisplayMode}`,\n );\n\n // Create IframeManager with appropriate display mode\n this.iframeManager = new IframeManager({\n container: container,\n displayMode: iframeDisplayMode,\n iframeId: this.config.iframeId,\n onClose: () => {\n this.logger.debug(\n \"Authentication close requested by user (backdrop click, close button, or Escape key)\",\n );\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Authentication cancelled by user\",\n });\n reject(\n new CivicAuthError(\n \"Authentication cancelled by user\",\n CivicAuthErrorCode.AUTH_PROCESS_TIMEOUT,\n ),\n );\n this.cleanup();\n },\n });\n\n // Create the iframe using IframeManager\n this.iframeElement = this.iframeManager.createIframe(fullAuthUrl);\n\n this.config.events?.emit(AuthEvent.SIGN_IN_STARTED, {\n detail: \"Iframe created with modal backdrop\",\n });\n\n this.iframeElement.onload = () => {\n this.logger.info(\"Iframe loaded\", {\n iframeSrc: this.iframeElement?.src,\n currentOrigin: window.location.origin,\n expectedAuthServerOrigin: new URL(this.config.oauthServerBaseUrl)\n .origin,\n });\n\n if (!this.iframeElement?.contentWindow) {\n const errorMsg = \"Iframe content window not available after load.\";\n this.logger.error(errorMsg, {\n iframeSrc: this.iframeElement?.src,\n });\n reject(new Error(errorMsg));\n this.cleanup();\n return;\n }\n\n // Set up postMessage listener for cross-origin communication\n if (this.messageEventHandler) {\n window.addEventListener(\"message\", this.messageEventHandler);\n this.logger.info(\n \"Added cross-origin message event listener for auth server communication\",\n {\n parentOrigin: window.location.origin,\n authServerOrigin: new URL(this.config.oauthServerBaseUrl).origin,\n },\n );\n } else {\n this.logger.error(\n \"messageEventHandler was not defined when trying to add listener.\",\n );\n }\n\n // Try to detect redirect to our domain\n try {\n const currentIframeHref =\n this.iframeElement.contentWindow.location.href;\n\n if (currentIframeHref.startsWith(this.config.redirectUrl)) {\n this.logger.info(\n \"Iframe has navigated to redirectUrl (same-origin). Setting up DOM observer.\",\n );\n\n if (\n this.iframeElement.contentDocument &&\n this.iframeElement.contentDocument.body\n ) {\n this.setupSignalObserver(this.iframeElement.contentDocument);\n }\n }\n } catch (error) {\n this.logger.error(\"Error checking iframe href\", {\n error,\n iframeSrc: this.iframeElement?.src,\n });\n // This is expected when the iframe is on the auth server domain\n this.logger.info(\n \"Iframe is on auth server domain - using postMessage for communication\",\n {\n parentOrigin: window.location.origin,\n authServerOrigin: new URL(this.config.oauthServerBaseUrl).origin,\n },\n );\n }\n };\n\n this.iframeElement.onerror = (event) => {\n this.logger.error(\"Iframe load error\", {\n event,\n iframeSrc: this.iframeElement?.src,\n currentOrigin: window.location.origin,\n });\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Iframe load error\",\n error: event,\n });\n reject(new Error(\"Iframe failed to load.\"));\n this.cleanup();\n };\n }\n\n /**\n * Starts the authentication process\n * @returns A promise that resolves with the authentication result\n * @throws {CivicAuthError} If authentication fails or times out\n */\n async startAuthentication(): Promise<AuthResult> {\n if (!this.endpoints) {\n const error = new CivicAuthError(\n \"OAuth endpoints not initialized. Please wait for initialization to complete.\",\n CivicAuthErrorCode.ENDPOINTS_NOT_INITIALIZED,\n );\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: error.message,\n });\n throw error;\n }\n\n if (this.authPromise) {\n this.logger.info(\n \"Authentication already in progress, returning existing promise\",\n );\n return this.authPromise;\n }\n\n const fullAuthUrl = await this.buildAuthUrl();\n\n this.logger.info(\"Starting authentication process\", {\n constructedIframeUrl: fullAuthUrl,\n displayMode: this.config.displayMode,\n authProcessTimeout: this.config.authProcessTimeout,\n });\n\n this.authPromise = new Promise<AuthResult>((resolve, reject) => {\n this.authPromiseResolve = resolve;\n this.authPromiseReject = reject;\n\n // Handle different display modes\n switch (this.config.displayMode) {\n case \"redirect\":\n // For redirect mode, just navigate to the auth URL\n window.location.href = fullAuthUrl;\n break;\n\n case \"new_tab\":\n this.handleNewTabAuth(fullAuthUrl, reject);\n break;\n\n case \"iframe\":\n default:\n this.handleIframeAuth(fullAuthUrl, reject);\n break;\n }\n\n // Set up timeout for all display modes\n if (\n this.config.authProcessTimeout &&\n this.config.authProcessTimeout > 0\n ) {\n this.logger.debug(\"Setting up authentication timeout\", {\n authProcessTimeout: this.config.authProcessTimeout,\n displayMode: this.config.displayMode,\n });\n this.authProcessTimeoutHandle = window.setTimeout(() => {\n this.logger.warn(\"Authentication timed out\", {\n displayMode: this.config.displayMode,\n currentOrigin: window.location.origin,\n });\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Authentication timed out\",\n });\n reject(new Error(\"Authentication timed out.\"));\n this.cleanup();\n }, this.config.authProcessTimeout);\n }\n });\n\n return this.authPromise;\n }\n\n /**\n * Cleans up resources and event listeners\n */\n public cleanup(): void {\n this.logger.info(\"Cleaning up iframe authentication client\");\n\n if (this.observer) {\n this.logger.debug(\"Disconnecting mutation observer\");\n this.observer.disconnect();\n this.observer = undefined;\n }\n\n if (this.messageEventHandler) {\n window.removeEventListener(\"message\", this.messageEventHandler);\n this.logger.debug(\"Removed 'message' event listener from window.\");\n }\n\n if (this.iframeManager) {\n this.logger.debug(\"Cleaning up iframe manager\");\n this.iframeManager.cleanup();\n this.iframeManager = undefined;\n }\n\n // Reset iframe element reference (actual removal handled by IframeManager)\n if (this.iframeElement) {\n this.iframeElement = undefined;\n }\n\n if (this.authProcessTimeoutHandle) {\n this.logger.debug(\"Clearing authentication process timeout\");\n window.clearTimeout(this.authProcessTimeoutHandle);\n this.authProcessTimeoutHandle = undefined;\n }\n\n this.logger.debug(\"Resetting promise state\");\n this.authPromise = undefined;\n this.authPromiseResolve = undefined;\n this.authPromiseReject = undefined;\n }\n\n private async handleCallback(): Promise<void> {\n try {\n const callbackHandled = await handleOAuthRedirectPage({\n clientId: this.config.clientId,\n oauthServer: this.config.oauthServerBaseUrl,\n redirectUrl: this.config.redirectUrl,\n textSignals: {\n success: this.config.textSignals.success,\n error: this.config.textSignals.error || \"Authentication failed\",\n },\n storageAdapter: this.storage,\n });\n\n if (callbackHandled) {\n const successSignal = document.getElementById(\n CONSTANTS.SUCCESS_SIGNAL_ID,\n );\n const errorSignal = document.getElementById(CONSTANTS.ERROR_SIGNAL_ID);\n\n if (successSignal) {\n let userInfo = null;\n const userInfoAttr = successSignal.getAttribute(\"data-user-info\");\n if (userInfoAttr) {\n try {\n userInfo = JSON.parse(userInfoAttr);\n } catch (error) {\n this.logger.error(\"Failed to parse user info:\", { error });\n }\n }\n this.config.events?.emit(AuthEvent.SIGN_IN_COMPLETE, {\n detail: \"Callback processed successfully\",\n user: userInfo,\n });\n } else if (errorSignal) {\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: errorSignal.textContent || \"Unknown error during callback\",\n });\n }\n }\n } catch (error) {\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail:\n error instanceof Error\n ? error.message\n : \"Unknown error during callback\",\n });\n }\n }\n\n /**\n * Get the current session\n */\n public async getCurrentSession(): Promise<Session | null> {\n return this.sessionManager?.getCurrentSession() || null;\n }\n\n /**\n * Check if user is authenticated\n */\n public async isAuthenticated(): Promise<boolean> {\n return this.sessionManager?.isAuthenticated() || false;\n }\n\n /**\n * Get the current user\n */\n public async getCurrentUser() {\n return this.sessionManager?.getCurrentUser() || null;\n }\n\n /**\n * Clear the current session\n */\n public async clearSession(): Promise<void> {\n if (!this.sessionManager) {\n throw new Error(\n \"SessionManager not initialized. Provide events in config.\",\n );\n }\n return this.sessionManager.clearSession();\n }\n\n /**\n * Manually refresh tokens\n */\n public async refreshTokens(): Promise<void> {\n if (!this.sessionManager) {\n throw new Error(\n \"SessionManager not initialized. Provide events in config.\",\n );\n }\n return this.sessionManager.refreshTokens();\n }\n\n /**\n * Get token refresher state for debugging\n */\n public getTokenRefresherState() {\n return this.sessionManager?.getTokenRefresherState() || null;\n }\n\n /**\n * Update the iframe display mode\n * @param mode - The display mode to use for the iframe\n */\n public setIframeDisplayMode(mode: \"modal\" | \"embedded\"): void {\n this.config.iframeDisplayMode = mode;\n this.logger.debug(`Iframe display mode updated to: ${mode}`);\n }\n\n /**\n * Get the current iframe display mode\n * @returns The current iframe display mode\n */\n public getIframeDisplayMode(): \"modal\" | \"embedded\" | undefined {\n return this.config.iframeDisplayMode;\n }\n\n /**\n * Destroy the auth client and clean up all resources\n */\n public async destroy(): Promise<void> {\n this.cleanup();\n await this.sessionManager?.destroy();\n this.sessionManager = undefined;\n this.logger.info(\"CivicAuth destroyed\");\n }\n}\n"]}
1
+ {"version":3,"file":"CivicAuth.js","sourceRoot":"","sources":["../../../src/vanillajs/auth/CivicAuth.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAE9C,OAAO,EAAE,YAAY,EAAE,MAAM,wBAAwB,CAAC;AAGtD,OAAO,EACL,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,+BAA+B,EAAE,MAAM,wBAAwB,CAAC;AACzE,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AACrD,OAAO,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AACrD,OAAO,EAAE,uBAAuB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,EACL,sBAAsB,EACtB,WAAW,EACX,cAAc,GACf,MAAM,0BAA0B,CAAC;AAOlC,OAAO,EACL,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,yBAAyB,EAA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YAChD,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,cAAc,EAAE;gBACjD,MAAM,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;aAC/D,CAAC,CAAC;YACH,MAAM,IAAI,cAAc,CACtB,eAAe,EACf,kBAAkB,CAAC,aAAa,CACjC,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AAID,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC","sourcesContent":["import { AuthEvent } from \"../types/index.js\";\nimport type { Endpoints, AuthStorage } from \"../../types.js\";\nimport { buildAuthUrl } from \"../utils/auth-utils.js\";\nimport type { AuthResult, Session } from \"../types/index.js\";\nimport type { createLogger } from \"../utils/logger.js\";\nimport {\n createMainLogger,\n configureLogging,\n setCurrentLogger,\n} from \"../utils/logger.js\";\nimport { GenericPublicClientPKCEProducer } from \"../../services/PKCE.js\";\nimport { generateState } from \"../../lib/oauth.js\";\nimport { SessionManager } from \"./SessionManager.js\";\nimport { PopupError } from \"../../services/types.js\";\nimport { handleOAuthRedirectPage } from \"./handlers/OAuthCallbackHandler.js\";\nimport {\n generateOauthLogoutUrl,\n clearTokens,\n retrieveTokens,\n} from \"../../shared/lib/util.js\";\n\n// Import new modular components\nimport type {\n CivicAuthClientConfig,\n ProcessedCivicAuthConfig,\n} from \"./types/AuthTypes.js\";\nimport {\n CivicAuthError,\n CivicAuthErrorCode,\n CIVIC_AUTH_CONSTANTS,\n} from \"./types/AuthTypes.js\";\nimport { processConfigWithDefaults } from \"./config/ConfigProcessor.js\";\nimport { MessageHandler } from \"./handlers/MessageHandler.js\";\nimport { PopupHandler } from \"./handlers/PopupHandler.js\";\nimport { IframeAuthHandler } from \"./handlers/IframeAuthHandler.js\";\n\n/**\n * CivicAuth client for handling OAuth authentication\n *\n * This is a refactored version that uses a modular architecture for better maintainability.\n */\nexport class CivicAuth {\n private config: ProcessedCivicAuthConfig;\n private storage: AuthStorage;\n private endpoints?: Endpoints;\n private logger: ReturnType<typeof createLogger>;\n private sessionManager?: SessionManager;\n private initialDisplayMode:\n | \"iframe\"\n | \"modal\"\n | \"redirect\"\n | \"new_tab\"\n | \"custom_tab\";\n\n // Authentication state\n private authPromise?: Promise<AuthResult>;\n private authPromiseResolve?: (value: AuthResult) => void;\n private authPromiseReject?: (reason?: Error) => void;\n private authProcessTimeoutHandle?: number;\n private popupFailureTimeoutHandle?: number;\n private hasPopupFailed: boolean = false;\n\n // Handlers\n private messageHandler?: MessageHandler;\n private popupHandler?: PopupHandler;\n private iframeAuthHandler?: IframeAuthHandler;\n\n /**\n * Private constructor - initializes configuration and handlers.\n * Use {@link CivicAuth.create} to create a new instance.\n */\n private constructor(config: CivicAuthClientConfig) {\n // Process config with defaults and validation\n this.config = processConfigWithDefaults(config);\n this.initialDisplayMode = this.config.displayMode;\n\n // Configure logging\n configureLogging(this.config.logging);\n\n // Initialize logger - always use \"vanillajs\" as base namespace\n if (this.config.logging?.enabled) {\n this.logger = createMainLogger(\"vanillajs\"); // Always use \"vanillajs\"\n } else {\n this.logger = {\n debug: () => {},\n info: () => {},\n warn: () => {},\n error: () => {},\n };\n }\n\n setCurrentLogger(this.logger);\n this.storage = this.config.storageAdapter;\n\n // Initialize SessionManager if events are provided\n if (config.events) {\n this.sessionManager = new SessionManager(this.storage, config.events);\n }\n\n // Initialize handlers\n this.initializeHandlers();\n }\n\n /**\n * Creates and initializes a new instance of CivicAuth.\n * This is the recommended way to create a CivicAuth instance.\n *\n * @param config - Configuration options for the auth client\n * @returns A promise that resolves with the initialized CivicAuth instance\n * @throws {CivicAuthError} If initialization fails or required configuration is missing\n *\n * @example\n * ```typescript\n * const auth = await CivicAuth.create({\n * clientId: \"your-client-id\",\n * // redirectUrl is optional - defaults to current page (window.location.origin + window.location.pathname)\n * redirectUrl: \"https://your-app.com/callback\", // optional\n * // oauthServerBaseUrl is optional - defaults to \"https://auth.civic.com/oauth/\"\n * oauthServerBaseUrl: \"https://auth-server.com/\", // optional\n * // scopes is optional - defaults to ['openid', 'profile', 'email', 'offline_access']\n * scopes: [\"openid\", \"profile\"], // optional\n * targetContainerElement: \"auth-container\",\n * textSignals: {\n * success: \"Authentication successful!\"\n * }\n * });\n * ```\n */\n public static async create(\n config: CivicAuthClientConfig,\n ): Promise<CivicAuth> {\n const instance = new CivicAuth(config);\n await instance.init();\n return instance;\n }\n\n /**\n * Initializes the auth client and checks for callback handling\n */\n private async init(): Promise<void> {\n this.logger.info(\"🚀 Initializing CivicAuth\", {\n currentUrl: window.location.href,\n redirectUrl: this.config.redirectUrl,\n oauthServerBaseUrl: this.config.oauthServerBaseUrl,\n isCallbackUrl: window.location.href.startsWith(this.config.redirectUrl),\n });\n\n try {\n // Get OAuth endpoints\n this.endpoints = {\n auth: `${this.config.oauthServerBaseUrl}auth`,\n token: `${this.config.oauthServerBaseUrl}token`,\n jwks: `${this.config.oauthServerBaseUrl}jwks`,\n userinfo: `${this.config.oauthServerBaseUrl}userinfo`,\n endsession: `${this.config.oauthServerBaseUrl}endsession`,\n };\n\n this.logger.info(\"🔗 OAuth endpoints configured\", {\n endpoints: this.endpoints,\n });\n\n // Initialize SessionManager with auth config\n if (this.sessionManager) {\n const authConfig = {\n clientId: this.config.clientId,\n redirectUrl: this.config.redirectUrl,\n oauthServer: this.config.oauthServerBaseUrl,\n scopes: this.config.scopes,\n endpoints: this.endpoints,\n };\n this.logger.info(\"🔧 Initializing SessionManager\", { authConfig });\n await this.sessionManager.initializeWithAuthConfig(authConfig);\n }\n\n // Check if we're on the callback page\n const isCallbackPage = window.location.href.startsWith(\n this.config.redirectUrl,\n );\n this.logger.info(\"🔍 Callback page check\", {\n isCallbackPage,\n currentUrl: window.location.href,\n redirectUrl: this.config.redirectUrl,\n });\n\n if (isCallbackPage) {\n this.logger.info(\"📞 Processing callback page\");\n await this.handleCallback();\n } else {\n this.logger.info(\"🏠 Not a callback page, initialization complete\");\n }\n } catch (error) {\n const errorMessage =\n error instanceof Error\n ? error.message\n : \"Failed to initialize authentication\";\n this.logger.error(\"❌ CivicAuth initialization failed\", {\n error: errorMessage,\n stack: error instanceof Error ? error.stack : undefined,\n });\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: errorMessage,\n });\n throw new CivicAuthError(errorMessage, CivicAuthErrorCode.INIT_FAILED);\n }\n }\n\n /**\n * Initialize all handlers with proper configuration\n */\n private initializeHandlers(): void {\n const handlerConfig = {\n config: this.config,\n logger: this.logger,\n onAuthSuccess: this.handleAuthSuccess.bind(this),\n onAuthError: this.handleAuthError.bind(this),\n cleanup: this.cleanup.bind(this),\n };\n\n this.messageHandler = new MessageHandler({\n ...handlerConfig,\n onPopupFailure: this.handlePopupFailure.bind(this),\n });\n\n this.popupHandler = new PopupHandler(handlerConfig);\n\n this.iframeAuthHandler = new IframeAuthHandler({\n ...handlerConfig,\n messageHandler: this.messageHandler.handleMessage,\n });\n }\n\n /**\n * Builds the authentication URL with PKCE challenge\n */\n private async buildAuthUrl(): Promise<string> {\n if (!this.endpoints) {\n throw new CivicAuthError(\n \"OAuth endpoints not initialized. Please wait for initialization to complete.\",\n CivicAuthErrorCode.ENDPOINTS_NOT_INITIALIZED,\n );\n }\n\n const pkceProducer = new GenericPublicClientPKCEProducer(this.storage);\n const codeChallenge = await pkceProducer.getCodeChallenge();\n const state =\n this.config.initialState ||\n generateState({\n displayMode: this.config.displayMode || \"iframe\",\n });\n\n return buildAuthUrl({\n endpoints: this.endpoints,\n clientId: this.config.clientId,\n redirectUrl: this.config.redirectUrl,\n scopes: this.config.scopes,\n codeChallenge,\n state,\n prompt: this.config.prompt,\n nonce: this.config.nonce,\n });\n }\n\n /**\n * Starts the authentication process\n * @returns A promise that resolves with the authentication result\n * @throws {CivicAuthError} If authentication fails or times out\n */\n async startAuthentication(): Promise<AuthResult> {\n this.logger.info(\"🎬 Starting authentication process\", {\n displayMode: this.config.displayMode,\n userAgent: navigator.userAgent,\n currentUrl: window.location.href,\n });\n\n if (!this.endpoints) {\n const error = new CivicAuthError(\n \"OAuth endpoints not initialized. Please wait for initialization to complete.\",\n CivicAuthErrorCode.ENDPOINTS_NOT_INITIALIZED,\n );\n this.logger.error(\"❌ Endpoints not initialized\", {\n error: error.message,\n });\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: error.message,\n });\n throw error;\n }\n\n if (this.authPromise) {\n this.logger.info(\n \"⏳ Authentication already in progress, returning existing promise\",\n );\n return this.authPromise;\n }\n\n const fullAuthUrl = await this.buildAuthUrl();\n this.logger.info(\"🔗 Built authentication URL\", {\n url: fullAuthUrl,\n displayMode: this.config.displayMode,\n authProcessTimeout: this.config.authProcessTimeout,\n });\n\n this.authPromise = new Promise<AuthResult>((resolve, reject) => {\n this.authPromiseResolve = resolve;\n this.authPromiseReject = reject;\n\n this.handleAuthenticationByDisplayMode(fullAuthUrl);\n this.setupAuthenticationTimeout();\n });\n\n return this.authPromise;\n }\n\n /**\n * Handle authentication based on display mode\n */\n private async handleAuthenticationByDisplayMode(\n fullAuthUrl: string,\n ): Promise<void> {\n this.logger.info(\"🎯 Handling authentication with display mode\", {\n displayMode: this.config.displayMode,\n });\n\n try {\n switch (this.config.displayMode) {\n case \"redirect\":\n this.logger.info(\"🌐 Using redirect mode\");\n window.location.href = fullAuthUrl;\n break;\n\n case \"new_tab\":\n this.logger.info(\"📱 Using new_tab mode\");\n if (!this.popupHandler) {\n throw new Error(\"Popup handler not initialized\");\n }\n await this.popupHandler.handleNewTabAuth(fullAuthUrl);\n break;\n\n case \"iframe\":\n default: {\n this.logger.info(\"🖼️ Using iframe mode\");\n if (!this.iframeAuthHandler || !this.messageHandler) {\n throw new Error(\"Iframe handler not initialized\");\n }\n const iframeElement =\n await this.iframeAuthHandler.handleIframeAuth(fullAuthUrl);\n this.messageHandler.updateIframeElement(iframeElement);\n break;\n }\n }\n } catch (error) {\n if (error instanceof PopupError) {\n await this.handlePopupErrorWithFallback(fullAuthUrl, error);\n } else {\n this.handleAuthError(\n error instanceof Error ? error : new Error(String(error)),\n );\n }\n }\n }\n\n /**\n * Handle popup error with redirect fallback\n */\n private async handlePopupErrorWithFallback(\n fullAuthUrl: string,\n error: PopupError,\n ): Promise<void> {\n this.logger.warn(\"🚫 Popup failed, falling back to redirect mode\", {\n originalDisplayMode: this.config.displayMode,\n error: error.message,\n });\n\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Popup blocked, falling back to redirect mode\",\n });\n\n try {\n this.logger.info(\"🔄 Attempting redirect fallback\");\n\n // Clean up current authentication attempt\n this.cleanup();\n\n // Always switch to redirect mode for Safari compatibility\n this.config.displayMode = \"redirect\";\n\n // Regenerate the auth URL with updated display mode in state\n const fallbackAuthUrl = await this.buildAuthUrl();\n\n this.logger.info(\"🌐 Redirecting to auth URL\", { url: fallbackAuthUrl });\n window.location.href = fallbackAuthUrl;\n this.logger.info(\"✅ Redirect initiated successfully\");\n } catch (redirectError) {\n this.logger.error(\"❌ Redirect fallback failed\", {\n error: redirectError,\n redirectUrl: fullAuthUrl,\n });\n\n const fallbackError = new CivicAuthError(\n \"Failed to open popup window and redirect fallback failed. Please check your browser's popup settings.\",\n CivicAuthErrorCode.INIT_FAILED,\n );\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: fallbackError.message,\n });\n this.handleAuthError(fallbackError);\n }\n }\n\n /**\n * Setup authentication timeout\n */\n private setupAuthenticationTimeout(): void {\n if (this.config.authProcessTimeout && this.config.authProcessTimeout > 0) {\n this.logger.debug(\"⏰ Setting up authentication timeout\", {\n authProcessTimeout: this.config.authProcessTimeout,\n displayMode: this.config.displayMode,\n });\n\n this.authProcessTimeoutHandle = window.setTimeout(() => {\n this.logger.error(\"⏰ Authentication timed out\", {\n displayMode: this.config.displayMode,\n currentOrigin: window.location.origin,\n authProcessTimeout: this.config.authProcessTimeout,\n });\n\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Authentication timed out\",\n });\n\n const error = new CivicAuthError(\n \"Authentication timed out\",\n CivicAuthErrorCode.AUTH_PROCESS_TIMEOUT,\n );\n this.handleAuthError(error);\n }, this.config.authProcessTimeout);\n }\n }\n\n /**\n * Handle successful authentication\n */\n private handleAuthSuccess(result: AuthResult): void {\n this.logger.info(\"✅ Authentication successful\");\n this.authPromiseResolve?.(result);\n this.cleanup();\n }\n\n /**\n * Handle authentication error\n */\n private handleAuthError(error: Error): void {\n this.logger.error(\"❌ Authentication failed\", { error: error.message });\n this.authPromiseReject?.(error);\n this.cleanup();\n }\n\n /**\n * Handle popup failure - simplified like React implementation\n */\n private handlePopupFailure(failedUrl?: string): void {\n this.hasPopupFailed = true;\n\n this.logger.warn(\"Popup failed, using redirect mode instead...\", {\n failedUrl,\n });\n\n // Clean up iframe if it exists\n if (this.iframeAuthHandler) {\n this.iframeAuthHandler.cleanupIframe();\n }\n\n // Always redirect to the failed URL or build a new one\n if (failedUrl) {\n window.location.href = failedUrl;\n } else {\n this.buildAuthUrl()\n .then((authUrl) => {\n window.location.href = authUrl;\n })\n .catch((error) => {\n this.logger.error(\"Failed to build auth URL for redirect fallback\", {\n error,\n });\n const fallbackError = new CivicAuthError(\n \"Failed to redirect for authentication\",\n CivicAuthErrorCode.INIT_FAILED,\n );\n this.handleAuthError(fallbackError);\n });\n }\n }\n\n /**\n * Show popup failure message to user\n */\n private showPopupFailureMessage(\n customMessage: string = \"Authentication will continue in this window. Please wait...\",\n ): void {\n const container = this.getContainerElement();\n if (!container) {\n this.logger.warn(\n \"Cannot show popup failure message - container not found\",\n );\n return;\n }\n const existingMessage = document.getElementById(\n \"civic-auth-popup-failure-message\",\n );\n if (existingMessage && existingMessage.parentNode) {\n existingMessage.parentNode.removeChild(existingMessage);\n }\n const messageOverlay = document.createElement(\"div\");\n messageOverlay.id = \"civic-auth-popup-failure-message\";\n messageOverlay.style.cssText =\n \"position:absolute;top:0;left:0;right:0;background:rgba(255,249,196,.95);border:1px solid #f59e0b;border-radius:6px;padding:12px;margin:8px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;font-size:14px;color:#92400e;z-index:1000;box-shadow:0 2px 4px rgba(0,0,0,.1);\";\n messageOverlay.innerHTML =\n '<div style=\"display:flex;align-items:center;gap:8px;\">' +\n '<span style=\"font-size:16px;\">⚠️</span>' +\n \"<div>\" +\n \"<strong>Popup blocked</strong><br>\" +\n '<span style=\"font-size:12px;\">' +\n customMessage +\n \"</span>\" +\n \"</div>\" +\n \"</div>\";\n\n if (getComputedStyle(container).position === \"static\") {\n container.style.position = \"relative\";\n }\n\n container.appendChild(messageOverlay);\n\n setTimeout(() => {\n if (messageOverlay.parentNode) {\n messageOverlay.parentNode.removeChild(messageOverlay);\n }\n }, 10000);\n this.logger.info(\"Popup failure message displayed to user\");\n }\n\n /**\n * Setup popup failure timeout\n */\n private setupPopupFailureTimeout(): void {\n this.popupFailureTimeoutHandle = window.setTimeout(() => {\n this.logger.info(\"⏰ Popup failure timeout reached\");\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Authentication timeout - popup failure scenario\",\n });\n\n const error = new CivicAuthError(\n \"Authentication timeout - popup failure scenario\",\n CivicAuthErrorCode.AUTH_PROCESS_TIMEOUT,\n );\n this.handleAuthError(error);\n }, 20000); // 20 seconds\n }\n\n /**\n * Gets the container element for the auth iframe\n */\n private getContainerElement(): HTMLElement | null {\n if (typeof this.config.targetContainerElement === \"string\") {\n const element = document.getElementById(\n this.config.targetContainerElement,\n );\n if (!element) {\n this.logger.warn(\n `Container element with ID \"${this.config.targetContainerElement}\" not found`,\n );\n }\n return element;\n }\n return this.config.targetContainerElement ?? null;\n }\n\n /**\n * Handle OAuth callback\n */\n private async handleCallback(): Promise<void> {\n this.logger.info(\"🔄 Handling OAuth callback\", {\n currentUrl: window.location.href,\n redirectUrl: this.config.redirectUrl,\n });\n\n try {\n const callbackHandled = await handleOAuthRedirectPage({\n clientId: this.config.clientId,\n oauthServer: this.config.oauthServerBaseUrl,\n redirectUrl: this.config.redirectUrl,\n textSignals: {\n success: this.config.textSignals.success,\n error: this.config.textSignals.error || \"Authentication failed\",\n },\n storageAdapter: this.storage,\n });\n\n this.logger.info(\"📋 Callback processing result\", { callbackHandled });\n\n if (callbackHandled) {\n const successSignal = document.getElementById(\n CIVIC_AUTH_CONSTANTS.SUCCESS_SIGNAL_ID,\n );\n const errorSignal = document.getElementById(\n CIVIC_AUTH_CONSTANTS.ERROR_SIGNAL_ID,\n );\n\n if (successSignal) {\n this.logger.info(\"✅ Success signal found\");\n let userInfo = null;\n const userInfoAttr = successSignal.getAttribute(\"data-user-info\");\n if (userInfoAttr) {\n try {\n userInfo = JSON.parse(userInfoAttr);\n } catch (error) {\n this.logger.error(\"❌ Failed to parse user info\", { error });\n }\n }\n this.config.events?.emit(AuthEvent.SIGN_IN_COMPLETE, {\n detail: \"Callback processed successfully\",\n user: userInfo,\n });\n } else if (errorSignal) {\n this.logger.error(\"❌ Error signal found\");\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: errorSignal.textContent || \"Unknown error during callback\",\n });\n }\n }\n } catch (error) {\n this.logger.error(\"❌ Callback handling failed\", { error });\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail:\n error instanceof Error\n ? error.message\n : \"Unknown error during callback\",\n });\n }\n }\n\n /**\n * Cleans up resources and event listeners\n */\n public cleanup(): void {\n this.logger.info(\"Cleaning up authentication client\");\n\n // Clean up handlers\n this.iframeAuthHandler?.cleanupIframe();\n\n // Clean up timeouts\n if (this.authProcessTimeoutHandle) {\n window.clearTimeout(this.authProcessTimeoutHandle);\n this.authProcessTimeoutHandle = undefined;\n }\n\n if (this.popupFailureTimeoutHandle) {\n window.clearTimeout(this.popupFailureTimeoutHandle);\n this.popupFailureTimeoutHandle = undefined;\n }\n\n // Reset state\n this.hasPopupFailed = false;\n this.authPromise = undefined;\n this.authPromiseResolve = undefined;\n this.authPromiseReject = undefined;\n\n // Remove message event listener\n if (this.messageHandler) {\n window.removeEventListener(\"message\", this.messageHandler.handleMessage);\n }\n }\n\n /**\n * Get the current session\n */\n public async getCurrentSession(): Promise<Session | null> {\n return this.sessionManager?.getCurrentSession() || null;\n }\n\n /**\n * Check if user is authenticated\n */\n public async isAuthenticated(): Promise<boolean> {\n return this.sessionManager?.isAuthenticated() || false;\n }\n\n /**\n * Get the current user\n */\n public async getCurrentUser() {\n return this.sessionManager?.getCurrentUser() || null;\n }\n\n /**\n * Clear the current session\n */\n public async clearSession(): Promise<void> {\n if (!this.sessionManager) {\n throw new Error(\n \"SessionManager not initialized. Provide events in config.\",\n );\n }\n return this.sessionManager.clearSession();\n }\n\n /**\n * Manually refresh tokens\n */\n public async refreshTokens(): Promise<void> {\n if (!this.sessionManager) {\n throw new Error(\n \"SessionManager not initialized. Provide events in config.\",\n );\n }\n return this.sessionManager.refreshTokens();\n }\n\n /**\n * Get token refresher state for debugging\n */\n public getTokenRefresherState() {\n return this.sessionManager?.getTokenRefresherState() || null;\n }\n\n /**\n * Update the iframe display mode\n * @param mode - The display mode to use for the iframe\n */\n public setIframeDisplayMode(mode: \"modal\" | \"embedded\"): void {\n this.config.iframeDisplayMode = mode;\n this.logger.debug(`Iframe display mode updated to: ${mode}`);\n }\n\n /**\n * Get the current iframe display mode\n * @returns The current iframe display mode\n */\n public getIframeDisplayMode(): \"modal\" | \"embedded\" | undefined {\n return this.config.iframeDisplayMode;\n }\n\n /**\n * Destroy the auth client and clean up all resources\n */\n public async destroy(): Promise<void> {\n this.cleanup();\n await this.sessionManager?.destroy();\n this.sessionManager = undefined;\n this.logger.info(\"CivicAuth destroyed\");\n }\n\n /**\n * Handle logout\n */\n public async logout(): Promise<void> {\n if (!this.sessionManager) {\n throw new Error(\n \"SessionManager not initialized. Provide events in config.\",\n );\n }\n\n try {\n this.logger.info(\"🔄 Starting logout process\");\n this.config.events?.emit(AuthEvent.SIGN_OUT_STARTED, {\n detail: \"Logout process started\",\n });\n\n // Get current tokens before clearing them\n const tokens = await retrieveTokens(this.storage);\n\n if (!tokens?.id_token) {\n this.logger.warn(\"⚠️ No ID token found, clearing local session only\");\n await clearTokens(this.storage);\n await this.sessionManager.clearSession();\n this.config.events?.emit(AuthEvent.SIGN_OUT_COMPLETE, {\n detail: \"Local session cleared\",\n });\n return;\n }\n\n if (!this.endpoints) {\n throw new Error(\"OAuth endpoints not initialized\");\n }\n\n // Generate a state for logout\n const state = generateState({\n displayMode: this.config.displayMode || \"iframe\",\n });\n\n // Generate logout URL\n const logoutUrl = await generateOauthLogoutUrl({\n clientId: this.config.clientId,\n redirectUrl: this.config.redirectUrl,\n idToken: tokens.id_token,\n state: state,\n oauthServer: this.config.oauthServerBaseUrl,\n });\n\n this.logger.info(\"🔗 Generated logout URL\", {\n logoutUrl: logoutUrl.toString(),\n });\n\n // Clear local tokens and session\n await clearTokens(this.storage);\n await this.sessionManager.clearSession();\n\n // Emit logout complete event before redirect\n this.config.events?.emit(AuthEvent.SIGN_OUT_COMPLETE, {\n detail: \"Logout successful\",\n });\n\n // Redirect to logout URL\n this.logger.info(\"🌐 Redirecting to logout URL\");\n window.location.href = logoutUrl.toString();\n } catch (error) {\n this.logger.error(\"❌ Logout failed\", { error });\n this.config.events?.emit(AuthEvent.SIGN_OUT_ERROR, {\n detail: error instanceof Error ? error.message : String(error),\n });\n throw new CivicAuthError(\n \"Logout failed\",\n CivicAuthErrorCode.LOGOUT_FAILED,\n );\n }\n }\n}\n\n// Export types for external use\nexport type { CivicAuthClientConfig } from \"./types/AuthTypes.js\";\nexport { CivicAuthErrorCode } from \"./types/AuthTypes.js\";\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"SessionManager.d.ts","sourceRoot":"","sources":["../../../src/vanillajs/auth/SessionManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACtE,O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AM,wBAAwB,CAAC;AAKzD,qBAAa,cAAc;IACzB,OAAO,CAAC,OAAO,CAAc;IAC7B,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,cAAc,CAAC,CAAiB;IACxC,OAAO,CAAC,MAAM,CAA2B;gBAE7B,cAAc,EAAE,WAAW,EAAE,MAAM,EAAE,oBAAoB;IAQrE;;OAEG;IACG,wBAAwB,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IA0BrE;;OAEG;IACG,iBAAiB,IAAI,OAAO,CAAC,OAAO,GAAG,IAAI,CAAC;IAyBlD;;OAEG;IACG,eAAe,IAAI,OAAO,CAAC,OAAO,CAAC;IAKzC;;OAEG;IACG,cAAc,IAAI,OAAO,CAAC,IAAI,GAAG,IAAI,CAAC;IAS5C;;OAEG;IACG,YAAY,IAAI,OAAO,CAAC,IAAI,CAAC;IAmBnC;;OAEG;IACG,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAUpC;;OAEG;IACH,sBAAsB,IAAI;QACxB,aAAa,EAAE,OAAO,CAAC;QACvB,eAAe,EAAE,OAAO,CAAC;QACzB,mBAAmB,EAAE,OAAO,CAAC;KAC9B,GAAG,IAAI;IAIR;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;CAK/B"}
@@ -1,5 +1,5 @@
1
1
  import { AuthEvent } from "../types/index.js";
2
- import { getCurrentLogger } from "../utils/logger.js";
2
+ import { createLogger } from "../utils/logger.js";
3
3
  import { TokenRefresher } from "./TokenRefresher.js";
4
4
  import { retrieveTokens, clearTokens } from "../../shared/lib/util.js";
5
5
  import { getUser } from "../../shared/lib/session.js";
@@ -8,7 +8,7 @@ export class SessionManager {
8
8
  storage;
9
9
  events;
10
10
  tokenRefresher;
11
- logger = getCurrentLogger();
11
+ logger = createLogger("session");
12
12
  constructor(storageAdapter, events) {
13
13
  this.storage = storageAdapter;
14
14
  this.events = events;
@@ -1 +1 @@
1
- {"version":3,"file":"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IAC/C,CAAC;CACF","sourcesContent":["import type { AuthStorage } from \"../../types.js\";\nimport type { AuthenticationEvents } from \"./AuthenticationEvents.js\";\nimport type { User, Session } from \"../types/index.js\"; // Assuming Session might be used internally\nimport { AuthEvent } from \"../types/index.js\";\nimport { getCurrentLogger } from \"../utils/logger.js\";\nimport { TokenRefresher } from \"./TokenRefresher.js\";\nimport type { AuthConfig } from \"../../server/config.js\";\nimport { retrieveTokens, clearTokens } from \"../../shared/lib/util.js\";\nimport { getUser } from \"../../shared/lib/session.js\";\nimport { GenericUserSession } from \"../../shared/lib/UserSession.js\";\n\nexport class SessionManager {\n private storage: AuthStorage;\n private events: AuthenticationEvents;\n private tokenRefresher?: TokenRefresher;\n private logger = getCurrentLogger();\n\n constructor(storageAdapter: AuthStorage, events: AuthenticationEvents) {\n this.storage = storageAdapter;\n this.events = events;\n this.logger.info(\n \"SessionManager initialized with shared lib token storage\",\n );\n }\n\n /**\n * Initialize the session manager with auth configuration to enable token refresh\n */\n async initializeWithAuthConfig(authConfig: AuthConfig): Promise<void> {\n try {\n // Initialize token refresher\n this.tokenRefresher = new TokenRefresher(\n this.storage,\n this.events,\n authConfig,\n );\n await this.tokenRefresher.initialize(authConfig);\n\n // Set current authentication state\n const isAuthenticated = await this.isAuthenticated();\n this.tokenRefresher.setAuthenticationState(isAuthenticated);\n\n this.logger.info(\n \"SessionManager initialized with token refresh capability\",\n );\n } catch (error) {\n this.logger.error(\n \"Failed to initialize SessionManager with auth config:\",\n error,\n );\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n }\n }\n\n /**\n * Build current session from shared lib storage\n */\n async getCurrentSession(): Promise<Session | null> {\n try {\n const tokens = await retrieveTokens(this.storage);\n const user = await this.getCurrentUser();\n\n if (!tokens?.id_token || !user) {\n this.logger.warn(\n \"No id_token or user available, cannot create session\",\n );\n return null;\n }\n\n return {\n user,\n accessToken: tokens.access_token,\n idToken: tokens.id_token,\n refreshToken: tokens.refresh_token ?? undefined,\n expiresAt: tokens.access_token_expires_at ?? undefined,\n };\n } catch (error) {\n this.logger.error(\"Failed to load session from shared storage:\", error);\n return null;\n }\n }\n\n /**\n * Check if user is authenticated using shared lib utilities\n */\n async isAuthenticated(): Promise<boolean> {\n const tokens = await retrieveTokens(this.storage);\n return !!tokens?.id_token;\n }\n\n /**\n * Get current user from shared lib storage\n */\n async getCurrentUser(): Promise<User | null> {\n try {\n return await getUser(this.storage);\n } catch (error) {\n this.logger.error(\"Failed to get user from shared storage:\", error);\n return null;\n }\n }\n\n /**\n * Clear all authentication data using shared lib utilities\n */\n async clearSession(): Promise<void> {\n try {\n await clearTokens(this.storage);\n\n // Clear user session using shared utilities\n const userSession = new GenericUserSession(this.storage);\n await userSession.clear();\n\n // Stop token refresher when session is cleared\n this.tokenRefresher?.setAuthenticationState(false);\n\n this.events.emit(AuthEvent.USER_SESSION_CHANGED, null);\n this.logger.info(\"Session cleared using shared lib utilities\");\n } catch (error) {\n this.logger.error(\"Failed to clear session:\", error);\n throw error;\n }\n }\n\n /**\n * Manually trigger token refresh\n */\n async refreshTokens(): Promise<void> {\n if (!this.tokenRefresher) {\n throw new Error(\n \"Token refresher not initialized. Call initializeWithAuthConfig first.\",\n );\n }\n\n return this.tokenRefresher.refreshTokens();\n }\n\n /**\n * Get token refresher state for debugging\n */\n getTokenRefresherState(): {\n isInitialized: boolean;\n isAuthenticated: boolean;\n isAutoRefreshActive: boolean;\n } | null {\n return this.tokenRefresher?.getState() || null;\n }\n\n /**\n * Clean up resources when session manager is destroyed\n */\n async destroy(): Promise<void> {\n await this.tokenRefresher?.destroy();\n this.tokenRefresher = undefined;\n this.logger.info(\"SessionManager destroyed\");\n }\n}\n"]}
1
+ {"version":3,"file":"SessionManager.js","sourceRoot":"","sources":["../../../src/vanillajs/auth/SessionManager.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;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CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YAEhC,4CAA4C;YAC5C,MAAM,WAAW,GAAG,IAAI,kBAAkB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACzD,MAAM,WAAW,CAAC,KAAK,EAAE,CAAC;YAE1B,+CAA+C;YAC/C,IAAI,CAAC,cAAc,EAAE,sBAAsB,CAAC,KAAK,CAAC,CAAC;YAEnD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC;YACvD,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,4CAA4C,CAAC,CAAC;QACjE,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,0BAA0B,EAAE,KAAK,CAAC,CAAC;YACrD,MAAM,KAAK,CAAC;QACd,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa;QACjB,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CACb,uEAAuE,CACxE,CAAC;QACJ,CAAC;QAED,OAAO,IAAI,CAAC,cAAc,CAAC,aAAa,EAAE,CAAC;IAC7C,CAAC;IAED;;OAEG;IACH,sBAAsB;QAKpB,OAAO,IAAI,CAAC,cAAc,EAAE,QAAQ,EAAE,IAAI,IAAI,CAAC;IACjD,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,OAAO;QACX,MAAM,IAAI,CAAC,cAAc,EAAE,OAAO,EAAE,CAAC;QACrC,IAAI,CAAC,cAAc,GAAG,SAAS,CAAC;QAChC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC;IAC/C,CAAC;CACF","sourcesContent":["import type { AuthStorage } from \"../../types.js\";\nimport type { AuthenticationEvents } from \"./AuthenticationEvents.js\";\nimport type { User, Session } from \"../types/index.js\"; // Assuming Session might be used internally\nimport { AuthEvent } from \"../types/index.js\";\nimport { createLogger } from \"../utils/logger.js\";\nimport { TokenRefresher } from \"./TokenRefresher.js\";\nimport type { AuthConfig } from \"../../server/config.js\";\nimport { retrieveTokens, clearTokens } from \"../../shared/lib/util.js\";\nimport { getUser } from \"../../shared/lib/session.js\";\nimport { GenericUserSession } from \"../../shared/lib/UserSession.js\";\n\nexport class SessionManager {\n private storage: AuthStorage;\n private events: AuthenticationEvents;\n private tokenRefresher?: TokenRefresher;\n private logger = createLogger(\"session\");\n\n constructor(storageAdapter: AuthStorage, events: AuthenticationEvents) {\n this.storage = storageAdapter;\n this.events = events;\n this.logger.info(\n \"SessionManager initialized with shared lib token storage\",\n );\n }\n\n /**\n * Initialize the session manager with auth configuration to enable token refresh\n */\n async initializeWithAuthConfig(authConfig: AuthConfig): Promise<void> {\n try {\n // Initialize token refresher\n this.tokenRefresher = new TokenRefresher(\n this.storage,\n this.events,\n authConfig,\n );\n await this.tokenRefresher.initialize(authConfig);\n\n // Set current authentication state\n const isAuthenticated = await this.isAuthenticated();\n this.tokenRefresher.setAuthenticationState(isAuthenticated);\n\n this.logger.info(\n \"SessionManager initialized with token refresh capability\",\n );\n } catch (error) {\n this.logger.error(\n \"Failed to initialize SessionManager with auth config:\",\n error,\n );\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n }\n }\n\n /**\n * Build current session from shared lib storage\n */\n async getCurrentSession(): Promise<Session | null> {\n try {\n const tokens = await retrieveTokens(this.storage);\n const user = await this.getCurrentUser();\n\n if (!tokens?.id_token || !user) {\n this.logger.warn(\n \"No id_token or user available, cannot create session\",\n );\n return null;\n }\n\n return {\n user,\n accessToken: tokens.access_token,\n idToken: tokens.id_token,\n refreshToken: tokens.refresh_token ?? undefined,\n expiresAt: tokens.access_token_expires_at ?? undefined,\n };\n } catch (error) {\n this.logger.error(\"Failed to load session from shared storage:\", error);\n return null;\n }\n }\n\n /**\n * Check if user is authenticated using shared lib utilities\n */\n async isAuthenticated(): Promise<boolean> {\n const tokens = await retrieveTokens(this.storage);\n return !!tokens?.id_token;\n }\n\n /**\n * Get current user from shared lib storage\n */\n async getCurrentUser(): Promise<User | null> {\n try {\n return await getUser(this.storage);\n } catch (error) {\n this.logger.error(\"Failed to get user from shared storage:\", error);\n return null;\n }\n }\n\n /**\n * Clear all authentication data using shared lib utilities\n */\n async clearSession(): Promise<void> {\n try {\n await clearTokens(this.storage);\n\n // Clear user session using shared utilities\n const userSession = new GenericUserSession(this.storage);\n await userSession.clear();\n\n // Stop token refresher when session is cleared\n this.tokenRefresher?.setAuthenticationState(false);\n\n this.events.emit(AuthEvent.USER_SESSION_CHANGED, null);\n this.logger.info(\"Session cleared using shared lib utilities\");\n } catch (error) {\n this.logger.error(\"Failed to clear session:\", error);\n throw error;\n }\n }\n\n /**\n * Manually trigger token refresh\n */\n async refreshTokens(): Promise<void> {\n if (!this.tokenRefresher) {\n throw new Error(\n \"Token refresher not initialized. Call initializeWithAuthConfig first.\",\n );\n }\n\n return this.tokenRefresher.refreshTokens();\n }\n\n /**\n * Get token refresher state for debugging\n */\n getTokenRefresherState(): {\n isInitialized: boolean;\n isAuthenticated: boolean;\n isAutoRefreshActive: boolean;\n } | null {\n return this.tokenRefresher?.getState() || null;\n }\n\n /**\n * Clean up resources when session manager is destroyed\n */\n async destroy(): Promise<void> {\n await this.tokenRefresher?.destroy();\n this.tokenRefresher = undefined;\n this.logger.info(\"SessionManager destroyed\");\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"TokenRefresher.d.ts","sourceRoot":"","sources":["../../../src/vanillajs/auth/TokenRefresher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAClD,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAMtE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,wBAAwB,CAAC;AAIzD;;;GAGG;AACH,qBAAa,cAAc;IACzB,OAAO,CAAC,SAAS,CAAC,CAAiC;IAC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,OAAO,CAAC,eAAe,CAAkB;IACzC,OAAO,CAAC,WAAW,CAAkB;IACrC,OAAO,CAAC,MAAM,CAAiC;gBAG7C,OAAO,EAAE,WAAW,EACpB,MAAM,EAAE,oBAAoB,EAC5B,UAAU,CAAC,EAAE,UAAU;IASzB;;OAEG;IACG,UAAU,CAAC,UAAU,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC;IAoDvD;;OAEG;IACH,sBAAsB,CAAC,eAAe,EAAE,OAAO,GAAG,IAAI;IAgBtD;;OAEG;IACG,aAAa,IAAI,OAAO,CAAC,IAAI,CAAC;IAuBpC;;OAEG;YACW,gBAAgB;IAwB9B;;OAEG;IACH,OAAO,CAAC,eAAe;IAOvB;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAW9B;;OAEG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAM9B;;OAEG;IACH,QAAQ,IAAI;QACV,aAAa,EAAE,OAAO,CAAC;QACvB,eAAe,EAAE,OAAO,CAAC;QACzB,mBAAmB,EAAE,OAAO,CAAC;KAC9B;CAOF"}
@@ -1,6 +1,6 @@
1
1
  import { AuthEvent } from "../types/index.js";
2
2
  import { BrowserAuthenticationRefresher, } from "../../shared/lib/BrowserAuthenticationRefresher.js";
3
- import { getCurrentLogger } from "../utils/logger.js";
3
+ import { createLogger } from "../utils/logger.js";
4
4
  import { retrieveAccessTokenExpiresAt } from "../../shared/lib/util.js";
5
5
  /**
6
6
  * TokenRefresher handles automatic token refresh for vanilla.js implementation
@@ -13,7 +13,7 @@ export class TokenRefresher {
13
13
  authConfig;
14
14
  isAuthenticated = false;
15
15
  isDestroyed = false;
16
- logger = getCurrentLogger();
16
+ logger = createLogger("token-refresh");
17
17
  constructor(storage, events, authConfig) {
18
18
  this.storage = storage;
19
19
  this.events = events;
@@ -1 +1 @@
1
- {"version":3,"file":"TokenRefresher.js","sourceRoot":"","sources":["../../../src/vanillajs/auth/TokenRefresher.ts"],"names":[],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AAC,kCAAkC,CAAC,CAAC;YACrD,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,CAAC;QACpC,CAAC;IACH,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,OAAO;QACX,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;QAE/C,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACnB,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE,CAAC;YAClC,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC;QAC7B,CAAC;QAED,IAAI,CAAC,eAAe,GAAG,KAAK,CAAC;IAC/B,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,OAAO;QACX,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC;QACxB,MAAM,IAAI,CAAC,OAAO,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,0BAA0B,CAAC,CAAC;IAC/C,CAAC;IAED;;OAEG;IACH,QAAQ;QAKN,OAAO;YACL,aAAa,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS;YAC/B,eAAe,EAAE,IAAI,CAAC,eAAe;YACrC,mBAAmB,EAAE,IAAI,CAAC,eAAe,IAAI,CAAC,CAAC,IAAI,CAAC,SAAS;SAC9D,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { AuthStorage } from \"../../types.js\";\nimport type { AuthenticationEvents } from \"./AuthenticationEvents.js\";\nimport { AuthEvent } from \"../types/index.js\";\nimport {\n BrowserAuthenticationRefresher,\n type RefreshEventCallbacks,\n} from \"../../shared/lib/BrowserAuthenticationRefresher.js\";\nimport type { AuthConfig } from \"../../server/config.js\";\nimport { getCurrentLogger } from \"../utils/logger.js\";\nimport { retrieveAccessTokenExpiresAt } from \"../../shared/lib/util.js\";\n\n/**\n * TokenRefresher handles automatic token refresh for vanilla.js implementation\n * Inspired by the React useRefresh hook and BrowserAuthenticationRefresher\n */\nexport class TokenRefresher {\n private refresher?: BrowserAuthenticationRefresher;\n private storage: AuthStorage;\n private events: AuthenticationEvents;\n private authConfig?: AuthConfig;\n private isAuthenticated: boolean = false;\n private isDestroyed: boolean = false;\n private logger = getCurrentLogger();\n\n constructor(\n storage: AuthStorage,\n events: AuthenticationEvents,\n authConfig?: AuthConfig,\n ) {\n this.storage = storage;\n this.events = events;\n this.authConfig = authConfig;\n\n this.logger.info(\"TokenRefresher initialized\");\n }\n\n /**\n * Initialize the token refresher with auth configuration\n */\n async initialize(authConfig: AuthConfig): Promise<void> {\n if (this.isDestroyed) return;\n\n this.authConfig = authConfig;\n\n try {\n // Clear any existing refresher\n await this.cleanup();\n\n const onError = async (error: Error) => {\n this.logger.error(\"Token refresh error:\", error);\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n\n // Clear auto-refresh on error\n this.refresher?.clearAutorefresh();\n\n // Optionally sign out the user on refresh token errors\n // This mirrors the React implementation behavior\n this.events.emit(AuthEvent.SIGN_OUT_STARTED, null);\n };\n\n // Create callbacks for refresh events\n const refreshEventCallbacks: RefreshEventCallbacks = {\n onRefreshStarted: () => {\n this.logger.info(\"Auto token refresh started\");\n this.events.emit(AuthEvent.TOKEN_REFRESH_STARTED, null);\n },\n onRefreshComplete: () => {\n this.logger.info(\"Auto token refresh completed\");\n this.events.emit(AuthEvent.TOKEN_REFRESH_COMPLETE, null);\n },\n onRefreshError: (error: Error) => {\n this.logger.error(\"Auto token refresh failed:\", error);\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n },\n };\n\n this.refresher = await BrowserAuthenticationRefresher.build(\n authConfig,\n this.storage,\n onError,\n undefined, // endpointOverrides\n refreshEventCallbacks,\n );\n\n this.logger.info(\"TokenRefresher initialized\");\n } catch (error) {\n this.logger.error(\"Failed to initialize TokenRefresher:\", error);\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n }\n }\n\n /**\n * Set authentication state and manage auto-refresh accordingly\n */\n setAuthenticationState(isAuthenticated: boolean): void {\n if (this.isDestroyed) return;\n\n this.isAuthenticated = isAuthenticated;\n\n if (isAuthenticated && this.refresher) {\n // Fire and forget the async call - we don't want to make setAuthenticationState async\n // as it would break the interface\n this.startAutoRefresh().catch((error) => {\n this.logger.error(\"Error starting auto refresh:\", error);\n });\n } else {\n this.stopAutoRefresh();\n }\n }\n\n /**\n * Manually refresh tokens\n */\n async refreshTokens(): Promise<void> {\n if (this.isDestroyed || !this.refresher) {\n const errorMsg = `TokenRefresher not initialized or destroyed. isDestroyed: ${this.isDestroyed}, hasRefresher: ${!!this.refresher}`;\n this.logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n try {\n this.events.emit(AuthEvent.TOKEN_REFRESH_STARTED, null);\n\n this.logger.info(\"Starting manual token refresh\");\n\n await this.refresher.refreshTokens();\n\n this.events.emit(AuthEvent.TOKEN_REFRESH_COMPLETE, null);\n this.logger.info(\"Manual token refresh completed\");\n } catch (error) {\n this.logger.error(\"Manual token refresh failed:\", error);\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n throw error;\n }\n }\n\n /**\n * Start automatic token refresh\n */\n private async startAutoRefresh(): Promise<void> {\n if (this.refresher && this.isAuthenticated) {\n this.logger.info(\"Starting automatic token refresh\");\n\n try {\n // Calculate when the next refresh will happen (same logic as BrowserAuthenticationRefresher)\n const now = Math.floor(Date.now() / 1000);\n const expiresAt =\n (await retrieveAccessTokenExpiresAt(this.storage)) || now + 60;\n const bufferTime = 30; // 30 seconds buffer\n const refreshTime = Math.max(0, expiresAt - bufferTime - now);\n\n const nextRefreshDate = new Date((now + refreshTime) * 1000);\n this.logger.info(\n `Next token refresh scheduled for: ${nextRefreshDate.toISOString()} (in ${refreshTime} seconds)`,\n );\n } catch (error) {\n this.logger.warn(\"Could not calculate next refresh time:\", error);\n }\n\n this.refresher.setupAutorefresh();\n }\n }\n\n /**\n * Stop automatic token refresh\n */\n private stopAutoRefresh(): void {\n if (this.refresher) {\n this.logger.info(\"Stopping automatic token refresh\");\n this.refresher.clearAutorefresh();\n }\n }\n\n /**\n * Clean up resources\n */\n async cleanup(): Promise<void> {\n this.logger.info(\"Cleaning up TokenRefresher\");\n\n if (this.refresher) {\n this.refresher.clearAutorefresh();\n this.refresher = undefined;\n }\n\n this.isAuthenticated = false;\n }\n\n /**\n * Destroy the token refresher permanently\n */\n async destroy(): Promise<void> {\n this.isDestroyed = true;\n await this.cleanup();\n this.logger.info(\"TokenRefresher destroyed\");\n }\n\n /**\n * Get current refresh state\n */\n getState(): {\n isInitialized: boolean;\n isAuthenticated: boolean;\n isAutoRefreshActive: boolean;\n } {\n return {\n isInitialized: !!this.refresher,\n isAuthenticated: this.isAuthenticated,\n isAutoRefreshActive: this.isAuthenticated && !!this.refresher,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"TokenRefresher.js","sourceRoot":"","sources":["../../../src/vanillajs/auth/TokenRefresher.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EACL,8BAA8B,GAE/B,MAAM,oDAAoD,CAAC;AAE5D,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,4BAA4B,EAAE,MAAM,0BAA0B,CAAC;AAExE;;;GAGG;AACH,MAAM,OAAO,cAAc;IACjB,SAAS,CAAkC;IAC3C,OAAO,CAAc;IACrB,MAAM,CAAuB;IAC7B,UAAU,CAAc;IACxB,eAAe,GAAY,KAAK,CAAC;IACjC,WAAW,GAAY,KAAK,CAAC;IAC7B,MAAM,GAAG,YAAY,CAAC,eAAe,CAAC,CAAC;IAE/C,YACE,OAAoB,EACpB,MAA4B,EAC5B,UAAuB;QAEvB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAE7B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,4BAA4B,CAAC,CAAC;IACjD,CA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B,eAAe,EAAE,IAAI,CAAC,eAAe;YACrC,mBAAmB,EAAE,IAAI,CAAC,eAAe,IAAI,CAAC,CAAC,IAAI,CAAC,SAAS;SAC9D,CAAC;IACJ,CAAC;CACF","sourcesContent":["import type { AuthStorage } from \"../../types.js\";\nimport type { AuthenticationEvents } from \"./AuthenticationEvents.js\";\nimport { AuthEvent } from \"../types/index.js\";\nimport {\n BrowserAuthenticationRefresher,\n type RefreshEventCallbacks,\n} from \"../../shared/lib/BrowserAuthenticationRefresher.js\";\nimport type { AuthConfig } from \"../../server/config.js\";\nimport { createLogger } from \"../utils/logger.js\";\nimport { retrieveAccessTokenExpiresAt } from \"../../shared/lib/util.js\";\n\n/**\n * TokenRefresher handles automatic token refresh for vanilla.js implementation\n * Inspired by the React useRefresh hook and BrowserAuthenticationRefresher\n */\nexport class TokenRefresher {\n private refresher?: BrowserAuthenticationRefresher;\n private storage: AuthStorage;\n private events: AuthenticationEvents;\n private authConfig?: AuthConfig;\n private isAuthenticated: boolean = false;\n private isDestroyed: boolean = false;\n private logger = createLogger(\"token-refresh\");\n\n constructor(\n storage: AuthStorage,\n events: AuthenticationEvents,\n authConfig?: AuthConfig,\n ) {\n this.storage = storage;\n this.events = events;\n this.authConfig = authConfig;\n\n this.logger.info(\"TokenRefresher initialized\");\n }\n\n /**\n * Initialize the token refresher with auth configuration\n */\n async initialize(authConfig: AuthConfig): Promise<void> {\n if (this.isDestroyed) return;\n\n this.authConfig = authConfig;\n\n try {\n // Clear any existing refresher\n await this.cleanup();\n\n const onError = async (error: Error) => {\n this.logger.error(\"Token refresh error:\", error);\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n\n // Clear auto-refresh on error\n this.refresher?.clearAutorefresh();\n\n // Optionally sign out the user on refresh token errors\n // This mirrors the React implementation behavior\n this.events.emit(AuthEvent.SIGN_OUT_STARTED, null);\n };\n\n // Create callbacks for refresh events\n const refreshEventCallbacks: RefreshEventCallbacks = {\n onRefreshStarted: () => {\n this.logger.info(\"Auto token refresh started\");\n this.events.emit(AuthEvent.TOKEN_REFRESH_STARTED, null);\n },\n onRefreshComplete: () => {\n this.logger.info(\"Auto token refresh completed\");\n this.events.emit(AuthEvent.TOKEN_REFRESH_COMPLETE, null);\n },\n onRefreshError: (error: Error) => {\n this.logger.error(\"Auto token refresh failed:\", error);\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n },\n };\n\n this.refresher = await BrowserAuthenticationRefresher.build(\n authConfig,\n this.storage,\n onError,\n undefined, // endpointOverrides\n refreshEventCallbacks,\n );\n\n this.logger.info(\"TokenRefresher initialized\");\n } catch (error) {\n this.logger.error(\"Failed to initialize TokenRefresher:\", error);\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n }\n }\n\n /**\n * Set authentication state and manage auto-refresh accordingly\n */\n setAuthenticationState(isAuthenticated: boolean): void {\n if (this.isDestroyed) return;\n\n this.isAuthenticated = isAuthenticated;\n\n if (isAuthenticated && this.refresher) {\n // Fire and forget the async call - we don't want to make setAuthenticationState async\n // as it would break the interface\n this.startAutoRefresh().catch((error) => {\n this.logger.error(\"Error starting auto refresh:\", error);\n });\n } else {\n this.stopAutoRefresh();\n }\n }\n\n /**\n * Manually refresh tokens\n */\n async refreshTokens(): Promise<void> {\n if (this.isDestroyed || !this.refresher) {\n const errorMsg = `TokenRefresher not initialized or destroyed. isDestroyed: ${this.isDestroyed}, hasRefresher: ${!!this.refresher}`;\n this.logger.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n try {\n this.events.emit(AuthEvent.TOKEN_REFRESH_STARTED, null);\n\n this.logger.info(\"Starting manual token refresh\");\n\n await this.refresher.refreshTokens();\n\n this.events.emit(AuthEvent.TOKEN_REFRESH_COMPLETE, null);\n this.logger.info(\"Manual token refresh completed\");\n } catch (error) {\n this.logger.error(\"Manual token refresh failed:\", error);\n this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);\n throw error;\n }\n }\n\n /**\n * Start automatic token refresh\n */\n private async startAutoRefresh(): Promise<void> {\n if (this.refresher && this.isAuthenticated) {\n this.logger.info(\"Starting automatic token refresh\");\n\n try {\n // Calculate when the next refresh will happen (same logic as BrowserAuthenticationRefresher)\n const now = Math.floor(Date.now() / 1000);\n const expiresAt =\n (await retrieveAccessTokenExpiresAt(this.storage)) || now + 60;\n const bufferTime = 30; // 30 seconds buffer\n const refreshTime = Math.max(0, expiresAt - bufferTime - now);\n\n const nextRefreshDate = new Date((now + refreshTime) * 1000);\n this.logger.info(\n `Next token refresh scheduled for: ${nextRefreshDate.toISOString()} (in ${refreshTime} seconds)`,\n );\n } catch (error) {\n this.logger.warn(\"Could not calculate next refresh time:\", error);\n }\n\n this.refresher.setupAutorefresh();\n }\n }\n\n /**\n * Stop automatic token refresh\n */\n private stopAutoRefresh(): void {\n if (this.refresher) {\n this.logger.info(\"Stopping automatic token refresh\");\n this.refresher.clearAutorefresh();\n }\n }\n\n /**\n * Clean up resources\n */\n async cleanup(): Promise<void> {\n this.logger.info(\"Cleaning up TokenRefresher\");\n\n if (this.refresher) {\n this.refresher.clearAutorefresh();\n this.refresher = undefined;\n }\n\n this.isAuthenticated = false;\n }\n\n /**\n * Destroy the token refresher permanently\n */\n async destroy(): Promise<void> {\n this.isDestroyed = true;\n await this.cleanup();\n this.logger.info(\"TokenRefresher destroyed\");\n }\n\n /**\n * Get current refresh state\n */\n getState(): {\n isInitialized: boolean;\n isAuthenticated: boolean;\n isAutoRefreshActive: boolean;\n } {\n return {\n isInitialized: !!this.refresher,\n isAuthenticated: this.isAuthenticated,\n isAutoRefreshActive: this.isAuthenticated && !!this.refresher,\n };\n }\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import type { CivicAuthClientConfig, ProcessedCivicAuthConfig } from "../types/AuthTypes.js";
2
+ /**
3
+ * Process the configuration with defaults and validation
4
+ */
5
+ export declare function processConfigWithDefaults(config: CivicAuthClientConfig): ProcessedCivicAuthConfig;
6
+ //# sourceMappingURL=ConfigProcessor.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConfigProcessor.d.ts","sourceRoot":"","sources":["../../../../src/vanillajs/auth/config/ConfigProcessor.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,qBAAqB,EACrB,wBAAwB,EAEzB,MAAM,uBAAuB,CAAC;AAO/B;;GAEG;AACH,wBAAgB,yBAAyB,CACvC,MAAM,EAAE,qBAAqB,GAC5B,wBAAwB,CAgC1B"}
@@ -0,0 +1,59 @@
1
+ import { LocalStorageAdapter } from "../../../browser/storage.js";
2
+ import { DEFAULT_SCOPES } from "../../../constants.js";
3
+ import { CivicAuthError, CivicAuthErrorCode, CIVIC_AUTH_CONSTANTS, } from "../types/AuthTypes.js";
4
+ /**
5
+ * Process the configuration with defaults and validation
6
+ */
7
+ export function processConfigWithDefaults(config) {
8
+ // Validate required configuration
9
+ validateRequiredConfig(config);
10
+ const loggingConfig = {
11
+ enabled: true,
12
+ namespace: "*",
13
+ level: "debug",
14
+ ...config.logging,
15
+ };
16
+ return {
17
+ ...config,
18
+ redirectUrl: config.redirectUrl ||
19
+ `${window.location.origin}${window.location.pathname}`,
20
+ oauthServerBaseUrl: config.oauthServerBaseUrl || "https://auth.civic.com/oauth/",
21
+ scopes: config.scopes || DEFAULT_SCOPES,
22
+ textSignals: config.textSignals || {
23
+ success: "Authentication successful!",
24
+ error: "Authentication failed. Please try again.",
25
+ },
26
+ displayMode: config.displayMode || "iframe",
27
+ authProcessTimeout: config.authProcessTimeout ||
28
+ CIVIC_AUTH_CONSTANTS.DEFAULT_AUTH_PROCESS_TIMEOUT,
29
+ iframeId: config.iframeId || CIVIC_AUTH_CONSTANTS.DEFAULT_IFRAME_ID,
30
+ prompt: "consent",
31
+ logging: loggingConfig,
32
+ storageAdapter: config.storageAdapter || new LocalStorageAdapter(),
33
+ };
34
+ }
35
+ /**
36
+ * Validates required configuration properties
37
+ */
38
+ function validateRequiredConfig(config) {
39
+ // Always required configurations
40
+ const requiredConfigs = [{ key: "clientId", value: config.clientId }];
41
+ // Validate always-required fields
42
+ for (const { key, value } of requiredConfigs) {
43
+ if (!value) {
44
+ throw new CivicAuthError(`CivicAuth: ${key} is required.`, CivicAuthErrorCode.CONFIG_REQUIRED);
45
+ }
46
+ }
47
+ // Conditional validation for targetContainerElement
48
+ // Only required for embedded iframe mode
49
+ const displayMode = config.displayMode || "iframe";
50
+ const iframeDisplayMode = config.iframeDisplayMode;
51
+ // Check if we need a container element
52
+ const needsContainer = displayMode === "iframe" && iframeDisplayMode === "embedded";
53
+ if (needsContainer && !config.targetContainerElement) {
54
+ throw new CivicAuthError("CivicAuth: targetContainerElement is required for embedded iframe mode. " +
55
+ "For modal iframe mode, set iframeDisplayMode to 'modal'. " +
56
+ "For non-iframe modes, use displayMode 'redirect' or 'new_tab'.", CivicAuthErrorCode.CONFIG_REQUIRED);
57
+ }
58
+ }
59
+ //# sourceMappingURL=ConfigProcessor.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConfigProcessor.js","sourceRoot":"","sources":["../../../../src/vanillajs/auth/config/ConfigProcessor.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAClE,OAAO,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAMvD,OAAO,EACL,cAAc,EACd,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,uBAAuB,CAAC;AAE/B;;GAEG;AACH,MAAM,UAAU,yBAAyB,CACvC,MAA6B;IAE7B,kCAAkC;IAClC,sBAAsB,CAAC,MAAM,CAAC,CAAC;IAE/B,MAAM,aAAa,GAAkB;QACnC,OAAO,EAAE,IAAI;QACb,SAAS,EAAE,GAAG;QACd,KAAK,EAAE,OAAgB;QACvB,GAAG,MAAM,CAAC,OAAO;KAClB,CAAC;IAEF,OAAO;QACL,GAAG,MAAM;QACT,WAAW,EACT,MAAM,CAAC,WAAW;YAClB,GAAG,MAAM,CAAC,QAAQ,CAAC,MAAM,GAAG,MAAM,CAAC,QA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BAAsB,EAAE,CAAC;QACrD,MAAM,IAAI,cAAc,CACtB,0EAA0E;YACxE,2DAA2D;YAC3D,gEAAgE,EAClE,kBAAkB,CAAC,eAAe,CACnC,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import { LocalStorageAdapter } from \"../../../browser/storage.js\";\nimport { DEFAULT_SCOPES } from \"../../../constants.js\";\nimport type {\n CivicAuthClientConfig,\n ProcessedCivicAuthConfig,\n LoggingConfig,\n} from \"../types/AuthTypes.js\";\nimport {\n CivicAuthError,\n CivicAuthErrorCode,\n CIVIC_AUTH_CONSTANTS,\n} from \"../types/AuthTypes.js\";\n\n/**\n * Process the configuration with defaults and validation\n */\nexport function processConfigWithDefaults(\n config: CivicAuthClientConfig,\n): ProcessedCivicAuthConfig {\n // Validate required configuration\n validateRequiredConfig(config);\n\n const loggingConfig: LoggingConfig = {\n enabled: true,\n namespace: \"*\",\n level: \"debug\" as const,\n ...config.logging,\n };\n\n return {\n ...config,\n redirectUrl:\n config.redirectUrl ||\n `${window.location.origin}${window.location.pathname}`,\n oauthServerBaseUrl:\n config.oauthServerBaseUrl || \"https://auth.civic.com/oauth/\",\n scopes: config.scopes || DEFAULT_SCOPES,\n textSignals: config.textSignals || {\n success: \"Authentication successful!\",\n error: \"Authentication failed. Please try again.\",\n },\n displayMode: config.displayMode || \"iframe\",\n authProcessTimeout:\n config.authProcessTimeout ||\n CIVIC_AUTH_CONSTANTS.DEFAULT_AUTH_PROCESS_TIMEOUT,\n iframeId: config.iframeId || CIVIC_AUTH_CONSTANTS.DEFAULT_IFRAME_ID,\n prompt: \"consent\",\n logging: loggingConfig,\n storageAdapter: config.storageAdapter || new LocalStorageAdapter(),\n };\n}\n\n/**\n * Validates required configuration properties\n */\nfunction validateRequiredConfig(config: CivicAuthClientConfig): void {\n // Always required configurations\n const requiredConfigs = [{ key: \"clientId\", value: config.clientId }];\n\n // Validate always-required fields\n for (const { key, value } of requiredConfigs) {\n if (!value) {\n throw new CivicAuthError(\n `CivicAuth: ${key} is required.`,\n CivicAuthErrorCode.CONFIG_REQUIRED,\n );\n }\n }\n\n // Conditional validation for targetContainerElement\n // Only required for embedded iframe mode\n const displayMode = config.displayMode || \"iframe\";\n const iframeDisplayMode = config.iframeDisplayMode;\n\n // Check if we need a container element\n const needsContainer =\n displayMode === \"iframe\" && iframeDisplayMode === \"embedded\";\n\n if (needsContainer && !config.targetContainerElement) {\n throw new CivicAuthError(\n \"CivicAuth: targetContainerElement is required for embedded iframe mode. \" +\n \"For modal iframe mode, set iframeDisplayMode to 'modal'. \" +\n \"For non-iframe modes, use displayMode 'redirect' or 'new_tab'.\",\n CivicAuthErrorCode.CONFIG_REQUIRED,\n );\n }\n}\n"]}
@@ -0,0 +1,40 @@
1
+ import type { AuthResult } from "../../types/index.js";
2
+ import type { ProcessedCivicAuthConfig } from "../types/AuthTypes.js";
3
+ import { IframeManager } from "../../iframe/IframeManager.js";
4
+ import type { createLogger } from "../../utils/logger.js";
5
+ export interface IframeAuthHandlerConfig {
6
+ config: ProcessedCivicAuthConfig;
7
+ logger: ReturnType<typeof createLogger>;
8
+ onAuthSuccess: (result: AuthResult) => void;
9
+ onAuthError: (error: Error) => void;
10
+ cleanup: () => void;
11
+ messageHandler: (event: MessageEvent) => void;
12
+ }
13
+ export declare class IframeAuthHandler {
14
+ private config;
15
+ private logger;
16
+ private onAuthSuccess;
17
+ private onAuthError;
18
+ private cleanup;
19
+ private messageHandler;
20
+ private iframeManager?;
21
+ private iframeElement?;
22
+ private signalObserver?;
23
+ constructor(handlerConfig: IframeAuthHandlerConfig);
24
+ handleIframeAuth(fullAuthUrl: string): Promise<HTMLIFrameElement>;
25
+ getIframeManager(): IframeManager | undefined;
26
+ getIframeElement(): HTMLIFrameElement | undefined;
27
+ cleanupIframe(): void;
28
+ private cleanupDynamicModalContainer;
29
+ private createModalContainer;
30
+ private getContainerElement;
31
+ private determineIframeDisplayMode;
32
+ private setupIframeEventHandlers;
33
+ private checkAndHideNonLoginContent;
34
+ private checkIframeRedirect;
35
+ private setupSignalObserver;
36
+ private setupIframeNavigationMonitoring;
37
+ private processCallbackUrl;
38
+ navigateIframe(url: string): void;
39
+ }
40
+ //# sourceMappingURL=IframeAuthHandler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"IframeAuthHandler.d.ts","sourceRoot":"","sources":["../../../../src/vanillajs/auth/handlers/IframeAuthHandler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,uBAAuB,CAAC;AAGtE,OAAO,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAG1D,MAAM,WAAW,uBAAuB;IACtC,MAAM,EAAE,wBAAwB,CAAC;IACjC,MAAM,EAAE,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;IACxC,aAAa,EAAE,CAAC,MAAM,EAAE,UAAU,KAAK,IAAI,CAAC;IAC5C,WAAW,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,IAAI,CAAC;IACpC,OAAO,EAAE,MAAM,IAAI,CAAC;IACpB,cAAc,EAAE,CAAC,KAAK,EAAE,YAAY,KAAK,IAAI,CAAC;CAC/C;AAED,qBAAa,iBAAiB;IAC5B,OAAO,CAAC,MAAM,CAA2B;IACzC,OAAO,CAAC,MAAM,CAAiC;IAC/C,OAAO,CAAC,aAAa,CAA+B;IACpD,OAAO,CAAC,WAAW,CAAyB;IAC5C,OAAO,CAAC,OAAO,CAAa;IAC5B,OAAO,CAAC,cAAc,CAAgC;IACtD,OAAO,CAAC,aAAa,CAAC,CAAgB;IACtC,OAAO,CAAC,aAAa,CAAC,CAAoB;IAC1C,OAAO,CAAC,cAAc,CAAC,CAAiB;gBAE5B,aAAa,EAAE,uBAAuB;IAQrC,gBAAgB,CAC3B,WAAW,EAAE,MAAM,GAClB,OAAO,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