@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.umd.js CHANGED
@@ -1,245 +1,589 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('zod')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'zod'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CAMS = {}, global.zod));
5
- })(this, (function (exports, zod) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('zod'), require('@opentelemetry/api'), require('axios')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'zod', '@opentelemetry/api', 'axios'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.CAMS = {}, global.zod, global.opentelemetry, global.axios));
5
+ })(this, (function (exports, zod, api, axios) { 'use strict';
6
6
 
7
7
  exports.CAMSErrorType = void 0;
8
8
  (function (CAMSErrorType) {
9
9
  CAMSErrorType["POPUP_BLOCKED"] = "POPUP_BLOCKED";
10
10
  CAMSErrorType["TIMEOUT"] = "TIMEOUT";
11
11
  CAMSErrorType["INVALID_ORIGIN"] = "INVALID_ORIGIN";
12
+ CAMSErrorType["API_UNAUTHORIZED_ERROR"] = "UNAUTHORIZED_USER";
12
13
  CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
13
14
  CAMSErrorType["INVALID_URL"] = "INVALID_URL";
14
15
  CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
16
+ CAMSErrorType["API_VALIDATION_ERROR"] = "VALIDATION_ERROR";
17
+ CAMSErrorType["NETWORK_ERROR"] = "NETWORK_ERROR";
15
18
  })(exports.CAMSErrorType || (exports.CAMSErrorType = {}));
16
19
  class CAMSError extends Error {
20
+ type;
17
21
  constructor(type, message) {
18
22
  super(message);
19
23
  this.type = type;
20
- this.name = 'CAMSError';
24
+ this.name = this.constructor.name;
21
25
  }
22
26
  }
23
27
 
24
- // Validate the returned token - Base64 format with minimum 20 chars
25
- const TokenMessageSchema = zod.z.object({
26
- 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(),
27
47
  });
28
48
  const ErrorMessageSchema = zod.z.object({
29
- error: zod.z.string(),
49
+ error: zod.z.string().min(1, "Error message cannot be empty"),
30
50
  });
31
- const TokenSchema = zod.z.object({
32
- access_token: zod.z.string(),
33
- refresh_token: zod.z.string().optional(),
34
- expires_in: zod.z.number(), // in seconds
35
- token_type: zod.z.string().default("Bearer"),
36
- 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()),
37
56
  });
38
- const ProfileSchema = zod.z.object({
39
- sub: zod.z.string(), // user ID
40
- name: zod.z.string().optional(),
41
- email: zod.z.email({ message: "Invalid email address" }).optional(),
42
- given_name: zod.z.string().optional(),
43
- family_name: zod.z.string().optional(),
44
- 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,
45
100
  });
46
- // Matches IPv4 addresses like 192.168.x.x, 10.x.x.x, 172.16–31.x.x
47
- 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+)?$/;
48
- const URLSchema = zod.z.url().refine((url) => url.startsWith("https://") || // normal HTTPS
49
- /^http:\/\/localhost(:\d+)?$/i.test(url) || // localhost
50
- internalIpRegex.test(url), // internal LAN IPs
51
- {
52
- 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,
53
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
+ };
54
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
+ */
55
257
  function validateConfig(config) {
56
- // Validate URL format
57
258
  const urlValidation = URLSchema.safeParse(config.camsUrl);
58
259
  if (!urlValidation.success) {
59
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
260
+ throw new CAMSError(exports.CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
60
261
  }
61
- // Domain validation is mandatory for security
62
- if (!config.allowedDomains?.length) {
63
- throw new CAMSError(exports.CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
64
- }
65
- const url = new URL(config.camsUrl); // URLSchema already validated this
66
- const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
67
- if (!isAllowed) {
68
- 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");
69
264
  }
265
+ return new URL(config.camsUrl);
70
266
  }
267
+ /**
268
+ * Open CAMS authentication popup and handle the authentication flow
269
+ */
71
270
  function openCAMSPopUpLogin(config) {
271
+ return withCAMSSpan("CAMS.Auth.Popup", () => openCAMSPopUpLoginInternal(config));
272
+ }
273
+ function openCAMSPopUpLoginInternal(config) {
72
274
  return new Promise((resolve, reject) => {
73
- try {
74
- 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;
75
279
  }
76
- catch (error) {
77
- 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"));
78
283
  return;
79
284
  }
80
- const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;
81
- let authWindow;
82
- let timeoutId = null;
83
- 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;
84
291
  try {
85
- authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
292
+ validatedUrl = validateConfig(config);
293
+ Logger.debug("Configuration validation passed");
86
294
  }
87
295
  catch (error) {
88
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " + (error instanceof Error ? error.message : "Unknown error")));
89
- return;
90
- }
91
- if (!authWindow) {
92
- 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);
93
300
  return;
94
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
+ */
95
314
  const cleanup = () => {
96
- window.removeEventListener("message", listener);
97
- if (timeoutId)
98
- 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);
99
323
  if (checkClosedInterval)
100
- clearInterval(checkClosedInterval);
324
+ NativeFunctions.clearTimeout(checkClosedInterval);
325
+ idleTimeoutId = null;
326
+ authTimeoutId = null;
327
+ checkClosedInterval = null;
101
328
  };
329
+ /**
330
+ * Clean up and close the popup window, then reject with error
331
+ */
102
332
  const cleanupAndClose = (error) => {
103
333
  cleanup();
104
- try {
105
- if (authWindow && !authWindow.closed) {
106
- 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
+ }
107
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;
108
402
  }
109
- catch {
110
- // 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;
111
412
  }
112
- if (error)
113
- reject(error);
114
- };
115
- const listener = (event) => {
116
- if (event.origin !== allowedOrigin) {
117
- // Sanitize origin for logging to prevent log injection
118
- const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
119
- 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();
120
419
  return;
121
420
  }
122
- // ✅ Validate payload
123
- const tokenMsg = TokenMessageSchema.safeParse(event.data);
124
- 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");
125
432
  cleanupAndClose();
126
- resolve({ token: tokenMsg.data.access_token });
433
+ resolve(profileValidation.data);
127
434
  return;
128
435
  }
129
- const errorMsg = ErrorMessageSchema.safeParse(event.data);
130
- if (errorMsg.success) {
131
- 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})` : ''}`));
132
446
  return;
133
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
+ });
134
465
  cleanupAndClose(new CAMSError(exports.CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
135
466
  };
136
- // Timeout handler
137
- timeoutId = setTimeout(() => {
138
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
139
- }, timeout);
140
- checkClosedInterval = setInterval(() => {
141
- if (authWindow && authWindow.closed) {
142
- cleanupAndClose(new CAMSError(exports.CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
143
- }
144
- }, 2000); // Reduced polling frequency
467
+ // Main authentication flow execution
145
468
  try {
146
- 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
+ }
147
510
  }
148
511
  catch (error) {
512
+ Logger.error("Failed to initialize authentication popup", {
513
+ error: error instanceof Error ? error.message : "Unknown error"
514
+ });
149
515
  cleanup();
150
- reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " + (error instanceof Error ? error.message : "Unknown error")));
151
- return;
516
+ reject(new CAMSError(exports.CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
517
+ (error instanceof Error ? error.message : "Unknown error")));
152
518
  }
153
519
  });
154
520
  }
