@nibssplc/cams-sdk 0.0.1-beta.4 → 0.0.1-beta.40

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
@@ -8,229 +8,547 @@ var CAMSErrorType;
8
8
  CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
9
9
  CAMSErrorType["INVALID_URL"] = "INVALID_URL";
10
10
  CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
11
+ CAMSErrorType["API_VALIDATION_ERROR"] = "VALIDATION_ERROR";
11
12
  })(CAMSErrorType || (CAMSErrorType = {}));
12
13
  class CAMSError extends Error {
14
+ type;
13
15
  constructor(type, message) {
14
16
  super(message);
15
17
  this.type = type;
16
- this.name = 'CAMSError';
18
+ this.name = this.constructor.name;
17
19
  }
18
20
  }
19
21
 
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"),
22
+ // Validate the returned token - non-empty string
23
+ const ProfileSchema = z.object({
24
+ type: z.literal("AUTH_SUCCESS").or(z.literal("AUTH_FAILURE")),
25
+ userProfile: z.object({
26
+ name: z.string(),
27
+ email: z.email(),
28
+ mfaIsEnabled: z.boolean(),
29
+ message: z.string(),
30
+ isAuthenticated: z.boolean(),
31
+ userType: z.enum(["SUPER_ADMIN", "ADMIN", "USER"]),
32
+ tokens: z.object({
33
+ Nonce: z.string(),
34
+ Bearer: z.string(),
35
+ }),
36
+ }),
23
37
  });
24
38
  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(),
39
+ error: z.string().min(1, "Error message cannot be empty"),
33
40
  });
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(),
41
+ const AuthFailureMessageSchema = z.object({
42
+ type: z.literal("AUTH_FAILURE"),
43
+ error: z.string().min(1, "Error message cannot be empty"),
44
+ errorCode: z.string(),
45
+ errorDetails: z.object().or(z.any()),
41
46
  });
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" });
47
+ const URLSchema = z.url();
48
+
49
+ var LogLevel;
50
+ (function (LogLevel) {
51
+ LogLevel[LogLevel["ERROR"] = 0] = "ERROR";
52
+ LogLevel[LogLevel["WARN"] = 1] = "WARN";
53
+ LogLevel[LogLevel["INFO"] = 2] = "INFO";
54
+ LogLevel[LogLevel["DEBUG"] = 3] = "DEBUG";
55
+ })(LogLevel || (LogLevel = {}));
56
+ class Logger {
57
+ static level = LogLevel.DEBUG;
58
+ static prefix = '[CAMS-SDK]';
59
+ static isTestEnv = typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test';
60
+ static setLevel(level) {
61
+ Logger.level = level;
62
+ }
63
+ static error(message, context) {
64
+ if (!Logger.isTestEnv && Logger.level >= LogLevel.ERROR) {
65
+ console.error(`${Logger.prefix} ERROR:`, message, context || '');
66
+ }
67
+ }
68
+ static warn(message, context) {
69
+ if (!Logger.isTestEnv && Logger.level >= LogLevel.WARN) {
70
+ console.warn(`${Logger.prefix} WARN:`, message, context || '');
71
+ }
72
+ }
73
+ static info(message, context) {
74
+ if (!Logger.isTestEnv && Logger.level >= LogLevel.INFO) {
75
+ console.info(`${Logger.prefix} INFO:`, message, context || '');
76
+ }
77
+ }
78
+ static debug(message, context) {
79
+ if (!Logger.isTestEnv && Logger.level >= LogLevel.DEBUG) {
80
+ console.debug(`${Logger.prefix} DEBUG:`, message, context || '');
81
+ }
82
+ }
83
+ }
44
84
 
