@nibssplc/cams-sdk 0.0.1-beta.7 → 0.0.1-beta.71

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
@@ -1,6 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  var zod = require('zod');
4
+ var axios = require('axios');
5
+ var https = require('https');
4
6
 
5
7
  exports.CAMSErrorType = void 0;
6
8
  (function (CAMSErrorType) {
@@ -10,229 +12,539 @@ exports.CAMSErrorType = void 0;
10
12
  CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
11
13
  CAMSErrorType["INVALID_URL"] = "INVALID_URL";
12
14
  CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
15
+ CAMSErrorType["API_VALIDATION_ERROR"] = "VALIDATION_ERROR";
16
+ CAMSErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
13
17
  })(exports.CAMSErrorType || (exports.CAMSErrorType = {}));
14
18
  class CAMSError extends Error {
19
+ type;
15
20
  constructor(type, message) {
16
21
  super(message);
17
22
  this.type = type;
18
- this.name = 'CAMSError';
23
+ this.name = this.constructor.name;
19
24
  }
20
25
  }
21
26
 
22
- // Validate the returned token - Base64 format with minimum 20 chars
23
- const TokenMessageSchema = zod.z.object({
24
- access_token: zod.z.string().regex(/^[A-Za-z0-9+/]{20,}={0,2}$/, "Invalid NIBSS CAMS token format"),
27
+ // Validate the returned token - non-empty string
28
+ const ProfileSchema = zod.z.object({
29
+ state: zod.z.literal("AUTH_SUCCESS").or(zod.z.literal("AUTH_FAILURE")),
30
+ role: zod.z.enum(["SUPER_ADMIN", "ADMIN", "USER"]),
31
+ message: zod.z.string(),
32
+ profile: zod.z.object({
33
+ id: zod.z.number(),
34
+ name: zod.z.string(),
35
+ email: zod.z.email(),
36
+ isMFAEnabled: zod.z.boolean(),
37
+ priviledges: zod.z.array(zod.z.string()).optional(),
38
+ tokens: zod.z.object({
39
+ Nonce: zod.z.string(),
40
+ Bearer: zod.z.string(),
41
+ }),
42
+ }),
25
43
  });
26
44
  const ErrorMessageSchema = zod.z.object({
27
- error: zod.z.string(),
28
- });
29
- const TokenSchema = zod.z.object({
30
- access_token: zod.z.string(),
31
- refresh_token: zod.z.string().optional(),
32
- expires_in: zod.z.number(), // in seconds
33
- token_type: zod.z.string().default("Bearer"),
34
- id_token: zod.z.string().optional(),
45
+ error: zod.z.string().min(1, "Error message cannot be empty"),
35
46
  });
36
- const ProfileSchema = zod.z.object({
37
- sub: zod.z.string(), // user ID
38
- name: zod.z.string().optional(),
39
- email: zod.z.email({ message: "Invalid email address" }).optional(),
40
- given_name: zod.z.string().optional(),
41
- family_name: zod.z.string().optional(),
42
- roles: zod.z.array(zod.z.string()).optional(),
47
+ const AuthFailureMessageSchema = zod.z.object({
48
+ type: zod.z.literal("AUTH_FAILURE"),
49
+ error: zod.z.string().min(1, "Error message cannot be empty"),
50
+ errorCode: zod.z.string(),
51
+ errorDetails: zod.z.object().or(zod.z.any()),
43
52
  });
44
- // URL validation schema - only HTTPS for production security
45
- const URLSchema = zod.z.string().url().refine((url) => url.startsWith('https://'), { message: "Only HTTPS URLs are allowed" });
53
+ const URLSchema = zod.z.url();
54
+
55
+ exports.LogLevel = void 0;
56
+ (function (LogLevel) {
57
+ LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
58
+ LogLevel[LogLevel["WARN"] = 1] = "WARN";
59
+ LogLevel[LogLevel["INFO"] = 2] = "INFO";
60
+ LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
61
+ })(exports.LogLevel || (exports.LogLevel = {}));
62
+ class Logger {
63
+ static level = exports.LogLevel.DEBUG;
64
+ static prefix = '[CAMS-SDK]';
65
+ static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
66
+ static setLevel(level) {
67
+ Logger.level = level;
68
+ }
69
+ static error(message, context) {
70
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.ERROR) {
71
+ console.error(`${Logger.prefix} ERROR:`, message, context || '');
72
+ }
73
+ }
74
+ static warn(message, context) {
75
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.WARN) {
76
+ console.warn(`${Logger.prefix} WARN:`, message, context || '');
77
+ }
78
+ }
79
+ static info(message, context) {
80
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.INFO) {
81
+ console.info(`${Logger.prefix} INFO:`, message, context || '');
82
+ }
83
+ }
84
+ static debug(message, context) {
85
+ if (!Logger.isTestEnv && Logger.level >= exports.LogLevel.DEBUG) {
86
+ console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
87
+ }
88
+ }
89
+ }
46
90
 
91
+ // Constants
92
+ const DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes
93
+ const DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes
94
+ const INITIAL_POLL_INTERVAL = 1000;
95
+ const WINDOW_FEATURES = "scrollbars=yes,resizable=yes";
96
+ // Default allowed Microsoft domains for Azure AD redirects
97
+ const DEFAULT_MICROSOFT_DOMAINS = [
98
+ ".microsoft.com",
99
+ ".microsoftonline.com",
100
+ ".live.com",
101
+ "login.microsoftonline.com"
102
+ ];
103
+ // Secure reference to native functions with proper binding
104
+ const NativeFunctions = {
105
+ addEventListener: typeof window !== "undefined" ? window.addEventListener.bind(window) : null,
106
+ removeEventListener: typeof window !== "undefined" ? window.removeEventListener.bind(window) : null,
107
+ setTimeout: typeof window !== "undefined" && window.setTimeout ? window.setTimeout.bind(window) : setTimeout,
108
+ clearTimeout: typeof window !== "undefined" && window.clearTimeout ? window.clearTimeout.bind(window) : clearTimeout,
109
+ };
110
+ /**
111
+ * Generate a secure random window name to prevent targeting
112
+ */
113
+ const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
114
+ /**
115
+ * Detect if current window is a popup to prevent recursive popups
116
+ */
117
+ const isPopupWindow = () => {
118
+ if (typeof window === "undefined")
119
+ return false;
120
+ // Skip popup detection in test environments
121
+ if (typeof process !== "undefined" && process.env && process.env.NODE_ENV === "test") {
122
+ return false;
123
+ }
124
+ try {
125
+ return window.opener !== null && window.opener !== window;
126
+ }
127
+ catch {
128
+ return false;
129
+ }
130
+ };
131
+ /**
132
+ * Safely close a window with error handling for cross-origin restrictions
133
+ */
134
+ const safeWindowClose = (window) => {
135
+ if (!window)
136
+ return;
137
+ try {
138
+ if (!window.closed) {
139
+ window.close();
140
+ }
141
+ }
142
+ catch (error) {
143
+ Logger.debug("Error closing window (cross-origin restriction)", {
144
+ error: error instanceof Error ? error.message : "Unknown error"
145
+ });
146
+ }
147
+ };
148
+ /**
149
+ * Center popup window on screen
150
+ */
151
+ const getPopupPosition = (width, height) => {
152
+ if (typeof window === "undefined")
153
+ return { left: 0, top: 0 };
154
+ const left = Math.max(0, (window.screen.width - width) / 2);
155
+ const top = Math.max(0, (window.screen.height - height) / 2);
156
+ return { left, top };
157
+ };
158
+ /**
159
+ * Validate origin against expected domain with support for subdomains and Microsoft redirects
160
+ */
161
+ const isValidOrigin = (eventOrigin, expectedOrigin, microsoftDomains = DEFAULT_MICROSOFT_DOMAINS) => {
162
+ try {
163
+ const originUrl = new URL(eventOrigin);
164
+ const expectedHostname = expectedOrigin.startsWith("http")
165
+ ? new URL(expectedOrigin).hostname
166
+ : expectedOrigin;
167
+ // Check Microsoft domains for Azure AD redirects
168
+ const isMicrosoftDomain = microsoftDomains.some(domain => originUrl.hostname === domain || originUrl.hostname.endsWith(domain));
169
+ // Allow exact match, subdomains, or Microsoft domains
170
+ return (originUrl.hostname === expectedHostname ||
171
+ originUrl.hostname.endsWith("." + expectedHostname) ||
172
+ isMicrosoftDomain);
173
+ }
174
+ catch {
175
+ return false;
176
+ }
177
+ };
178
+ /**
179
+ * Safely check if window is closed with cross-origin handling
180
+ */
181
+ const isWindowClosed = (window) => {
182
+ if (!window)
183
+ return true;
184
+ try {
185
+ return window.closed;
186
+ }
187
+ catch (error) {
188
+ // Cross-origin error means we can't access the property
189
+ // This typically happens when redirected to external auth providers
190
+ Logger.debug("Cannot access window.closed due to cross-origin restrictions - assuming window is still open", error);
191
+ return false;
192
+ }
193
+ };
194
+ /**
195
+ * Safely add message event listener with error handling
196
+ */
197
+ const addMessageListener = (listener) => {
198
+ if (!NativeFunctions.addEventListener) {
199
+ throw new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Message listener not available in current environment");
200
+ }
201
+ const wrappedListener = (event) => {
202
+ try {
203
+ listener(event);
204
+ }
205
+ catch (error) {
206
+ Logger.error("Error in message listener", {
207
+ error: error instanceof Error ? error.message : "Unknown error"
208
+ });
209
+ }
210
+ };
211
+ NativeFunctions.addEventListener("message", wrappedListener);
212
+ return () => {
213
+ if (NativeFunctions.removeEventListener) {
214
+ NativeFunctions.removeEventListener("message", wrappedListener);
215
+ }
216
+ };
217
+ };
218
+ /**
219
+ * Validate configuration and return parsed URL
220
+ */
47
221
  function validateConfig(config) {
48
- var _a;
49
- // Validate URL format
50
222
  const urlValidation = URLSchema.safeParse(config.camsUrl);
51
223
  if (!urlValidation.success) {
52
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
53
- }
54
- // Domain validation is mandatory for security
55
- if (!((_a = config.allowedDomains) === null || _a === void 0 ? void 0 : _a.length)) {
56
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
224
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
57
225
  }
58
- const url = new URL(config.camsUrl); // URLSchema already validated this
59
- const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
60
- if (!isAllowed) {
61
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'URL not in allowed domains list');
226
+ if (!config.messageOrigin) {
227
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
62
228
  }
229
+ return new URL(config.camsUrl);
63
230
  }
231
+ /**
232
+ * Open CAMS authentication popup and handle the authentication flow
233
+ */
64
234
  function openCAMSPopUpLogin(config) {
65
235
  return new Promise((resolve, reject) => {
66
- try {
67
- validateConfig(config);
236
+ // Environment validation
237
+ if (typeof window === "undefined") {
238
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot open popup in server-side environment"));
239
+ return;
68
240
  }
69
- catch (error) {
70
- reject(error);
241
+ if (isPopupWindow()) {
242
+ Logger.warn("Attempted to open popup from within popup window");
243
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot open authentication popup from within popup window"));
71
244
  return;
72
245
  }
73
- const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;
74
- let authWindow;
75
- let timeoutId = null;
76
- let checkClosedInterval = null;
246
+ // Initialize logging
247
+ if (config.debug)
248
+ Logger.setLevel(exports.LogLevel.DEBUG);
249
+ Logger.info("Starting CAMS authentication", { url: config.camsUrl });
250
+ // Validate configuration
251
+ let validatedUrl;
77
252
  try {
78
- authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
253
+ validatedUrl = validateConfig(config);
254
+ Logger.debug("Configuration validation passed");
79
255
  }
80
256
  catch (error) {
81
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " + (error instanceof Error ? error.message : "Unknown error")));
82
- return;
83
- }
84
- if (!authWindow) {
85
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window. Please allow popups."));
257
+ Logger.error("Configuration validation failed", {
258
+ error: error instanceof Error ? error.message : "Unknown error"
259
+ });
260
+ reject(error);
86
261
  return;
87
262
  }
263
+ // Extract configuration with defaults
264
+ const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = [...DEFAULT_MICROSOFT_DOMAINS, messageOrigin], } = config;
265
+ // State management
266
+ let authWindow = null;
267
+ let authTimeoutId = null;
268
+ let idleTimeoutId = null;
269
+ let checkClosedInterval = null;
270
+ let removeMessageListener = null;
271
+ let hasReceivedValidMessage = false;
272
+ /**
273
+ * Clean up all resources and timeouts
274
+ */
88
275
  const cleanup = () => {
89
- window.removeEventListener("message", listener);
90
- if (timeoutId)
91
- clearTimeout(timeoutId);
276
+ if (removeMessageListener) {
277
+ removeMessageListener();
278
+ removeMessageListener = null;
279
+ }
280
+ if (idleTimeoutId)
281
+ NativeFunctions.clearTimeout(idleTimeoutId);
282
+ if (authTimeoutId)
283
+ NativeFunctions.clearTimeout(authTimeoutId);
92
284
  if (checkClosedInterval)
93
- clearInterval(checkClosedInterval);
285
+ NativeFunctions.clearTimeout(checkClosedInterval);
286
+ idleTimeoutId = null;
287
+ authTimeoutId = null;
288
+ checkClosedInterval = null;
94
289
  };
290
+ /**
291
+ * Clean up and close the popup window, then reject with error
292
+ */
95
293
  const cleanupAndClose = (error) => {
96
294
  cleanup();
97
- try {
98
- if (authWindow && !authWindow.closed) {
99
- authWindow.close();
295
+ safeWindowClose(authWindow);
296
+ if (error) {
297
+ reject(error);
298
+ }
299
+ };
300
+ /**
301
+ * Reset idle timeout on user activity
302
+ */
303
+ const resetIdleTimeout = () => {
304
+ if (idleTimeoutId)
305
+ NativeFunctions.clearTimeout(idleTimeoutId);
306
+ Logger.debug("Resetting idle timeout", { idleTimeout });
307
+ idleTimeoutId = NativeFunctions.setTimeout(() => {
308
+ Logger.warn("Authentication idle timeout reached", { idleTimeout });
309
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
310
+ }, idleTimeout);
311
+ };
312
+ /**
313
+ * Set up popup window closure detection with cross-origin handling
314
+ */
315
+ const setupClosureDetection = () => {
316
+ let pollInterval = INITIAL_POLL_INTERVAL;
317
+ const checkClosed = () => {
318
+ // Skip closure detection when on Microsoft domains
319
+ if (authWindow) {
320
+ try {
321
+ const currentUrl = authWindow.location.href;
322
+ const isMicrosoftDomain = allowedRedirectDomains.some(domain => currentUrl.includes(domain));
323
+ if (isMicrosoftDomain) {
324
+ Logger.debug("Skipping closure check - on Microsoft domain");
325
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
326
+ return;
327
+ }
328
+ }
329
+ catch (error) {
330
+ // Cross-origin error - assume we're on Microsoft domain and skip check
331
+ Logger.debug("Cross-origin error - skipping closure check");
332
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
333
+ return;
334
+ }
335
+ }
336
+ const isClosed = isWindowClosed(authWindow);
337
+ if (isClosed && !hasReceivedValidMessage) {
338
+ Logger.info("Authentication window closed by user");
339
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
340
+ return;
100
341
  }
342
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
343
+ };
344
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
345
+ };
346
+ /**
347
+ * Handle incoming message events from the popup
348
+ */
349
+ const handleMessage = (event) => {
350
+ Logger.debug("Received message", {
351
+ origin: event.origin,
352
+ expectedOrigin: messageOrigin,
353
+ data: event.data,
354
+ });
355
+ // Security: Validate origin
356
+ if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {
357
+ Logger.warn("Blocked message from unauthorized origin", {
358
+ origin: event.origin,
359
+ expected: messageOrigin,
360
+ data: event.data,
361
+ });
362
+ return;
101
363
  }
102
- catch {
103
- // Ignore close errors
364
+ // Security: Validate message source
365
+ if (event.source !== authWindow) {
366
+ Logger.warn("Message from unexpected source", {
367
+ source: event.source,
368
+ origin: event.origin,
369
+ expected: messageOrigin,
370
+ data: event.data,
371
+ });
372
+ return;
104
373
  }
105
- if (error)
106
- reject(error);
107
- };
108
- const listener = (event) => {
109
- if (event.origin !== allowedOrigin) {
110
- // Sanitize origin for logging to prevent log injection
111
- const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
112
- console.warn("Blocked message from origin:", sanitizedOrigin);
374
+ // Mark that we've received a valid message (prevents false closure detection)
375
+ hasReceivedValidMessage = true;
376
+ // Handle heartbeat messages (reset idle timeout)
377
+ if (event.data?.type === "heartbeat") {
378
+ Logger.debug("Received heartbeat message");
379
+ resetIdleTimeout();
113
380
  return;
114
381
  }
115
- // ✅ Validate payload
116
- const tokenMsg = TokenMessageSchema.safeParse(event.data);
117
- if (tokenMsg.success) {
382
+ // Process authentication messages
383
+ processAuthenticationMessage(event.data);
384
+ };
385
+ /**
386
+ * Process and validate authentication message payloads
387
+ */
388
+ const processAuthenticationMessage = (data) => {
389
+ // Success case: Valid profile received
390
+ const profileValidation = ProfileSchema.safeParse(data);
391
+ if (profileValidation.success) {
392
+ Logger.info("Authentication successful");
118
393
  cleanupAndClose();
119
- resolve({ token: tokenMsg.data.access_token });
394
+ resolve(profileValidation.data);
395
+ return;
396
+ }
397
+ // Authentication failure case
398
+ const authFailureValidation = AuthFailureMessageSchema.safeParse(data);
399
+ if (authFailureValidation.success) {
400
+ const { error, errorCode, errorDetails } = authFailureValidation.data;
401
+ Logger.warn("Authentication failure received", {
402
+ error,
403
+ errorCode,
404
+ errorDetails,
405
+ });
406
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`));
120
407
  return;
121
408
  }
122
- const errorMsg = ErrorMessageSchema.safeParse(event.data);
123
- if (errorMsg.success) {
124
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
409
+ // Generic error case
410
+ const errorValidation = ErrorMessageSchema.safeParse(data);
411
+ if (errorValidation.success) {
412
+ Logger.warn("Authentication error received", {
413
+ error: errorValidation.data.error,
414
+ });
415
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, `Authentication failed: ${errorValidation.data.error}`));
125
416
  return;
126
417
  }
418
+ // Invalid message format
419
+ Logger.error("Invalid message format received", {
420
+ messageData: data,
421
+ dataType: typeof data,
422
+ profileValidationError: profileValidation.error?.issues,
423
+ authFailureValidationError: authFailureValidation.error?.issues,
424
+ errorValidationError: errorValidation.error?.issues,
425
+ });
127
426
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
128
427
  };
129
- // Timeout handler
130
- timeoutId = setTimeout(() => {
131
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
132
- }, timeout);
133
- checkClosedInterval = setInterval(() => {
134
- if (authWindow && authWindow.closed) {
135
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
136
- }
137
- }, 2000); // Reduced polling frequency
428
+ // Main authentication flow execution
138
429
  try {
139
- window.addEventListener("message", listener);
430
+ // Open popup window
431
+ const { left, top } = getPopupPosition(windowWidth, windowHeight);
432
+ const secureWindowName = generateSecureWindowName();
433
+ Logger.debug("Opening popup window", {
434
+ width: windowWidth,
435
+ height: windowHeight,
436
+ left,
437
+ top,
438
+ });
439
+ authWindow = window.open(validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`);
440
+ // Check for popup blocking
441
+ if (!authWindow) {
442
+ Logger.error("Popup window blocked or failed to open");
443
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
444
+ return;
445
+ }
446
+ // Check for immediate closure (aggressive popup blockers)
447
+ if (isWindowClosed(authWindow)) {
448
+ Logger.error("Popup immediately closed by blocker");
449
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
450
+ return;
451
+ }
452
+ Logger.debug("Popup window opened successfully");
453
+ // Set up message listener
454
+ removeMessageListener = addMessageListener(handleMessage);
455
+ Logger.debug("Message listener attached");
456
+ // Set up timeouts
457
+ Logger.debug("Setting authentication timeout", { authTimeout });
458
+ authTimeoutId = NativeFunctions.setTimeout(() => {
459
+ Logger.warn("Authentication timeout reached", { authTimeout });
460
+ cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication process exceeded time limit of ${authTimeout}ms`));
461
+ }, authTimeout);
462
+ resetIdleTimeout();
463
+ setupClosureDetection();
464
+ // Focus popup for better UX
465
+ try {
466
+ authWindow.focus();
467
+ }
468
+ catch (error) {
469
+ Logger.debug("Could not focus popup window (cross-origin restriction)");
470
+ }
140
471
  }
141
472
  catch (error) {
473
+ Logger.error("Failed to initialize authentication popup", {
474
+ error: error instanceof Error ? error.message : "Unknown error"
475
+ });
142
476
  cleanup();
143
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " + (error instanceof Error ? error.message : "Unknown error")));
144
- return;
477
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
478
+ (error instanceof Error ? error.message : "Unknown error")));
145
479
  }
146
480
  });
147
481
  }
148
482
 
149
- class TokenManager {
150
- constructor(storage = sessionStorage, storageKey = "cams_token") {
151
- this.storage = storage;
152
- this.token = null;
153
- this.storageKey = storageKey;
483
+ class CAMSSessionManager {
484
+ storage;
485
+ keyPrefix;
486
+ events;
487
+ token = null;
488
+ profile = null;
489
+ constructor(storage = null, keyPrefix, events = {}) {
490
+ this.storage = storage || getDefaultStorage();
491
+ this.keyPrefix = keyPrefix ?? "CAMS-SDK";
492
+ this.events = events;
154
493
  }
155
- setToken(token) {
156
- const parsed = TokenSchema.parse(token);
157
- this.token = parsed;
158
- this.storage.setItem(this.storageKey, JSON.stringify(parsed));
494
+ setItem(key, value) {
495
+ this.storage.setItem(`${this.keyPrefix}:${key}`, value);
159
496
  }
160
- loadToken() {
161
- if (this.token)
162
- return this.token;
163
- const raw = this.storage.getItem(this.storageKey);
164
- if (!raw)
165
- return null;
166
- try {
167
- const parsed = JSON.parse(raw);
168
- try {
169
- this.token = TokenSchema.parse(parsed);
170
- return this.token;
171
- }
172
- catch (validationError) {
173
- console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
174
- this.storage.removeItem(this.storageKey);
175
- return null;
176
- }
177
- }
178
- catch (parseError) {
179
- console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
180
- this.storage.removeItem(this.storageKey);
181
- return null;
182
- }
497
+ getItem(key) {
498
+ return this.storage.getItem(`${this.keyPrefix}:${key}`);
183
499
  }
184
- clearToken() {
185
- this.token = null;
186
- this.storage.removeItem(this.storageKey);
500
+ removeItem(key) {
501
+ this.storage.removeItem(`${this.keyPrefix}:${key}`);
187
502
  }
188
- getAccessToken() {
189
- var _a;
190
- const token = this.loadToken();
191
- return (_a = token === null || token === void 0 ? void 0 : token.access_token) !== null && _a !== void 0 ? _a : null;
192
- }
193
- isExpired() {
194
- const token = this.loadToken();
195
- if (!token)
196
- return true;
197
- // JWT expiration check if available
198
- if (token.id_token) {
199
- try {
200
- const parts = token.id_token.split(".");
201
- if (parts.length < 3)
202
- return true; // Invalid JWT format
203
- const payload = JSON.parse(atob(parts[1]));
204
- const exp = payload.exp * 1000;
205
- return Date.now() > exp;
503
+ clear() {
504
+ // clear only CAMS-prefixed items
505
+ Object.keys(this.storage).forEach((k) => {
506
+ if (k.startsWith(this.keyPrefix)) {
507
+ this.storage.removeItem(k);
206
508
  }
207
- catch (error) {
208
- console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
209
- return true;
210
- }
211
- }
212
- // Fallback: return true for safety when expiration cannot be determined
213
- return true;
214
- }
215
- }
216
-
217
- class CAMSSession {
218
- constructor(storage = sessionStorage, storageKey, events = {}) {
219
- this.tokenManager = new TokenManager(storage, storageKey);
220
- this.events = events;
509
+ });
221
510
  }
222
511
  async login(config) {
223
- var _a, _b, _c, _d, _e, _f, _g;
224
512
  try {
225
- (_b = (_a = this.events).onAuthStart) === null || _b === void 0 ? void 0 : _b.call(_a);
513
+ Logger.info("Session login started");
514
+ // If we're in a popup, don't attempt to open another popup
515
+ if (isPopupWindow()) {
516
+ Logger.warn("Cannot initiate login from popup window");
517
+ throw new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Cannot initiate authentication from within popup window");
518
+ }
519
+ if (this.events.onAuthStart)
520
+ this.events.onAuthStart();
226
521
  let attempts = 0;
227
- const maxAttempts = ((_c = config.retryAttempts) !== null && _c !== void 0 ? _c : 0) + 1;
522
+ const maxAttempts = (config.retryAttempts ?? 0) + 1;
523
+ Logger.debug("Login retry configuration", { maxAttempts });
228
524
  while (attempts < maxAttempts) {
229
525
  try {
526
+ attempts++;
527
+ Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
528
+ // Add exponential backoff delay for retries
529
+ if (attempts > 1) {
530
+ const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
531
+ Logger.debug("Retry delay", { delay });
532
+ await new Promise((resolve) => setTimeout(resolve, delay));
533
+ }
230
534
  const response = await openCAMSPopUpLogin(config);
231
- (_e = (_d = this.events).onAuthSuccess) === null || _e === void 0 ? void 0 : _e.call(_d, response);
535
+ Logger.debug("Login Response", response);
536
+ this.profile = response;
537
+ this.setToken(response.profile.tokens.Bearer);
538
+ Logger.info("Session login successful");
539
+ if (this.events.onAuthSuccess)
540
+ this.events.onAuthSuccess(response);
232
541
  return response;
233
542
  }
234
543
  catch (error) {
235
- attempts++;
544
+ Logger.warn("Login attempt failed", {
545
+ attempt: attempts,
546
+ error: error instanceof Error ? error.message : "Unknown error",
547
+ });
236
548
  if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
237
549
  throw error;
238
550
  }
@@ -240,82 +552,385 @@ class CAMSSession {
240
552
  if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
241
553
  throw error;
242
554
  }
555
+ Logger.info("Retrying login", { nextAttempt: attempts + 1 });
243
556
  }
244
557
  }
245
- throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
558
+ throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
246
559
  }
247
560
  catch (error) {
248
- const camsError = error instanceof CAMSError ? error :
249
- new CAMSError(exports.CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
250
- (_g = (_f = this.events).onAuthError) === null || _g === void 0 ? void 0 : _g.call(_f, camsError);
561
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
562
+ const camsError = error instanceof CAMSError
563
+ ? error
564
+ : new CAMSError(exports.CAMSErrorType.USER_CANCELLED, errorMessage);
565
+ Logger.error("Session login failed", {
566
+ error: camsError.message,
567
+ type: camsError.type,
568
+ });
569
+ if (this.events.onAuthError)
570
+ this.events.onAuthError(camsError);
251
571
  throw camsError;
252
572
  }
253
573
  }
254
574
  async logout() {
255
- this.tokenManager.clearToken();
575
+ Logger.info("Session logout");
576
+ this.clearToken();
256
577
  }
257
- isAuthenticated() {
258
- var _a, _b;
259
- const token = this.tokenManager.loadToken();
578
+ setToken(token) {
579
+ this.token = token;
580
+ this.storage.setItem(this.keyPrefix, token);
581
+ Logger.debug("Token stored", { storageKey: this.keyPrefix });
582
+ }
583
+ getAccessToken() {
584
+ // Return cached token if available, avoiding redundant storage access
585
+ if (this.token)
586
+ return this.token;
587
+ const raw = this.storage.getItem(this.keyPrefix);
588
+ if (!raw)
589
+ return null;
590
+ this.token = raw;
591
+ Logger.debug("Token loaded from storage");
592
+ return this.token;
593
+ }
594
+ clearToken() {
595
+ this.token = null;
596
+ this.storage.removeItem(this.keyPrefix);
597
+ Logger.debug("Token cleared");
598
+ }
599
+ isExpired() {
600
+ const token = this.getAccessToken();
260
601
  if (!token)
602
+ return true;
603
+ try {
604
+ const parts = token.split(".");
605
+ if (parts.length < 3)
606
+ return true; // Invalid JWT format
607
+ const payload = JSON.parse(atob(parts[1]));
608
+ if (typeof payload.exp !== "number")
609
+ return true;
610
+ const exp = payload.exp * 1000;
611
+ return Date.now() > exp;
612
+ }
613
+ catch (error) {
614
+ Logger.warn("Failed to parse JWT token", {
615
+ error: error instanceof Error ? error.message : "Unknown error",
616
+ });
617
+ return true;
618
+ }
619
+ }
620
+ isPaddedExpired() {
621
+ const token = this.getAccessToken();
622
+ if (!token)
623
+ return true;
624
+ try {
625
+ const parts = token.split(".");
626
+ if (parts.length < 3)
627
+ return true; // Invalid JWT format
628
+ const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
629
+ const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
630
+ const payload = JSON.parse(atob(padded));
631
+ if (typeof payload.exp !== "number")
632
+ return true;
633
+ const exp = payload.exp * 1000;
634
+ return Date.now() > exp;
635
+ }
636
+ catch (error) {
637
+ Logger.warn("Failed to parse JWT token", {
638
+ error: error instanceof Error ? error.message : "Unknown error",
639
+ });
640
+ return true;
641
+ }
642
+ }
643
+ checkTokenExpiration() {
644
+ if (this.isExpired()) {
645
+ Logger.info("Token expired");
646
+ if (this.events.onTokenExpired)
647
+ this.events.onTokenExpired();
648
+ return true;
649
+ }
650
+ return false;
651
+ }
652
+ isAuthenticated() {
653
+ const token = this.getAccessToken();
654
+ if (!token) {
655
+ Logger.debug("No Token Found");
261
656
  return false;
262
- if (this.tokenManager.isExpired()) {
263
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
657
+ }
658
+ if (this.checkTokenExpiration()) {
264
659
  return false;
265
660
  }
661
+ Logger.debug("Token is valid");
266
662
  return true;
267
663
  }
268
- getAccessToken() {
269
- var _a, _b;
270
- const token = this.tokenManager.loadToken();
271
- if (!token)
664
+ async getProfile() {
665
+ const storedToken = this.getAccessToken();
666
+ if (!storedToken)
272
667
  return null;
273
- if (this.tokenManager.isExpired()) {
274
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
668
+ // Check token expiration before processing
669
+ if (this.checkTokenExpiration()) {
275
670
  return null;
276
671
  }
277
- return token.access_token;
672
+ return this.profile;
278
673
  }
279
- decodeBase64Url(str) {
280
- // Convert base64url to base64
281
- str = str.replace(/-/g, '+').replace(/_/g, '/');
282
- // Add padding if needed
283
- while (str.length % 4) {
284
- str += '=';
674
+ getSessionError() {
675
+ return null;
676
+ }
677
+ /**
678
+ * Complete authentication in popup window
679
+ * This should be called by popup apps when authentication is successful
680
+ */
681
+ completePopupAuth(user, targetOrigin) {
682
+ if (!isPopupWindow()) {
683
+ Logger.warn("completePopupAuth called outside of popup window");
684
+ return;
685
+ }
686
+ try {
687
+ // Store the authentication data locally in the popup
688
+ this.profile = user;
689
+ this.setToken(user.profile.tokens.Bearer);
690
+ Logger.info("Authentication completed in popup, forwarding to parent");
691
+ }
692
+ catch (error) {
693
+ Logger.error("Failed to complete popup authentication", {
694
+ error: error instanceof Error ? error.message : "Unknown error"
695
+ });
285
696
  }
286
- return atob(str);
287
697
  }
288
- async getProfile() {
289
- const storedToken = this.tokenManager.loadToken();
290
- if (!(storedToken === null || storedToken === void 0 ? void 0 : storedToken.id_token))
291
- return null;
698
+ /**
699
+ * Report authentication error in popup window
700
+ */
701
+ errorPopupAuth(error, targetOrigin) {
702
+ if (!isPopupWindow()) {
703
+ Logger.warn("errorPopupAuth called outside of popup window");
704
+ return;
705
+ }
706
+ Logger.warn("Reporting authentication error from popup");
707
+ }
708
+ }
709
+ // 🔹 Safe fallback for Node/SSR
710
+ function getDefaultStorage() {
711
+ if (typeof window !== "undefined" && window.localStorage) {
712
+ return window.localStorage;
713
+ }
714
+ const memoryStore = {};
715
+ return {
716
+ getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
717
+ setItem: (key, value) => {
718
+ memoryStore[key] = value;
719
+ },
720
+ removeItem: (key) => {
721
+ delete memoryStore[key];
722
+ },
723
+ key: (i) => Object.keys(memoryStore)[i] ?? null,
724
+ get length() {
725
+ return Object.keys(memoryStore).length;
726
+ },
727
+ };
728
+ }
729
+
730
+ // Function to parse userAgent and generate a device ID
731
+ const GenerateDeviceId = () => {
732
+ if (typeof window === "undefined" || !window.navigator) {
733
+ return "unknown-device";
734
+ }
735
+ const userAgent = window.navigator.userAgent;
736
+ let deviceId = "";
737
+ // Parse browser, version, OS, and device type
738
+ const browserMatch = Array.from(userAgent.matchAll(/(Chrome|Firefox|Safari|Edge|Opera)\/([\d.]+)/gi));
739
+ const osMatch = Array.from(userAgent.matchAll(/\(([^)]+)\)/g));
740
+ const isMobile = /Mobile|Android|iPhone|iPad/i.test(userAgent);
741
+ // Browser info
742
+ if (browserMatch.length > 0) {
743
+ const [, browserName, browserVersion] = browserMatch[0];
744
+ const majorVersion = browserVersion.split(".")[0];
745
+ deviceId += `${browserName}-${majorVersion}`;
746
+ }
747
+ else {
748
+ deviceId += "UnknownBrowser";
749
+ }
750
+ // OS info
751
+ if (osMatch.length > 0) {
752
+ const osInfo = osMatch[0][1]
753
+ .split(";")[0]
754
+ .trim()
755
+ .replace(/[\s/()]/g, "_");
756
+ deviceId += `_${osInfo}`;
757
+ }
758
+ else {
759
+ deviceId += "_UnknownOS";
760
+ }
761
+ // Device type
762
+ deviceId += isMobile ? "_Mobile" : "_Desktop";
763
+ // Add a simple hash of userAgent for uniqueness
764
+ const hash = btoa(userAgent).slice(0, 8);
765
+ deviceId += `_${hash}`;
766
+ return deviceId.replace(/[^a-zA-Z0-9-_]/g, "_") ?? "unknown-device";
767
+ };
768
+ const APIHeaders = {
769
+ "X-DEVICE-ID": GenerateDeviceId(),
770
+ "X-API-VERSION": "1.0",
771
+ };
772
+
773
+ // Creates an Axios instance with a base URL determined by the environment (production or development).
774
+ const axiosInstance = axios.create({
775
+ httpsAgent: new https.Agent({ rejectUnauthorized: false }),
776
+ headers: {
777
+ "Content-Type": "application/json",
778
+ ...APIHeaders,
779
+ },
780
+ });
781
+ // Intercepts outgoing requests to add authorization token, version header, and timeout settings.
782
+ axiosInstance.interceptors.request.use((config) => {
783
+ config.timeout = Number(process.env.NEXT_PUBLIC_API_TIMEOUT ?? 605000);
784
+ config.timeoutErrorMessage = "Operation Timed Out"; // Custom error message for timeouts.
785
+ return config; // Returns the modified request configuration.
786
+ }, (axiosError) => {
787
+ // Handles request errors.
788
+ return {
789
+ status: axiosError.response?.status, // Extracts HTTP status from the error response.
790
+ message: axiosError.message, // Extracts the error message.
791
+ data: axiosError.response?.data, // Extracts response data from the error.
792
+ };
793
+ });
794
+
795
+ class CAMSMFAAuthenticator {
796
+ attemptCount = 0;
797
+ maxAttempts = 3;
798
+ async GetUserMFAConfig(config) {
292
799
  try {
293
- const parts = storedToken.id_token.split('.');
294
- if (parts.length >= 3) { // JWT has header.payload.signature format
295
- try {
296
- const payload = JSON.parse(this.decodeBase64Url(parts[1]));
297
- return ProfileSchema.parse(payload);
298
- }
299
- catch (decodeError) {
300
- console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');
301
- }
800
+ const response = await axiosInstance.post(config.APIAuthEndpoint, {
801
+ provider: config.provider,
802
+ accessToken: config.accessToken,
803
+ idToken: config.idToken,
804
+ });
805
+ Logger.debug("GetUserMFAConfig Response", response);
806
+ return response.data;
807
+ }
808
+ catch (error) {
809
+ Logger.error("GetUserMFAConfig failed", error);
810
+ if (error.code === 'ERR_NETWORK' || error.code === 'ECONNREFUSED') {
811
+ throw new CAMSError(exports.CAMSErrorType.NETWORK_ERROR, `Cannot connect to authentication server at ${config.APIAuthEndpoint}. Please ensure the server is running.`);
812
+ }
813
+ throw new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `Failed to retrieve MFA configuration: ${error.message || 'Unknown error'}`);
814
+ }
815
+ }
816
+ async VerifyMFAOTP(ValidateRequest, MFAEndpoint) {
817
+ if (this.attemptCount >= this.maxAttempts) {
818
+ throw new CAMSError(exports.CAMSErrorType.MAX_RETRIES_EXCEEDED, "Maximum MFA attempts exceeded");
819
+ }
820
+ this.attemptCount++;
821
+ try {
822
+ Logger.debug("Verifying User MFA Code", { attempt: this.attemptCount });
823
+ const response = await axiosInstance.post(MFAEndpoint, ValidateRequest);
824
+ if (response.status != 200) {
825
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
826
+ }
827
+ const data = response.data;
828
+ console.log("MFA Response >>>", data);
829
+ if (data.isValid) {
830
+ Logger.info("MFA verification successful");
831
+ this.ResetUserAttempts();
832
+ return data;
833
+ }
834
+ else {
835
+ throw new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, "User Verification failed");
302
836
  }
303
837
  }
304
838
  catch (error) {
305
- console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');
839
+ Logger.error("MFA verification failed", {
840
+ error,
841
+ attempt: this.attemptCount,
842
+ });
843
+ if (error instanceof CAMSError) {
844
+ throw error;
845
+ }
846
+ if (error.code === 'ERR_NETWORK' || error.code === 'ECONNREFUSED') {
847
+ throw new CAMSError(exports.CAMSErrorType.NETWORK_ERROR, `Cannot connect to MFA server at ${MFAEndpoint}. Please ensure the server is running.`);
848
+ }
849
+ throw new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `MFA verification failed: ${error instanceof Error ? error.message : "Unknown error"}`);
306
850
  }
307
- return null;
851
+ }
852
+ async LoginADCredentials(credentials, CredentialsAuthEndpoint) {
853
+ try {
854
+ const response = await axiosInstance.post(CredentialsAuthEndpoint, credentials);
855
+ credentials.password = ""; // Clear password after use
856
+ Logger.debug("LoginADCredentials Response", response);
857
+ return response.data;
858
+ }
859
+ catch (error) {
860
+ credentials.password = ""; // Clear password even on error
861
+ Logger.error("LoginADCredentials failed", error);
862
+ if (error.code === 'ERR_NETWORK' || error.code === 'ECONNREFUSED') {
863
+ throw new CAMSError(exports.CAMSErrorType.NETWORK_ERROR, `Cannot connect to authentication server at ${CredentialsAuthEndpoint}. Please ensure the server is running.`);
864
+ }
865
+ throw new CAMSError(exports.CAMSErrorType.API_VALIDATION_ERROR, `AD login failed: ${error.message || 'Unknown error'}`);
866
+ }
867
+ }
868
+ async HandleFIDOLogin(RetrieveAuthChallengeEndpoint, AuthChallengeVerifyEndpoint, authenticate) {
869
+ try {
870
+ // 1. Fetch authentication challenge from your server
871
+ console.log("Requesting authentication challenge from server...");
872
+ const { data: options } = await axiosInstance.post(RetrieveAuthChallengeEndpoint, {});
873
+ console.log("Received challenge:", options);
874
+ // 2. Call the SDK to trigger the browser's passkey authentication UI
875
+ console.log("Calling SDK authenticate function...");
876
+ const assertionResponse = await authenticate({
877
+ ...options,
878
+ userVerification: "discouraged",
879
+ });
880
+ console.log("Authentication assertion received from client:", assertionResponse);
881
+ // 3. Send the assertion back to the server for verification
882
+ console.log("Sending assertion to server for verification...");
883
+ await axiosInstance.post(AuthChallengeVerifyEndpoint, assertionResponse);
884
+ return true;
885
+ }
886
+ catch (error) {
887
+ console.error("Authentication failed:", error);
888
+ // toast.error("❌ Could not sign in.");
889
+ return false;
890
+ }
891
+ }
892
+ async HandleRegister(RegisterNewChallengeEndpoint, RegisterVerify, register, data) {
893
+ try {
894
+ // 1. Fetch challenge from your server
895
+ console.log("Requesting registration challenge from server...");
896
+ const { data: options } = await axiosInstance.post(RegisterNewChallengeEndpoint, { ...data });
897
+ console.log("Received challenge:", options);
898
+ // 2. Call the SDK to trigger the browser's passkey creation UI
899
+ console.log("Calling SDK register function...");
900
+ const attestationResponse = await register(options);
901
+ console.log("Passkey created on client:", attestationResponse);
902
+ // 3. Send the response back to the server for verification
903
+ console.log("Sending attestation to server for verification...");
904
+ await axiosInstance.post(RegisterVerify + `?username=${data.username}`, attestationResponse);
905
+ // toast.success("✅ Registration successful! Passkey created.");
906
+ return true;
907
+ }
908
+ catch (error) {
909
+ console.error("Registration failed:", error);
910
+ // toast.error("❌ Could not create passkey.");
911
+ return false;
912
+ }
913
+ }
914
+ GetRemainingAttempts() {
915
+ return Math.max(0, this.maxAttempts - this.attemptCount);
916
+ }
917
+ ResetUserAttempts() {
918
+ this.attemptCount = 0;
308
919
  }
309
920
  }
310
921
 
922
+ exports.APIHeaders = APIHeaders;
923
+ exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
311
924
  exports.CAMSError = CAMSError;
312
- exports.CAMSSession = CAMSSession;
925
+ exports.CAMSMFAAuthenticator = CAMSMFAAuthenticator;
926
+ exports.CAMSSessionManager = CAMSSessionManager;
313
927
  exports.ErrorMessageSchema = ErrorMessageSchema;
928
+ exports.Logger = Logger;
314
929
  exports.ProfileSchema = ProfileSchema;
315
- exports.TokenManager = TokenManager;
316
- exports.TokenMessageSchema = TokenMessageSchema;
317
- exports.TokenSchema = TokenSchema;
318
930
  exports.URLSchema = URLSchema;
931
+ exports.axiosInstance = axiosInstance;
932
+ exports.generateSecureWindowName = generateSecureWindowName;
933
+ exports.isPopupWindow = isPopupWindow;
319
934
  exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
320
935
  exports.validateConfig = validateConfig;
321
936
  //# sourceMappingURL=index.cjs.js.map