@civic/auth 0.6.0 → 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.
- package/dist/nextjs/config.d.ts.map +1 -1
- package/dist/nextjs/config.js +3 -1
- package/dist/nextjs/config.js.map +1 -1
- package/dist/nextjs/hooks/useUserCookie.d.ts.map +1 -1
- package/dist/nextjs/hooks/useUserCookie.js.map +1 -1
- package/dist/nextjs/providers/NextAuthProvider.d.ts.map +1 -1
- package/dist/nextjs/providers/NextAuthProvider.js +1 -0
- package/dist/nextjs/providers/NextAuthProvider.js.map +1 -1
- package/dist/shared/components/CivicAuthIframeContainer.js +1 -1
- package/dist/shared/components/CivicAuthIframeContainer.js.map +1 -1
- package/dist/shared/hooks/useSignIn.d.ts +9 -4
- package/dist/shared/hooks/useSignIn.d.ts.map +1 -1
- package/dist/shared/hooks/useSignIn.js +75 -42
- package/dist/shared/hooks/useSignIn.js.map +1 -1
- package/dist/shared/lib/BrowserAuthenticationRefresher.d.ts +7 -1
- package/dist/shared/lib/BrowserAuthenticationRefresher.d.ts.map +1 -1
- package/dist/shared/lib/BrowserAuthenticationRefresher.js +15 -2
- package/dist/shared/lib/BrowserAuthenticationRefresher.js.map +1 -1
- package/dist/shared/lib/util.d.ts +1 -1
- package/dist/shared/lib/util.d.ts.map +1 -1
- package/dist/shared/lib/util.js +6 -1
- package/dist/shared/lib/util.js.map +1 -1
- package/dist/shared/providers/AuthContext.d.ts +7 -2
- package/dist/shared/providers/AuthContext.d.ts.map +1 -1
- package/dist/shared/providers/AuthContext.js.map +1 -1
- package/dist/shared/providers/UserProvider.d.ts +5 -1
- package/dist/shared/providers/UserProvider.d.ts.map +1 -1
- package/dist/shared/providers/UserProvider.js.map +1 -1
- package/dist/shared/version.d.ts +1 -1
- package/dist/shared/version.d.ts.map +1 -1
- package/dist/shared/version.js +1 -1
- package/dist/shared/version.js.map +1 -1
- package/dist/vanillajs/auth/AuthenticationEvents.d.ts.map +1 -1
- package/dist/vanillajs/auth/AuthenticationEvents.js +2 -2
- package/dist/vanillajs/auth/AuthenticationEvents.js.map +1 -1
- package/dist/vanillajs/auth/CivicAuth.d.ts +111 -92
- package/dist/vanillajs/auth/CivicAuth.d.ts.map +1 -1
- package/dist/vanillajs/auth/CivicAuth.js +474 -321
- package/dist/vanillajs/auth/CivicAuth.js.map +1 -1
- package/dist/vanillajs/auth/SessionManager.d.ts +40 -9
- package/dist/vanillajs/auth/SessionManager.d.ts.map +1 -1
- package/dist/vanillajs/auth/SessionManager.js +96 -61
- package/dist/vanillajs/auth/SessionManager.js.map +1 -1
- package/dist/vanillajs/auth/TokenRefresher.d.ts +54 -0
- package/dist/vanillajs/auth/TokenRefresher.d.ts.map +1 -0
- package/dist/vanillajs/auth/TokenRefresher.js +166 -0
- package/dist/vanillajs/auth/TokenRefresher.js.map +1 -0
- package/dist/vanillajs/auth/config/ConfigProcessor.d.ts +6 -0
- package/dist/vanillajs/auth/config/ConfigProcessor.d.ts.map +1 -0
- package/dist/vanillajs/auth/config/ConfigProcessor.js +59 -0
- package/dist/vanillajs/auth/config/ConfigProcessor.js.map +1 -0
- package/dist/vanillajs/auth/handlers/IframeAuthHandler.d.ts +40 -0
- package/dist/vanillajs/auth/handlers/IframeAuthHandler.d.ts.map +1 -0
- package/dist/vanillajs/auth/handlers/IframeAuthHandler.js +388 -0
- package/dist/vanillajs/auth/handlers/IframeAuthHandler.js.map +1 -0
- package/dist/vanillajs/auth/handlers/MessageHandler.d.ts +170 -0
- package/dist/vanillajs/auth/handlers/MessageHandler.d.ts.map +1 -0
- package/dist/vanillajs/auth/handlers/MessageHandler.js +367 -0
- package/dist/vanillajs/auth/handlers/MessageHandler.js.map +1 -0
- package/dist/vanillajs/auth/handlers/OAuthCallbackHandler.d.ts +90 -0
- package/dist/vanillajs/auth/handlers/OAuthCallbackHandler.d.ts.map +1 -0
- package/dist/vanillajs/auth/handlers/OAuthCallbackHandler.js +301 -0
- package/dist/vanillajs/auth/handlers/OAuthCallbackHandler.js.map +1 -0
- package/dist/vanillajs/auth/handlers/PopupHandler.d.ts +108 -0
- package/dist/vanillajs/auth/handlers/PopupHandler.d.ts.map +1 -0
- package/dist/vanillajs/auth/handlers/PopupHandler.js +333 -0
- package/dist/vanillajs/auth/handlers/PopupHandler.js.map +1 -0
- package/dist/vanillajs/auth/types/AuthTypes.d.ts +128 -0
- package/dist/vanillajs/auth/types/AuthTypes.d.ts.map +1 -0
- package/dist/vanillajs/auth/types/AuthTypes.js +40 -0
- package/dist/vanillajs/auth/types/AuthTypes.js.map +1 -0
- package/dist/vanillajs/iframe/IframeManager.d.ts +115 -0
- package/dist/vanillajs/iframe/IframeManager.d.ts.map +1 -0
- package/dist/vanillajs/iframe/IframeManager.js +614 -0
- package/dist/vanillajs/iframe/IframeManager.js.map +1 -0
- package/dist/vanillajs/iframe/IframeResizer.d.ts +15 -0
- package/dist/vanillajs/iframe/IframeResizer.d.ts.map +1 -0
- package/dist/vanillajs/iframe/IframeResizer.js +127 -0
- package/dist/vanillajs/iframe/IframeResizer.js.map +1 -0
- package/dist/vanillajs/index.d.ts +8 -7
- package/dist/vanillajs/index.d.ts.map +1 -1
- package/dist/vanillajs/index.js +10 -7
- package/dist/vanillajs/index.js.map +1 -1
- package/dist/vanillajs/services/ApiService.d.ts.map +1 -1
- package/dist/vanillajs/services/ApiService.js +2 -2
- package/dist/vanillajs/services/ApiService.js.map +1 -1
- package/dist/vanillajs/types/index.d.ts +17 -12
- package/dist/vanillajs/types/index.d.ts.map +1 -1
- package/dist/vanillajs/types/index.js +15 -10
- package/dist/vanillajs/types/index.js.map +1 -1
- package/dist/vanillajs/ui/LoadingComponents.d.ts +51 -0
- package/dist/vanillajs/ui/LoadingComponents.d.ts.map +1 -0
- package/dist/vanillajs/ui/LoadingComponents.js +363 -0
- package/dist/vanillajs/ui/LoadingComponents.js.map +1 -0
- package/dist/vanillajs/utils/auth-utils.d.ts +2 -1
- package/dist/vanillajs/utils/auth-utils.d.ts.map +1 -1
- package/dist/vanillajs/utils/auth-utils.js +6 -3
- package/dist/vanillajs/utils/auth-utils.js.map +1 -1
- package/dist/vanillajs/utils/logger.d.ts +16 -15
- package/dist/vanillajs/utils/logger.d.ts.map +1 -1
- package/dist/vanillajs/utils/logger.js +35 -19
- package/dist/vanillajs/utils/logger.js.map +1 -1
- package/package.json +1 -1
- package/dist/vanillajs/iframe/domUtils.d.ts +0 -4
- package/dist/vanillajs/iframe/domUtils.d.ts.map +0 -1
- package/dist/vanillajs/iframe/domUtils.js +0 -25
- package/dist/vanillajs/iframe/domUtils.js.map +0 -1
- package/dist/vanillajs/storage/BrowserCookieStorageAdapter.d.ts +0 -19
- package/dist/vanillajs/storage/BrowserCookieStorageAdapter.d.ts.map +0 -1
- package/dist/vanillajs/storage/BrowserCookieStorageAdapter.js +0 -101
- package/dist/vanillajs/storage/BrowserCookieStorageAdapter.js.map +0 -1
- package/dist/vanillajs/storage/BrowserLocalStorageAdapter.d.ts +0 -9
- package/dist/vanillajs/storage/BrowserLocalStorageAdapter.d.ts.map +0 -1
- package/dist/vanillajs/storage/BrowserLocalStorageAdapter.js +0 -36
- package/dist/vanillajs/storage/BrowserLocalStorageAdapter.js.map +0 -1
- package/dist/vanillajs/storage/InMemoryStorageAdapter.d.ts +0 -9
- package/dist/vanillajs/storage/InMemoryStorageAdapter.d.ts.map +0 -1
- package/dist/vanillajs/storage/InMemoryStorageAdapter.js +0 -16
- package/dist/vanillajs/storage/InMemoryStorageAdapter.js.map +0 -1
- package/dist/vanillajs/storage/StorageAdapter.d.ts +0 -15
- package/dist/vanillajs/storage/StorageAdapter.d.ts.map +0 -1
- package/dist/vanillajs/storage/StorageAdapter.js +0 -16
- package/dist/vanillajs/storage/StorageAdapter.js.map +0 -1
- package/dist/vanillajs/utils/page-handlers.d.ts +0 -29
- package/dist/vanillajs/utils/page-handlers.d.ts.map +0 -1
- package/dist/vanillajs/utils/page-handlers.js +0 -165
- package/dist/vanillajs/utils/page-handlers.js.map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IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE;wBACnD,MAAM,EAAE,iCAAiC;wBACzC,IAAI,EAAE,QAAQ;qBACf,CAAC,CAAC;gBACL,CAAC;qBAAM,IAAI,WAAW,EAAE,CAAC;oBACvB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,EAAE;wBAChD,MAAM,EAAE,WAAW,CAAC,WAAW,IAAI,+BAA+B;qBACnE,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;QACH,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,EAAE;gBAChD,MAAM,EACJ,KAAK,YAAY,KAAK;oBACpB,CAAC,CAAC,KAAK,CAAC,OAAO;oBACf,CAAC,CAAC,+BAA+B;aACtC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;CACF","sourcesContent":["import { createIframe, removeIframe } from \"../iframe/domUtils.js\";\nimport { AuthEvent } from \"../types/index.js\";\nimport type { AuthenticationEvents } from \"./AuthenticationEvents.js\";\nimport {\n StorageAdapterToAuthStorage,\n type StorageAdapter,\n} from \"../storage/StorageAdapter.js\";\nimport { BrowserCookieStorageAdapter } from \"../storage/BrowserCookieStorageAdapter.js\";\nimport { handleOAuthRedirectPage } from \"../utils/page-handlers.js\";\nimport type { Endpoints, DisplayMode } from \"../../types.js\";\nimport { buildAuthUrl } from \"../utils/auth-utils.js\";\nimport type { AuthResult } 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\";\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 /**\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 */\n storageAdapter?: StorageAdapter;\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 * CivicAuth client for handling OAuth authentication\n */\nexport class CivicAuth {\n private config: CivicAuthClientConfig;\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: StorageAdapter;\n private endpoints?: Endpoints;\n private logger: ReturnType<typeof createLogger>;\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 const loggingConfig = {\n enabled: true,\n namespace: \"iframe\",\n level: \"debug\" as const,\n ...config.logging,\n };\n\n this.config = {\n displayMode: \"iframe\",\n authProcessTimeout:\n config.authProcessTimeout || CONSTANTS.DEFAULT_AUTH_PROCESS_TIMEOUT,\n iframeId: config.iframeId || CONSTANTS.DEFAULT_IFRAME_ID,\n logging: loggingConfig,\n ...config,\n };\n\n // Configure logging based on config\n configureLogging(loggingConfig);\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 this.storage = config.storageAdapter || new BrowserCookieStorageAdapter();\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 // 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 * 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 const authStorage = new StorageAdapterToAuthStorage(this.storage);\n const pkceProducer = new GenericPublicClientPKCEProducer(authStorage);\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\", {\n url: fullAuthUrl,\n containerId: container?.id,\n iframeId: this.config.iframeId,\n origin: window.location.origin,\n });\n\n this.iframeElement = createIframe(\n fullAuthUrl,\n container,\n this.config.iframeId,\n );\n this.config.events?.emit(AuthEvent.SIGN_IN_STARTED, {\n detail: \"Iframe created\",\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.iframeElement) {\n this.logger.debug(\"Removing iframe element\");\n removeIframe(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 });\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"]}
|
|
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,EAAE,MA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,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,17 +1,48 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { AuthStorage } from "../../types.js";
|
|
2
2
|
import type { AuthenticationEvents } from "./AuthenticationEvents.js";
|
|
3
3
|
import type { User, Session } from "../types/index.js";
|
|
4
|
+
import type { AuthConfig } from "../../server/config.js";
|
|
4
5
|
export declare class SessionManager {
|
|
5
6
|
private storage;
|
|
6
7
|
private events;
|
|
7
|
-
private
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
8
|
+
private tokenRefresher?;
|
|
9
|
+
private logger;
|
|
10
|
+
constructor(storageAdapter: AuthStorage, events: AuthenticationEvents);
|
|
11
|
+
/**
|
|
12
|
+
* Initialize the session manager with auth configuration to enable token refresh
|
|
13
|
+
*/
|
|
14
|
+
initializeWithAuthConfig(authConfig: AuthConfig): Promise<void>;
|
|
15
|
+
/**
|
|
16
|
+
* Build current session from shared lib storage
|
|
17
|
+
*/
|
|
18
|
+
getCurrentSession(): Promise<Session | null>;
|
|
19
|
+
/**
|
|
20
|
+
* Check if user is authenticated using shared lib utilities
|
|
21
|
+
*/
|
|
14
22
|
isAuthenticated(): Promise<boolean>;
|
|
15
|
-
|
|
23
|
+
/**
|
|
24
|
+
* Get current user from shared lib storage
|
|
25
|
+
*/
|
|
26
|
+
getCurrentUser(): Promise<User | null>;
|
|
27
|
+
/**
|
|
28
|
+
* Clear all authentication data using shared lib utilities
|
|
29
|
+
*/
|
|
30
|
+
clearSession(): Promise<void>;
|
|
31
|
+
/**
|
|
32
|
+
* Manually trigger token refresh
|
|
33
|
+
*/
|
|
34
|
+
refreshTokens(): Promise<void>;
|
|
35
|
+
/**
|
|
36
|
+
* Get token refresher state for debugging
|
|
37
|
+
*/
|
|
38
|
+
getTokenRefresherState(): {
|
|
39
|
+
isInitialized: boolean;
|
|
40
|
+
isAuthenticated: boolean;
|
|
41
|
+
isAutoRefreshActive: boolean;
|
|
42
|
+
} | null;
|
|
43
|
+
/**
|
|
44
|
+
* Clean up resources when session manager is destroyed
|
|
45
|
+
*/
|
|
46
|
+
destroy(): Promise<void>;
|
|
16
47
|
}
|
|
17
48
|
//# sourceMappingURL=SessionManager.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SessionManager.d.ts","sourceRoot":"","sources":["../../../src/vanillajs/auth/SessionManager.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,
|
|
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,OAAO,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAIvD,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,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,86 +1,121 @@
|
|
|
1
1
|
import { AuthEvent } from "../types/index.js";
|
|
2
|
-
import {
|
|
3
|
-
|
|
2
|
+
import { createLogger } from "../utils/logger.js";
|
|
3
|
+
import { TokenRefresher } from "./TokenRefresher.js";
|
|
4
|
+
import { retrieveTokens, clearTokens } from "../../shared/lib/util.js";
|
|
5
|
+
import { getUser } from "../../shared/lib/session.js";
|
|
6
|
+
import { GenericUserSession } from "../../shared/lib/UserSession.js";
|
|
4
7
|
export class SessionManager {
|
|
5
8
|
storage;
|
|
6
9
|
events;
|
|
7
|
-
|
|
10
|
+
tokenRefresher;
|
|
11
|
+
logger = createLogger("session");
|
|
8
12
|
constructor(storageAdapter, events) {
|
|
9
13
|
this.storage = storageAdapter;
|
|
10
14
|
this.events = events;
|
|
11
|
-
this.
|
|
15
|
+
this.logger.info("SessionManager initialized with shared lib token storage");
|
|
12
16
|
}
|
|
13
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Initialize the session manager with auth configuration to enable token refresh
|
|
19
|
+
*/
|
|
20
|
+
async initializeWithAuthConfig(authConfig) {
|
|
14
21
|
try {
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
}
|
|
22
|
+
// Initialize token refresher
|
|
23
|
+
this.tokenRefresher = new TokenRefresher(this.storage, this.events, authConfig);
|
|
24
|
+
await this.tokenRefresher.initialize(authConfig);
|
|
25
|
+
// Set current authentication state
|
|
26
|
+
const isAuthenticated = await this.isAuthenticated();
|
|
27
|
+
this.tokenRefresher.setAuthenticationState(isAuthenticated);
|
|
28
|
+
this.logger.info("SessionManager initialized with token refresh capability");
|
|
23
29
|
}
|
|
24
30
|
catch (error) {
|
|
25
|
-
|
|
26
|
-
this.
|
|
31
|
+
this.logger.error("Failed to initialize SessionManager with auth config:", error);
|
|
32
|
+
this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);
|
|
27
33
|
}
|
|
28
34
|
}
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Build current session from shared lib storage
|
|
37
|
+
*/
|
|
38
|
+
async getCurrentSession() {
|
|
39
|
+
try {
|
|
40
|
+
const tokens = await retrieveTokens(this.storage);
|
|
41
|
+
const user = await this.getCurrentUser();
|
|
42
|
+
if (!tokens?.id_token || !user) {
|
|
43
|
+
this.logger.warn("No id_token or user available, cannot create session");
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
return {
|
|
47
|
+
user,
|
|
48
|
+
accessToken: tokens.access_token,
|
|
49
|
+
idToken: tokens.id_token,
|
|
50
|
+
refreshToken: tokens.refresh_token ?? undefined,
|
|
51
|
+
expiresAt: tokens.access_token_expires_at ?? undefined,
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
catch (error) {
|
|
55
|
+
this.logger.error("Failed to load session from shared storage:", error);
|
|
56
|
+
return null;
|
|
34
57
|
}
|
|
35
|
-
// TODO: schedule token refresh if applicable based on session.expiresAt
|
|
36
|
-
}
|
|
37
|
-
async clearSession() {
|
|
38
|
-
this.currentSession = null;
|
|
39
|
-
await this.storage.removeItem(SESSION_STORAGE_KEY);
|
|
40
|
-
this.events.emit(AuthEvent.USER_SESSION_CHANGED, null);
|
|
41
|
-
// TODO: cancel any scheduled token refresh
|
|
42
|
-
loggers.session("SessionManager: Session cleared.");
|
|
43
|
-
}
|
|
44
|
-
async getUser() {
|
|
45
|
-
// Potentially refresh or validate session before returning user
|
|
46
|
-
return this.currentSession?.user || null;
|
|
47
|
-
}
|
|
48
|
-
async getSession() {
|
|
49
|
-
return this.currentSession;
|
|
50
58
|
}
|
|
59
|
+
/**
|
|
60
|
+
* Check if user is authenticated using shared lib utilities
|
|
61
|
+
*/
|
|
51
62
|
async isAuthenticated() {
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
if (!this.currentSession || !this.currentSession.idToken) {
|
|
55
|
-
return false;
|
|
56
|
-
}
|
|
57
|
-
// Placeholder: In a real scenario, validate token (e.g. using TokenService)
|
|
58
|
-
// const tokenService = new TokenService(); // Or get as dependency
|
|
59
|
-
// return tokenService.isValid(this.currentSession.accessToken);
|
|
60
|
-
return !!this.currentSession.user;
|
|
63
|
+
const tokens = await retrieveTokens(this.storage);
|
|
64
|
+
return !!tokens?.id_token;
|
|
61
65
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
66
|
+
/**
|
|
67
|
+
* Get current user from shared lib storage
|
|
68
|
+
*/
|
|
69
|
+
async getCurrentUser() {
|
|
65
70
|
try {
|
|
66
|
-
|
|
67
|
-
// For now, just a placeholder that does nothing or simulates a failure/success
|
|
68
|
-
loggers.session("SessionManager: refreshToken() not implemented.");
|
|
69
|
-
// const newSession = await ApiService.refreshToken(this.currentSession.refreshToken);
|
|
70
|
-
// if (newSession) {
|
|
71
|
-
// await this.setSession(newSession);
|
|
72
|
-
// this.events.emit(AuthEvent.TOKEN_REFRESH_COMPLETE, newSession.user);
|
|
73
|
-
// return newSession;
|
|
74
|
-
// }
|
|
75
|
-
throw new Error("Refresh token flow not implemented.");
|
|
71
|
+
return await getUser(this.storage);
|
|
76
72
|
}
|
|
77
73
|
catch (error) {
|
|
78
|
-
|
|
79
|
-
this.events.emit(AuthEvent.TOKEN_REFRESH_ERROR, error);
|
|
80
|
-
// Potentially clear session if refresh fails critically
|
|
81
|
-
// await this.clearSession();
|
|
74
|
+
this.logger.error("Failed to get user from shared storage:", error);
|
|
82
75
|
return null;
|
|
83
76
|
}
|
|
84
77
|
}
|
|
78
|
+
/**
|
|
79
|
+
* Clear all authentication data using shared lib utilities
|
|
80
|
+
*/
|
|
81
|
+
async clearSession() {
|
|
82
|
+
try {
|
|
83
|
+
await clearTokens(this.storage);
|
|
84
|
+
// Clear user session using shared utilities
|
|
85
|
+
const userSession = new GenericUserSession(this.storage);
|
|
86
|
+
await userSession.clear();
|
|
87
|
+
// Stop token refresher when session is cleared
|
|
88
|
+
this.tokenRefresher?.setAuthenticationState(false);
|
|
89
|
+
this.events.emit(AuthEvent.USER_SESSION_CHANGED, null);
|
|
90
|
+
this.logger.info("Session cleared using shared lib utilities");
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
this.logger.error("Failed to clear session:", error);
|
|
94
|
+
throw error;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Manually trigger token refresh
|
|
99
|
+
*/
|
|
100
|
+
async refreshTokens() {
|
|
101
|
+
if (!this.tokenRefresher) {
|
|
102
|
+
throw new Error("Token refresher not initialized. Call initializeWithAuthConfig first.");
|
|
103
|
+
}
|
|
104
|
+
return this.tokenRefresher.refreshTokens();
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Get token refresher state for debugging
|
|
108
|
+
*/
|
|
109
|
+
getTokenRefresherState() {
|
|
110
|
+
return this.tokenRefresher?.getState() || null;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Clean up resources when session manager is destroyed
|
|
114
|
+
*/
|
|
115
|
+
async destroy() {
|
|
116
|
+
await this.tokenRefresher?.destroy();
|
|
117
|
+
this.tokenRefresher = undefined;
|
|
118
|
+
this.logger.info("SessionManager destroyed");
|
|
119
|
+
}
|
|
85
120
|
}
|
|
86
121
|
//# sourceMappingURL=SessionManager.js.map
|
|
@@ -1 +1 @@
|
|
|
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,
|
|
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;AAClD,OAAO,EAAE,cAAc,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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"]}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { AuthStorage } from "../../types.js";
|
|
2
|
+
import type { AuthenticationEvents } from "./AuthenticationEvents.js";
|
|
3
|
+
import type { AuthConfig } from "../../server/config.js";
|
|
4
|
+
/**
|
|
5
|
+
* TokenRefresher handles automatic token refresh for vanilla.js implementation
|
|
6
|
+
* Inspired by the React useRefresh hook and BrowserAuthenticationRefresher
|
|
7
|
+
*/
|
|
8
|
+
export declare class TokenRefresher {
|
|
9
|
+
private refresher?;
|
|
10
|
+
private storage;
|
|
11
|
+
private events;
|
|
12
|
+
private authConfig?;
|
|
13
|
+
private isAuthenticated;
|
|
14
|
+
private isDestroyed;
|
|
15
|
+
private logger;
|
|
16
|
+
constructor(storage: AuthStorage, events: AuthenticationEvents, authConfig?: AuthConfig);
|
|
17
|
+
/**
|
|
18
|
+
* Initialize the token refresher with auth configuration
|
|
19
|
+
*/
|
|
20
|
+
initialize(authConfig: AuthConfig): Promise<void>;
|
|
21
|
+
/**
|
|
22
|
+
* Set authentication state and manage auto-refresh accordingly
|
|
23
|
+
*/
|
|
24
|
+
setAuthenticationState(isAuthenticated: boolean): void;
|
|
25
|
+
/**
|
|
26
|
+
* Manually refresh tokens
|
|
27
|
+
*/
|
|
28
|
+
refreshTokens(): Promise<void>;
|
|
29
|
+
/**
|
|
30
|
+
* Start automatic token refresh
|
|
31
|
+
*/
|
|
32
|
+
private startAutoRefresh;
|
|
33
|
+
/**
|
|
34
|
+
* Stop automatic token refresh
|
|
35
|
+
*/
|
|
36
|
+
private stopAutoRefresh;
|
|
37
|
+
/**
|
|
38
|
+
* Clean up resources
|
|
39
|
+
*/
|
|
40
|
+
cleanup(): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Destroy the token refresher permanently
|
|
43
|
+
*/
|
|
44
|
+
destroy(): Promise<void>;
|
|
45
|
+
/**
|
|
46
|
+
* Get current refresh state
|
|
47
|
+
*/
|
|
48
|
+
getState(): {
|
|
49
|
+
isInitialized: boolean;
|
|
50
|
+
isAuthenticated: boolean;
|
|
51
|
+
isAutoRefreshActive: boolean;
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
//# sourceMappingURL=TokenRefresher.d.ts.map
|
|
@@ -0,0 +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;IACnD,OAAO,CAAC,OAAO,CAAc;IAC7B,OAAO,CAAC,MAAM,CAAuB;IACrC,OAAO,CAAC,UAAU,CAAC,CAAa;IAChC,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"}
|