@nibssplc/cams-sdk 0.0.1-beta.8 → 0.0.1-beta.82

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