@nibssplc/cams-sdk 0.0.1-beta.36 → 0.0.1-beta.38

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.esm.js CHANGED
@@ -54,7 +54,7 @@ var LogLevel;
54
54
  LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
55
55
  })(LogLevel || (LogLevel = {}));
56
56
  class Logger {
57
- static level = LogLevel.WARN;
57
+ static level = LogLevel.DEBUG;
58
58
  static prefix = '[CAMS-SDK]';
59
59
  static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
60
60
  static setLevel(level) {
@@ -83,16 +83,31 @@ class Logger {
83
83
  }
84
84
 
85
85
  // Capture original functions to prevent tampering (client-side only)
86
- const originalWindowOpen = typeof window !== "undefined" ? window.open : null;
87
- const originalAddEventListener = typeof window !== "undefined" ? window.addEventListener : null;
88
- const originalRemoveEventListener = typeof window !== "undefined" ? window.removeEventListener : null;
89
- const originalSetTimeout = typeof window !== "undefined" ? window.setTimeout : setTimeout;
90
- const originalClearTimeout = typeof window !== "undefined" ? window.clearTimeout : clearTimeout;
91
- // Generate random window name to prevent targeting
92
- const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
93
- // Track active auth window for manual closure
94
- let activeAuthWindow = null;
95
- // Detect if current window is a popup
86
+ // Constants
87
+ const DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes
88
+ const DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes
89
+ const INITIAL_POLL_INTERVAL = 1000;
90
+ const MAX_POLL_INTERVAL = 5000;
91
+ const WINDOW_FEATURES = "scrollbars=yes,resizable=yes";
92
+ // Secure reference to native functions
93
+ const NativeFunctions = {
94
+ addEventListener: typeof window !== "undefined" ? window.addEventListener : null,
95
+ removeEventListener: typeof window !== "undefined" ? window.removeEventListener : null,
96
+ setTimeout: typeof window !== "undefined" ? window.setTimeout : setTimeout,
97
+ clearTimeout: typeof window !== "undefined" ? window.clearTimeout : clearTimeout,
98
+ };
99
+ const defaultMicrosoftDomains = [
100
+ ".microsoft.com",
101
+ ".microsoftonline.com",
102
+ ".live.com",
103
+ ];
104
+ /**
105
+ * Generate a secure random window name to prevent targeting
106
+ */
107
+ const generateSecureWindowName = () => `NINSS_CAS_AUTH_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
108
+ /**
109
+ * Detect if current window is a popup to prevent recursive popups
110
+ */
96
111
  const isPopupWindow = () => {
97
112
  if (typeof window === "undefined")
98
113
  return false;
@@ -103,354 +118,330 @@ const isPopupWindow = () => {
103
118
  return false;
104
119
  }
105
120
  };
106
- // Forward authentication result to parent window
107
- const forwardAuthToParent = (data, targetOrigin = "*") => {
108
- if (typeof window === "undefined")
121
+ /**
122
+ * Safely close a window with error handling for cross-origin restrictions
123
+ */
124
+ const safeWindowClose = (window) => {
125
+ if (!window)
109
126
  return;
110
- if (isPopupWindow() && window.opener) {
111
- try {
112
- window.opener.postMessage(data, targetOrigin);
127
+ try {
128
+ if (!window.closed) {
113
129
  window.close();
114
130
  }
115
- catch (error) {
116
- console.error("Failed to forward auth to parent:", error);
117
- }
118
131
  }
132
+ catch (error) {
133
+ Logger.debug("Error closing window (cross-origin restriction)", {
134
+ error: error instanceof Error ? error.message : "Unknown error",
135
+ });
136
+ }
137
+ };
138
+ /**
139
+ * Center popup window on screen
140
+ */
141
+ const getPopupPosition = (width, height) => {
142
+ if (typeof window === "undefined")
143
+ return { left: 0, top: 0 };
144
+ const left = Math.max(0, (window.screen.width - width) / 2);
145
+ const top = Math.max(0, (window.screen.height - height) / 2);
146
+ return { left, top };
119
147
  };
120
- const closeWindow = () => {
121
- if (activeAuthWindow && !activeAuthWindow.closed) {
122
- activeAuthWindow.close();
123
- activeAuthWindow = null;
148
+ /**
149
+ * Validate origin against expected domain with support for subdomains and Microsoft redirects
150
+ */
151
+ const isValidOrigin = (eventOrigin, expectedOrigin, microsoftDomains = defaultMicrosoftDomains) => {
152
+ try {
153
+ const originUrl = new URL(eventOrigin);
154
+ const expectedHostname = expectedOrigin.startsWith("http")
155
+ ? new URL(expectedOrigin).hostname
156
+ : expectedOrigin;
157
+ // Check Microsoft domains for Azure AD redirects
158
+ const isMicrosoftDomain = microsoftDomains.some((domain) => originUrl.hostname.endsWith(domain));
159
+ // Allow exact match, subdomains, or Microsoft domains
160
+ return (originUrl.hostname === expectedHostname ||
161
+ originUrl.hostname.endsWith("." + expectedHostname) ||
162
+ isMicrosoftDomain);
124
163
  }
164
+ catch {
165
+ return false;
166
+ }
167
+ };
168
+ /**
169
+ * Safely add message event listener with error handling
170
+ */
171
+ const addMessageListener = (listener) => {
172
+ if (!NativeFunctions.addEventListener) {
173
+ throw new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Message listener not available in current environment");
174
+ }
175
+ const wrappedListener = (event) => {
176
+ try {
177
+ listener(event);
178
+ }
179
+ catch (error) {
180
+ Logger.error("Error in message listener", {
181
+ error: error instanceof Error ? error.message : "Unknown error",
182
+ });
183
+ }
184
+ };
185
+ NativeFunctions.addEventListener.call(window, "message", wrappedListener);
186
+ return () => {
187
+ if (NativeFunctions.removeEventListener) {
188
+ NativeFunctions.removeEventListener.call(window, "message", wrappedListener);
189
+ }
190
+ };
125
191
  };
192
+ /**
193
+ * Validate configuration and return parsed URL
194
+ */
126
195
  function validateConfig(config) {
127
- // Validate URL format and parse once
128
196
  const urlValidation = URLSchema.safeParse(config.camsUrl);
129
197
  if (!urlValidation.success) {
130
198
  throw new CAMSError(CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
131
199
  }
132
- // Domain validation is mandatory for security
133
200
  if (!config.messageOrigin) {
134
201
  throw new CAMSError(CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
135
202
  }
136
- const url = new URL(config.camsUrl);
137
- return url;
203
+ return new URL(config.camsUrl);
138
204
  }
205
+ /**
206
+ * Open CAMS authentication popup and handle the authentication flow
207
+ */
139
208
  function openCAMSPopUpLogin(config) {
140
209
  return new Promise((resolve, reject) => {
210
+ // Environment validation
141
211
  if (typeof window === "undefined") {
142
212
  reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot open popup in server-side environment"));
143
213
  return;
144
214
  }
145
- if (config.debug)
146
- Logger.setLevel(LogLevel.DEBUG);
147
- // If this is a popup window, don't open another popup
148
215
  if (isPopupWindow()) {
149
- Logger.warn("Cannot open popup from within popup window");
216
+ Logger.warn("Attempted to open popup from within popup window");
150
217
  reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot open authentication popup from within popup window"));
151
218
  return;
152
219
  }
220
+ // Initialize logging
221
+ if (config.debug)
222
+ Logger.setLevel(LogLevel.DEBUG);
153
223
  Logger.info("Starting CAMS authentication", { url: config.camsUrl });
224
+ // Validate configuration
154
225
  let validatedUrl;
155
226
  try {
156
227
  validatedUrl = validateConfig(config);
157
- Logger.debug("Config validation passed");
228
+ Logger.debug("Configuration validation passed");
158
229
  }
159
230
  catch (error) {
160
- Logger.error("Config validation failed", {
231
+ Logger.error("Configuration validation failed", {
161
232
  error: error instanceof Error ? error.message : "Unknown error",
162
233
  });
163
234
  reject(error);
164
235
  return;
165
236
  }
166
- const { messageOrigin, windowHeight, windowWidth, authTimeout = 300000, // 5 minutes as a final failsafe
167
- idleTimeout = 120000, // 2 minutes of inactivity
237
+ // Extract configuration with defaults
238
+ const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT,
239
+ // allowedRedirectDomains = defaultMicrosoftDomains,
168
240
  } = config;
169
- let authWindow;
241
+ // State management
242
+ let authWindow = null;
170
243
  let authTimeoutId = null;
171
244
  let idleTimeoutId = null;
172
245
  let checkClosedInterval = null;
173
- try {
174
- Logger.debug("Opening popup window", {
175
- width: windowWidth,
176
- height: windowHeight,
177
- });
178
- // Center the popup window
179
- const left = (window.screen.width - windowWidth) / 2;
180
- const top = (window.screen.height - windowHeight) / 2;
181
- const secureWindowName = generateSecureWindowName();
182
- authWindow = originalWindowOpen
183
- ? originalWindowOpen.call(window, validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},scrollbars=yes,resizable=yes`)
184
- : null;
185
- // Track active window for manual closure
186
- activeAuthWindow = authWindow;
187
- }
188
- catch (error) {
189
- Logger.error("Failed to open popup window", {
190
- error: error instanceof Error ? error.message : "Unknown error",
191
- });
192
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
193
- return;
194
- }
195
- if (!authWindow) {
196
- Logger.error("Popup window blocked");
197
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
198
- return;
199
- }
200
- // Only check for immediate closure (true popup blocking)
201
- if (authWindow.closed) {
202
- Logger.error("Popup immediately closed by blocker");
203
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
204
- return;
205
- }
206
- Logger.debug("Popup window opened successfully");
246
+ let removeMessageListener = null;
247
+ /**
248
+ * Clean up all resources and timeouts
249
+ */
207
250
  const cleanup = () => {
208
- if (originalRemoveEventListener) {
209
- originalRemoveEventListener.call(window, "message", listener);
251
+ if (removeMessageListener) {
252
+ removeMessageListener();
253
+ removeMessageListener = null;
210
254
  }
211
255
  if (idleTimeoutId)
212
- originalClearTimeout(idleTimeoutId);
256
+ NativeFunctions.clearTimeout(idleTimeoutId);
213
257
  if (authTimeoutId)
214
- originalClearTimeout(authTimeoutId);
258
+ NativeFunctions.clearTimeout(authTimeoutId);
215
259
  if (checkClosedInterval)
216
- originalClearTimeout(checkClosedInterval);
260
+ NativeFunctions.clearTimeout(checkClosedInterval);
217
261
  idleTimeoutId = null;
218
262
  authTimeoutId = null;
219
263
  checkClosedInterval = null;
220
264
  };
221
- const listener = (event) => {
222
- const messageEvent = event;
265
+ /**
266
+ * Clean up and close the popup window, then reject with error
267
+ */
268
+ const cleanupAndClose = (error) => {
269
+ cleanup();
270
+ safeWindowClose(authWindow);
271
+ if (error) {
272
+ reject(error);
273
+ }
274
+ };
275
+ /**
276
+ * Reset idle timeout on user activity
277
+ */
278
+ const resetIdleTimeout = () => {
279
+ if (idleTimeoutId)
280
+ NativeFunctions.clearTimeout(idleTimeoutId);
281
+ Logger.debug("Resetting idle timeout", { idleTimeout });
282
+ idleTimeoutId = NativeFunctions.setTimeout(() => {
283
+ Logger.warn("Authentication idle timeout reached", { idleTimeout });
284
+ cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
285
+ }, idleTimeout);
286
+ };
287
+ /**
288
+ * Set up popup window closure detection with exponential backoff
289
+ */
290
+ const setupClosureDetection = () => {
291
+ let pollInterval = INITIAL_POLL_INTERVAL;
292
+ const checkClosed = () => {
293
+ try {
294
+ if (authWindow?.closed) {
295
+ Logger.info("Authentication window closed by user");
296
+ cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
297
+ return;
298
+ }
299
+ }
300
+ catch (error) {
301
+ // Cross-origin access error means window is still open but on different domain
302
+ Logger.debug("Cannot access window.closed due to cross-origin restrictions", error);
303
+ }
304
+ // Exponential backoff with maximum limit
305
+ pollInterval = Math.min(pollInterval * 1.2, MAX_POLL_INTERVAL);
306
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
307
+ };
308
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
309
+ };
310
+ /**
311
+ * Handle incoming message events from the popup
312
+ */
313
+ const handleMessage = (event) => {
223
314
  Logger.debug("Received message", {
224
- origin: messageEvent.origin,
315
+ origin: event.origin,
225
316
  expectedOrigin: messageOrigin,
226
- data: messageEvent.data,
317
+ data: event.data,
227
318
  });
228
- const originUrl = new URL(messageEvent.origin);
229
- const expectedHostname = messageOrigin.startsWith("http")
230
- ? new URL(messageOrigin).hostname
231
- : messageOrigin;
232
- // Allow Microsoft redirect domains for Azure AD authentication
233
- const isMicrosoftDomain = originUrl.hostname.endsWith(".microsoft.com") ||
234
- originUrl.hostname.endsWith(".microsoftonline.com") ||
235
- originUrl.hostname.endsWith(".live.com");
236
- const isAllowedOrigin = originUrl.hostname === expectedHostname ||
237
- originUrl.hostname.endsWith("." + expectedHostname) ||
238
- isMicrosoftDomain;
239
- if (!isAllowedOrigin) {
319
+ // Security: Validate origin
320
+ if (!isValidOrigin(event.origin, messageOrigin, defaultMicrosoftDomains)) {
240
321
  Logger.warn("Blocked message from unauthorized origin", {
241
- origin: messageEvent.origin,
322
+ origin: event.origin,
242
323
  expected: messageOrigin,
243
- data: messageEvent.data,
324
+ data: event.data,
244
325
  });
245
326
  return;
246
327
  }
247
- // Validate event source
248
- if (messageEvent.source !== authWindow) {
328
+ // Security: Validate message source
329
+ if (event.source !== authWindow) {
249
330
  Logger.warn("Message from unexpected source", {
250
- source: messageEvent.source,
251
- origin: messageEvent.origin,
331
+ source: event.source,
332
+ origin: event.origin,
252
333
  expected: messageOrigin,
253
- data: messageEvent.data,
334
+ data: event.data,
254
335
  });
255
336
  return;
256
337
  }
257
- // Validate event source
258
- if (messageEvent.source !== authWindow) {
259
- Logger.warn("Message from unexpected source", {
260
- source: messageEvent.source,
261
- origin: messageEvent.origin,
262
- expected: messageOrigin,
263
- data: messageEvent.data,
264
- });
265
- return;
266
- }
267
- // Ignore heartbeat messages
268
- if (messageEvent.data?.type === "heartbeat") {
338
+ // Handle heartbeat messages (reset idle timeout)
339
+ if (event.data?.type === "heartbeat") {
269
340
  Logger.debug("Received heartbeat message");
270
341
  resetIdleTimeout();
271
342
  return;
272
343
  }
273
- // ✅ Validate payload
274
- const tokenMsg = ProfileSchema.safeParse(messageEvent.data);
275
- if (tokenMsg.success) {
344
+ // Process authentication messages
345
+ processAuthenticationMessage(event.data);
346
+ };
347
+ /**
348
+ * Process and validate authentication message payloads
349
+ */
350
+ const processAuthenticationMessage = (data) => {
351
+ // Success case: Valid profile received
352
+ const profileValidation = ProfileSchema.safeParse(data);
353
+ if (profileValidation.success) {
276
354
  Logger.info("Authentication successful");
277
355
  cleanupAndClose();
278
- resolve(tokenMsg.data);
356
+ resolve(profileValidation.data);
279
357
  return;
280
358
  }
281
- const authFailureMsg = AuthFailureMessageSchema.safeParse(messageEvent.data);
282
- if (authFailureMsg.success) {
359
+ // Authentication failure case
360
+ const authFailureValidation = AuthFailureMessageSchema.safeParse(data);
361
+ if (authFailureValidation.success) {
362
+ const { error, errorCode, errorDetails } = authFailureValidation.data;
283
363
  Logger.warn("Authentication failure received", {
284
- errorDetails: authFailureMsg.data.errorDetails,
285
- error: authFailureMsg.data.error,
286
- errorCode: authFailureMsg.data.errorCode,
364
+ error,
365
+ errorCode,
366
+ errorDetails,
287
367
  });
288
- cleanupAndClose(new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "Authentication failed: " + authFailureMsg.data.error));
368
+ cleanupAndClose(new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ""}`));
289
369
  return;
290
370
  }
291
- const errorMsg = ErrorMessageSchema.safeParse(messageEvent.data);
292
- if (errorMsg.success) {
371
+ // Generic error case
372
+ const errorValidation = ErrorMessageSchema.safeParse(data);
373
+ if (errorValidation.success) {
293
374
  Logger.warn("Authentication error received", {
294
- error: errorMsg.data.error,
375
+ error: errorValidation.data.error,
295
376
  });
296
- cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
377
+ cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, `Authentication failed: ${errorValidation.data.error}`));
297
378
  return;
298
379
  }
380
+ // Invalid message format
299
381
  Logger.error("Invalid message format received", {
300
- messageData: messageEvent.data,
301
- dataType: typeof messageEvent.data,
302
- tokenValidationError: tokenMsg.error
303
- ? tokenMsg.error.issues
304
- : undefined,
305
- errorValidationError: errorMsg.error
306
- ? errorMsg.error.issues
307
- : undefined,
382
+ messageData: data,
383
+ dataType: typeof data,
384
+ profileValidationError: profileValidation.error?.issues,
385
+ authFailureValidationError: authFailureValidation.error?.issues,
386
+ errorValidationError: errorValidation.error?.issues,
308
387
  });
309
388
  cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
310
389
  };
311
- const cleanupAndClose = (error) => {
312
- cleanup();
313
- try {
314
- if (authWindow && !authWindow.closed) {
315
- authWindow.close();
316
- }
317
- activeAuthWindow = null;
318
- }
319
- catch {
320
- // Ignore close errors
390
+ // Main authentication flow execution
391
+ try {
392
+ // Open popup window
393
+ const { left, top } = getPopupPosition(windowWidth, windowHeight);
394
+ const secureWindowName = generateSecureWindowName();
395
+ Logger.debug("Opening popup window", {
396
+ width: windowWidth,
397
+ height: windowHeight,
398
+ left,
399
+ top,
400
+ });
401
+ authWindow = window.open(validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`);
402
+ // Check for popup blocking
403
+ if (!authWindow) {
404
+ Logger.error("Popup window blocked or failed to open");
405
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
406
+ return;
321
407
  }
322
- if (error)
323
- reject(error);
324
- };
325
- const resetIdleTimeout = () => {
326
- // Timeout handler
327
- if (idleTimeoutId)
328
- originalClearTimeout(idleTimeoutId);
329
- Logger.debug("Resetting idle timeout", { idleTimeout });
330
- idleTimeoutId = originalSetTimeout(() => {
331
- Logger.warn("Authentication idle timeout reached", { idleTimeout });
332
- cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
333
- }, idleTimeout);
334
- };
335
- Logger.debug("Setting auth timeout", { authTimeout });
336
- authTimeoutId = originalSetTimeout(() => {
337
- Logger.warn("Authentication auth timeout reached", { authTimeout });
338
- cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication process exceeded auth time limit of ${authTimeout}ms`));
339
- }, authTimeout);
340
- resetIdleTimeout();
341
- // Use exponential backoff for popup closure checking
342
- let pollInterval = 1000; // Start with 1 second
343
- const maxPollInterval = 5000; // Max 5 seconds
344
- const checkClosed = () => {
345
- if (authWindow?.closed) {
346
- Logger.info("Authentication window closed by user");
347
- cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
408
+ // Check for immediate closure (aggressive popup blockers)
409
+ if (authWindow.closed) {
410
+ Logger.error("Popup immediately closed by blocker");
411
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
348
412
  return;
349
413
  }
350
- // Exponential backoff: increase interval up to max
351
- pollInterval = Math.min(pollInterval * 1.2, maxPollInterval);
352
- checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
353
- };
354
- checkClosedInterval = originalSetTimeout(checkClosed, pollInterval);
355
- try {
356
- if (originalAddEventListener) {
357
- originalAddEventListener.call(window, "message", listener);
358
- Logger.debug("Message listener attached");
414
+ Logger.debug("Popup window opened successfully");
415
+ // Set up message listener
416
+ removeMessageListener = addMessageListener(handleMessage);
417
+ Logger.debug("Message listener attached");
418
+ // Set up timeouts
419
+ Logger.debug("Setting authentication timeout", { authTimeout });
420
+ authTimeoutId = NativeFunctions.setTimeout(() => {
421
+ Logger.warn("Authentication timeout reached", { authTimeout });
422
+ cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication process exceeded time limit of ${authTimeout}ms`));
423
+ }, authTimeout);
424
+ resetIdleTimeout();
425
+ setupClosureDetection();
426
+ // Focus popup for better UX
427
+ try {
428
+ authWindow.focus();
359
429
  }
360
- else {
361
- throw new Error("addEventListener not available");
430
+ catch (error) {
431
+ Logger.debug("Could not focus popup window (cross-origin restriction)", error);
362
432
  }
363
433
  }
364
434
  catch (error) {
365
- Logger.error("Failed to attach message listener", {
435
+ Logger.error("Failed to initialize authentication popup", {
366
436
  error: error instanceof Error ? error.message : "Unknown error",
367
437
  });
368
438
  cleanup();
369
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " +
439
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
370
440
  (error instanceof Error ? error.message : "Unknown error")));
371
- return;
372
- }
373
- // Add focus to the popup for better UX
374
- try {
375
- if (authWindow && !authWindow.closed) {
376
- authWindow.focus();
377
- }
378
- }
379
- catch {
380
- // Ignore focus errors (cross-origin restrictions)
381
441
  }
382
442
  });
383
443
  }
384
444
 
385
- /**
386
- * Initialize popup authentication handler
387
- * This should be called in the popup window to handle auth completion
388
- */
389
- function initializePopupAuth(targetOrigin) {
390
- if (!isPopupWindow()) {
391
- Logger.debug("Not in popup window, skipping popup auth initialization");
392
- return;
393
- }
394
- Logger.info("Initializing popup authentication handler");
395
- // Listen for auth completion events from the popup app
396
- const handleAuthComplete = (profile) => {
397
- Logger.info("Authentication completed in popup, forwarding to parent");
398
- forwardAuthToParent(profile, targetOrigin);
399
- };
400
- // Listen for auth errors
401
- const handleAuthError = (error) => {
402
- Logger.warn("Authentication error in popup, forwarding to parent");
403
- forwardAuthToParent({
404
- type: "AUTH_FAILURE",
405
- error: error.message || "Authentication failed",
406
- errorCode: error.code,
407
- errorDetails: error
408
- }, targetOrigin);
409
- };
410
- // Expose global handlers for the popup app to use
411
- window.__CAMS_POPUP_AUTH__ = {
412
- completeAuth: handleAuthComplete,
413
- errorAuth: handleAuthError,
414
- isPopup: true
415
- };
416
- Logger.debug("Popup authentication handlers registered");
417
- }
418
- /**
419
- * Complete authentication in popup window
420
- * Call this when authentication is successful in the popup
421
- */
422
- function completePopupAuth(profile, targetOrigin) {
423
- if (!isPopupWindow()) {
424
- Logger.warn("completePopupAuth called outside of popup window");
425
- return;
426
- }
427
- Logger.info("Completing popup authentication");
428
- forwardAuthToParent(profile, targetOrigin);
429
- }
430
- /**
431
- * Report authentication error in popup window
432
- * Call this when authentication fails in the popup
433
- */
434
- function errorPopupAuth(error, targetOrigin) {
435
- if (!isPopupWindow()) {
436
- Logger.warn("errorPopupAuth called outside of popup window");
437
- return;
438
- }
439
- Logger.warn("Reporting popup authentication error");
440
- forwardAuthToParent({
441
- type: "AUTH_FAILURE",
442
- error: error.message || "Authentication failed",
443
- errorCode: error.code,
444
- errorDetails: error
445
- }, targetOrigin);
446
- }
447
- /**
448
- * Check if current window is a CAMS popup
449
- */
450
- function isCAMSPopup() {
451
- return isPopupWindow() && !!window.__CAMS_POPUP_AUTH__;
452
- }
453
-
454
445
  class CAMSSessionManager {
455
446
  storage;
456
447
  keyPrefix;
@@ -659,13 +650,11 @@ class CAMSSessionManager {
659
650
  this.profile = profile;
660
651
  this.setToken(profile.userProfile.tokens.Bearer);
661
652
  Logger.info("Authentication completed in popup, forwarding to parent");
662
- completePopupAuth(profile, targetOrigin);
663
653
  }
664
654
  catch (error) {
665
655
  Logger.error("Failed to complete popup authentication", {
666
656
  error: error instanceof Error ? error.message : "Unknown error"
667
657
  });
668
- errorPopupAuth(error, targetOrigin);
669
658
  }
670
659
  }
671
660
  /**
@@ -677,7 +666,6 @@ class CAMSSessionManager {
677
666
  return;
678
667
  }
679
668
  Logger.warn("Reporting authentication error from popup");
680
- errorPopupAuth(error, targetOrigin);
681
669
  }
682
670
  }
683
671
  // 🔹 Safe fallback for Node/SSR
@@ -746,6 +734,7 @@ class CAMSMFAAuthenticator {
746
734
  throw new Error(`HTTP ${response.status}: ${response.statusText}`);
747
735
  }
748
736
  const data = await response.json();
737
+ console.log("MFA Response >>>", data);
749
738
  if (data.isAuthenticated) {
750
739
  Logger.info("MFA verification successful");
751
740
  this.resetAttempts();
@@ -771,5 +760,5 @@ class CAMSMFAAuthenticator {
771
760
  }
772
761
  }
773
762
 
774
- export { AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSMFAAuthenticator, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, URLSchema, closeWindow, completePopupAuth, errorPopupAuth, forwardAuthToParent, generateSecureWindowName, initializePopupAuth, isCAMSPopup, isPopupWindow, openCAMSPopUpLogin, validateConfig };
763
+ export { AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSMFAAuthenticator, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, URLSchema, generateSecureWindowName, isPopupWindow, openCAMSPopUpLogin, validateConfig };
775
764
  //# sourceMappingURL=index.esm.js.map