@nibssplc/cams-sdk 0.0.1-beta.55 → 0.0.1-beta.62

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.d.ts CHANGED
@@ -1,915 +1,8 @@
1
- import { z } from 'zod';
2
- import axios from 'axios';
3
- import https from 'https';
4
-
5
- var CAMSErrorType;
6
- (function (CAMSErrorType) {
7
- CAMSErrorType["POPUP_BLOCKED"] = "POPUP_BLOCKED";
8
- CAMSErrorType["TIMEOUT"] = "TIMEOUT";
9
- CAMSErrorType["INVALID_ORIGIN"] = "INVALID_ORIGIN";
10
- CAMSErrorType["USER_CANCELLED"] = "USER_CANCELLED";
11
- CAMSErrorType["INVALID_URL"] = "INVALID_URL";
12
- CAMSErrorType["MAX_RETRIES_EXCEEDED"] = "MAX_RETRIES_EXCEEDED";
13
- CAMSErrorType["API_VALIDATION_ERROR"] = "VALIDATION_ERROR";
14
- })(CAMSErrorType || (CAMSErrorType = {}));
15
- class CAMSError extends Error {
16
- type;
17
- constructor(type, message) {
18
- super(message);
19
- this.type = type;
20
- this.name = this.constructor.name;
21
- }
22
- }
23
-
24
- // Validate the returned token - non-empty string
25
- const ProfileSchema = z.object({
26
- type: z.literal("AUTH_SUCCESS").or(z.literal("AUTH_FAILURE")),
27
- userProfile: z.object({
28
- name: z.string(),
29
- email: z.email(),
30
- mfaIsEnabled: z.boolean(),
31
- message: z.string(),
32
- isAuthenticated: z.boolean(),
33
- userType: z.enum(["SUPER_ADMIN", "ADMIN", "USER"]),
34
- roles: z.array(z.string()).optional(),
35
- tokens: z.object({
36
- Nonce: z.string(),
37
- Bearer: z.string(),
38
- }),
39
- }),
40
- });
41
- const ErrorMessageSchema = z.object({
42
- error: z.string().min(1, "Error message cannot be empty"),
43
- });
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()),
49
- });
50
- const URLSchema = z.url();
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
- */
218
- function validateConfig(config) {
219
- const urlValidation = URLSchema.safeParse(config.camsUrl);
220
- if (!urlValidation.success) {
221
- throw new CAMSError(CAMSErrorType.INVALID_URL, "Invalid CAMS URL format");
222
- }
223
- if (!config.messageOrigin) {
224
- throw new CAMSError(CAMSErrorType.INVALID_URL, "Message Origin must be specified for security");
225
- }
226
- return new URL(config.camsUrl);
227
- }
228
- /**
229
- * Open CAMS authentication popup and handle the authentication flow
230
- */
231
- function openCAMSPopUpLogin(config) {
232
- return new Promise((resolve, reject) => {
233
- // Environment validation
234
- if (typeof window === "undefined") {
235
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Cannot open popup in server-side environment"));
236
- return;
237
- }
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"));
241
- return;
242
- }
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;
249
- try {
250
- validatedUrl = validateConfig(config);
251
- Logger.debug("Configuration validation passed");
252
- }
253
- catch (error) {
254
- Logger.error("Configuration validation failed", {
255
- error: error instanceof Error ? error.message : "Unknown error"
256
- });
257
- reject(error);
258
- return;
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
- */
272
- const cleanup = () => {
273
- if (removeMessageListener) {
274
- removeMessageListener();
275
- removeMessageListener = null;
276
- }
277
- if (idleTimeoutId)
278
- NativeFunctions.clearTimeout(idleTimeoutId);
279
- if (authTimeoutId)
280
- NativeFunctions.clearTimeout(authTimeoutId);
281
- if (checkClosedInterval)
282
- NativeFunctions.clearTimeout(checkClosedInterval);
283
- idleTimeoutId = null;
284
- authTimeoutId = null;
285
- checkClosedInterval = null;
286
- };
287
- /**
288
- * Clean up and close the popup window, then reject with error
289
- */
290
- const cleanupAndClose = (error) => {
291
- cleanup();
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
- }
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;
360
- }
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;
370
- }
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();
377
- return;
378
- }
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");
390
- cleanupAndClose();
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})` : ''}`));
404
- return;
405
- }
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}`));
413
- return;
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
- });
423
- cleanupAndClose(new CAMSError(CAMSErrorType.INVALID_ORIGIN, "Invalid message format"));
424
- };
425
- // Main authentication flow execution
426
- try {
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
- }
468
- }
469
- catch (error) {
470
- Logger.error("Failed to initialize authentication popup", {
471
- error: error instanceof Error ? error.message : "Unknown error"
472
- });
473
- cleanup();
474
- reject(new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Failed to initialize authentication: " +
475
- (error instanceof Error ? error.message : "Unknown error")));
476
- }
477
- });
478
- }
479
-
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;
490
- }
491
- setItem(key, value) {
492
- this.storage.setItem(`${this.keyPrefix}:${key}`, value);
493
- }
494
- getItem(key) {
495
- return this.storage.getItem(`${this.keyPrefix}:${key}`);
496
- }
497
- removeItem(key) {
498
- this.storage.removeItem(`${this.keyPrefix}:${key}`);
499
- }
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);
505
- }
506
- });
507
- }
508
- async login(config) {
509
- try {
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();
518
- let attempts = 0;
519
- const maxAttempts = (config.retryAttempts ?? 0) + 1;
520
- Logger.debug("Login retry configuration", { maxAttempts });
521
- while (attempts < maxAttempts) {
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
- }
531
- const response = await openCAMSPopUpLogin(config);
532
- Logger.debug("Login Response", response);
533
- this.profile = response;
534
- this.setToken(response.userProfile.tokens.Bearer);
535
- Logger.info("Session login successful");
536
- if (this.events.onAuthSuccess)
537
- this.events.onAuthSuccess(response);
538
- return response;
539
- }
540
- catch (error) {
541
- Logger.warn("Login attempt failed", {
542
- attempt: attempts,
543
- error: error instanceof Error ? error.message : "Unknown error",
544
- });
545
- if (attempts >= maxAttempts || !(error instanceof CAMSError)) {
546
- throw error;
547
- }
548
- // Only retry on specific error types
549
- if (![CAMSErrorType.TIMEOUT, CAMSErrorType.POPUP_BLOCKED].includes(error.type)) {
550
- throw error;
551
- }
552
- Logger.info("Retrying login", { nextAttempt: attempts + 1 });
553
- }
554
- }
555
- throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Max retry attempts exceeded");
556
- }
557
- catch (error) {
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);
568
- throw camsError;
569
- }
570
- }
571
- async logout() {
572
- Logger.info("Session logout");
573
- this.clearToken();
574
- }
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();
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");
653
- return false;
654
- }
655
- if (this.checkTokenExpiration()) {
656
- return false;
657
- }
658
- Logger.debug("Token is valid");
659
- return true;
660
- }
661
- async getProfile() {
662
- const storedToken = this.getAccessToken();
663
- if (!storedToken)
664
- return null;
665
- // Check token expiration before processing
666
- if (this.checkTokenExpiration()) {
667
- return null;
668
- }
669
- return this.profile;
670
- }
671
- getSessionError() {
672
- return null;
673
- }
674
- /**
675
- * Complete authentication in popup window
676
- * This should be called by popup apps when authentication is successful
677
- */
678
- completePopupAuth(profile, 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 = profile;
686
- this.setToken(profile.userProfile.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
- });
693
- }
694
- }
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
- constructor() {
796
- Logger.info("CAMS MFA Authenticator initialized");
797
- }
798
- async GetUserMFAConfig(config) {
799
- const response = await axios.post(config.APIAuthEndpoint, {
800
- provider: config.provider,
801
- accessToken: config.accessToken,
802
- idToken: config.idToken,
803
- });
804
- Logger.debug("GetUserMFAConfig Response", response);
805
- if (response) {
806
- return response.data;
807
- }
808
- else {
809
- return {
810
- isValid: false,
811
- message: `Failed to retrieve MFA configuration. ${response.statusText}`,
812
- userInfo: {
813
- id: 0,
814
- email: "",
815
- name: "",
816
- isMFAEnabled: false,
817
- },
818
- };
819
- }
820
- }
821
- async VerifyMFAOTP(ValidateRequest, MFAEndpoint) {
822
- if (this.attemptCount >= this.maxAttempts) {
823
- throw new CAMSError(CAMSErrorType.MAX_RETRIES_EXCEEDED, "Maximum MFA attempts exceeded");
824
- }
825
- this.attemptCount++;
826
- try {
827
- Logger.debug("Verifying User MFA Code", { attempt: this.attemptCount });
828
- const response = await axiosInstance.post(MFAEndpoint, ValidateRequest);
829
- if (response.status != 200) {
830
- throw new Error(`HTTP ${response.status}: ${response.statusText}`);
831
- }
832
- const data = response.data;
833
- console.log("MFA Response >>>", data);
834
- if (data.isValid) {
835
- Logger.info("MFA verification successful");
836
- this.ResetUserAttempts();
837
- return data;
838
- }
839
- else {
840
- throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "User Verification failed");
841
- }
842
- }
843
- catch (error) {
844
- Logger.error("MFA verification failed", {
845
- error,
846
- attempt: this.attemptCount,
847
- });
848
- if (error instanceof CAMSError) {
849
- throw error;
850
- }
851
- throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, `MFA verification failed: ${error instanceof Error ? error.message : "Unknown error"}`);
852
- }
853
- }
854
- async LoginADCredentials({ username, password, MFACode }, appCode, CredentialsAuthEndpoint) {
855
- const response = await axiosInstance.post(CredentialsAuthEndpoint, { username, password, MFACode });
856
- // Implement your AD login logic here
857
- console.log("AD Login:", { username, password, MFACode });
858
- // Example: await adLoginService(username, password, mfaCode);
859
- return response.data;
860
- }
861
- async HandleFIDOLogin(RetrieveAuthChallengeEndpoint, AuthChallengeVerifyEndpoint, authenticate) {
862
- try {
863
- // 1. Fetch authentication challenge from your server
864
- console.log("Requesting authentication challenge from server...");
865
- const { data: options } = await axiosInstance.post(RetrieveAuthChallengeEndpoint, {});
866
- console.log("Received challenge:", options);
867
- // 2. Call the SDK to trigger the browser's passkey authentication UI
868
- console.log("Calling SDK authenticate function...");
869
- const assertionResponse = await authenticate({
870
- ...options,
871
- userVerification: "discouraged",
872
- });
873
- console.log("Authentication assertion received from client:", assertionResponse);
874
- // 3. Send the assertion back to the server for verification
875
- console.log("Sending assertion to server for verification...");
876
- await axiosInstance.post(AuthChallengeVerifyEndpoint, assertionResponse);
877
- return true;
878
- }
879
- catch (error) {
880
- console.error("Authentication failed:", error);
881
- // toast.error("❌ Could not sign in.");
882
- return false;
883
- }
884
- }
885
- async HandleRegister(RegisterNewChallengeEndpoint, RegisterVerify, register, data) {
886
- try {
887
- // 1. Fetch challenge from your server
888
- console.log("Requesting registration challenge from server...");
889
- const { data: options } = await axiosInstance.post(RegisterNewChallengeEndpoint, { ...data });
890
- console.log("Received challenge:", options);
891
- // 2. Call the SDK to trigger the browser's passkey creation UI
892
- console.log("Calling SDK register function...");
893
- const attestationResponse = await register(options);
894
- console.log("Passkey created on client:", attestationResponse);
895
- // 3. Send the response back to the server for verification
896
- console.log("Sending attestation to server for verification...");
897
- await axiosInstance.post(RegisterVerify + `?username=${data.username}`, attestationResponse);
898
- // toast.success("✅ Registration successful! Passkey created.");
899
- return true;
900
- }
901
- catch (error) {
902
- console.error("Registration failed:", error);
903
- // toast.error("❌ Could not create passkey.");
904
- return false;
905
- }
906
- }
907
- GetRemainingAttempts() {
908
- return Math.max(0, this.maxAttempts - this.attemptCount);
909
- }
910
- ResetUserAttempts() {
911
- this.attemptCount = 0;
912
- }
913
- }
914
-
915
- export { APIHeaders, AuthFailureMessageSchema, CAMSError, CAMSErrorType, CAMSMFAAuthenticator, CAMSSessionManager, ErrorMessageSchema, LogLevel, Logger, ProfileSchema, URLSchema, axiosInstance, generateSecureWindowName, isPopupWindow, openCAMSPopUpLogin, validateConfig };
1
+ export * from "./auth";
2
+ export * from "./types";
3
+ export * from "./validators";
4
+ export * from "./sessionManager";
5
+ export * from "./logger";
6
+ export * from "./MFAAuth";
7
+ export * from "./lib/Axiosinstance";
8
+ export * from "./lib/DeviceID";