@nibssplc/cams-sdk 0.0.1-beta.42 → 0.0.1-beta.44
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +8 -8
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.esm.js +8 -8
- package/dist/index.esm.js.map +1 -1
- package/dist/index.umd.js +8 -8
- package/dist/index.umd.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs.js
CHANGED
|
@@ -97,12 +97,12 @@ const DEFAULT_MICROSOFT_DOMAINS = [
|
|
|
97
97
|
".live.com",
|
|
98
98
|
"login.microsoftonline.com"
|
|
99
99
|
];
|
|
100
|
-
// Secure reference to native functions
|
|
100
|
+
// Secure reference to native functions with proper binding
|
|
101
101
|
const NativeFunctions = {
|
|
102
|
-
addEventListener: typeof window !== "undefined" ? window.addEventListener : null,
|
|
103
|
-
removeEventListener: typeof window !== "undefined" ? window.removeEventListener : null,
|
|
104
|
-
setTimeout: typeof window !== "undefined" ? window.setTimeout : setTimeout,
|
|
105
|
-
clearTimeout: typeof window !== "undefined" ? window.clearTimeout : clearTimeout,
|
|
102
|
+
addEventListener: typeof window !== "undefined" ? window.addEventListener.bind(window) : null,
|
|
103
|
+
removeEventListener: typeof window !== "undefined" ? window.removeEventListener.bind(window) : null,
|
|
104
|
+
setTimeout: typeof window !== "undefined" ? window.setTimeout.bind(window) : setTimeout,
|
|
105
|
+
clearTimeout: typeof window !== "undefined" ? window.clearTimeout.bind(window) : clearTimeout,
|
|
106
106
|
};
|
|
107
107
|
/**
|
|
108
108
|
* Generate a secure random window name to prevent targeting
|
|
@@ -205,10 +205,10 @@ const addMessageListener = (listener) => {
|
|
|
205
205
|
});
|
|
206
206
|
}
|
|
207
207
|
};
|
|
208
|
-
NativeFunctions.addEventListener
|
|
208
|
+
NativeFunctions.addEventListener("message", wrappedListener);
|
|
209
209
|
return () => {
|
|
210
210
|
if (NativeFunctions.removeEventListener) {
|
|
211
|
-
NativeFunctions.removeEventListener
|
|
211
|
+
NativeFunctions.removeEventListener("message", wrappedListener);
|
|
212
212
|
}
|
|
213
213
|
};
|
|
214
214
|
};
|
|
@@ -258,7 +258,7 @@ function openCAMSPopUpLogin(config) {
|
|
|
258
258
|
return;
|
|
259
259
|
}
|
|
260
260
|
// Extract configuration with defaults
|
|
261
|
-
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = DEFAULT_MICROSOFT_DOMAINS, } = config;
|
|
261
|
+
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin], } = config;
|
|
262
262
|
// State management
|
|
263
263
|
let authWindow = null;
|
|
264
264
|
let authTimeoutId = null;
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts","../src/MFAAuth.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n allowedRedirectDomains?: string[];\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\").or(z.literal(\"AUTH_FAILURE\")),\n userProfile: z.object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n roles: z.array(z.string()).optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.DEBUG;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Constants\nconst DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes\nconst DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes\nconst INITIAL_POLL_INTERVAL = 1000;\nconst MAX_POLL_INTERVAL = 5000;\nconst WINDOW_FEATURES = \"scrollbars=yes,resizable=yes\";\n\n// Default allowed Microsoft domains for Azure AD redirects\nconst DEFAULT_MICROSOFT_DOMAINS = [\n \".microsoft.com\",\n \".microsoftonline.com\", \n \".live.com\",\n \"login.microsoftonline.com\"\n];\n\n// Secure reference to native functions\nconst NativeFunctions = {\n addEventListener: typeof window !== \"undefined\" ? window.addEventListener : null,\n removeEventListener: typeof window !== \"undefined\" ? window.removeEventListener : null,\n setTimeout: typeof window !== \"undefined\" ? window.setTimeout : setTimeout,\n clearTimeout: typeof window !== \"undefined\" ? window.clearTimeout : clearTimeout,\n};\n\n// Types\ntype TimeoutHandle = ReturnType<typeof setTimeout>;\ntype MessageListener = (event: MessageEvent) => void;\n\n/**\n * Generate a secure random window name to prevent targeting\n */\nexport const generateSecureWindowName = (): string =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\n/**\n * Detect if current window is a popup to prevent recursive popups\n */\nexport const isPopupWindow = (): boolean => {\n if (typeof window === \"undefined\") return false;\n \n // Skip popup detection in test environments\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_ENV === \"test\") {\n return false;\n }\n \n try {\n return window.opener !== null && window.opener !== window;\n } catch {\n return false;\n }\n};\n\n/**\n * Safely close a window with error handling for cross-origin restrictions\n */\nconst safeWindowClose = (window: Window | null): void => {\n if (!window) return;\n \n try {\n if (!window.closed) {\n window.close();\n }\n } catch (error) {\n Logger.debug(\"Error closing window (cross-origin restriction)\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n};\n\n/**\n * Center popup window on screen\n */\nconst getPopupPosition = (width: number, height: number): { left: number; top: number } => {\n if (typeof window === \"undefined\") return { left: 0, top: 0 };\n \n const left = Math.max(0, (window.screen.width - width) / 2);\n const top = Math.max(0, (window.screen.height - height) / 2);\n \n return { left, top };\n};\n\n/**\n * Validate origin against expected domain with support for subdomains and Microsoft redirects\n */\nconst isValidOrigin = (\n eventOrigin: string, \n expectedOrigin: string,\n microsoftDomains: string[] = DEFAULT_MICROSOFT_DOMAINS\n): boolean => {\n try {\n const originUrl = new URL(eventOrigin);\n const expectedHostname = expectedOrigin.startsWith(\"http\")\n ? new URL(expectedOrigin).hostname\n : expectedOrigin;\n\n // Check Microsoft domains for Azure AD redirects\n const isMicrosoftDomain = microsoftDomains.some(domain => \n originUrl.hostname === domain || originUrl.hostname.endsWith(domain)\n );\n\n // Allow exact match, subdomains, or Microsoft domains\n return (\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain\n );\n } catch {\n return false;\n }\n};\n\n/**\n * Safely check if window is closed with cross-origin handling\n */\nconst isWindowClosed = (window: Window | null): boolean => {\n if (!window) return true;\n \n try {\n return window.closed;\n } catch (error) {\n // Cross-origin error means we can't access the property\n // This typically happens when redirected to external auth providers\n Logger.debug(\"Cannot access window.closed due to cross-origin restrictions - assuming window is still open\", error as any);\n return false;\n }\n};\n\n/**\n * Safely add message event listener with error handling\n */\nconst addMessageListener = (listener: MessageListener): (() => void) => {\n if (!NativeFunctions.addEventListener) {\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Message listener not available in current environment\"\n );\n }\n\n const wrappedListener = (event: Event) => {\n try {\n listener(event as MessageEvent);\n } catch (error) {\n Logger.error(\"Error in message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n };\n\n NativeFunctions.addEventListener.call(window, \"message\", wrappedListener);\n \n return () => {\n if (NativeFunctions.removeEventListener) {\n NativeFunctions.removeEventListener.call(window, \"message\", wrappedListener);\n }\n };\n};\n\n/**\n * Validate configuration and return parsed URL\n */\nexport function validateConfig(config: CAMSConfig): URL {\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n return new URL(config.camsUrl);\n}\n\n/**\n * Open CAMS authentication popup and handle the authentication flow\n */\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n // Environment validation\n if (typeof window === \"undefined\") {\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open popup in server-side environment\"\n )\n );\n return;\n }\n\n if (isPopupWindow()) {\n Logger.warn(\"Attempted to open popup from within popup window\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open authentication popup from within popup window\"\n )\n );\n return;\n }\n\n // Initialize logging\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n // Validate configuration\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Configuration validation passed\");\n } catch (error) {\n Logger.error(\"Configuration validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n reject(error as Error);\n return;\n }\n\n // Extract configuration with defaults\n const {\n messageOrigin,\n windowHeight = 600,\n windowWidth = 500,\n authTimeout = DEFAULT_AUTH_TIMEOUT,\n idleTimeout = DEFAULT_IDLE_TIMEOUT,\n allowedRedirectDomains = DEFAULT_MICROSOFT_DOMAINS,\n } = config;\n\n // State management\n let authWindow: Window | null = null;\n let authTimeoutId: TimeoutHandle | null = null;\n let idleTimeoutId: TimeoutHandle | null = null;\n let checkClosedInterval: TimeoutHandle | null = null;\n let removeMessageListener: (() => void) | null = null;\n let hasReceivedValidMessage = false;\n\n /**\n * Clean up all resources and timeouts\n */\n const cleanup = (): void => {\n if (removeMessageListener) {\n removeMessageListener();\n removeMessageListener = null;\n }\n\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n if (authTimeoutId) NativeFunctions.clearTimeout(authTimeoutId);\n if (checkClosedInterval) NativeFunctions.clearTimeout(checkClosedInterval);\n\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n /**\n * Clean up and close the popup window, then reject with error\n */\n const cleanupAndClose = (error?: CAMSError): void => {\n cleanup();\n safeWindowClose(authWindow);\n \n if (error) {\n reject(error);\n }\n };\n\n /**\n * Reset idle timeout on user activity\n */\n const resetIdleTimeout = (): void => {\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n \n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n /**\n * Set up popup window closure detection with cross-origin handling\n */\n const setupClosureDetection = (): void => {\n let pollInterval = INITIAL_POLL_INTERVAL;\n\n const checkClosed = (): void => {\n // Skip closure detection when on Microsoft domains\n if (authWindow) {\n try {\n const currentUrl = authWindow.location.href;\n const isMicrosoftDomain = allowedRedirectDomains.some(domain => \n currentUrl.includes(domain)\n );\n \n if (isMicrosoftDomain) {\n Logger.debug(\"Skipping closure check - on Microsoft domain\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n } catch (error) {\n // Cross-origin error - assume we're on Microsoft domain and skip check\n Logger.debug(\"Cross-origin error - skipping closure check\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n }\n\n const isClosed = isWindowClosed(authWindow);\n \n if (isClosed && !hasReceivedValidMessage) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n /**\n * Handle incoming message events from the popup\n */\n const handleMessage = (event: MessageEvent): void => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n // Security: Validate origin\n if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Security: Validate message source\n if (event.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: event.source,\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Mark that we've received a valid message (prevents false closure detection)\n hasReceivedValidMessage = true;\n\n // Handle heartbeat messages (reset idle timeout)\n if (event.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // Process authentication messages\n processAuthenticationMessage(event.data);\n };\n\n /**\n * Process and validate authentication message payloads\n */\n const processAuthenticationMessage = (data: unknown): void => {\n // Success case: Valid profile received\n const profileValidation = ProfileSchema.safeParse(data);\n if (profileValidation.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(profileValidation.data);\n return;\n }\n\n // Authentication failure case\n const authFailureValidation = AuthFailureMessageSchema.safeParse(data);\n if (authFailureValidation.success) {\n const { error, errorCode, errorDetails } = authFailureValidation.data;\n Logger.warn(\"Authentication failure received\", {\n error,\n errorCode,\n errorDetails,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`\n )\n );\n return;\n }\n\n // Generic error case\n const errorValidation = ErrorMessageSchema.safeParse(data);\n if (errorValidation.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorValidation.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n `Authentication failed: ${errorValidation.data.error}`\n )\n );\n return;\n }\n\n // Invalid message format\n Logger.error(\"Invalid message format received\", {\n messageData: data,\n dataType: typeof data,\n profileValidationError: profileValidation.error?.issues,\n authFailureValidationError: authFailureValidation.error?.issues,\n errorValidationError: errorValidation.error?.issues,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n // Main authentication flow execution\n try {\n // Open popup window\n const { left, top } = getPopupPosition(windowWidth, windowHeight);\n const secureWindowName = generateSecureWindowName();\n \n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n left,\n top,\n });\n\n authWindow = window.open(\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`\n );\n\n // Check for popup blocking\n if (!authWindow) {\n Logger.error(\"Popup window blocked or failed to open\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Check for immediate closure (aggressive popup blockers)\n if (isWindowClosed(authWindow)) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n // Set up message listener\n removeMessageListener = addMessageListener(handleMessage);\n Logger.debug(\"Message listener attached\");\n\n // Set up timeouts\n Logger.debug(\"Setting authentication timeout\", { authTimeout });\n authTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n setupClosureDetection();\n\n // Focus popup for better UX\n try {\n authWindow.focus();\n } catch (error) {\n Logger.debug(\"Could not focus popup window (cross-origin restriction)\");\n }\n\n } catch (error) {\n Logger.error(\"Failed to initialize authentication popup\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to initialize authentication: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n }\n });\n}","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin, isPopupWindow } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n \n // If we're in a popup, don't attempt to open another popup\n if (isPopupWindow()) {\n Logger.warn(\"Cannot initiate login from popup window\");\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot initiate authentication from within popup window\"\n );\n }\n \n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n\n /**\n * Complete authentication in popup window\n * This should be called by popup apps when authentication is successful\n */\n completePopupAuth(profile: Profile, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"completePopupAuth called outside of popup window\");\n return;\n }\n\n try {\n // Store the authentication data locally in the popup\n this.profile = profile;\n this.setToken(profile.userProfile.tokens.Bearer);\n \n Logger.info(\"Authentication completed in popup, forwarding to parent\");\n } catch (error) {\n Logger.error(\"Failed to complete popup authentication\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n }\n\n /**\n * Report authentication error in popup window\n */\n errorPopupAuth(error: any, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"errorPopupAuth called outside of popup window\");\n return;\n }\n\n Logger.warn(\"Reporting authentication error from popup\");\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// 🔹 Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n","import { CAMSError, CAMSErrorType } from \"./types\";\nimport { Logger } from \"./logger\";\n\nexport interface MFAConfig {\n accessToken: string;\n idToken: string;\n appCode: string;\n provider: string;\n apiEndpoint?: string;\n}\n\nexport interface MFAResponse {\n name: string;\n email: string;\n isAuthenticated: boolean;\n message: string;\n mfaIsEnabled: boolean;\n userType: string;\n tokens: {\n Bearer: string;\n Nonce: string;\n };\n}\n\nexport interface MFAAuthenticator {\n sendEmailOTP(): Promise<boolean>;\n verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse>;\n getRemainingAttempts(): number;\n resetAttempts(): void;\n}\n\nexport class CAMSMFAAuthenticator implements MFAAuthenticator {\n private config: MFAConfig;\n private attemptCount = 0;\n private readonly maxAttempts = 3;\n\n constructor(config: MFAConfig) {\n this.config = config;\n }\n\n async sendEmailOTP(): Promise<boolean> {\n try {\n Logger.debug(\"Sending Email OTP\");\n // Implementation would call your API to send email OTP\n // For now, return true as placeholder\n return true;\n } catch (error) {\n Logger.error(\"Failed to send Email OTP\", { error });\n return false;\n }\n }\n\n async verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse> {\n if (this.attemptCount >= this.maxAttempts) {\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Maximum MFA attempts exceeded\"\n );\n }\n\n this.attemptCount++;\n\n try {\n Logger.debug(\"Verifying MFA code\", { type, attempt: this.attemptCount });\n\n const response = await fetch(this.config.apiEndpoint || '/api/auth/verify-mfa', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.accessToken}`,\n },\n body: JSON.stringify({\n provider: this.config.provider,\n accessToken: this.config.accessToken,\n idToken: this.config.idToken,\n authenticationType: type,\n MFACode: code,\n appCode: this.config.appCode,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data: MFAResponse = await response.json();\n console.log(\"MFA Response >>>\", data)\n \n if (data.isAuthenticated) {\n Logger.info(\"MFA verification successful\");\n this.resetAttempts();\n return data;\n } else {\n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n data.message || \"MFA verification failed\"\n );\n }\n } catch (error) {\n Logger.error(\"MFA verification failed\", { error, attempt: this.attemptCount });\n \n if (error instanceof CAMSError) {\n throw error;\n }\n \n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `MFA verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n getRemainingAttempts(): number {\n return Math.max(0, this.maxAttempts - this.attemptCount);\n }\n\n resetAttempts(): void {\n this.attemptCount = 0;\n }\n}"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;AAaYA;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,kBAAyC;AAC3C,CAAC,EARWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;AAUnB,MAAO,SAAU,SAAQ,KAAK,CAAA;AACf,IAAA,IAAA;IAAnB,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;QAErB,IAAI,CAA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AEA,MAAM,IAAI,SAAS,CACjBA,qBAAa,CAAC,oBAAoB,EAClC,CAAA,yBAAA,EAA4B,KAAK,YAAY,KAAK,GAAG,KAAK,CAAC,OAAO,GAAG,eAAe,CAAA,CAAE,CACvF;QACH;IACF;IAEA,oBAAoB,GAAA;AAClB,QAAA,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC;IAC1D;IAEA,aAAa,GAAA;AACX,QAAA,IAAI,CAAC,YAAY,GAAG,CAAC;IACvB;AACD;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts","../src/MFAAuth.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n allowedRedirectDomains?: string[];\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\").or(z.literal(\"AUTH_FAILURE\")),\n userProfile: z.object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n roles: z.array(z.string()).optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.DEBUG;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Constants\nconst DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes\nconst DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes\nconst INITIAL_POLL_INTERVAL = 1000;\nconst MAX_POLL_INTERVAL = 5000;\nconst WINDOW_FEATURES = \"scrollbars=yes,resizable=yes\";\n\n// Default allowed Microsoft domains for Azure AD redirects\nconst DEFAULT_MICROSOFT_DOMAINS = [\n \".microsoft.com\",\n \".microsoftonline.com\", \n \".live.com\",\n \"login.microsoftonline.com\"\n];\n\n// Secure reference to native functions with proper binding\nconst NativeFunctions = {\n addEventListener: typeof window !== \"undefined\" ? window.addEventListener.bind(window) : null,\n removeEventListener: typeof window !== \"undefined\" ? window.removeEventListener.bind(window) : null,\n setTimeout: typeof window !== \"undefined\" ? window.setTimeout.bind(window) : setTimeout,\n clearTimeout: typeof window !== \"undefined\" ? window.clearTimeout.bind(window) : clearTimeout,\n};\n\n// Types\ntype TimeoutHandle = ReturnType<typeof setTimeout>;\ntype MessageListener = (event: MessageEvent) => void;\n\n/**\n * Generate a secure random window name to prevent targeting\n */\nexport const generateSecureWindowName = (): string =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\n/**\n * Detect if current window is a popup to prevent recursive popups\n */\nexport const isPopupWindow = (): boolean => {\n if (typeof window === \"undefined\") return false;\n \n // Skip popup detection in test environments\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_ENV === \"test\") {\n return false;\n }\n \n try {\n return window.opener !== null && window.opener !== window;\n } catch {\n return false;\n }\n};\n\n/**\n * Safely close a window with error handling for cross-origin restrictions\n */\nconst safeWindowClose = (window: Window | null): void => {\n if (!window) return;\n \n try {\n if (!window.closed) {\n window.close();\n }\n } catch (error) {\n Logger.debug(\"Error closing window (cross-origin restriction)\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n};\n\n/**\n * Center popup window on screen\n */\nconst getPopupPosition = (width: number, height: number): { left: number; top: number } => {\n if (typeof window === \"undefined\") return { left: 0, top: 0 };\n \n const left = Math.max(0, (window.screen.width - width) / 2);\n const top = Math.max(0, (window.screen.height - height) / 2);\n \n return { left, top };\n};\n\n/**\n * Validate origin against expected domain with support for subdomains and Microsoft redirects\n */\nconst isValidOrigin = (\n eventOrigin: string, \n expectedOrigin: string,\n microsoftDomains: string[] = DEFAULT_MICROSOFT_DOMAINS\n): boolean => {\n try {\n const originUrl = new URL(eventOrigin);\n const expectedHostname = expectedOrigin.startsWith(\"http\")\n ? new URL(expectedOrigin).hostname\n : expectedOrigin;\n\n // Check Microsoft domains for Azure AD redirects\n const isMicrosoftDomain = microsoftDomains.some(domain => \n originUrl.hostname === domain || originUrl.hostname.endsWith(domain)\n );\n\n // Allow exact match, subdomains, or Microsoft domains\n return (\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain\n );\n } catch {\n return false;\n }\n};\n\n/**\n * Safely check if window is closed with cross-origin handling\n */\nconst isWindowClosed = (window: Window | null): boolean => {\n if (!window) return true;\n \n try {\n return window.closed;\n } catch (error) {\n // Cross-origin error means we can't access the property\n // This typically happens when redirected to external auth providers\n Logger.debug(\"Cannot access window.closed due to cross-origin restrictions - assuming window is still open\", error as any);\n return false;\n }\n};\n\n/**\n * Safely add message event listener with error handling\n */\nconst addMessageListener = (listener: MessageListener): (() => void) => {\n if (!NativeFunctions.addEventListener) {\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Message listener not available in current environment\"\n );\n }\n\n const wrappedListener = (event: Event) => {\n try {\n listener(event as MessageEvent);\n } catch (error) {\n Logger.error(\"Error in message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n };\n\n NativeFunctions.addEventListener(\"message\", wrappedListener);\n \n return () => {\n if (NativeFunctions.removeEventListener) {\n NativeFunctions.removeEventListener(\"message\", wrappedListener);\n }\n };\n};\n\n/**\n * Validate configuration and return parsed URL\n */\nexport function validateConfig(config: CAMSConfig): URL {\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n return new URL(config.camsUrl);\n}\n\n/**\n * Open CAMS authentication popup and handle the authentication flow\n */\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n // Environment validation\n if (typeof window === \"undefined\") {\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open popup in server-side environment\"\n )\n );\n return;\n }\n\n if (isPopupWindow()) {\n Logger.warn(\"Attempted to open popup from within popup window\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open authentication popup from within popup window\"\n )\n );\n return;\n }\n\n // Initialize logging\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n // Validate configuration\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Configuration validation passed\");\n } catch (error) {\n Logger.error(\"Configuration validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n reject(error as Error);\n return;\n }\n\n // Extract configuration with defaults\n const {\n messageOrigin,\n windowHeight = 600,\n windowWidth = 500,\n authTimeout = DEFAULT_AUTH_TIMEOUT,\n idleTimeout = DEFAULT_IDLE_TIMEOUT,\n allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin],\n } = config;\n\n // State management\n let authWindow: Window | null = null;\n let authTimeoutId: TimeoutHandle | null = null;\n let idleTimeoutId: TimeoutHandle | null = null;\n let checkClosedInterval: TimeoutHandle | null = null;\n let removeMessageListener: (() => void) | null = null;\n let hasReceivedValidMessage = false;\n\n /**\n * Clean up all resources and timeouts\n */\n const cleanup = (): void => {\n if (removeMessageListener) {\n removeMessageListener();\n removeMessageListener = null;\n }\n\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n if (authTimeoutId) NativeFunctions.clearTimeout(authTimeoutId);\n if (checkClosedInterval) NativeFunctions.clearTimeout(checkClosedInterval);\n\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n /**\n * Clean up and close the popup window, then reject with error\n */\n const cleanupAndClose = (error?: CAMSError): void => {\n cleanup();\n safeWindowClose(authWindow);\n \n if (error) {\n reject(error);\n }\n };\n\n /**\n * Reset idle timeout on user activity\n */\n const resetIdleTimeout = (): void => {\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n \n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n /**\n * Set up popup window closure detection with cross-origin handling\n */\n const setupClosureDetection = (): void => {\n let pollInterval = INITIAL_POLL_INTERVAL;\n\n const checkClosed = (): void => {\n // Skip closure detection when on Microsoft domains\n if (authWindow) {\n try {\n const currentUrl = authWindow.location.href;\n const isMicrosoftDomain = allowedRedirectDomains.some(domain => \n currentUrl.includes(domain)\n );\n \n if (isMicrosoftDomain) {\n Logger.debug(\"Skipping closure check - on Microsoft domain\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n } catch (error) {\n // Cross-origin error - assume we're on Microsoft domain and skip check\n Logger.debug(\"Cross-origin error - skipping closure check\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n }\n\n const isClosed = isWindowClosed(authWindow);\n \n if (isClosed && !hasReceivedValidMessage) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n /**\n * Handle incoming message events from the popup\n */\n const handleMessage = (event: MessageEvent): void => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n // Security: Validate origin\n if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Security: Validate message source\n if (event.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: event.source,\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Mark that we've received a valid message (prevents false closure detection)\n hasReceivedValidMessage = true;\n\n // Handle heartbeat messages (reset idle timeout)\n if (event.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // Process authentication messages\n processAuthenticationMessage(event.data);\n };\n\n /**\n * Process and validate authentication message payloads\n */\n const processAuthenticationMessage = (data: unknown): void => {\n // Success case: Valid profile received\n const profileValidation = ProfileSchema.safeParse(data);\n if (profileValidation.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(profileValidation.data);\n return;\n }\n\n // Authentication failure case\n const authFailureValidation = AuthFailureMessageSchema.safeParse(data);\n if (authFailureValidation.success) {\n const { error, errorCode, errorDetails } = authFailureValidation.data;\n Logger.warn(\"Authentication failure received\", {\n error,\n errorCode,\n errorDetails,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`\n )\n );\n return;\n }\n\n // Generic error case\n const errorValidation = ErrorMessageSchema.safeParse(data);\n if (errorValidation.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorValidation.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n `Authentication failed: ${errorValidation.data.error}`\n )\n );\n return;\n }\n\n // Invalid message format\n Logger.error(\"Invalid message format received\", {\n messageData: data,\n dataType: typeof data,\n profileValidationError: profileValidation.error?.issues,\n authFailureValidationError: authFailureValidation.error?.issues,\n errorValidationError: errorValidation.error?.issues,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n // Main authentication flow execution\n try {\n // Open popup window\n const { left, top } = getPopupPosition(windowWidth, windowHeight);\n const secureWindowName = generateSecureWindowName();\n \n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n left,\n top,\n });\n\n authWindow = window.open(\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`\n );\n\n // Check for popup blocking\n if (!authWindow) {\n Logger.error(\"Popup window blocked or failed to open\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Check for immediate closure (aggressive popup blockers)\n if (isWindowClosed(authWindow)) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n // Set up message listener\n removeMessageListener = addMessageListener(handleMessage);\n Logger.debug(\"Message listener attached\");\n\n // Set up timeouts\n Logger.debug(\"Setting authentication timeout\", { authTimeout });\n authTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n setupClosureDetection();\n\n // Focus popup for better UX\n try {\n authWindow.focus();\n } catch (error) {\n Logger.debug(\"Could not focus popup window (cross-origin restriction)\");\n }\n\n } catch (error) {\n Logger.error(\"Failed to initialize authentication popup\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to initialize authentication: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n }\n });\n}","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin, isPopupWindow } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n \n // If we're in a popup, don't attempt to open another popup\n if (isPopupWindow()) {\n Logger.warn(\"Cannot initiate login from popup window\");\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot initiate authentication from within popup window\"\n );\n }\n \n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n\n /**\n * Complete authentication in popup window\n * This should be called by popup apps when authentication is successful\n */\n completePopupAuth(profile: Profile, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"completePopupAuth called outside of popup window\");\n return;\n }\n\n try {\n // Store the authentication data locally in the popup\n this.profile = profile;\n this.setToken(profile.userProfile.tokens.Bearer);\n \n Logger.info(\"Authentication completed in popup, forwarding to parent\");\n } catch (error) {\n Logger.error(\"Failed to complete popup authentication\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n }\n\n /**\n * Report authentication error in popup window\n */\n errorPopupAuth(error: any, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"errorPopupAuth called outside of popup window\");\n return;\n }\n\n Logger.warn(\"Reporting authentication error from popup\");\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// 🔹 Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n","import { CAMSError, CAMSErrorType } from \"./types\";\nimport { Logger } from \"./logger\";\n\nexport interface MFAConfig {\n accessToken: string;\n idToken: string;\n appCode: string;\n provider: string;\n apiEndpoint?: string;\n}\n\nexport interface MFAResponse {\n name: string;\n email: string;\n isAuthenticated: boolean;\n message: string;\n mfaIsEnabled: boolean;\n userType: string;\n tokens: {\n Bearer: string;\n Nonce: string;\n };\n}\n\nexport interface MFAAuthenticator {\n sendEmailOTP(): Promise<boolean>;\n verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse>;\n getRemainingAttempts(): number;\n resetAttempts(): void;\n}\n\nexport class CAMSMFAAuthenticator implements MFAAuthenticator {\n private config: MFAConfig;\n private attemptCount = 0;\n private readonly maxAttempts = 3;\n\n constructor(config: MFAConfig) {\n this.config = config;\n }\n\n async sendEmailOTP(): Promise<boolean> {\n try {\n Logger.debug(\"Sending Email OTP\");\n // Implementation would call your API to send email OTP\n // For now, return true as placeholder\n return true;\n } catch (error) {\n Logger.error(\"Failed to send Email OTP\", { error });\n return false;\n }\n }\n\n async verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse> {\n if (this.attemptCount >= this.maxAttempts) {\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Maximum MFA attempts exceeded\"\n );\n }\n\n this.attemptCount++;\n\n try {\n Logger.debug(\"Verifying MFA code\", { type, attempt: this.attemptCount });\n\n const response = await fetch(this.config.apiEndpoint || '/api/auth/verify-mfa', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.accessToken}`,\n },\n body: JSON.stringify({\n provider: this.config.provider,\n accessToken: this.config.accessToken,\n idToken: this.config.idToken,\n authenticationType: type,\n MFACode: code,\n appCode: this.config.appCode,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data: MFAResponse = await response.json();\n console.log(\"MFA Response >>>\", data)\n \n if (data.isAuthenticated) {\n Logger.info(\"MFA verification successful\");\n this.resetAttempts();\n return data;\n } else {\n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n data.message || \"MFA verification failed\"\n );\n }\n } catch (error) {\n Logger.error(\"MFA verification failed\", { error, attempt: this.attemptCount });\n \n if (error instanceof CAMSError) {\n throw error;\n }\n \n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `MFA verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n getRemainingAttempts(): number {\n return Math.max(0, this.maxAttempts - this.attemptCount);\n }\n\n resetAttempts(): void {\n this.attemptCount = 0;\n }\n}"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;AAaYA;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,kBAAyC;AAC3C,CAAC,EARWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;AAUnB,MAAO,SAAU,SAAQ,KAAK,CAAA;AACf,IAAA,IAAA;IAAnB,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;QAErB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI;IACnC;AACD;;AC1BD;AACO,MAAM,aAAa,GAAGC,KAAC,CAAC,MAAM,CAAC;AACpC,IAAA,IAAI,EAAEA,KAAC,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,EAAE,CAACA,KAAC,CAAC,OAAO,CAAC,cAAc,CAAC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K,CAAC,OAAO,GAAG,eAAe,CAAA,CAAE,CACvF;QACH;IACF;IAEA,oBAAoB,GAAA;AAClB,QAAA,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC;IAC1D;IAEA,aAAa,GAAA;AACX,QAAA,IAAI,CAAC,YAAY,GAAG,CAAC;IACvB;AACD;;;;;;;;;;;;;;;"}
|
package/dist/index.esm.js
CHANGED
|
@@ -95,12 +95,12 @@ const DEFAULT_MICROSOFT_DOMAINS = [
|
|
|
95
95
|
".live.com",
|
|
96
96
|
"login.microsoftonline.com"
|
|
97
97
|
];
|
|
98
|
-
// Secure reference to native functions
|
|
98
|
+
// Secure reference to native functions with proper binding
|
|
99
99
|
const NativeFunctions = {
|
|
100
|
-
addEventListener: typeof window !== "undefined" ? window.addEventListener : null,
|
|
101
|
-
removeEventListener: typeof window !== "undefined" ? window.removeEventListener : null,
|
|
102
|
-
setTimeout: typeof window !== "undefined" ? window.setTimeout : setTimeout,
|
|
103
|
-
clearTimeout: typeof window !== "undefined" ? window.clearTimeout : clearTimeout,
|
|
100
|
+
addEventListener: typeof window !== "undefined" ? window.addEventListener.bind(window) : null,
|
|
101
|
+
removeEventListener: typeof window !== "undefined" ? window.removeEventListener.bind(window) : null,
|
|
102
|
+
setTimeout: typeof window !== "undefined" ? window.setTimeout.bind(window) : setTimeout,
|
|
103
|
+
clearTimeout: typeof window !== "undefined" ? window.clearTimeout.bind(window) : clearTimeout,
|
|
104
104
|
};
|
|
105
105
|
/**
|
|
106
106
|
* Generate a secure random window name to prevent targeting
|
|
@@ -203,10 +203,10 @@ const addMessageListener = (listener) => {
|
|
|
203
203
|
});
|
|
204
204
|
}
|
|
205
205
|
};
|
|
206
|
-
NativeFunctions.addEventListener
|
|
206
|
+
NativeFunctions.addEventListener("message", wrappedListener);
|
|
207
207
|
return () => {
|
|
208
208
|
if (NativeFunctions.removeEventListener) {
|
|
209
|
-
NativeFunctions.removeEventListener
|
|
209
|
+
NativeFunctions.removeEventListener("message", wrappedListener);
|
|
210
210
|
}
|
|
211
211
|
};
|
|
212
212
|
};
|
|
@@ -256,7 +256,7 @@ function openCAMSPopUpLogin(config) {
|
|
|
256
256
|
return;
|
|
257
257
|
}
|
|
258
258
|
// Extract configuration with defaults
|
|
259
|
-
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = DEFAULT_MICROSOFT_DOMAINS, } = config;
|
|
259
|
+
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin], } = config;
|
|
260
260
|
// State management
|
|
261
261
|
let authWindow = null;
|
|
262
262
|
let authTimeoutId = null;
|
package/dist/index.esm.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.esm.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts","../src/MFAAuth.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n allowedRedirectDomains?: string[];\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\").or(z.literal(\"AUTH_FAILURE\")),\n userProfile: z.object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n roles: z.array(z.string()).optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.DEBUG;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Constants\nconst DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes\nconst DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes\nconst INITIAL_POLL_INTERVAL = 1000;\nconst MAX_POLL_INTERVAL = 5000;\nconst WINDOW_FEATURES = \"scrollbars=yes,resizable=yes\";\n\n// Default allowed Microsoft domains for Azure AD redirects\nconst DEFAULT_MICROSOFT_DOMAINS = [\n \".microsoft.com\",\n \".microsoftonline.com\", \n \".live.com\",\n \"login.microsoftonline.com\"\n];\n\n// Secure reference to native functions\nconst NativeFunctions = {\n addEventListener: typeof window !== \"undefined\" ? window.addEventListener : null,\n removeEventListener: typeof window !== \"undefined\" ? window.removeEventListener : null,\n setTimeout: typeof window !== \"undefined\" ? window.setTimeout : setTimeout,\n clearTimeout: typeof window !== \"undefined\" ? window.clearTimeout : clearTimeout,\n};\n\n// Types\ntype TimeoutHandle = ReturnType<typeof setTimeout>;\ntype MessageListener = (event: MessageEvent) => void;\n\n/**\n * Generate a secure random window name to prevent targeting\n */\nexport const generateSecureWindowName = (): string =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\n/**\n * Detect if current window is a popup to prevent recursive popups\n */\nexport const isPopupWindow = (): boolean => {\n if (typeof window === \"undefined\") return false;\n \n // Skip popup detection in test environments\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_ENV === \"test\") {\n return false;\n }\n \n try {\n return window.opener !== null && window.opener !== window;\n } catch {\n return false;\n }\n};\n\n/**\n * Safely close a window with error handling for cross-origin restrictions\n */\nconst safeWindowClose = (window: Window | null): void => {\n if (!window) return;\n \n try {\n if (!window.closed) {\n window.close();\n }\n } catch (error) {\n Logger.debug(\"Error closing window (cross-origin restriction)\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n};\n\n/**\n * Center popup window on screen\n */\nconst getPopupPosition = (width: number, height: number): { left: number; top: number } => {\n if (typeof window === \"undefined\") return { left: 0, top: 0 };\n \n const left = Math.max(0, (window.screen.width - width) / 2);\n const top = Math.max(0, (window.screen.height - height) / 2);\n \n return { left, top };\n};\n\n/**\n * Validate origin against expected domain with support for subdomains and Microsoft redirects\n */\nconst isValidOrigin = (\n eventOrigin: string, \n expectedOrigin: string,\n microsoftDomains: string[] = DEFAULT_MICROSOFT_DOMAINS\n): boolean => {\n try {\n const originUrl = new URL(eventOrigin);\n const expectedHostname = expectedOrigin.startsWith(\"http\")\n ? new URL(expectedOrigin).hostname\n : expectedOrigin;\n\n // Check Microsoft domains for Azure AD redirects\n const isMicrosoftDomain = microsoftDomains.some(domain => \n originUrl.hostname === domain || originUrl.hostname.endsWith(domain)\n );\n\n // Allow exact match, subdomains, or Microsoft domains\n return (\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain\n );\n } catch {\n return false;\n }\n};\n\n/**\n * Safely check if window is closed with cross-origin handling\n */\nconst isWindowClosed = (window: Window | null): boolean => {\n if (!window) return true;\n \n try {\n return window.closed;\n } catch (error) {\n // Cross-origin error means we can't access the property\n // This typically happens when redirected to external auth providers\n Logger.debug(\"Cannot access window.closed due to cross-origin restrictions - assuming window is still open\", error as any);\n return false;\n }\n};\n\n/**\n * Safely add message event listener with error handling\n */\nconst addMessageListener = (listener: MessageListener): (() => void) => {\n if (!NativeFunctions.addEventListener) {\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Message listener not available in current environment\"\n );\n }\n\n const wrappedListener = (event: Event) => {\n try {\n listener(event as MessageEvent);\n } catch (error) {\n Logger.error(\"Error in message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n };\n\n NativeFunctions.addEventListener.call(window, \"message\", wrappedListener);\n \n return () => {\n if (NativeFunctions.removeEventListener) {\n NativeFunctions.removeEventListener.call(window, \"message\", wrappedListener);\n }\n };\n};\n\n/**\n * Validate configuration and return parsed URL\n */\nexport function validateConfig(config: CAMSConfig): URL {\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n return new URL(config.camsUrl);\n}\n\n/**\n * Open CAMS authentication popup and handle the authentication flow\n */\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n // Environment validation\n if (typeof window === \"undefined\") {\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open popup in server-side environment\"\n )\n );\n return;\n }\n\n if (isPopupWindow()) {\n Logger.warn(\"Attempted to open popup from within popup window\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open authentication popup from within popup window\"\n )\n );\n return;\n }\n\n // Initialize logging\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n // Validate configuration\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Configuration validation passed\");\n } catch (error) {\n Logger.error(\"Configuration validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n reject(error as Error);\n return;\n }\n\n // Extract configuration with defaults\n const {\n messageOrigin,\n windowHeight = 600,\n windowWidth = 500,\n authTimeout = DEFAULT_AUTH_TIMEOUT,\n idleTimeout = DEFAULT_IDLE_TIMEOUT,\n allowedRedirectDomains = DEFAULT_MICROSOFT_DOMAINS,\n } = config;\n\n // State management\n let authWindow: Window | null = null;\n let authTimeoutId: TimeoutHandle | null = null;\n let idleTimeoutId: TimeoutHandle | null = null;\n let checkClosedInterval: TimeoutHandle | null = null;\n let removeMessageListener: (() => void) | null = null;\n let hasReceivedValidMessage = false;\n\n /**\n * Clean up all resources and timeouts\n */\n const cleanup = (): void => {\n if (removeMessageListener) {\n removeMessageListener();\n removeMessageListener = null;\n }\n\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n if (authTimeoutId) NativeFunctions.clearTimeout(authTimeoutId);\n if (checkClosedInterval) NativeFunctions.clearTimeout(checkClosedInterval);\n\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n /**\n * Clean up and close the popup window, then reject with error\n */\n const cleanupAndClose = (error?: CAMSError): void => {\n cleanup();\n safeWindowClose(authWindow);\n \n if (error) {\n reject(error);\n }\n };\n\n /**\n * Reset idle timeout on user activity\n */\n const resetIdleTimeout = (): void => {\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n \n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n /**\n * Set up popup window closure detection with cross-origin handling\n */\n const setupClosureDetection = (): void => {\n let pollInterval = INITIAL_POLL_INTERVAL;\n\n const checkClosed = (): void => {\n // Skip closure detection when on Microsoft domains\n if (authWindow) {\n try {\n const currentUrl = authWindow.location.href;\n const isMicrosoftDomain = allowedRedirectDomains.some(domain => \n currentUrl.includes(domain)\n );\n \n if (isMicrosoftDomain) {\n Logger.debug(\"Skipping closure check - on Microsoft domain\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n } catch (error) {\n // Cross-origin error - assume we're on Microsoft domain and skip check\n Logger.debug(\"Cross-origin error - skipping closure check\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n }\n\n const isClosed = isWindowClosed(authWindow);\n \n if (isClosed && !hasReceivedValidMessage) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n /**\n * Handle incoming message events from the popup\n */\n const handleMessage = (event: MessageEvent): void => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n // Security: Validate origin\n if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Security: Validate message source\n if (event.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: event.source,\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Mark that we've received a valid message (prevents false closure detection)\n hasReceivedValidMessage = true;\n\n // Handle heartbeat messages (reset idle timeout)\n if (event.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // Process authentication messages\n processAuthenticationMessage(event.data);\n };\n\n /**\n * Process and validate authentication message payloads\n */\n const processAuthenticationMessage = (data: unknown): void => {\n // Success case: Valid profile received\n const profileValidation = ProfileSchema.safeParse(data);\n if (profileValidation.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(profileValidation.data);\n return;\n }\n\n // Authentication failure case\n const authFailureValidation = AuthFailureMessageSchema.safeParse(data);\n if (authFailureValidation.success) {\n const { error, errorCode, errorDetails } = authFailureValidation.data;\n Logger.warn(\"Authentication failure received\", {\n error,\n errorCode,\n errorDetails,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`\n )\n );\n return;\n }\n\n // Generic error case\n const errorValidation = ErrorMessageSchema.safeParse(data);\n if (errorValidation.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorValidation.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n `Authentication failed: ${errorValidation.data.error}`\n )\n );\n return;\n }\n\n // Invalid message format\n Logger.error(\"Invalid message format received\", {\n messageData: data,\n dataType: typeof data,\n profileValidationError: profileValidation.error?.issues,\n authFailureValidationError: authFailureValidation.error?.issues,\n errorValidationError: errorValidation.error?.issues,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n // Main authentication flow execution\n try {\n // Open popup window\n const { left, top } = getPopupPosition(windowWidth, windowHeight);\n const secureWindowName = generateSecureWindowName();\n \n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n left,\n top,\n });\n\n authWindow = window.open(\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`\n );\n\n // Check for popup blocking\n if (!authWindow) {\n Logger.error(\"Popup window blocked or failed to open\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Check for immediate closure (aggressive popup blockers)\n if (isWindowClosed(authWindow)) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n // Set up message listener\n removeMessageListener = addMessageListener(handleMessage);\n Logger.debug(\"Message listener attached\");\n\n // Set up timeouts\n Logger.debug(\"Setting authentication timeout\", { authTimeout });\n authTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n setupClosureDetection();\n\n // Focus popup for better UX\n try {\n authWindow.focus();\n } catch (error) {\n Logger.debug(\"Could not focus popup window (cross-origin restriction)\");\n }\n\n } catch (error) {\n Logger.error(\"Failed to initialize authentication popup\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to initialize authentication: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n }\n });\n}","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin, isPopupWindow } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n \n // If we're in a popup, don't attempt to open another popup\n if (isPopupWindow()) {\n Logger.warn(\"Cannot initiate login from popup window\");\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot initiate authentication from within popup window\"\n );\n }\n \n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n\n /**\n * Complete authentication in popup window\n * This should be called by popup apps when authentication is successful\n */\n completePopupAuth(profile: Profile, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"completePopupAuth called outside of popup window\");\n return;\n }\n\n try {\n // Store the authentication data locally in the popup\n this.profile = profile;\n this.setToken(profile.userProfile.tokens.Bearer);\n \n Logger.info(\"Authentication completed in popup, forwarding to parent\");\n } catch (error) {\n Logger.error(\"Failed to complete popup authentication\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n }\n\n /**\n * Report authentication error in popup window\n */\n errorPopupAuth(error: any, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"errorPopupAuth called outside of popup window\");\n return;\n }\n\n Logger.warn(\"Reporting authentication error from popup\");\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// 🔹 Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n","import { CAMSError, CAMSErrorType } from \"./types\";\nimport { Logger } from \"./logger\";\n\nexport interface MFAConfig {\n accessToken: string;\n idToken: string;\n appCode: string;\n provider: string;\n apiEndpoint?: string;\n}\n\nexport interface MFAResponse {\n name: string;\n email: string;\n isAuthenticated: boolean;\n message: string;\n mfaIsEnabled: boolean;\n userType: string;\n tokens: {\n Bearer: string;\n Nonce: string;\n };\n}\n\nexport interface MFAAuthenticator {\n sendEmailOTP(): Promise<boolean>;\n verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse>;\n getRemainingAttempts(): number;\n resetAttempts(): void;\n}\n\nexport class CAMSMFAAuthenticator implements MFAAuthenticator {\n private config: MFAConfig;\n private attemptCount = 0;\n private readonly maxAttempts = 3;\n\n constructor(config: MFAConfig) {\n this.config = config;\n }\n\n async sendEmailOTP(): Promise<boolean> {\n try {\n Logger.debug(\"Sending Email OTP\");\n // Implementation would call your API to send email OTP\n // For now, return true as placeholder\n return true;\n } catch (error) {\n Logger.error(\"Failed to send Email OTP\", { error });\n return false;\n }\n }\n\n async verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse> {\n if (this.attemptCount >= this.maxAttempts) {\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Maximum MFA attempts exceeded\"\n );\n }\n\n this.attemptCount++;\n\n try {\n Logger.debug(\"Verifying MFA code\", { type, attempt: this.attemptCount });\n\n const response = await fetch(this.config.apiEndpoint || '/api/auth/verify-mfa', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.accessToken}`,\n },\n body: JSON.stringify({\n provider: this.config.provider,\n accessToken: this.config.accessToken,\n idToken: this.config.idToken,\n authenticationType: type,\n MFACode: code,\n appCode: this.config.appCode,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data: MFAResponse = await response.json();\n console.log(\"MFA Response >>>\", data)\n \n if (data.isAuthenticated) {\n Logger.info(\"MFA verification successful\");\n this.resetAttempts();\n return data;\n } else {\n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n data.message || \"MFA verification failed\"\n );\n }\n } catch (error) {\n Logger.error(\"MFA verification failed\", { error, attempt: this.attemptCount });\n \n if (error instanceof CAMSError) {\n throw error;\n }\n \n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `MFA verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n getRemainingAttempts(): number {\n return Math.max(0, this.maxAttempts - this.attemptCount);\n }\n\n resetAttempts(): void {\n this.attemptCount = 0;\n }\n}"],"names":[],"mappings":";;IAaY;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,kBAAyC;AAC3C,CAAC,EARW,aAAa,KAAb,aAAa,GAAA,EAAA,CAAA,CAAA;AAUnB,MAAO,SAAU,SAAQ,KAAK,CAAA;AACf,IAAA,IAAA;IAAnB,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;QAErB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,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e,CAAA,CAAE,CACvF;QACH;IACF;IAEA,oBAAoB,GAAA;AAClB,QAAA,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,YAAY,CAAC;IAC1D;IAEA,aAAa,GAAA;AACX,QAAA,IAAI,CAAC,YAAY,GAAG,CAAC;IACvB;AACD;;;;"}
|
|
1
|
+
{"version":3,"file":"index.esm.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts","../src/MFAAuth.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n allowedRedirectDomains?: string[];\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\").or(z.literal(\"AUTH_FAILURE\")),\n userProfile: z.object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n roles: z.array(z.string()).optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.DEBUG;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Constants\nconst DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes\nconst DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes\nconst INITIAL_POLL_INTERVAL = 1000;\nconst MAX_POLL_INTERVAL = 5000;\nconst WINDOW_FEATURES = \"scrollbars=yes,resizable=yes\";\n\n// Default allowed Microsoft domains for Azure AD redirects\nconst DEFAULT_MICROSOFT_DOMAINS = [\n \".microsoft.com\",\n \".microsoftonline.com\", \n \".live.com\",\n \"login.microsoftonline.com\"\n];\n\n// Secure reference to native functions with proper binding\nconst NativeFunctions = {\n addEventListener: typeof window !== \"undefined\" ? window.addEventListener.bind(window) : null,\n removeEventListener: typeof window !== \"undefined\" ? window.removeEventListener.bind(window) : null,\n setTimeout: typeof window !== \"undefined\" ? window.setTimeout.bind(window) : setTimeout,\n clearTimeout: typeof window !== \"undefined\" ? window.clearTimeout.bind(window) : clearTimeout,\n};\n\n// Types\ntype TimeoutHandle = ReturnType<typeof setTimeout>;\ntype MessageListener = (event: MessageEvent) => void;\n\n/**\n * Generate a secure random window name to prevent targeting\n */\nexport const generateSecureWindowName = (): string =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\n/**\n * Detect if current window is a popup to prevent recursive popups\n */\nexport const isPopupWindow = (): boolean => {\n if (typeof window === \"undefined\") return false;\n \n // Skip popup detection in test environments\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_ENV === \"test\") {\n return false;\n }\n \n try {\n return window.opener !== null && window.opener !== window;\n } catch {\n return false;\n }\n};\n\n/**\n * Safely close a window with error handling for cross-origin restrictions\n */\nconst safeWindowClose = (window: Window | null): void => {\n if (!window) return;\n \n try {\n if (!window.closed) {\n window.close();\n }\n } catch (error) {\n Logger.debug(\"Error closing window (cross-origin restriction)\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n};\n\n/**\n * Center popup window on screen\n */\nconst getPopupPosition = (width: number, height: number): { left: number; top: number } => {\n if (typeof window === \"undefined\") return { left: 0, top: 0 };\n \n const left = Math.max(0, (window.screen.width - width) / 2);\n const top = Math.max(0, (window.screen.height - height) / 2);\n \n return { left, top };\n};\n\n/**\n * Validate origin against expected domain with support for subdomains and Microsoft redirects\n */\nconst isValidOrigin = (\n eventOrigin: string, \n expectedOrigin: string,\n microsoftDomains: string[] = DEFAULT_MICROSOFT_DOMAINS\n): boolean => {\n try {\n const originUrl = new URL(eventOrigin);\n const expectedHostname = expectedOrigin.startsWith(\"http\")\n ? new URL(expectedOrigin).hostname\n : expectedOrigin;\n\n // Check Microsoft domains for Azure AD redirects\n const isMicrosoftDomain = microsoftDomains.some(domain => \n originUrl.hostname === domain || originUrl.hostname.endsWith(domain)\n );\n\n // Allow exact match, subdomains, or Microsoft domains\n return (\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain\n );\n } catch {\n return false;\n }\n};\n\n/**\n * Safely check if window is closed with cross-origin handling\n */\nconst isWindowClosed = (window: Window | null): boolean => {\n if (!window) return true;\n \n try {\n return window.closed;\n } catch (error) {\n // Cross-origin error means we can't access the property\n // This typically happens when redirected to external auth providers\n Logger.debug(\"Cannot access window.closed due to cross-origin restrictions - assuming window is still open\", error as any);\n return false;\n }\n};\n\n/**\n * Safely add message event listener with error handling\n */\nconst addMessageListener = (listener: MessageListener): (() => void) => {\n if (!NativeFunctions.addEventListener) {\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Message listener not available in current environment\"\n );\n }\n\n const wrappedListener = (event: Event) => {\n try {\n listener(event as MessageEvent);\n } catch (error) {\n Logger.error(\"Error in message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n };\n\n NativeFunctions.addEventListener(\"message\", wrappedListener);\n \n return () => {\n if (NativeFunctions.removeEventListener) {\n NativeFunctions.removeEventListener(\"message\", wrappedListener);\n }\n };\n};\n\n/**\n * Validate configuration and return parsed URL\n */\nexport function validateConfig(config: CAMSConfig): URL {\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n return new URL(config.camsUrl);\n}\n\n/**\n * Open CAMS authentication popup and handle the authentication flow\n */\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n // Environment validation\n if (typeof window === \"undefined\") {\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open popup in server-side environment\"\n )\n );\n return;\n }\n\n if (isPopupWindow()) {\n Logger.warn(\"Attempted to open popup from within popup window\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open authentication popup from within popup window\"\n )\n );\n return;\n }\n\n // Initialize logging\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n // Validate configuration\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Configuration validation passed\");\n } catch (error) {\n Logger.error(\"Configuration validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n reject(error as Error);\n return;\n }\n\n // Extract configuration with defaults\n const {\n messageOrigin,\n windowHeight = 600,\n windowWidth = 500,\n authTimeout = DEFAULT_AUTH_TIMEOUT,\n idleTimeout = DEFAULT_IDLE_TIMEOUT,\n allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin],\n } = config;\n\n // State management\n let authWindow: Window | null = null;\n let authTimeoutId: TimeoutHandle | null = null;\n let idleTimeoutId: TimeoutHandle | null = null;\n let checkClosedInterval: TimeoutHandle | null = null;\n let removeMessageListener: (() => void) | null = null;\n let hasReceivedValidMessage = false;\n\n /**\n * Clean up all resources and timeouts\n */\n const cleanup = (): void => {\n if (removeMessageListener) {\n removeMessageListener();\n removeMessageListener = null;\n }\n\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n if (authTimeoutId) NativeFunctions.clearTimeout(authTimeoutId);\n if (checkClosedInterval) NativeFunctions.clearTimeout(checkClosedInterval);\n\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n /**\n * Clean up and close the popup window, then reject with error\n */\n const cleanupAndClose = (error?: CAMSError): void => {\n cleanup();\n safeWindowClose(authWindow);\n \n if (error) {\n reject(error);\n }\n };\n\n /**\n * Reset idle timeout on user activity\n */\n const resetIdleTimeout = (): void => {\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n \n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n /**\n * Set up popup window closure detection with cross-origin handling\n */\n const setupClosureDetection = (): void => {\n let pollInterval = INITIAL_POLL_INTERVAL;\n\n const checkClosed = (): void => {\n // Skip closure detection when on Microsoft domains\n if (authWindow) {\n try {\n const currentUrl = authWindow.location.href;\n const isMicrosoftDomain = allowedRedirectDomains.some(domain => \n currentUrl.includes(domain)\n );\n \n if (isMicrosoftDomain) {\n Logger.debug(\"Skipping closure check - on Microsoft domain\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n } catch (error) {\n // Cross-origin error - assume we're on Microsoft domain and skip check\n Logger.debug(\"Cross-origin error - skipping closure check\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n }\n\n const isClosed = isWindowClosed(authWindow);\n \n if (isClosed && !hasReceivedValidMessage) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n /**\n * Handle incoming message events from the popup\n */\n const handleMessage = (event: MessageEvent): void => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n // Security: Validate origin\n if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Security: Validate message source\n if (event.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: event.source,\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Mark that we've received a valid message (prevents false closure detection)\n hasReceivedValidMessage = true;\n\n // Handle heartbeat messages (reset idle timeout)\n if (event.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // Process authentication messages\n processAuthenticationMessage(event.data);\n };\n\n /**\n * Process and validate authentication message payloads\n */\n const processAuthenticationMessage = (data: unknown): void => {\n // Success case: Valid profile received\n const profileValidation = ProfileSchema.safeParse(data);\n if (profileValidation.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(profileValidation.data);\n return;\n }\n\n // Authentication failure case\n const authFailureValidation = AuthFailureMessageSchema.safeParse(data);\n if (authFailureValidation.success) {\n const { error, errorCode, errorDetails } = authFailureValidation.data;\n Logger.warn(\"Authentication failure received\", {\n error,\n errorCode,\n errorDetails,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`\n )\n );\n return;\n }\n\n // Generic error case\n const errorValidation = ErrorMessageSchema.safeParse(data);\n if (errorValidation.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorValidation.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n `Authentication failed: ${errorValidation.data.error}`\n )\n );\n return;\n }\n\n // Invalid message format\n Logger.error(\"Invalid message format received\", {\n messageData: data,\n dataType: typeof data,\n profileValidationError: profileValidation.error?.issues,\n authFailureValidationError: authFailureValidation.error?.issues,\n errorValidationError: errorValidation.error?.issues,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n // Main authentication flow execution\n try {\n // Open popup window\n const { left, top } = getPopupPosition(windowWidth, windowHeight);\n const secureWindowName = generateSecureWindowName();\n \n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n left,\n top,\n });\n\n authWindow = window.open(\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`\n );\n\n // Check for popup blocking\n if (!authWindow) {\n Logger.error(\"Popup window blocked or failed to open\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Check for immediate closure (aggressive popup blockers)\n if (isWindowClosed(authWindow)) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n // Set up message listener\n removeMessageListener = addMessageListener(handleMessage);\n Logger.debug(\"Message listener attached\");\n\n // Set up timeouts\n Logger.debug(\"Setting authentication timeout\", { authTimeout });\n authTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n setupClosureDetection();\n\n // Focus popup for better UX\n try {\n authWindow.focus();\n } catch (error) {\n Logger.debug(\"Could not focus popup window (cross-origin restriction)\");\n }\n\n } catch (error) {\n Logger.error(\"Failed to initialize authentication popup\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to initialize authentication: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n }\n });\n}","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin, isPopupWindow } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n \n // If we're in a popup, don't attempt to open another popup\n if (isPopupWindow()) {\n Logger.warn(\"Cannot initiate login from popup window\");\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot initiate authentication from within popup window\"\n );\n }\n \n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n\n /**\n * Complete authentication in popup window\n * This should be called by popup apps when authentication is successful\n */\n completePopupAuth(profile: Profile, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"completePopupAuth called outside of popup window\");\n return;\n }\n\n try {\n // Store the authentication data locally in the popup\n this.profile = profile;\n this.setToken(profile.userProfile.tokens.Bearer);\n \n Logger.info(\"Authentication completed in popup, forwarding to parent\");\n } catch (error) {\n Logger.error(\"Failed to complete popup authentication\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n }\n\n /**\n * Report authentication error in popup window\n */\n errorPopupAuth(error: any, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"errorPopupAuth called outside of popup window\");\n return;\n }\n\n Logger.warn(\"Reporting authentication error from popup\");\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// 🔹 Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n","import { CAMSError, CAMSErrorType } from \"./types\";\nimport { Logger } from \"./logger\";\n\nexport interface MFAConfig {\n accessToken: string;\n idToken: string;\n appCode: string;\n provider: string;\n apiEndpoint?: string;\n}\n\nexport interface MFAResponse {\n name: string;\n email: string;\n isAuthenticated: boolean;\n message: string;\n mfaIsEnabled: boolean;\n userType: string;\n tokens: {\n Bearer: string;\n Nonce: string;\n };\n}\n\nexport interface MFAAuthenticator {\n sendEmailOTP(): Promise<boolean>;\n verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse>;\n getRemainingAttempts(): number;\n resetAttempts(): void;\n}\n\nexport class CAMSMFAAuthenticator implements MFAAuthenticator {\n private config: MFAConfig;\n private attemptCount = 0;\n private readonly maxAttempts = 3;\n\n constructor(config: MFAConfig) {\n this.config = config;\n }\n\n async sendEmailOTP(): Promise<boolean> {\n try {\n Logger.debug(\"Sending Email OTP\");\n // Implementation would call your API to send email OTP\n // For now, return true as placeholder\n return true;\n } catch (error) {\n Logger.error(\"Failed to send Email OTP\", { error });\n return false;\n }\n }\n\n async verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse> {\n if (this.attemptCount >= this.maxAttempts) {\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Maximum MFA attempts exceeded\"\n );\n }\n\n this.attemptCount++;\n\n try {\n Logger.debug(\"Verifying MFA code\", { type, attempt: this.attemptCount });\n\n const response = await fetch(this.config.apiEndpoint || '/api/auth/verify-mfa', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.accessToken}`,\n },\n body: JSON.stringify({\n provider: this.config.provider,\n accessToken: this.config.accessToken,\n idToken: this.config.idToken,\n authenticationType: type,\n MFACode: code,\n appCode: this.config.appCode,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data: MFAResponse = await response.json();\n console.log(\"MFA Response >>>\", data)\n \n if (data.isAuthenticated) {\n Logger.info(\"MFA verification successful\");\n this.resetAttempts();\n return data;\n } else {\n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n data.message || \"MFA verification failed\"\n );\n }\n } catch (error) {\n Logger.error(\"MFA verification failed\", { error, attempt: this.attemptCount });\n \n if (error instanceof CAMSError) {\n throw error;\n }\n \n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `MFA verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n getRemainingAttempts(): number {\n return Math.max(0, this.maxAttempts - this.attemptCount);\n }\n\n resetAttempts(): void {\n this.attemptCount = 0;\n }\n}"],"names":[],"mappings":";;IAaY;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;AAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;AACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;AAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;AAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,kBAAyC;AAC3C,CAAC,EARW,aAAa,KAAb,aAAa,GAAA,EAAA,CAAA,CAAA;AAUnB,MAAO,SAAU,SAAQ,KAAK,CAAA;AACf,IAAA,IAAA;IAAnB,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;QACrD,KAAK,CAAC,OAAO,CAAC;QADG,IAAA,CAAA,IAAI,GAAJ,IAAI;QAErB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI;IACnC;AACD;;AC1BD;AACO,MAAM,aAAa,GAAG,CAAC,CAAC,MAAM,CAAC;AACpC,IAAA,IAAI,EAAE,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;AAC7D,IAAA,WAAW,EAAE,CAAC,CAAC,MAAM,CAAC;AACpB,QAAA,IAAI,EAAE,CAAC,CAAC,MAAM,EAAE;AAChB,QAAA,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE;AAChB,QAAA,YAAY,EAAE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/dist/index.umd.js
CHANGED
|
@@ -99,12 +99,12 @@
|
|
|
99
99
|
".live.com",
|
|
100
100
|
"login.microsoftonline.com"
|
|
101
101
|
];
|
|
102
|
-
// Secure reference to native functions
|
|
102
|
+
// Secure reference to native functions with proper binding
|
|
103
103
|
const NativeFunctions = {
|
|
104
|
-
addEventListener: typeof window !== "undefined" ? window.addEventListener : null,
|
|
105
|
-
removeEventListener: typeof window !== "undefined" ? window.removeEventListener : null,
|
|
106
|
-
setTimeout: typeof window !== "undefined" ? window.setTimeout : setTimeout,
|
|
107
|
-
clearTimeout: typeof window !== "undefined" ? window.clearTimeout : clearTimeout,
|
|
104
|
+
addEventListener: typeof window !== "undefined" ? window.addEventListener.bind(window) : null,
|
|
105
|
+
removeEventListener: typeof window !== "undefined" ? window.removeEventListener.bind(window) : null,
|
|
106
|
+
setTimeout: typeof window !== "undefined" ? window.setTimeout.bind(window) : setTimeout,
|
|
107
|
+
clearTimeout: typeof window !== "undefined" ? window.clearTimeout.bind(window) : clearTimeout,
|
|
108
108
|
};
|
|
109
109
|
/**
|
|
110
110
|
* Generate a secure random window name to prevent targeting
|
|
@@ -207,10 +207,10 @@
|
|
|
207
207
|
});
|
|
208
208
|
}
|
|
209
209
|
};
|
|
210
|
-
NativeFunctions.addEventListener
|
|
210
|
+
NativeFunctions.addEventListener("message", wrappedListener);
|
|
211
211
|
return () => {
|
|
212
212
|
if (NativeFunctions.removeEventListener) {
|
|
213
|
-
NativeFunctions.removeEventListener
|
|
213
|
+
NativeFunctions.removeEventListener("message", wrappedListener);
|
|
214
214
|
}
|
|
215
215
|
};
|
|
216
216
|
};
|
|
@@ -260,7 +260,7 @@
|
|
|
260
260
|
return;
|
|
261
261
|
}
|
|
262
262
|
// Extract configuration with defaults
|
|
263
|
-
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = DEFAULT_MICROSOFT_DOMAINS, } = config;
|
|
263
|
+
const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin], } = config;
|
|
264
264
|
// State management
|
|
265
265
|
let authWindow = null;
|
|
266
266
|
let authTimeoutId = null;
|
package/dist/index.umd.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts","../src/MFAAuth.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n allowedRedirectDomains?: string[];\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\").or(z.literal(\"AUTH_FAILURE\")),\n userProfile: z.object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n roles: z.array(z.string()).optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.DEBUG;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Constants\nconst DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes\nconst DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes\nconst INITIAL_POLL_INTERVAL = 1000;\nconst MAX_POLL_INTERVAL = 5000;\nconst WINDOW_FEATURES = \"scrollbars=yes,resizable=yes\";\n\n// Default allowed Microsoft domains for Azure AD redirects\nconst DEFAULT_MICROSOFT_DOMAINS = [\n \".microsoft.com\",\n \".microsoftonline.com\", \n \".live.com\",\n \"login.microsoftonline.com\"\n];\n\n// Secure reference to native functions\nconst NativeFunctions = {\n addEventListener: typeof window !== \"undefined\" ? window.addEventListener : null,\n removeEventListener: typeof window !== \"undefined\" ? window.removeEventListener : null,\n setTimeout: typeof window !== \"undefined\" ? window.setTimeout : setTimeout,\n clearTimeout: typeof window !== \"undefined\" ? window.clearTimeout : clearTimeout,\n};\n\n// Types\ntype TimeoutHandle = ReturnType<typeof setTimeout>;\ntype MessageListener = (event: MessageEvent) => void;\n\n/**\n * Generate a secure random window name to prevent targeting\n */\nexport const generateSecureWindowName = (): string =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\n/**\n * Detect if current window is a popup to prevent recursive popups\n */\nexport const isPopupWindow = (): boolean => {\n if (typeof window === \"undefined\") return false;\n \n // Skip popup detection in test environments\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_ENV === \"test\") {\n return false;\n }\n \n try {\n return window.opener !== null && window.opener !== window;\n } catch {\n return false;\n }\n};\n\n/**\n * Safely close a window with error handling for cross-origin restrictions\n */\nconst safeWindowClose = (window: Window | null): void => {\n if (!window) return;\n \n try {\n if (!window.closed) {\n window.close();\n }\n } catch (error) {\n Logger.debug(\"Error closing window (cross-origin restriction)\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n};\n\n/**\n * Center popup window on screen\n */\nconst getPopupPosition = (width: number, height: number): { left: number; top: number } => {\n if (typeof window === \"undefined\") return { left: 0, top: 0 };\n \n const left = Math.max(0, (window.screen.width - width) / 2);\n const top = Math.max(0, (window.screen.height - height) / 2);\n \n return { left, top };\n};\n\n/**\n * Validate origin against expected domain with support for subdomains and Microsoft redirects\n */\nconst isValidOrigin = (\n eventOrigin: string, \n expectedOrigin: string,\n microsoftDomains: string[] = DEFAULT_MICROSOFT_DOMAINS\n): boolean => {\n try {\n const originUrl = new URL(eventOrigin);\n const expectedHostname = expectedOrigin.startsWith(\"http\")\n ? new URL(expectedOrigin).hostname\n : expectedOrigin;\n\n // Check Microsoft domains for Azure AD redirects\n const isMicrosoftDomain = microsoftDomains.some(domain => \n originUrl.hostname === domain || originUrl.hostname.endsWith(domain)\n );\n\n // Allow exact match, subdomains, or Microsoft domains\n return (\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain\n );\n } catch {\n return false;\n }\n};\n\n/**\n * Safely check if window is closed with cross-origin handling\n */\nconst isWindowClosed = (window: Window | null): boolean => {\n if (!window) return true;\n \n try {\n return window.closed;\n } catch (error) {\n // Cross-origin error means we can't access the property\n // This typically happens when redirected to external auth providers\n Logger.debug(\"Cannot access window.closed due to cross-origin restrictions - assuming window is still open\", error as any);\n return false;\n }\n};\n\n/**\n * Safely add message event listener with error handling\n */\nconst addMessageListener = (listener: MessageListener): (() => void) => {\n if (!NativeFunctions.addEventListener) {\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Message listener not available in current environment\"\n );\n }\n\n const wrappedListener = (event: Event) => {\n try {\n listener(event as MessageEvent);\n } catch (error) {\n Logger.error(\"Error in message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n };\n\n NativeFunctions.addEventListener.call(window, \"message\", wrappedListener);\n \n return () => {\n if (NativeFunctions.removeEventListener) {\n NativeFunctions.removeEventListener.call(window, \"message\", wrappedListener);\n }\n };\n};\n\n/**\n * Validate configuration and return parsed URL\n */\nexport function validateConfig(config: CAMSConfig): URL {\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n return new URL(config.camsUrl);\n}\n\n/**\n * Open CAMS authentication popup and handle the authentication flow\n */\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n // Environment validation\n if (typeof window === \"undefined\") {\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open popup in server-side environment\"\n )\n );\n return;\n }\n\n if (isPopupWindow()) {\n Logger.warn(\"Attempted to open popup from within popup window\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open authentication popup from within popup window\"\n )\n );\n return;\n }\n\n // Initialize logging\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n // Validate configuration\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Configuration validation passed\");\n } catch (error) {\n Logger.error(\"Configuration validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n reject(error as Error);\n return;\n }\n\n // Extract configuration with defaults\n const {\n messageOrigin,\n windowHeight = 600,\n windowWidth = 500,\n authTimeout = DEFAULT_AUTH_TIMEOUT,\n idleTimeout = DEFAULT_IDLE_TIMEOUT,\n allowedRedirectDomains = DEFAULT_MICROSOFT_DOMAINS,\n } = config;\n\n // State management\n let authWindow: Window | null = null;\n let authTimeoutId: TimeoutHandle | null = null;\n let idleTimeoutId: TimeoutHandle | null = null;\n let checkClosedInterval: TimeoutHandle | null = null;\n let removeMessageListener: (() => void) | null = null;\n let hasReceivedValidMessage = false;\n\n /**\n * Clean up all resources and timeouts\n */\n const cleanup = (): void => {\n if (removeMessageListener) {\n removeMessageListener();\n removeMessageListener = null;\n }\n\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n if (authTimeoutId) NativeFunctions.clearTimeout(authTimeoutId);\n if (checkClosedInterval) NativeFunctions.clearTimeout(checkClosedInterval);\n\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n /**\n * Clean up and close the popup window, then reject with error\n */\n const cleanupAndClose = (error?: CAMSError): void => {\n cleanup();\n safeWindowClose(authWindow);\n \n if (error) {\n reject(error);\n }\n };\n\n /**\n * Reset idle timeout on user activity\n */\n const resetIdleTimeout = (): void => {\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n \n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n /**\n * Set up popup window closure detection with cross-origin handling\n */\n const setupClosureDetection = (): void => {\n let pollInterval = INITIAL_POLL_INTERVAL;\n\n const checkClosed = (): void => {\n // Skip closure detection when on Microsoft domains\n if (authWindow) {\n try {\n const currentUrl = authWindow.location.href;\n const isMicrosoftDomain = allowedRedirectDomains.some(domain => \n currentUrl.includes(domain)\n );\n \n if (isMicrosoftDomain) {\n Logger.debug(\"Skipping closure check - on Microsoft domain\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n } catch (error) {\n // Cross-origin error - assume we're on Microsoft domain and skip check\n Logger.debug(\"Cross-origin error - skipping closure check\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n }\n\n const isClosed = isWindowClosed(authWindow);\n \n if (isClosed && !hasReceivedValidMessage) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n /**\n * Handle incoming message events from the popup\n */\n const handleMessage = (event: MessageEvent): void => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n // Security: Validate origin\n if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Security: Validate message source\n if (event.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: event.source,\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Mark that we've received a valid message (prevents false closure detection)\n hasReceivedValidMessage = true;\n\n // Handle heartbeat messages (reset idle timeout)\n if (event.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // Process authentication messages\n processAuthenticationMessage(event.data);\n };\n\n /**\n * Process and validate authentication message payloads\n */\n const processAuthenticationMessage = (data: unknown): void => {\n // Success case: Valid profile received\n const profileValidation = ProfileSchema.safeParse(data);\n if (profileValidation.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(profileValidation.data);\n return;\n }\n\n // Authentication failure case\n const authFailureValidation = AuthFailureMessageSchema.safeParse(data);\n if (authFailureValidation.success) {\n const { error, errorCode, errorDetails } = authFailureValidation.data;\n Logger.warn(\"Authentication failure received\", {\n error,\n errorCode,\n errorDetails,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`\n )\n );\n return;\n }\n\n // Generic error case\n const errorValidation = ErrorMessageSchema.safeParse(data);\n if (errorValidation.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorValidation.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n `Authentication failed: ${errorValidation.data.error}`\n )\n );\n return;\n }\n\n // Invalid message format\n Logger.error(\"Invalid message format received\", {\n messageData: data,\n dataType: typeof data,\n profileValidationError: profileValidation.error?.issues,\n authFailureValidationError: authFailureValidation.error?.issues,\n errorValidationError: errorValidation.error?.issues,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n // Main authentication flow execution\n try {\n // Open popup window\n const { left, top } = getPopupPosition(windowWidth, windowHeight);\n const secureWindowName = generateSecureWindowName();\n \n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n left,\n top,\n });\n\n authWindow = window.open(\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`\n );\n\n // Check for popup blocking\n if (!authWindow) {\n Logger.error(\"Popup window blocked or failed to open\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Check for immediate closure (aggressive popup blockers)\n if (isWindowClosed(authWindow)) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n // Set up message listener\n removeMessageListener = addMessageListener(handleMessage);\n Logger.debug(\"Message listener attached\");\n\n // Set up timeouts\n Logger.debug(\"Setting authentication timeout\", { authTimeout });\n authTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n setupClosureDetection();\n\n // Focus popup for better UX\n try {\n authWindow.focus();\n } catch (error) {\n Logger.debug(\"Could not focus popup window (cross-origin restriction)\");\n }\n\n } catch (error) {\n Logger.error(\"Failed to initialize authentication popup\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to initialize authentication: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n }\n });\n}","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin, isPopupWindow } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n \n // If we're in a popup, don't attempt to open another popup\n if (isPopupWindow()) {\n Logger.warn(\"Cannot initiate login from popup window\");\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot initiate authentication from within popup window\"\n );\n }\n \n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n\n /**\n * Complete authentication in popup window\n * This should be called by popup apps when authentication is successful\n */\n completePopupAuth(profile: Profile, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"completePopupAuth called outside of popup window\");\n return;\n }\n\n try {\n // Store the authentication data locally in the popup\n this.profile = profile;\n this.setToken(profile.userProfile.tokens.Bearer);\n \n Logger.info(\"Authentication completed in popup, forwarding to parent\");\n } catch (error) {\n Logger.error(\"Failed to complete popup authentication\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n }\n\n /**\n * Report authentication error in popup window\n */\n errorPopupAuth(error: any, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"errorPopupAuth called outside of popup window\");\n return;\n }\n\n Logger.warn(\"Reporting authentication error from popup\");\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// 🔹 Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n","import { CAMSError, CAMSErrorType } from \"./types\";\nimport { Logger } from \"./logger\";\n\nexport interface MFAConfig {\n accessToken: string;\n idToken: string;\n appCode: string;\n provider: string;\n apiEndpoint?: string;\n}\n\nexport interface MFAResponse {\n name: string;\n email: string;\n isAuthenticated: boolean;\n message: string;\n mfaIsEnabled: boolean;\n userType: string;\n tokens: {\n Bearer: string;\n Nonce: string;\n };\n}\n\nexport interface MFAAuthenticator {\n sendEmailOTP(): Promise<boolean>;\n verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse>;\n getRemainingAttempts(): number;\n resetAttempts(): void;\n}\n\nexport class CAMSMFAAuthenticator implements MFAAuthenticator {\n private config: MFAConfig;\n private attemptCount = 0;\n private readonly maxAttempts = 3;\n\n constructor(config: MFAConfig) {\n this.config = config;\n }\n\n async sendEmailOTP(): Promise<boolean> {\n try {\n Logger.debug(\"Sending Email OTP\");\n // Implementation would call your API to send email OTP\n // For now, return true as placeholder\n return true;\n } catch (error) {\n Logger.error(\"Failed to send Email OTP\", { error });\n return false;\n }\n }\n\n async verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse> {\n if (this.attemptCount >= this.maxAttempts) {\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Maximum MFA attempts exceeded\"\n );\n }\n\n this.attemptCount++;\n\n try {\n Logger.debug(\"Verifying MFA code\", { type, attempt: this.attemptCount });\n\n const response = await fetch(this.config.apiEndpoint || '/api/auth/verify-mfa', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.accessToken}`,\n },\n body: JSON.stringify({\n provider: this.config.provider,\n accessToken: this.config.accessToken,\n idToken: this.config.idToken,\n authenticationType: type,\n MFACode: code,\n appCode: this.config.appCode,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data: MFAResponse = await response.json();\n console.log(\"MFA Response >>>\", data)\n \n if (data.isAuthenticated) {\n Logger.info(\"MFA verification successful\");\n this.resetAttempts();\n return data;\n } else {\n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n data.message || \"MFA verification failed\"\n );\n }\n } catch (error) {\n Logger.error(\"MFA verification failed\", { error, attempt: this.attemptCount });\n \n if (error instanceof CAMSError) {\n throw error;\n }\n \n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `MFA verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n getRemainingAttempts(): number {\n return Math.max(0, this.maxAttempts - this.attemptCount);\n }\n\n resetAttempts(): void {\n this.attemptCount = 0;\n }\n}"],"names":["CAMSErrorType","z","LogLevel"],"mappings":";;;;;;AAaYA;IAAZ,CAAA,UAAY,aAAa,EAAA;IACvB,IAAA,aAAA,CAAA,eAAA,CAAA,GAAA,eAA+B;IAC/B,IAAA,aAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;IACnB,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,gBAAA,CAAA,GAAA,gBAAiC;IACjC,IAAA,aAAA,CAAA,aAAA,CAAA,GAAA,aAA2B;IAC3B,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,sBAA6C;IAC7C,IAAA,aAAA,CAAA,sBAAA,CAAA,GAAA,kBAAyC;IAC3C,CAAC,EARWA,qBAAa,KAAbA,qBAAa,GAAA,EAAA,CAAA,CAAA;IAUnB,MAAO,SAAU,SAAQ,KAAK,CAAA;IACf,IAAA,IAAA;QAAnB,WAAA,CAAmB,IAAmB,EAAE,OAAe,EAAA;YACrD,KAAK,CAAC,OAAO,CAAC;YADG,IAAA,CAAA,IAAI,GAAJ,IAAI;YAErB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,IAAI;QACnC;IACD;;IC1BD;AACO,UAAM,aAAa,GAAGC,KAAC,CAAC,MAAM,CAAC;IACpC,IAAA,IAAI,EAAEA,KAAC,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC,EAAE,CAACA,KAAC,CAAC,OAAO,CAAC,cAAc,CAAC,CAAC;IAC7D,IAAA,WAAW,EAAEA,KAAC,CAAC,MAAM,CAAC;IACpB,QAAA,IAAI,EAAEA,KAAC,CAAC,MAAM,EAAE;IAChB,QAAA,KAAK,EAA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,YAAY,CAAC;QAC1D;QAEA,aAAa,GAAA;IACX,QAAA,IAAI,CAAC,YAAY,GAAG,CAAC;QACvB;IACD;;;;;;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"index.umd.js","sources":["../src/types.ts","../src/validators.ts","../src/logger.ts","../src/auth.ts","../src/sessionManager.ts","../src/MFAAuth.ts"],"sourcesContent":["export interface CAMSConfig {\n camsUrl: string;\n messageOrigin: string; // Expected message origin\n allowedRedirectDomains?: string[];\n windowWidth: number;\n windowHeight: number;\n authTimeout?: number; // Auth timeout in ms (default: 300000) // 5 minutes as a final failsafe\n idleTimeout?: number; // 1 minute of inactivity\n storageKey?: string; // Custom storage key\n retryAttempts?: number; // Auto-retry on failure (default: 0)\n debug?: boolean; // Enable debug logging (default: false)\n}\n\nexport enum CAMSErrorType {\n POPUP_BLOCKED = \"POPUP_BLOCKED\",\n TIMEOUT = \"TIMEOUT\",\n INVALID_ORIGIN = \"INVALID_ORIGIN\",\n USER_CANCELLED = \"USER_CANCELLED\",\n INVALID_URL = \"INVALID_URL\",\n MAX_RETRIES_EXCEEDED = \"MAX_RETRIES_EXCEEDED\",\n API_VALIDATION_ERROR = \"VALIDATION_ERROR\",\n}\n\nexport class CAMSError extends Error {\n constructor(public type: CAMSErrorType, message: string) {\n super(message);\n this.name = this.constructor.name;\n }\n}","import { z } from \"zod\";\n\n// Validate the returned token - non-empty string\nexport const ProfileSchema = z.object({\n type: z.literal(\"AUTH_SUCCESS\").or(z.literal(\"AUTH_FAILURE\")),\n userProfile: z.object({\n name: z.string(),\n email: z.email(),\n mfaIsEnabled: z.boolean(),\n message: z.string(),\n isAuthenticated: z.boolean(),\n userType: z.enum([\"SUPER_ADMIN\", \"ADMIN\", \"USER\"]),\n roles: z.array(z.string()).optional(),\n tokens: z.object({\n Nonce: z.string(),\n Bearer: z.string(),\n }),\n }),\n});\n\nexport type Profile = z.infer<typeof ProfileSchema>;\n\nexport const ErrorMessageSchema = z.object({\n error: z.string().min(1, \"Error message cannot be empty\"),\n});\n\nexport const AuthFailureMessageSchema = z.object({\n type: z.literal(\"AUTH_FAILURE\"),\n error: z.string().min(1, \"Error message cannot be empty\"),\n errorCode: z.string(),\n errorDetails: z.object().or(z.any()),\n});\n\nexport type AuthFailureMessage = z.infer<typeof AuthFailureMessageSchema>;\n\nexport const URLSchema = z.url();\n","export enum LogLevel {\n ERROR = 0,\n WARN = 1,\n INFO = 2,\n DEBUG = 3\n}\n\nexport interface LogContext {\n [key: string]: any;\n}\n\nexport class Logger {\n private static level: LogLevel = LogLevel.DEBUG;\n private static readonly prefix = '[CAMS-SDK]';\n private static readonly isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';\n\n static setLevel(level: LogLevel): void {\n Logger.level = level;\n }\n\n static error(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {\n console.error(`${Logger.prefix} ERROR:`, message, context || '');\n }\n }\n\n static warn(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {\n console.warn(`${Logger.prefix} WARN:`, message, context || '');\n }\n }\n\n static info(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {\n console.info(`${Logger.prefix} INFO:`, message, context || '');\n }\n }\n\n static debug(message: string, context?: LogContext): void {\n if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {\n console.debug(`${Logger.prefix} DEBUG:`, message, context || '');\n }\n }\n}","import { CAMSConfig, CAMSError, CAMSErrorType } from \"./types\";\nimport {\n ProfileSchema,\n ErrorMessageSchema,\n AuthFailureMessageSchema,\n URLSchema,\n Profile,\n} from \"./validators\";\nimport { Logger, LogLevel } from \"./logger\";\n\n// Constants\nconst DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes\nconst DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes\nconst INITIAL_POLL_INTERVAL = 1000;\nconst MAX_POLL_INTERVAL = 5000;\nconst WINDOW_FEATURES = \"scrollbars=yes,resizable=yes\";\n\n// Default allowed Microsoft domains for Azure AD redirects\nconst DEFAULT_MICROSOFT_DOMAINS = [\n \".microsoft.com\",\n \".microsoftonline.com\", \n \".live.com\",\n \"login.microsoftonline.com\"\n];\n\n// Secure reference to native functions with proper binding\nconst NativeFunctions = {\n addEventListener: typeof window !== \"undefined\" ? window.addEventListener.bind(window) : null,\n removeEventListener: typeof window !== \"undefined\" ? window.removeEventListener.bind(window) : null,\n setTimeout: typeof window !== \"undefined\" ? window.setTimeout.bind(window) : setTimeout,\n clearTimeout: typeof window !== \"undefined\" ? window.clearTimeout.bind(window) : clearTimeout,\n};\n\n// Types\ntype TimeoutHandle = ReturnType<typeof setTimeout>;\ntype MessageListener = (event: MessageEvent) => void;\n\n/**\n * Generate a secure random window name to prevent targeting\n */\nexport const generateSecureWindowName = (): string =>\n `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;\n\n/**\n * Detect if current window is a popup to prevent recursive popups\n */\nexport const isPopupWindow = (): boolean => {\n if (typeof window === \"undefined\") return false;\n \n // Skip popup detection in test environments\n if (typeof process !== \"undefined\" && process.env && process.env.NODE_ENV === \"test\") {\n return false;\n }\n \n try {\n return window.opener !== null && window.opener !== window;\n } catch {\n return false;\n }\n};\n\n/**\n * Safely close a window with error handling for cross-origin restrictions\n */\nconst safeWindowClose = (window: Window | null): void => {\n if (!window) return;\n \n try {\n if (!window.closed) {\n window.close();\n }\n } catch (error) {\n Logger.debug(\"Error closing window (cross-origin restriction)\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n};\n\n/**\n * Center popup window on screen\n */\nconst getPopupPosition = (width: number, height: number): { left: number; top: number } => {\n if (typeof window === \"undefined\") return { left: 0, top: 0 };\n \n const left = Math.max(0, (window.screen.width - width) / 2);\n const top = Math.max(0, (window.screen.height - height) / 2);\n \n return { left, top };\n};\n\n/**\n * Validate origin against expected domain with support for subdomains and Microsoft redirects\n */\nconst isValidOrigin = (\n eventOrigin: string, \n expectedOrigin: string,\n microsoftDomains: string[] = DEFAULT_MICROSOFT_DOMAINS\n): boolean => {\n try {\n const originUrl = new URL(eventOrigin);\n const expectedHostname = expectedOrigin.startsWith(\"http\")\n ? new URL(expectedOrigin).hostname\n : expectedOrigin;\n\n // Check Microsoft domains for Azure AD redirects\n const isMicrosoftDomain = microsoftDomains.some(domain => \n originUrl.hostname === domain || originUrl.hostname.endsWith(domain)\n );\n\n // Allow exact match, subdomains, or Microsoft domains\n return (\n originUrl.hostname === expectedHostname ||\n originUrl.hostname.endsWith(\".\" + expectedHostname) ||\n isMicrosoftDomain\n );\n } catch {\n return false;\n }\n};\n\n/**\n * Safely check if window is closed with cross-origin handling\n */\nconst isWindowClosed = (window: Window | null): boolean => {\n if (!window) return true;\n \n try {\n return window.closed;\n } catch (error) {\n // Cross-origin error means we can't access the property\n // This typically happens when redirected to external auth providers\n Logger.debug(\"Cannot access window.closed due to cross-origin restrictions - assuming window is still open\", error as any);\n return false;\n }\n};\n\n/**\n * Safely add message event listener with error handling\n */\nconst addMessageListener = (listener: MessageListener): (() => void) => {\n if (!NativeFunctions.addEventListener) {\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Message listener not available in current environment\"\n );\n }\n\n const wrappedListener = (event: Event) => {\n try {\n listener(event as MessageEvent);\n } catch (error) {\n Logger.error(\"Error in message listener\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n };\n\n NativeFunctions.addEventListener(\"message\", wrappedListener);\n \n return () => {\n if (NativeFunctions.removeEventListener) {\n NativeFunctions.removeEventListener(\"message\", wrappedListener);\n }\n };\n};\n\n/**\n * Validate configuration and return parsed URL\n */\nexport function validateConfig(config: CAMSConfig): URL {\n const urlValidation = URLSchema.safeParse(config.camsUrl);\n if (!urlValidation.success) {\n throw new CAMSError(CAMSErrorType.INVALID_URL, \"Invalid CAMS URL format\");\n }\n\n if (!config.messageOrigin) {\n throw new CAMSError(\n CAMSErrorType.INVALID_URL,\n \"Message Origin must be specified for security\"\n );\n }\n\n return new URL(config.camsUrl);\n}\n\n/**\n * Open CAMS authentication popup and handle the authentication flow\n */\nexport function openCAMSPopUpLogin(config: CAMSConfig): Promise<Profile> {\n return new Promise((resolve, reject) => {\n // Environment validation\n if (typeof window === \"undefined\") {\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open popup in server-side environment\"\n )\n );\n return;\n }\n\n if (isPopupWindow()) {\n Logger.warn(\"Attempted to open popup from within popup window\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot open authentication popup from within popup window\"\n )\n );\n return;\n }\n\n // Initialize logging\n if (config.debug) Logger.setLevel(LogLevel.DEBUG);\n Logger.info(\"Starting CAMS authentication\", { url: config.camsUrl });\n\n // Validate configuration\n let validatedUrl: URL;\n try {\n validatedUrl = validateConfig(config);\n Logger.debug(\"Configuration validation passed\");\n } catch (error) {\n Logger.error(\"Configuration validation failed\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n reject(error as Error);\n return;\n }\n\n // Extract configuration with defaults\n const {\n messageOrigin,\n windowHeight = 600,\n windowWidth = 500,\n authTimeout = DEFAULT_AUTH_TIMEOUT,\n idleTimeout = DEFAULT_IDLE_TIMEOUT,\n allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin],\n } = config;\n\n // State management\n let authWindow: Window | null = null;\n let authTimeoutId: TimeoutHandle | null = null;\n let idleTimeoutId: TimeoutHandle | null = null;\n let checkClosedInterval: TimeoutHandle | null = null;\n let removeMessageListener: (() => void) | null = null;\n let hasReceivedValidMessage = false;\n\n /**\n * Clean up all resources and timeouts\n */\n const cleanup = (): void => {\n if (removeMessageListener) {\n removeMessageListener();\n removeMessageListener = null;\n }\n\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n if (authTimeoutId) NativeFunctions.clearTimeout(authTimeoutId);\n if (checkClosedInterval) NativeFunctions.clearTimeout(checkClosedInterval);\n\n idleTimeoutId = null;\n authTimeoutId = null;\n checkClosedInterval = null;\n };\n\n /**\n * Clean up and close the popup window, then reject with error\n */\n const cleanupAndClose = (error?: CAMSError): void => {\n cleanup();\n safeWindowClose(authWindow);\n \n if (error) {\n reject(error);\n }\n };\n\n /**\n * Reset idle timeout on user activity\n */\n const resetIdleTimeout = (): void => {\n if (idleTimeoutId) NativeFunctions.clearTimeout(idleTimeoutId);\n \n Logger.debug(\"Resetting idle timeout\", { idleTimeout });\n idleTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication idle timeout reached\", { idleTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication timed out due to inactivity after ${idleTimeout}ms`\n )\n );\n }, idleTimeout);\n };\n\n /**\n * Set up popup window closure detection with cross-origin handling\n */\n const setupClosureDetection = (): void => {\n let pollInterval = INITIAL_POLL_INTERVAL;\n\n const checkClosed = (): void => {\n // Skip closure detection when on Microsoft domains\n if (authWindow) {\n try {\n const currentUrl = authWindow.location.href;\n const isMicrosoftDomain = allowedRedirectDomains.some(domain => \n currentUrl.includes(domain)\n );\n \n if (isMicrosoftDomain) {\n Logger.debug(\"Skipping closure check - on Microsoft domain\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n } catch (error) {\n // Cross-origin error - assume we're on Microsoft domain and skip check\n Logger.debug(\"Cross-origin error - skipping closure check\");\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n return;\n }\n }\n\n const isClosed = isWindowClosed(authWindow);\n \n if (isClosed && !hasReceivedValidMessage) {\n Logger.info(\"Authentication window closed by user\");\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n \"Authentication window was closed\"\n )\n );\n return;\n }\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);\n };\n\n /**\n * Handle incoming message events from the popup\n */\n const handleMessage = (event: MessageEvent): void => {\n Logger.debug(\"Received message\", {\n origin: event.origin,\n expectedOrigin: messageOrigin,\n data: event.data,\n });\n\n // Security: Validate origin\n if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {\n Logger.warn(\"Blocked message from unauthorized origin\", {\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Security: Validate message source\n if (event.source !== authWindow) {\n Logger.warn(\"Message from unexpected source\", {\n source: event.source,\n origin: event.origin,\n expected: messageOrigin,\n data: event.data,\n });\n return;\n }\n\n // Mark that we've received a valid message (prevents false closure detection)\n hasReceivedValidMessage = true;\n\n // Handle heartbeat messages (reset idle timeout)\n if (event.data?.type === \"heartbeat\") {\n Logger.debug(\"Received heartbeat message\");\n resetIdleTimeout();\n return;\n }\n\n // Process authentication messages\n processAuthenticationMessage(event.data);\n };\n\n /**\n * Process and validate authentication message payloads\n */\n const processAuthenticationMessage = (data: unknown): void => {\n // Success case: Valid profile received\n const profileValidation = ProfileSchema.safeParse(data);\n if (profileValidation.success) {\n Logger.info(\"Authentication successful\");\n cleanupAndClose();\n resolve(profileValidation.data);\n return;\n }\n\n // Authentication failure case\n const authFailureValidation = AuthFailureMessageSchema.safeParse(data);\n if (authFailureValidation.success) {\n const { error, errorCode, errorDetails } = authFailureValidation.data;\n Logger.warn(\"Authentication failure received\", {\n error,\n errorCode,\n errorDetails,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`\n )\n );\n return;\n }\n\n // Generic error case\n const errorValidation = ErrorMessageSchema.safeParse(data);\n if (errorValidation.success) {\n Logger.warn(\"Authentication error received\", {\n error: errorValidation.data.error,\n });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.USER_CANCELLED,\n `Authentication failed: ${errorValidation.data.error}`\n )\n );\n return;\n }\n\n // Invalid message format\n Logger.error(\"Invalid message format received\", {\n messageData: data,\n dataType: typeof data,\n profileValidationError: profileValidation.error?.issues,\n authFailureValidationError: authFailureValidation.error?.issues,\n errorValidationError: errorValidation.error?.issues,\n });\n cleanupAndClose(\n new CAMSError(CAMSErrorType.INVALID_ORIGIN, \"Invalid message format\")\n );\n };\n\n // Main authentication flow execution\n try {\n // Open popup window\n const { left, top } = getPopupPosition(windowWidth, windowHeight);\n const secureWindowName = generateSecureWindowName();\n \n Logger.debug(\"Opening popup window\", {\n width: windowWidth,\n height: windowHeight,\n left,\n top,\n });\n\n authWindow = window.open(\n validatedUrl.toString(),\n secureWindowName,\n `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`\n );\n\n // Check for popup blocking\n if (!authWindow) {\n Logger.error(\"Popup window blocked or failed to open\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n // Check for immediate closure (aggressive popup blockers)\n if (isWindowClosed(authWindow)) {\n Logger.error(\"Popup immediately closed by blocker\");\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Popup blocked by browser. Please allow popups and try again.\"\n )\n );\n return;\n }\n\n Logger.debug(\"Popup window opened successfully\");\n\n // Set up message listener\n removeMessageListener = addMessageListener(handleMessage);\n Logger.debug(\"Message listener attached\");\n\n // Set up timeouts\n Logger.debug(\"Setting authentication timeout\", { authTimeout });\n authTimeoutId = NativeFunctions.setTimeout(() => {\n Logger.warn(\"Authentication timeout reached\", { authTimeout });\n cleanupAndClose(\n new CAMSError(\n CAMSErrorType.TIMEOUT,\n `Authentication process exceeded time limit of ${authTimeout}ms`\n )\n );\n }, authTimeout);\n\n resetIdleTimeout();\n setupClosureDetection();\n\n // Focus popup for better UX\n try {\n authWindow.focus();\n } catch (error) {\n Logger.debug(\"Could not focus popup window (cross-origin restriction)\");\n }\n\n } catch (error) {\n Logger.error(\"Failed to initialize authentication popup\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n cleanup();\n reject(\n new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Failed to initialize authentication: \" +\n (error instanceof Error ? error.message : \"Unknown error\")\n )\n );\n }\n });\n}","import {\n CAMSConfig,\n CAMSError,\n CAMSErrorType,\n} from \"./types\";\nimport { openCAMSPopUpLogin, isPopupWindow } from \"./auth\";\nimport { AuthFailureMessage, Profile } from \"./validators\";\nimport { Logger } from \"./logger\";\n\nexport interface CAMSEvents {\n onAuthStart?: () => void;\n onAuthSuccess?: (profile: Profile) => void;\n onAuthError?: (error: CAMSError) => void;\n onTokenExpired?: () => void;\n}\n\nexport class CAMSSessionManager {\n private readonly storage: StorageLike;\n private readonly keyPrefix: string;\n private readonly events: CAMSEvents;\n\n private token: string | null = null;\n private profile: Profile | null = null;\n\n constructor(\n storage: StorageLike | null = null,\n keyPrefix?: string,\n events: CAMSEvents = {}\n ) {\n this.storage = storage || getDefaultStorage();\n this.keyPrefix = keyPrefix ?? \"CAMS-SDK\";\n this.events = events;\n }\n\n setItem(key: string, value: string) {\n this.storage.setItem(`${this.keyPrefix}:${key}`, value);\n }\n\n getItem(key: string) {\n return this.storage.getItem(`${this.keyPrefix}:${key}`);\n }\n\n removeItem(key: string) {\n this.storage.removeItem(`${this.keyPrefix}:${key}`);\n }\n\n clear() {\n // clear only CAMS-prefixed items\n Object.keys(this.storage).forEach((k) => {\n if (k.startsWith(this.keyPrefix)) {\n this.storage.removeItem(k);\n }\n });\n }\n\n async login(config: CAMSConfig): Promise<Profile> {\n try {\n Logger.info(\"Session login started\");\n \n // If we're in a popup, don't attempt to open another popup\n if (isPopupWindow()) {\n Logger.warn(\"Cannot initiate login from popup window\");\n throw new CAMSError(\n CAMSErrorType.POPUP_BLOCKED,\n \"Cannot initiate authentication from within popup window\"\n );\n }\n \n if (this.events.onAuthStart) this.events.onAuthStart();\n\n let attempts = 0;\n const maxAttempts = (config.retryAttempts ?? 0) + 1;\n Logger.debug(\"Login retry configuration\", { maxAttempts });\n\n while (attempts < maxAttempts) {\n try {\n attempts++;\n Logger.debug(\"Login attempt\", { attempt: attempts, maxAttempts });\n\n // Add exponential backoff delay for retries\n if (attempts > 1) {\n const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay\n Logger.debug(\"Retry delay\", { delay });\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n const response = await openCAMSPopUpLogin(config);\n\n Logger.debug(\"Login Response\", response);\n this.profile = response;\n this.setToken(response.userProfile.tokens.Bearer);\n Logger.info(\"Session login successful\");\n if (this.events.onAuthSuccess) this.events.onAuthSuccess(response);\n return response;\n } catch (error) {\n Logger.warn(\"Login attempt failed\", {\n attempt: attempts,\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n if (attempts >= maxAttempts || !(error instanceof CAMSError)) {\n throw error;\n }\n // Only retry on specific error types\n if (\n ![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(\n error.type\n )\n ) {\n throw error;\n }\n Logger.info(\"Retrying login\", { nextAttempt: attempts + 1 });\n }\n }\n\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Max retry attempts exceeded\"\n );\n } catch (error) {\n const errorMessage =\n error instanceof Error ? error.message : \"Unknown error\";\n const camsError =\n error instanceof CAMSError\n ? error\n : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);\n Logger.error(\"Session login failed\", {\n error: camsError.message,\n type: camsError.type,\n });\n if (this.events.onAuthError) this.events.onAuthError(camsError);\n throw camsError;\n }\n }\n\n async logout(): Promise<void> {\n Logger.info(\"Session logout\");\n this.clearToken();\n }\n\n setToken(token: string) {\n this.token = token;\n this.storage.setItem(this.keyPrefix, token);\n Logger.debug(\"Token stored\", { storageKey: this.keyPrefix });\n }\n\n getAccessToken(): string | null {\n // Return cached token if available, avoiding redundant storage access\n if (this.token) return this.token;\n\n const raw = this.storage.getItem(this.keyPrefix);\n if (!raw) return null;\n\n this.token = raw;\n Logger.debug(\"Token loaded from storage\");\n return this.token;\n }\n\n clearToken() {\n this.token = null;\n this.storage.removeItem(this.keyPrefix);\n Logger.debug(\"Token cleared\");\n }\n\n private isExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const payload = JSON.parse(atob(parts[1]));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n isPaddedExpired(): boolean {\n const token = this.getAccessToken();\n if (!token) return true;\n\n try {\n const parts = token.split(\".\");\n if (parts.length < 3) return true; // Invalid JWT format\n const base64 = parts[1].replace(/-/g, \"+\").replace(/_/g, \"/\");\n const padded = base64.padEnd(\n base64.length + ((4 - (base64.length % 4)) % 4),\n \"=\"\n );\n const payload = JSON.parse(atob(padded));\n if (typeof payload.exp !== \"number\") return true;\n const exp = payload.exp * 1000;\n return Date.now() > exp;\n } catch (error) {\n Logger.warn(\"Failed to parse JWT token\", {\n error: error instanceof Error ? error.message : \"Unknown error\",\n });\n return true;\n }\n }\n\n private checkTokenExpiration(): boolean {\n if (this.isExpired()) {\n Logger.info(\"Token expired\");\n if (this.events.onTokenExpired) this.events.onTokenExpired();\n return true;\n }\n return false;\n }\n\n isAuthenticated(): boolean {\n const token = this.getAccessToken();\n if (!token) {\n Logger.debug(\"No token found\");\n return false;\n }\n\n if (this.checkTokenExpiration()) {\n return false;\n }\n\n Logger.debug(\"Token is valid\");\n return true;\n }\n\n async getProfile(): Promise<Profile | null> {\n const storedToken = this.getAccessToken();\n if (!storedToken) return null;\n\n // Check token expiration before processing\n if (this.checkTokenExpiration()) {\n return null;\n }\n\n return this.profile;\n }\n\n getSessionError(): AuthFailureMessage | null {\n return null;\n }\n\n /**\n * Complete authentication in popup window\n * This should be called by popup apps when authentication is successful\n */\n completePopupAuth(profile: Profile, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"completePopupAuth called outside of popup window\");\n return;\n }\n\n try {\n // Store the authentication data locally in the popup\n this.profile = profile;\n this.setToken(profile.userProfile.tokens.Bearer);\n \n Logger.info(\"Authentication completed in popup, forwarding to parent\");\n } catch (error) {\n Logger.error(\"Failed to complete popup authentication\", {\n error: error instanceof Error ? error.message : \"Unknown error\"\n });\n }\n }\n\n /**\n * Report authentication error in popup window\n */\n errorPopupAuth(error: any, targetOrigin?: string): void {\n if (!isPopupWindow()) {\n Logger.warn(\"errorPopupAuth called outside of popup window\");\n return;\n }\n\n Logger.warn(\"Reporting authentication error from popup\");\n }\n}\n\ninterface StorageLike {\n getItem(key: string): string | null;\n setItem(key: string, value: string): void;\n removeItem(key: string): void;\n [key: string]: any; // allows Object.keys to work\n}\n\n// 🔹 Safe fallback for Node/SSR\nfunction getDefaultStorage(): StorageLike {\n if (typeof window !== \"undefined\" && window.localStorage) {\n return window.localStorage;\n }\n\n const memoryStore: Record<string, string> = {};\n return {\n getItem: (key) => (key in memoryStore ? memoryStore[key] : null),\n setItem: (key, value) => {\n memoryStore[key] = value;\n },\n removeItem: (key) => {\n delete memoryStore[key];\n },\n key: (i: number) => Object.keys(memoryStore)[i] ?? null,\n get length() {\n return Object.keys(memoryStore).length;\n },\n };\n}\n","import { CAMSError, CAMSErrorType } from \"./types\";\nimport { Logger } from \"./logger\";\n\nexport interface MFAConfig {\n accessToken: string;\n idToken: string;\n appCode: string;\n provider: string;\n apiEndpoint?: string;\n}\n\nexport interface MFAResponse {\n name: string;\n email: string;\n isAuthenticated: boolean;\n message: string;\n mfaIsEnabled: boolean;\n userType: string;\n tokens: {\n Bearer: string;\n Nonce: string;\n };\n}\n\nexport interface MFAAuthenticator {\n sendEmailOTP(): Promise<boolean>;\n verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse>;\n getRemainingAttempts(): number;\n resetAttempts(): void;\n}\n\nexport class CAMSMFAAuthenticator implements MFAAuthenticator {\n private config: MFAConfig;\n private attemptCount = 0;\n private readonly maxAttempts = 3;\n\n constructor(config: MFAConfig) {\n this.config = config;\n }\n\n async sendEmailOTP(): Promise<boolean> {\n try {\n Logger.debug(\"Sending Email OTP\");\n // Implementation would call your API to send email OTP\n // For now, return true as placeholder\n return true;\n } catch (error) {\n Logger.error(\"Failed to send Email OTP\", { error });\n return false;\n }\n }\n\n async verifyOTP(code: string, type: 'EmailOTP' | 'AuthenticatorCode'): Promise<MFAResponse> {\n if (this.attemptCount >= this.maxAttempts) {\n throw new CAMSError(\n CAMSErrorType.MAX_RETRIES_EXCEEDED,\n \"Maximum MFA attempts exceeded\"\n );\n }\n\n this.attemptCount++;\n\n try {\n Logger.debug(\"Verifying MFA code\", { type, attempt: this.attemptCount });\n\n const response = await fetch(this.config.apiEndpoint || '/api/auth/verify-mfa', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.accessToken}`,\n },\n body: JSON.stringify({\n provider: this.config.provider,\n accessToken: this.config.accessToken,\n idToken: this.config.idToken,\n authenticationType: type,\n MFACode: code,\n appCode: this.config.appCode,\n }),\n });\n\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${response.statusText}`);\n }\n\n const data: MFAResponse = await response.json();\n console.log(\"MFA Response >>>\", data)\n \n if (data.isAuthenticated) {\n Logger.info(\"MFA verification successful\");\n this.resetAttempts();\n return data;\n } else {\n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n data.message || \"MFA verification failed\"\n );\n }\n } catch (error) {\n Logger.error(\"MFA verification failed\", { error, attempt: this.attemptCount });\n \n if (error instanceof CAMSError) {\n throw error;\n }\n \n throw new CAMSError(\n CAMSErrorType.API_VALIDATION_ERROR,\n `MFA verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`\n );\n }\n }\n\n getRemainingAttempts(): number {\n return Math.max(0, this.maxAttemp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