@nibssplc/cams-sdk 0.0.1-beta.7 → 0.0.1-beta.71

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 from 'axios';
3
+ import https from 'https';
2
4
 
3
5
  var CAMSErrorType;
4
6
  (function (CAMSErrorType) {
@@ -8,229 +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
- var _a;
47
- // Validate URL format
48
220
  const urlValidation = URLSchema.safeParse(config.camsUrl);
49
221
  if (!urlValidation.success) {
50
- throw new CAMSError(CAMSErrorType.INVALID_URL, 'Invalid CAMS URL format');
51
- }
52
- // Domain validation is mandatory for security
53
- if (!((_a = config.allowedDomains) === null || _a === void 0 ? void 0 : _a.length)) {
54
- throw new CAMSError(CAMSErrorType.INVALID_URL, 'allowedDomains must be specified for security');
222
+ throw new CAMSError(CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
55
223
  }
56
- const url = new URL(config.camsUrl); // URLSchema already validated this
57
- const isAllowed = config.allowedDomains.some(domain => url.hostname === domain || url.hostname.endsWith('.' + domain));
58
- if (!isAllowed) {
59
- 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");
60
226
  }
227
+ return new URL(config.camsUrl);
61
228
  }
229
+ /**
230
+ * Open CAMS authentication popup and handle the authentication flow
231
+ */
62
232
  function openCAMSPopUpLogin(config) {
63
233
  return new Promise((resolve, reject) => {
64
- try {
65
- 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;
66
238
  }
67
- catch (error) {
68
- 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"));
69
242
  return;
70
243
  }
71
- const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;
72
- let authWindow;
73
- let timeoutId = null;
74
- 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;
75
250
  try {
76
- authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
251
+ validatedUrl = validateConfig(config);
252
+ Logger.debug("Configuration validation passed");
77
253
  }
78
254
  catch (error) {
79
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to open authentication window: " + (error instanceof Error ? error.message : "Unknown error")));
80
- return;
81
- }
82
- if (!authWindow) {
83
- 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);
84
259
  return;
85
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
+ */
86
273
  const cleanup = () => {
87
- window.removeEventListener("message", listener);
88
- if (timeoutId)
89
- 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);
90
282
  if (checkClosedInterval)
91
- clearInterval(checkClosedInterval);
283
+ NativeFunctions.clearTimeout(checkClosedInterval);
284
+ idleTimeoutId = null;
285
+ authTimeoutId = null;
286
+ checkClosedInterval = null;
92
287
  };
288
+ /**
289
+ * Clean up and close the popup window, then reject with error
290
+ */
93
291
  const cleanupAndClose = (error) => {
94
292
  cleanup();
95
- try {
96
- if (authWindow && !authWindow.closed) {
97
- 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;
98
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;
99
361
  }
100
- catch {
101
- // 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;
102
371
  }
103
- if (error)
104
- reject(error);
105
- };
106
- const listener = (event) => {
107
- if (event.origin !== allowedOrigin) {
108
- // Sanitize origin for logging to prevent log injection
109
- const sanitizedOrigin = event.origin.replace(/[\r\n]/g, '');
110
- 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();
111
378
  return;
112
379
  }
113
- // ✅ Validate payload
114
- const tokenMsg = TokenMessageSchema.safeParse(event.data);
115
- 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");
116
391
  cleanupAndClose();
117
- resolve({ token: tokenMsg.data.access_token });
392
+ resolve(profileValidation.data);
393
+ return;
394
+ }
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})` : ''}`));
118
405
  return;
119
406
  }
120
- const errorMsg = ErrorMessageSchema.safeParse(event.data);
121
- if (errorMsg.success) {
122
- cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
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}`));
123
414
  return;
124
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
+ });
125
424
  cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
126
425
  };
127
- // Timeout handler
128
- timeoutId = setTimeout(() => {
129
- cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timeout after ${timeout}ms`));
130
- }, timeout);
131
- checkClosedInterval = setInterval(() => {
132
- if (authWindow && authWindow.closed) {
133
- cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
134
- }
135
- }, 2000); // Reduced polling frequency
426
+ // Main authentication flow execution
136
427
  try {
137
- 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
+ }
138
469
  }
139
470
  catch (error) {
471
+ Logger.error("Failed to initialize authentication popup", {
472
+ error: error instanceof Error ? error.message : "Unknown error"
473
+ });
140
474
  cleanup();
141
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " + (error instanceof Error ? error.message : "Unknown error")));
142
- return;
475
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
476
+ (error instanceof Error ? error.message : "Unknown error")));
143
477
  }
