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

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