85
+ // Constants
86
+ const DEFAULT_AUTH_TIMEOUT = 300000; // 5 minutes
87
+ const DEFAULT_IDLE_TIMEOUT = 120000; // 2 minutes
88
+ const INITIAL_POLL_INTERVAL = 1000;
89
+ const MAX_POLL_INTERVAL = 5000;
90
+ const WINDOW_FEATURES = "scrollbars=yes,resizable=yes";
91
+ // Default allowed Microsoft domains for Azure AD redirects
92
+ const DEFAULT_MICROSOFT_DOMAINS = [
93
+ ".microsoft.com",
94
+ ".microsoftonline.com",
95
+ ".live.com",
96
+ "login.microsoftonline.com"
97
+ ];
98
+ // Secure reference to native functions
99
+ const NativeFunctions = {
100
+ addEventListener: typeof window !== "undefined" ? window.addEventListener : null,
101
+ removeEventListener: typeof window !== "undefined" ? window.removeEventListener : null,
102
+ setTimeout: typeof window !== "undefined" ? window.setTimeout : setTimeout,
103
+ clearTimeout: typeof window !== "undefined" ? window.clearTimeout : clearTimeout,
104
+ };
105
+ /**
106
+ * Generate a secure random window name to prevent targeting
107
+ */
108
+ const generateSecureWindowName = () => `cams_auth_${Math.random().toString(36).slice(2, 9)}_${Date.now()}`;
109
+ /**
110
+ * Detect if current window is a popup to prevent recursive popups
111
+ */
112
+ const isPopupWindow = () => {
113
+ if (typeof window === "undefined")
114
+ return false;
115
+ try {
116
+ return window.opener !== null && window.opener !== window;
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ };
122
+ /**
123
+ * Safely close a window with error handling for cross-origin restrictions
124
+ */
125
+ const safeWindowClose = (window) => {
126
+ if (!window)
127
+ return;
128
+ try {
129
+ if (!window.closed) {
130
+ window.close();
131
+ }
132
+ }
133
+ catch (error) {
134
+ Logger.debug("Error closing window (cross-origin restriction)", {
135
+ error: error instanceof Error ? error.message : "Unknown error"
136
+ });
137
+ }
138
+ };
139
+ /**
140
+ * Center popup window on screen
141
+ */
142
+ const getPopupPosition = (width, height) => {
143
+ if (typeof window === "undefined")
144
+ return { left: 0, top: 0 };
145
+ const left = Math.max(0, (window.screen.width - width) / 2);
146
+ const top = Math.max(0, (window.screen.height - height) / 2);
147
+ return { left, top };
148
+ };
149
+ /**
150
+ * Validate origin against expected domain with support for subdomains and Microsoft redirects
151
+ */
152
+ const isValidOrigin = (eventOrigin, expectedOrigin, microsoftDomains = DEFAULT_MICROSOFT_DOMAINS) => {
153
+ try {
154
+ const originUrl = new URL(eventOrigin);
155
+ const expectedHostname = expectedOrigin.startsWith("http")
156
+ ? new URL(expectedOrigin).hostname
157
+ : expectedOrigin;
158
+ // Check Microsoft domains for Azure AD redirects
159
+ const isMicrosoftDomain = microsoftDomains.some(domain => originUrl.hostname === domain || originUrl.hostname.endsWith(domain));
160
+ // Allow exact match, subdomains, or Microsoft domains
161
+ return (originUrl.hostname === expectedHostname ||
162
+ originUrl.hostname.endsWith("." + expectedHostname) ||
163
+ isMicrosoftDomain);
164
+ }
165
+ catch {
166
+ return false;
167
+ }
168
+ };
169
+ /**
170
+ * Safely check if window is closed with cross-origin handling
171
+ */
172
+ const isWindowClosed = (window) => {
173
+ if (!window)
174
+ return true;
175
+ try {
176
+ return window.closed;
177
+ }
178
+ catch (error) {
179
+ // Cross-origin error means we can't access the property
180
+ // This typically happens when redirected to external auth providers
181
+ Logger.debug("Cannot access window.closed due to cross-origin restrictions - assuming window is still open", error);
182
+ return false;
183
+ }
184
+ };
185
+ /**
186
+ * Safely add message event listener with error handling
187
+ */
188
+ const addMessageListener = (listener) => {
189
+ if (!NativeFunctions.addEventListener) {
190
+ throw new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Message listener not available in current environment");
191
+ }
192
+ const wrappedListener = (event) => {
193
+ try {
194
+ listener(event);
195
+ }
196
+ catch (error) {
197
+ Logger.error("Error in message listener", {
198
+ error: error instanceof Error ? error.message : "Unknown error"
199
+ });
200
+ }
201
+ };
202
+ NativeFunctions.addEventListener.call(window, "message", wrappedListener);
203
+ return () => {
204
+ if (NativeFunctions.removeEventListener) {
205
+ NativeFunctions.removeEventListener.call(window, "message", wrappedListener);
206
+ }
207
+ };
208
+ };
209
+ /**
210
+ * Validate configuration and return parsed URL
211
+ */
45
212
  function validateConfig(config) {
46
- var _a;
47
- // Validate URL format
48
213
  const urlValidation = URLSchema.safeParse(config.camsUrl);
49
214
  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');
215
+ throw new CAMSError(CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
55
216
  }
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');
217
+ if (!config.messageOrigin) {
218
+ throw new CAMSError(CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
60
219
  }
220
+ return new URL(config.camsUrl);
61
221
  }
222
+ /**
223
+ * Open CAMS authentication popup and handle the authentication flow
224
+ */
62
225
  function openCAMSPopUpLogin(config) {
63
226
  return new Promise((resolve, reject) => {
64
- try {
65
- validateConfig(config);
227
+ // Environment validation
228
+ if (typeof window === "undefined") {
229
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot open popup in server-side environment"));
230
+ return;
66
231
  }
67
- catch (error) {
68
- reject(error);
232
+ if (isPopupWindow()) {
233
+ Logger.warn("Attempted to open popup from within popup window");
234
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot open authentication popup from within popup window"));
69
235
  return;
70
236
  }
71
- const { camsUrl, allowedOrigin, windowHeight, windowWidth, timeout = 300000 } = config;
72
- let authWindow;
73
- let timeoutId = null;
74
- let checkClosedInterval = null;
237
+ // Initialize logging
238
+ if (config.debug)
239
+ Logger.setLevel(LogLevel.DEBUG);
240
+ Logger.info("Starting CAMS authentication", { url: config.camsUrl });
241
+ // Validate configuration
242
+ let validatedUrl;
75
243
  try {
76
- authWindow = window.open(camsUrl, "NIBSS CAMS Login", `width=${windowWidth},height=${windowHeight}`);
244
+ validatedUrl = validateConfig(config);
245
+ Logger.debug("Configuration validation passed");
77
246
  }
78
247
  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."));
248
+ Logger.error("Configuration validation failed", {
249
+ error: error instanceof Error ? error.message : "Unknown error"
250
+ });
251
+ reject(error);
84
252
  return;
85
253
  }
254
+ // Extract configuration with defaults
255
+ const { messageOrigin, windowHeight = 600, windowWidth = 500, authTimeout = DEFAULT_AUTH_TIMEOUT, idleTimeout = DEFAULT_IDLE_TIMEOUT, allowedRedirectDomains = DEFAULT_MICROSOFT_DOMAINS, } = config;
256
+ // State management
257
+ let authWindow = null;
258
+ let authTimeoutId = null;
259
+ let idleTimeoutId = null;
260
+ let checkClosedInterval = null;
261
+ let removeMessageListener = null;
262
+ let hasReceivedValidMessage = false;
263
+ /**
264
+ * Clean up all resources and timeouts
265
+ */
86
266
  const cleanup = () => {
87
- window.removeEventListener("message", listener);
88
- if (timeoutId)
89
- clearTimeout(timeoutId);
267
+ if (removeMessageListener) {
268
+ removeMessageListener();
269
+ removeMessageListener = null;
270
+ }
271
+ if (idleTimeoutId)
272
+ NativeFunctions.clearTimeout(idleTimeoutId);
273
+ if (authTimeoutId)
274
+ NativeFunctions.clearTimeout(authTimeoutId);
90
275
  if (checkClosedInterval)
91
- clearInterval(checkClosedInterval);
276
+ NativeFunctions.clearTimeout(checkClosedInterval);
277
+ idleTimeoutId = null;
278
+ authTimeoutId = null;
279
+ checkClosedInterval = null;
92
280
  };
281
+ /**
282
+ * Clean up and close the popup window, then reject with error
283
+ */
93
284
  const cleanupAndClose = (error) => {
94
285
  cleanup();
95
- try {
96
- if (authWindow && !authWindow.closed) {
97
- authWindow.close();
286
+ safeWindowClose(authWindow);
287
+ if (error) {
288
+ reject(error);
289
+ }
290
+ };
291
+ /**
292
+ * Reset idle timeout on user activity
293
+ */
294
+ const resetIdleTimeout = () => {
295
+ if (idleTimeoutId)
296
+ NativeFunctions.clearTimeout(idleTimeoutId);
297
+ Logger.debug("Resetting idle timeout", { idleTimeout });
298
+ idleTimeoutId = NativeFunctions.setTimeout(() => {
299
+ Logger.warn("Authentication idle timeout reached", { idleTimeout });
300
+ cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication timed out due to inactivity after ${idleTimeout}ms`));
301
+ }, idleTimeout);
302
+ };
303
+ /**
304
+ * Set up popup window closure detection with cross-origin handling
305
+ */
306
+ const setupClosureDetection = () => {
307
+ let pollInterval = INITIAL_POLL_INTERVAL;
308
+ let consecutiveCrossOriginErrors = 0;
309
+ const MAX_CROSS_ORIGIN_ERRORS = 10; // Allow some cross-origin redirects
310
+ const checkClosed = () => {
311
+ const isClosed = isWindowClosed(authWindow);
312
+ if (isClosed) {
313
+ // Only treat as user cancellation if we haven't received any valid messages
314
+ // This prevents false positives when Microsoft redirects cause cross-origin errors
315
+ if (!hasReceivedValidMessage) {
316
+ Logger.info("Authentication window closed by user before any successful communication");
317
+ cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication window was closed"));
318
+ }
319
+ else {
320
+ Logger.info("Authentication window closed after successful communication - likely completed flow");
321
+ // Don't reject here - wait for the actual message or timeout
322
+ }
323
+ return;
98
324
  }
325
+ // If we get a cross-origin error, count it but don't immediately fail
326
+ // This is normal during redirects to external auth providers
327
+ if (authWindow && !isClosed) {
328
+ try {
329
+ // Try to access a property to see if we get cross-origin error
330
+ const test = authWindow.location;
331
+ consecutiveCrossOriginErrors = 0; // Reset counter if no error
332
+ }
333
+ catch (error) {
334
+ consecutiveCrossOriginErrors++;
335
+ Logger.debug(`Cross-origin redirect detected (${consecutiveCrossOriginErrors}/${MAX_CROSS_ORIGIN_ERRORS})`, error);
336
+ // Only fail if we get too many consecutive cross-origin errors without any valid messages
337
+ if (consecutiveCrossOriginErrors >= MAX_CROSS_ORIGIN_ERRORS && !hasReceivedValidMessage) {
338
+ Logger.error("Too many consecutive cross-origin errors - possible navigation issue");
339
+ cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, "Authentication failed due to navigation issues"));
340
+ return;
341
+ }
342
+ }
343
+ }
344
+ // Exponential backoff with maximum limit
345
+ pollInterval = Math.min(pollInterval * 1.2, MAX_POLL_INTERVAL);
346
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
347
+ };
348
+ checkClosedInterval = NativeFunctions.setTimeout(checkClosed, pollInterval);
349
+ };
350
+ /**
351
+ * Handle incoming message events from the popup
352
+ */
353
+ const handleMessage = (event) => {
354
+ Logger.debug("Received message", {
355
+ origin: event.origin,
356
+ expectedOrigin: messageOrigin,
357
+ data: event.data,
358
+ });
359
+ // Security: Validate origin
360
+ if (!isValidOrigin(event.origin, messageOrigin, allowedRedirectDomains)) {
361
+ Logger.warn("Blocked message from unauthorized origin", {
362
+ origin: event.origin,
363
+ expected: messageOrigin,
364
+ data: event.data,
365
+ });
366
+ return;
99
367
  }
100
- catch {
101
- // Ignore close errors
368
+ // Security: Validate message source
369
+ if (event.source !== authWindow) {
370
+ Logger.warn("Message from unexpected source", {
371
+ source: event.source,
372
+ origin: event.origin,
373
+ expected: messageOrigin,
374
+ data: event.data,
375
+ });
376
+ return;
102
377
  }
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);
378
+ // Mark that we've received a valid message (prevents false closure detection)
379
+ hasReceivedValidMessage = true;
380
+ // Handle heartbeat messages (reset idle timeout)
381
+ if (event.data?.type === "heartbeat") {
382
+ Logger.debug("Received heartbeat message");
383
+ resetIdleTimeout();
111
384
  return;
112
385
  }
113
- // ✅ Validate payload
114
- const tokenMsg = TokenMessageSchema.safeParse(event.data);
115
- if (tokenMsg.success) {
386
+ // Process authentication messages
387
+ processAuthenticationMessage(event.data);
388
+ };
389
+ /**
390
+ * Process and validate authentication message payloads
391
+ */
392
+ const processAuthenticationMessage = (data) => {
393
+ // Success case: Valid profile received
394
+ const profileValidation = ProfileSchema.safeParse(data);
395
+ if (profileValidation.success) {
396
+ Logger.info("Authentication successful");
116
397
  cleanupAndClose();
117
- resolve({ token: tokenMsg.data.access_token });
398
+ resolve(profileValidation.data);
399
+ return;
400
+ }
401
+ // Authentication failure case
402
+ const authFailureValidation = AuthFailureMessageSchema.safeParse(data);
403
+ if (authFailureValidation.success) {
404
+ const { error, errorCode, errorDetails } = authFailureValidation.data;
405
+ Logger.warn("Authentication failure received", {
406
+ error,
407
+ errorCode,
408
+ errorDetails,
409
+ });
410
+ cleanupAndClose(new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `Authentication failed: ${error}${errorCode ? ` (${errorCode})` : ''}`));
118
411
  return;
119
412
  }
120
- const errorMsg = ErrorMessageSchema.safeParse(event.data);
121
- if (errorMsg.success) {
122
- cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, "Authentication failed: " + errorMsg.data.error));
413
+ // Generic error case
414
+ const errorValidation = ErrorMessageSchema.safeParse(data);
415
+ if (errorValidation.success) {
416
+ Logger.warn("Authentication error received", {
417
+ error: errorValidation.data.error,
418
+ });
419
+ cleanupAndClose(new CAMSError(CAMSErrorType.USER_CANCELLED, `Authentication failed: ${errorValidation.data.error}`));
123
420
  return;
124
421
  }
422
+ // Invalid message format
423
+ Logger.error("Invalid message format received", {
424
+ messageData: data,
425
+ dataType: typeof data,
426
+ profileValidationError: profileValidation.error?.issues,
427
+ authFailureValidationError: authFailureValidation.error?.issues,
428
+ errorValidationError: errorValidation.error?.issues,
429
+ });
125
430
  cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
126
431
  };
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
432
+ // Main authentication flow execution
136
433
  try {
137
- window.addEventListener("message", listener);
434
+ // Open popup window
435
+ const { left, top } = getPopupPosition(windowWidth, windowHeight);
436
+ const secureWindowName = generateSecureWindowName();
437
+ Logger.debug("Opening popup window", {
438
+ width: windowWidth,
439
+ height: windowHeight,
440
+ left,
441
+ top,
442
+ });
443
+ authWindow = window.open(validatedUrl.toString(), secureWindowName, `width=${windowWidth},height=${windowHeight},left=${left},top=${top},${WINDOW_FEATURES}`);
444
+ // Check for popup blocking
445
+ if (!authWindow) {
446
+ Logger.error("Popup window blocked or failed to open");
447
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
448
+ return;
449
+ }
450
+ // Check for immediate closure (aggressive popup blockers)
451
+ if (isWindowClosed(authWindow)) {
452
+ Logger.error("Popup immediately closed by blocker");
453
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again."));
454
+ return;
455
+ }
456
+ Logger.debug("Popup window opened successfully");
457
+ // Set up message listener
458
+ removeMessageListener = addMessageListener(handleMessage);
459
+ Logger.debug("Message listener attached");
460
+ // Set up timeouts
461
+ Logger.debug("Setting authentication timeout", { authTimeout });
462
+ authTimeoutId = NativeFunctions.setTimeout(() => {
463
+ Logger.warn("Authentication timeout reached", { authTimeout });
464
+ cleanupAndClose(new CAMSError(CAMSErrorType.TIMEOUT, `Authentication process exceeded time limit of ${authTimeout}ms`));
465
+ }, authTimeout);
466
+ resetIdleTimeout();
467
+ setupClosureDetection();
468
+ // Focus popup for better UX
469
+ try {
470
+ authWindow.focus();
471
+ }
472
+ catch (error) {
473
+ Logger.debug("Could not focus popup window (cross-origin restriction)");
474
+ }
138
475
  }
139
476
  catch (error) {
477
+ Logger.error("Failed to initialize authentication popup", {
478
+ error: error instanceof Error ? error.message : "Unknown error"
479
+ });
140
480
  cleanup();
141
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to set up message listener: " + (error instanceof Error ? error.message : "Unknown error")));
142
- return;
481
+ reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
482
+ (error instanceof Error ? error.message : "Unknown error")));
143
483
  }
144
484
  });
145
485
  }
146
486
 
147
- class TokenManager {
148
- constructor(storage = sessionStorage, storageKey = "cams_token") {
149
- this.storage = storage;
150
- this.token = null;
151
- this.storageKey = storageKey;
152
- }
153
- setToken(token) {
154
- const parsed = TokenSchema.parse(token);
155
- this.token = parsed;
156
- this.storage.setItem(this.storageKey, JSON.stringify(parsed));
487
+ class CAMSSessionManager {
488
+ storage;
489
+ keyPrefix;
490
+ events;
491
+ token = null;
492
+ profile = null;
493
+ constructor(storage = null, keyPrefix, events = {}) {
494
+ this.storage = storage || getDefaultStorage();
495
+ this.keyPrefix = keyPrefix ?? "CAMS-SDK";
496
+ this.events = events;
157
497
  }
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
- }
498
+ setItem(key, value) {
499
+ this.storage.setItem(`${this.keyPrefix}:${key}`, value);
181
500
  }
182
- clearToken() {
183
- this.token = null;
184
- this.storage.removeItem(this.storageKey);
501
+ getItem(key) {
502
+ return this.storage.getItem(`${this.keyPrefix}:${key}`);
185
503
  }
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;
504
+ removeItem(key) {
505
+ this.storage.removeItem(`${this.keyPrefix}:${key}`);
190
506
  }
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;
204
- }
205
- catch (error) {
206
- console.warn('Failed to parse JWT token:', error instanceof Error ? error.message : 'Unknown error');
207
- return true;
507
+ clear() {
508
+ // clear only CAMS-prefixed items
509
+ Object.keys(this.storage).forEach((k) => {
510
+ if (k.startsWith(this.keyPrefix)) {
511
+ this.storage.removeItem(k);
208
512
  }
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;
513
+ });
219
514
  }
220
515
  async login(config) {
221
- var _a, _b, _c, _d, _e, _f, _g;
222
516
  try {
223
- (_b = (_a = this.events).onAuthStart) === null || _b === void 0 ? void 0 : _b.call(_a);
517
+ Logger.info("Session login started");
518
+ // If we're in a popup, don't attempt to open another popup
519
+ if (isPopupWindow()) {
520
+ Logger.warn("Cannot initiate login from popup window");
521
+ throw new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot initiate authentication from within popup window");
522
+ }
523
+ if (this.events.onAuthStart)
524
+ this.events.onAuthStart();
224
525
  let attempts = 0;
225
- const maxAttempts = ((_c = config.retryAttempts) !== null && _c !== void 0 ? _c : 0) + 1;
526
+ const maxAttempts = (config.retryAttempts ?? 0) + 1;
527
+ Logger.debug("Login retry configuration", { maxAttempts });
226
528
  while (attempts < maxAttempts) {
227
529
  try {
530
+ attempts++;
531
+ Logger.debug("Login attempt", { attempt: attempts, maxAttempts });
532
+ // Add exponential backoff delay for retries
533
+ if (attempts > 1) {
534
+ const delay = Math.min(1000 * Math.pow(2, attempts - 2), 10000); // Max 10s delay
535
+ Logger.debug("Retry delay", { delay });
536
+ await new Promise((resolve) => setTimeout(resolve, delay));
537
+ }
228
538
  const response = await openCAMSPopUpLogin(config);
229
- (_e = (_d = this.events).onAuthSuccess) === null || _e === void 0 ? void 0 : _e.call(_d, response);
539
+ Logger.debug("Login Response", response);
540
+ this.profile = response;
541
+ this.setToken(response.userProfile.tokens.Bearer);
542
+ Logger.info("Session login successful");
543
+ if (this.events.onAuthSuccess)
544
+ this.events.onAuthSuccess(response);
230
545
  return response;
231
546
  }
232
547
  catch (error) {
233
- attempts++;
548
+ Logger.warn("Login attempt failed", {
549
+ attempt: attempts,
550
+ error: error instanceof Error ? error.message : "Unknown error",
551
+ });
234
552
  if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
235
553
  throw error;
236
554
  }
@@ -238,73 +556,251 @@ class CAMSSession {
238
556
  if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
239
557
  throw error;
240
558
  }
559
+ Logger.info("Retrying login", { nextAttempt: attempts + 1 });
241
560
  }
242
561
  }
243
- throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, 'Max retry attempts exceeded');
562
+ throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
244
563
  }
245
564
  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);
565
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
566
+ const camsError = error instanceof CAMSError
567
+ ? error
568
+ : new CAMSError(CAMSErrorType.USER_CANCELLED, errorMessage);
569
+ Logger.error("Session login failed", {
570
+ error: camsError.message,
571
+ type: camsError.type,
572
+ });
573
+ if (this.events.onAuthError)
574
+ this.events.onAuthError(camsError);
249
575
  throw camsError;
250
576
  }
251
577
  }
252
578
  async logout() {
253
- this.tokenManager.clearToken();
579
+ Logger.info("Session logout");
580
+ this.clearToken();
254
581
  }
255
- isAuthenticated() {
256
- var _a, _b;
257
- const token = this.tokenManager.loadToken();
582
+ setToken(token) {
583
+ this.token = token;
584
+ this.storage.setItem(this.keyPrefix, token);
585
+ Logger.debug("Token stored", { storageKey: this.keyPrefix });
586
+ }
587
+ getAccessToken() {
588
+ // Return cached token if available, avoiding redundant storage access
589
+ if (this.token)
590
+ return this.token;
591
+ const raw = this.storage.getItem(this.keyPrefix);
592
+ if (!raw)
593
+ return null;
594
+ this.token = raw;
595
+ Logger.debug("Token loaded from storage");
596
+ return this.token;
597
+ }
598
+ clearToken() {
599
+ this.token = null;
600
+ this.storage.removeItem(this.keyPrefix);
601
+ Logger.debug("Token cleared");
602
+ }
603
+ isExpired() {
604
+ const token = this.getAccessToken();
605
+ if (!token)
606
+ return true;
607
+ try {
608
+ const parts = token.split(".");
609
+ if (parts.length < 3)
610
+ return true; // Invalid JWT format
611
+ const payload = JSON.parse(atob(parts[1]));
612
+ if (typeof payload.exp !== "number")
613
+ return true;
614
+ const exp = payload.exp * 1000;
615
+ return Date.now() > exp;
616
+ }
617
+ catch (error) {
618
+ Logger.warn("Failed to parse JWT token", {
619
+ error: error instanceof Error ? error.message : "Unknown error",
620
+ });
621
+ return true;
622
+ }
623
+ }
624
+ isPaddedExpired() {
625
+ const token = this.getAccessToken();
258
626
  if (!token)
627
+ return true;
628
+ try {
629
+ const parts = token.split(".");
630
+ if (parts.length < 3)
631
+ return true; // Invalid JWT format
632
+ const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
633
+ const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
634
+ const payload = JSON.parse(atob(padded));
635
+ if (typeof payload.exp !== "number")
636
+ return true;
637
+ const exp = payload.exp * 1000;
638
+ return Date.now() > exp;
639
+ }
640
+ catch (error) {
641
+ Logger.warn("Failed to parse JWT token", {
642
+ error: error instanceof Error ? error.message : "Unknown error",
643
+ });
644
+ return true;
645
+ }
646
+ }
647
+ checkTokenExpiration() {
648
+ if (this.isExpired()) {
649
+ Logger.info("Token expired");
650
+ if (this.events.onTokenExpired)
651
+ this.events.onTokenExpired();
652
+ return true;
653
+ }
654
+ return false;
655
+ }
656
+ isAuthenticated() {
657
+ const token = this.getAccessToken();
658
+ if (!token) {
659
+ Logger.debug("No token found");
259
660
  return false;
260
- if (this.tokenManager.isExpired()) {
261
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
661
+ }
662
+ if (this.checkTokenExpiration()) {
262
663
  return false;
263
664
  }
665
+ Logger.debug("Token is valid");
264
666
  return true;
265
667
  }
266
- getAccessToken() {
267
- var _a, _b;
268
- const token = this.tokenManager.loadToken();
269
- if (!token)
668
+ async getProfile() {
669
+ const storedToken = this.getAccessToken();
670
+ if (!storedToken)
270
671
  return null;
271
- if (this.tokenManager.isExpired()) {
272
- (_b = (_a = this.events).onTokenExpired) === null || _b === void 0 ? void 0 : _b.call(_a);
672
+ // Check token expiration before processing
673
+ if (this.checkTokenExpiration()) {
273
674
  return null;
274
675
  }
275
- return token.access_token;
676
+ return this.profile;
677
+ }
678
+ getSessionError() {
679
+ return null;
680
+ }
681
+ /**
682
+ * Complete authentication in popup window
683
+ * This should be called by popup apps when authentication is successful
684
+ */
685
+ completePopupAuth(profile, targetOrigin) {
686
+ if (!isPopupWindow()) {
687
+ Logger.warn("completePopupAuth called outside of popup window");
688
+ return;
689
+ }
690
+ try {
691
+ // Store the authentication data locally in the popup
692
+ this.profile = profile;
693
+ this.setToken(profile.userProfile.tokens.Bearer);
694
+ Logger.info("Authentication completed in popup, forwarding to parent");
695
+ }
696
+ catch (error) {
697
+ Logger.error("Failed to complete popup authentication", {
698
+ error: error instanceof Error ? error.message : "Unknown error"
699
+ });
700
+ }
276
701
  }
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 += '=';
702
+ /**
703
+ * Report authentication error in popup window
704
+ */
705
+ errorPopupAuth(error, targetOrigin) {
706
+ if (!isPopupWindow()) {
707
+ Logger.warn("errorPopupAuth called outside of popup window");
708
+ return;
283
709
  }
284
- return atob(str);
710
+ Logger.warn("Reporting authentication error from popup");
285
711
  }
286
- async getProfile() {
287
- const storedToken = this.tokenManager.loadToken();
288
- if (!(storedToken === null || storedToken === void 0 ? void 0 : storedToken.id_token))
289
- return null;
712
+ }
713
+ // 🔹 Safe fallback for Node/SSR
714
+ function getDefaultStorage() {
715
+ if (typeof window !== "undefined" && window.localStorage) {
716
+ return window.localStorage;
717
+ }
718
+ const memoryStore = {};
719
+ return {
720
+ getItem: (key) => (key in memoryStore ? memoryStore[key] : null),
721
+ setItem: (key, value) => {
722
+ memoryStore[key] = value;
723
+ },
724
+ removeItem: (key) => {
725
+ delete memoryStore[key];
726
+ },
727
+ key: (i) => Object.keys(memoryStore)[i] ?? null,
728
+ get length() {
729
+ return Object.keys(memoryStore).length;
730
+ },
731
+ };
732
+ }
733
+
734
+ class CAMSMFAAuthenticator {
735
+ config;
736
+ attemptCount = 0;
737
+ maxAttempts = 3;
738
+ constructor(config) {
739
+ this.config = config;
740
+ }
741
+ async sendEmailOTP() {
290
742
  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
- }
743
+ Logger.debug("Sending Email OTP");
744
+ // Implementation would call your API to send email OTP
745
+ // For now, return true as placeholder
746
+ return true;
747
+ }
748
+ catch (error) {
749
+ Logger.error("Failed to send Email OTP", { error });
750
+ return false;
751
+ }
752
+ }
753
+ async verifyOTP(code, type) {
754
+ if (this.attemptCount >= this.maxAttempts) {
755
+ throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Maximum MFA attempts exceeded");
756
+ }
757
+ this.attemptCount++;
758
+ try {
759
+ Logger.debug("Verifying MFA code", { type, attempt: this.attemptCount });
760
+ const response = await fetch(this.config.apiEndpoint || '/api/auth/verify-mfa', {
761
+ method: 'POST',
762
+ headers: {
763
+ 'Content-Type': 'application/json',
764
+ 'Authorization': `Bearer ${this.config.accessToken}`,
765
+ },
766
+ body: JSON.stringify({
767
+ provider: this.config.provider,
768
+ accessToken: this.config.accessToken,
769
+ idToken: this.config.idToken,
770
+ authenticationType: type,
771
+ MFACode: code,
772
+ appCode: this.config.appCode,
773
+ }),
774
+ });
775
+ if (!response.ok) {
776
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
777
+ }
778
+ const data = await response.json();
779
+ console.log("MFA Response >>>", data);
780
+ if (data.isAuthenticated) {
781
+ Logger.info("MFA verification successful");
782
+ this.resetAttempts();
783
+ return data;
784
+ }
785
+ else {
786
+ throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, data.message || "MFA verification failed");
300
787
  }
301
788
  }
302
789
  catch (error) {
303
- console.warn('Failed to extract profile from token:', error instanceof Error ? error.message : 'Unknown error');
790
+ Logger.error("MFA verification failed", { error, attempt: this.attemptCount });
791
+ if (error instanceof CAMSError) {
792
+ throw error;
793
+ }
794
+ throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `MFA verification failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
304
795
  }
305
- return null;
796
+ }
797
+ getRemainingAttempts() {
798
+ return Math.max(0, this.maxAttempts - this.attemptCount);
799
+ }
800
+ resetAttempts() {
801
+ this.attemptCount = 0;
306
802
  }
307
803
  }
308
804
 
309
- export { CAMSError, CAMSErrorType, CAMSSession, ErrorMessageSchema, ProfileSchema, TokenManager, TokenMessageSchema, TokenSchema, URLSchema, openCAMSPopUpLogin, validateConfig };
805
+ export { AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSMFAAuthenticator, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, URLSchema, generateSecureWindowName, isPopupWindow, openCAMSPopUpLogin, validateConfig };
310
806
  //# sourceMappingURL=index.esm.js.map