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

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