144
478
  });
145
479
  }
146
480
 
147
- class TokenManager {
148
- constructor(storage = sessionStorage, storageKey = "cams_token") {
149
- this.storage = storage;
150
- this.token = null;
151
- this.storageKey = storageKey;
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;
152
491
  }
153
- setToken(token) {
154
- const parsed = TokenSchema.parse(token);
155
- this.token = parsed;
156
- this.storage.setItem(this.storageKey, JSON.stringify(parsed));
492
+ setItem(key, value) {
493
+ this.storage.setItem(`${this.keyPrefix}:${key}`, value);
157
494
  }
158
- loadToken() {
159
- if (this.token)
160
- return this.token;
161
- const raw = this.storage.getItem(this.storageKey);
162
- if (!raw)
163
- return null;
164
- try {
165
- const parsed = JSON.parse(raw);
166
- try {
167
- this.token = TokenSchema.parse(parsed);
168
- return this.token;
169
- }
170
- catch (validationError) {
171
- console.warn('Token validation failed:', validationError instanceof Error ? validationError.message : 'Unknown error');
172
- this.storage.removeItem(this.storageKey);
173
- return null;
174
- }
175
- }
176
- catch (parseError) {
177
- console.warn('Failed to parse stored token JSON:', parseError instanceof Error ? parseError.message : 'Unknown error');
178
- this.storage.removeItem(this.storageKey);
179
- return null;
180
- }
495
+ getItem(key) {
496
+ return this.storage.getItem(`${this.keyPrefix}:${key}`);
181
497
  }
182
- clearToken() {
183
- this.token = null;
184
- this.storage.removeItem(this.storageKey);
498
+ removeItem(key) {
499
+ this.storage.removeItem(`${this.keyPrefix}:${key}`);
185
500
  }
186
- getAccessToken() {
187
- var _a;
188
- const token = this.loadToken();
189
- return (_a = token === null || token === void 0 ? void 0 : token.access_token) !== null && _a !== void 0 ? _a : null;
190
- }
191
- isExpired() {
192
- const token = this.loadToken();
193
- if (!token)
194
- return true;
195
- // JWT expiration check if available
196
- if (token.id_token) {
197
- try {
198
- const parts = token.id_token.split(".");
199
- if (parts.length < 3)
200
- return true; // Invalid JWT format
201
- const payload = JSON.parse(atob(parts[1]));
202
- const exp = payload.exp * 1000;
203
- return Date.now() > exp;
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);
204
506
  }
205
- catch (error) {
206
- console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
207
- return true;
208
- }
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
- var _a, _b, _c, _d, _e, _f, _g;
222
510
  try {
223
- (_b = (_a = this.events).onAuthStart) === null || _b === void 0 ? void 0 : _b.call(_a);
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();
224
519
  let attempts = 0;
225
- const maxAttempts = ((_c = config.retryAttempts) !== null && _c !== void 0 ? _c : 0) + 1;
520
+ const maxAttempts = (config.retryAttempts ?? 0) + 1;
521
+ Logger.debug("Login retry configuration", { maxAttempts });
226
522
  while (attempts < maxAttempts) {
227
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
+ }
228
532
  const response = await openCAMSPopUpLogin(config);
229
- (_e = (_d = this.events).onAuthSuccess) === null || _e === void 0 ? void 0 : _e.call(_d, 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);
230
539
  return response;
231
540
  }
232
541
  catch (error) {
233
- attempts++;
542
+ Logger.warn("Login attempt failed", {
543
+ attempt: attempts,
544
+ error: error instanceof Error ? error.message : "Unknown error",
545
+ });
234
546
  if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
235
547
  throw error;
236
548
  }
@@ -238,73 +550,372 @@ class CAMSSession {
238
550
  if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
239
551
  throw error;
240
552
  }
553
+ Logger.info("Retrying login", { nextAttempt: attempts + 1 });
241
554
  }
242
555
  }
243
- throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
556
+ throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
244
557
  }
245
558
  catch (error) {
246
- const camsError = error instanceof CAMSError ? error :
247
- new CAMSError(CAMSErrorType.USER_CANCELLED, error instanceof Error ? error.message : 'Unknown error');
248
- (_g = (_f = this.events).onAuthError) === null || _g === void 0 ? void 0 : _g.call(_f, 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);
249
569
  throw camsError;
250
570
  }
251
571
  }
252
572
  async logout() {
253
- this.tokenManager.clearToken();
573
+ Logger.info("Session logout");
574
+ this.clearToken();
254
575
  }
255
- isAuthenticated() {
256
- var _a, _b;
257
- 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();
258
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();
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");
259
654
  return false;
260
- if (this.tokenManager.isExpired()) {
261
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
655
+ }
656
+ if (this.checkTokenExpiration()) {
262
657
  return false;
263
658
  }
659
+ Logger.debug("Token is valid");
264
660
  return true;
265
661
  }
266
- getAccessToken() {
267
- var _a, _b;
268
- const token = this.tokenManager.loadToken();
269
- if (!token)
662
+ async getProfile() {
663
+ const storedToken = this.getAccessToken();
664
+ if (!storedToken)
270
665
  return null;
271
- if (this.tokenManager.isExpired()) {
272
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
666
+ // Check token expiration before processing
667
+ if (this.checkTokenExpiration()) {
273
668
  return null;
274
669
  }
275
- return token.access_token;
670
+ return this.profile;
276
671
  }
277
- decodeBase64Url(str) {
278
- // Convert base64url to base64
279
- str = str.replace(/-/g, '+').replace(/_/g, '/');
280
- // Add padding if needed
281
- while (str.length % 4) {
282
- str += '=';
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
+ });
283
694
  }
284
- return atob(str);
285
695
  }
286
- async getProfile() {
287
- const storedToken = this.tokenManager.loadToken();
288
- if (!(storedToken === null || storedToken === void 0 ? void 0 : storedToken.id_token))
289
- return null;
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;
703
+ }
704
+ Logger.warn("Reporting authentication error from popup");
705
+ }
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
+ config.timeout = Number(process.env.NEXT_PUBLIC_API_TIMEOUT ?? 605000);
782
+ config.timeoutErrorMessage = "Operation Timed Out"; // Custom error message for timeouts.
783
+ return config; // Returns the modified request configuration.
784
+ }, (axiosError) => {
785
+ // Handles request errors.
786
+ return {
787
+ status: axiosError.response?.status, // Extracts HTTP status from the error response.
788
+ message: axiosError.message, // Extracts the error message.
789
+ data: axiosError.response?.data, // Extracts response data from the error.
790
+ };
791
+ });
792
+
793
+ class CAMSMFAAuthenticator {
794
+ attemptCount = 0;
795
+ maxAttempts = 3;
796
+ async GetUserMFAConfig(config) {
290
797
  try {
291
- const parts = storedToken.id_token.split('.');
292
- if (parts.length >= 3) { // JWT has header.payload.signature format
293
- try {
294
- const payload = JSON.parse(this.decodeBase64Url(parts[1]));
295
- return ProfileSchema.parse(payload);
296
- }
297
- catch (decodeError) {
298
- console.warn('Failed to decode JWT payload:', decodeError instanceof Error ? decodeError.message : 'Unknown error');
299
- }
798
+ const response = await axiosInstance.post(config.APIAuthEndpoint, {
799
+ provider: config.provider,
800
+ accessToken: config.accessToken,
801
+ idToken: config.idToken,
802
+ });
803
+ Logger.debug("GetUserMFAConfig Response", response);
804
+ return response.data;
805
+ }
806
+ catch (error) {
807
+ Logger.error("GetUserMFAConfig failed", error);
808
+ if (error.code === 'ERR_NETWORK' || error.code === 'ECONNREFUSED') {
809
+ throw new CAMSError(CAMSErrorType.NETWORK_ERROR, `Cannot connect to authentication server at ${config.APIAuthEndpoint}. Please ensure the server is running.`);
810
+ }
811
+ throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `Failed to retrieve MFA configuration: ${error.message || 'Unknown error'}`);
812
+ }
813
+ }
814
+ async VerifyMFAOTP(ValidateRequest, MFAEndpoint) {
815
+ if (this.attemptCount >= this.maxAttempts) {
816
+ throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Maximum MFA attempts exceeded");
817
+ }
818
+ this.attemptCount++;
819
+ try {
820
+ Logger.debug("Verifying User MFA Code", { attempt: this.attemptCount });
821
+ const response = await axiosInstance.post(MFAEndpoint, ValidateRequest);
822
+ if (response.status != 200) {
823
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
824
+ }
825
+ const data = response.data;
826
+ console.log("MFA Response >>>", data);
827
+ if (data.isValid) {
828
+ Logger.info("MFA verification successful");
829
+ this.ResetUserAttempts();
830
+ return data;
831
+ }
832
+ else {
833
+ throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "User Verification failed");
300
834
  }
301
835
  }
302
836
  catch (error) {
303
- console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');
837
+ Logger.error("MFA verification failed", {
838
+ error,
839
+ attempt: this.attemptCount,
840
+ });
841
+ if (error instanceof CAMSError) {
842
+ throw error;
843
+ }
844
+ if (error.code === 'ERR_NETWORK' || error.code === 'ECONNREFUSED') {
845
+ throw new CAMSError(CAMSErrorType.NETWORK_ERROR, `Cannot connect to MFA server at ${MFAEndpoint}. Please ensure the server is running.`);
846
+ }
847
+ throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `MFA verification failed: ${error instanceof Error ? error.message : "Unknown error"}`);
304
848
  }
