@nibssplc/cams-sdk 0.0.1-beta.9 → 0.0.1-beta.90

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