155
521
 
156
- class TokenManager {
157
- constructor(storage = sessionStorage, storageKey) {
158
- this.storage = storage;
159
- this.token = null;
160
- this.storageKey = storageKey || "cams_token";
161
- }
162
- setToken(token) {
163
- const parsed = TokenSchema.parse(token);
164
- this.token = parsed;
165
- 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;
166
532
  }
167
- loadToken() {
168
- if (this.token)
169
- return this.token;
170
- const raw = this.storage.getItem(this.storageKey);
171
- if (!raw)
172
- return null;
173
- try {
174
- const parsed = JSON.parse(raw);
175
- try {
176
- this.token = TokenSchema.parse(parsed);
177
- return this.token;
178
- }
179
- catch (validationError) {
180
- console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
181
- this.storage.removeItem(this.storageKey);
182
- return null;
183
- }
184
- }
185
- catch (parseError) {
186
- console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
187
- this.storage.removeItem(this.storageKey);
188
- return null;
189
- }
533
+ setItem(key, value) {
534
+ this.storage.setItem(`${this.keyPrefix}:${key}`, value);
190
535
  }
191
- clearToken() {
192
- this.token = null;
193
- this.storage.removeItem(this.storageKey);
536
+ getItem(key) {
537
+ return this.storage.getItem(`${this.keyPrefix}:${key}`);
194
538
  }
195
- getAccessToken() {
196
- const token = this.loadToken();
197
- return token ? token.access_token : null;
539
+ removeItem(key) {
540
+ this.storage.removeItem(`${this.keyPrefix}:${key}`);
198
541
  }
199
- isExpired() {
200
- const token = this.loadToken();
201
- if (!token)
202
- return true;
203
- // JWT expiration check if available
204
- if (token.id_token) {
205
- try {
206
- const parts = token.id_token.split(".");
207
- if (parts.length < 3)
208
- return true; // Invalid JWT format
209
- const payload = JSON.parse(atob(parts[1]));
210
- if (typeof payload.exp !== 'number')
211
- return true;
212
- const exp = payload.exp * 1000;
213
- return Date.now() > exp;
214
- }
215
- catch (error) {
216
- console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
217
- 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);
218
547
  }
219
- }
220
- // Fallback: return true for safety when expiration cannot be determined
221
- return true;
222
- }
223
- }
224
-
225
- class CAMSSession {
226
- constructor(storage = sessionStorage, storageKey, events = {}) {
227
- this.tokenManager = new TokenManager(storage, storageKey);
228
- this.events = events;
548
+ });
229
549
  }
230
550
  async login(config) {
231
551
  try {
232
- 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();
233
560
  let attempts = 0;
234
561
  const maxAttempts = (config.retryAttempts ?? 0) + 1;
562
+ Logger.debug("Login retry configuration", { maxAttempts });
235
563
  while (attempts < maxAttempts) {
236
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
+ }
237
573
  const response = await openCAMSPopUpLogin(config);
238
- 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);
239
580
  return response;
240
581
  }
241
582
  catch (error) {
242
- attempts++;
583
+ Logger.warn("Login attempt failed", {
584
+ attempt: attempts,
585
+ error: error instanceof Error ? error.message : "Unknown error",
586
+ });
243
587
  if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
244
588
  throw error;
245
589
  }
@@ -247,81 +591,525 @@
247
591
  if (![exports.CAMSErrorType.TIMEOUT, exports.CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
248
592
  throw error;
249
593
  }
594
+ Logger.info("Retrying login", { nextAttempt: attempts + 1 });
250
595
  }
251
596
  }