305
- return null;
849
+ }
850
+ async LoginADCredentials(credentials, CredentialsAuthEndpoint) {
851
+ try {
852
+ const response = await axiosInstance.post(CredentialsAuthEndpoint, credentials);
853
+ credentials.password = ""; // Clear password after use
854
+ Logger.debug("LoginADCredentials Response", response);
855
+ return response.data;
856
+ }
857
+ catch (error) {
858
+ credentials.password = ""; // Clear password even on error
859
+ Logger.error("LoginADCredentials failed", error);
860
+ if (error.code === 'ERR_NETWORK' || error.code === 'ECONNREFUSED') {
861
+ throw new CAMSError(CAMSErrorType.NETWORK_ERROR, `Cannot connect to authentication server at ${CredentialsAuthEndpoint}. Please ensure the server is running.`);
862
+ }
863
+ throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `AD login failed: ${error.message || 'Unknown error'}`);
864
+ }
865
+ }
866
+ async HandleFIDOLogin(RetrieveAuthChallengeEndpoint, AuthChallengeVerifyEndpoint, authenticate) {
867
+ try {
868
+ // 1. Fetch authentication challenge from your server
869
+ console.log("Requesting authentication challenge from server...");
870
+ const { data: options } = await axiosInstance.post(RetrieveAuthChallengeEndpoint, {});
871
+ console.log("Received challenge:", options);
872
+ // 2. Call the SDK to trigger the browser's passkey authentication UI
873
+ console.log("Calling SDK authenticate function...");
874
+ const assertionResponse = await authenticate({
875
+ ...options,
876
+ userVerification: "discouraged",
877
+ });
878
+ console.log("Authentication assertion received from client:", assertionResponse);
879
+ // 3. Send the assertion back to the server for verification
880
+ console.log("Sending assertion to server for verification...");
881
+ await axiosInstance.post(AuthChallengeVerifyEndpoint, assertionResponse);
882
+ return true;
883
+ }
884
+ catch (error) {
885
+ console.error("Authentication failed:", error);
886
+ // toast.error("❌ Could not sign in.");
887
+ return false;
888
+ }
889
+ }
890
+ async HandleRegister(RegisterNewChallengeEndpoint, RegisterVerify, register, data) {
891
+ try {
892
+ // 1. Fetch challenge from your server
893
+ console.log("Requesting registration challenge from server...");
894
+ const { data: options } = await axiosInstance.post(RegisterNewChallengeEndpoint, { ...data });
895
+ console.log("Received challenge:", options);
896
+ // 2. Call the SDK to trigger the browser's passkey creation UI
897
+ console.log("Calling SDK register function...");
898
+ const attestationResponse = await register(options);
899
+ console.log("Passkey created on client:", attestationResponse);
900
+ // 3. Send the response back to the server for verification
901
+ console.log("Sending attestation to server for verification...");
902
+ await axiosInstance.post(RegisterVerify + `?username=${data.username}`, attestationResponse);
903
+ // toast.success("✅ Registration successful! Passkey created.");
904
+ return true;
905
+ }
906
+ catch (error) {
907
+ console.error("Registration failed:", error);
908
+ // toast.error("❌ Could not create passkey.");
909
+ return false;
910
+ }
911
+ }
912
+ GetRemainingAttempts() {
913
+ return Math.max(0, this.maxAttempts - this.attemptCount);
914
+ }
915
+ ResetUserAttempts() {
916
+ this.attemptCount = 0;
306
917
  }
307
918
  }
308
919
 
309
- export { CAMSError, CAMSErrorType, CAMSSession, ErrorMessageSchema, ProfileSchema, TokenManager, TokenMessageSchema, TokenSchema, URLSchema, openCAMSPopUpLogin, validateConfig };
920
+ export { APIHeaders, AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSMFAAuthenticator, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, URLSchema, axiosInstance, generateSecureWindowName, isPopupWindow, openCAMSPopUpLogin, validateConfig };
310
921
  //# sourceMappingURL=index.esm.js.map