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