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

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