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