252
- 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");
253
598
  }
254
599
  catch (error) {
255
- const camsError = error instanceof CAMSError ? error :
256
- new CAMSError(exports.CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
257
- 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);
258
610
  throw camsError;
259
611
  }
260
612
  }
261
613
  async logout() {
262
- this.tokenManager.clearToken();
614
+ Logger.info("Session logout");
615
+ this.clearToken();
263
616
  }
264
- isAuthenticated() {
265
- 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();
266
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");
267
695
  return false;
268
- if (this.tokenManager.isExpired()) {
269
- this.events.onTokenExpired?.();
696
+ }
697
+ if (this.checkTokenExpiration()) {
270
698
  return false;
271
699
  }
700
+ Logger.debug("Token is valid");
272
701
  return true;
273
702
  }
274
- getAccessToken() {
275
- const token = this.tokenManager.loadToken();
276
- if (!token)
703
+ async getProfile() {
704
+ const storedToken = this.getAccessToken();
705
+ if (!storedToken)
277
706
  return null;
278
- if (this.tokenManager.isExpired()) {
279
- this.events.onTokenExpired?.();
707
+ // Check token expiration before processing
708
+ if (this.checkTokenExpiration()) {
280
709
  return null;
281
710
  }
282
- return token.access_token;
711
+ return this.profile;
712
+ }
713
+ getSessionError() {
714
+ return null;
283
715
  }
284
- decodeBase64Url(str) {
285
- // Convert base64url to base64
286
- str = str.replace(/-/g, '+').replace(/_/g, '/');
287
- // Add padding if needed
288
- while (str.length % 4) {
289
- 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
+ });
290
735
  }
291
- return atob(str);
292
736
  }
293
- async getProfile() {
294
- const storedToken = this.tokenManager.loadToken();
295
- if (!storedToken || !storedToken.id_token)
296
- 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) {
297
939
  try {
298
- const parts = storedToken.id_token.split('.');
299
- if (parts.length >= 3) { // JWT has header.payload.signature format
300
- try {
301
- const payload = JSON.parse(this.decodeBase64Url(parts[1]));
302
- return ProfileSchema.parse(payload);
303
- }
304
- catch (decodeError) {
305
- console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');
306
- }
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");
307
978
  }
308
979
  }
309
980
  catch (error) {
310
- 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"}`);
311
1002
  }
312
- 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;
313
1091
  }
314
1092
  }
315
1093
 
1094
+ exports.APIHeaders = APIHeaders;
1095
+ exports.AuthFailureMessageSchema = AuthFailureMessageSchema;
316
1096
  exports.CAMSError = CAMSError;
317
- exports.CAMSSession = CAMSSession;
1097
+ exports.CAMSMFAAuthenticator = CAMSMFAAuthenticator;
1098
+ exports.CAMSSessionManager = CAMSSessionManager;
318
1099
  exports.ErrorMessageSchema = ErrorMessageSchema;
1100
+ exports.Logger = Logger;
319
1101
  exports.ProfileSchema = ProfileSchema;
320
- exports.TokenManager = TokenManager;
321
- exports.TokenMessageSchema = TokenMessageSchema;
322
- exports.TokenSchema = TokenSchema;
323
1102
  exports.URLSchema = URLSchema;
1103
+ exports.axiosInstance = axiosInstance;
1104
+ exports.base64urlToBuffer = base64urlToBuffer;
1105
+ exports.bufferToBase64url = bufferToBase64url;
1106
+ exports.generateSecureWindowName = generateSecureWindowName;
1107
+ exports.isPopupWindow = isPopupWindow;
324
1108
  exports.openCAMSPopUpLogin = openCAMSPopUpLogin;
1109
+ exports.prepareAssertionOptions = prepareAssertionOptions;
1110
+ exports.prepareRegistrationOptions = prepareRegistrationOptions;
1111
+ exports.serializeAssertion = serializeAssertion;
1112
+ exports.serializeAttestation = serializeAttestation;
325
1113
  exports.validateConfig = validateConfig;
326
1114
 
327
1115
  }));