@nibssplc/cams-sdk-react 1.0.0-rc.5 → 1.0.0-rc.50

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
@@ -18,6 +18,7 @@ import * as DialogPrimitive from '@radix-ui/react-dialog';
18
18
  import { toast } from 'sonner';
19
19
  import { motion } from 'framer-motion';
20
20
  import axios from 'axios';
21
+ import https from 'https';
21
22
 
22
23
  /******************************************************************************
23
24
  Copyright (c) Microsoft Corporation.
@@ -59,7 +60,7 @@ function __rest(s, e) {
59
60
  return t;
60
61
  }
61
62
 
62
- function __awaiter(thisArg, _arguments, P, generator) {
63
+ function __awaiter$1(thisArg, _arguments, P, generator) {
63
64
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
64
65
  return new (P || (P = Promise))(function (resolve, reject) {
65
66
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -69,7 +70,7 @@ function __awaiter(thisArg, _arguments, P, generator) {
69
70
  });
70
71
  }
71
72
 
72
- function __generator(thisArg, body) {
73
+ function __generator$1(thisArg, body) {
73
74
  var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
74
75
  return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
75
76
  function verb(n) { return function (v) { return step([n, v]); }; }
@@ -166,10 +167,10 @@ function useCAMSAuth(options) {
166
167
  }
167
168
  }
168
169
  }, [options.storageKey]);
169
- var login = useCallback(function (config) { return __awaiter(_this, void 0, void 0, function () {
170
+ var login = useCallback(function (config) { return __awaiter$1(_this, void 0, void 0, function () {
170
171
  var loginConfig, userProfile, err_1, e, isPopupClosedError, restoredToken, userProfile;
171
172
  var _a, _b, _c;
172
- return __generator(this, function (_d) {
173
+ return __generator$1(this, function (_d) {
173
174
  switch (_d.label) {
174
175
  case 0:
175
176
  if (!sessionManagerRef.current)
@@ -217,8 +218,8 @@ function useCAMSAuth(options) {
217
218
  }
218
219
  });
219
220
  }); }, [options.idleTimeout]);
220
- var logout = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
221
- return __generator(this, function (_a) {
221
+ var logout = useCallback(function () { return __awaiter$1(_this, void 0, void 0, function () {
222
+ return __generator$1(this, function (_a) {
222
223
  switch (_a.label) {
223
224
  case 0:
224
225
  if (!sessionManagerRef.current)
@@ -248,11 +249,154 @@ function useCAMSAuth(options) {
248
249
  };
249
250
  }
250
251
 
251
- var setCookie$1 = function (name, value, days) {
252
+ var _a;
253
+ // Crypto polyfill for MSAL browser compatibility
254
+ // Only apply if crypto.subtle is completely missing
255
+ if (typeof window !== "undefined" && !((_a = window.crypto) === null || _a === void 0 ? void 0 : _a.subtle)) {
256
+ // Ensure crypto object exists
257
+ if (!window.crypto) {
258
+ window.crypto = {};
259
+ }
260
+ // Polyfill getRandomValues
261
+ if (!window.crypto.getRandomValues) {
262
+ window.crypto.getRandomValues = function (array) {
263
+ var bytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
264
+ for (var i = 0; i < bytes.length; i++) {
265
+ bytes[i] = Math.floor(Math.random() * 256);
266
+ }
267
+ return array;
268
+ };
269
+ }
270
+ var sha256_1 = function (data) { return __awaiter(void 0, void 0, void 0, function () {
271
+ var toUint8, bytes, hash, k, ml, msg, dv, high, low, i, w, j, j, s0, s1, a, b, c, d, e, f, g, h, j, S1, ch, temp1, S0, maj, temp2, result, i;
272
+ return __generator(this, function (_a) {
273
+ toUint8 = function (src) {
274
+ if (src instanceof ArrayBuffer)
275
+ return new Uint8Array(src);
276
+ if (ArrayBuffer.isView(src)) {
277
+ var view = src;
278
+ return new Uint8Array(view.buffer, view.byteOffset || 0, view.byteLength);
279
+ }
280
+ throw new TypeError("Unsupported BufferSource");
281
+ };
282
+ bytes = toUint8(data);
283
+ hash = new Uint32Array(8);
284
+ k = new Uint32Array([
285
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1,
286
+ 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
287
+ 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786,
288
+ 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
289
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147,
290
+ 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
291
+ 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b,
292
+ 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
293
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a,
294
+ 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
295
+ 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
296
+ ]);
297
+ hash[0] = 0x6a09e667;
298
+ hash[1] = 0xbb67ae85;
299
+ hash[2] = 0x3c6ef372;
300
+ hash[3] = 0xa54ff53a;
301
+ hash[4] = 0x510e527f;
302
+ hash[5] = 0x9b05688c;
303
+ hash[6] = 0x1f83d9ab;
304
+ hash[7] = 0x5be0cd19;
305
+ ml = bytes.length * 8;
306
+ msg = new Uint8Array(bytes.length + 64 + ((64 - ((bytes.length + 9) % 64)) % 64));
307
+ msg.set(bytes);
308
+ msg[bytes.length] = 0x80;
309
+ dv = new DataView(msg.buffer);
310
+ high = Math.floor(ml / 0x100000000);
311
+ low = ml >>> 0;
312
+ dv.setUint32(msg.length - 8, high, false);
313
+ dv.setUint32(msg.length - 4, low, false);
314
+ for (i = 0; i < msg.length; i += 64) {
315
+ w = new Uint32Array(64);
316
+ for (j = 0; j < 16; j++)
317
+ w[j] = new DataView(msg.buffer).getUint32(i + j * 4, false);
318
+ for (j = 16; j < 64; j++) {
319
+ s0 = ((w[j - 15] >>> 7) | (w[j - 15] << 25)) ^
320
+ ((w[j - 15] >>> 18) | (w[j - 15] << 14)) ^
321
+ (w[j - 15] >>> 3);
322
+ s1 = ((w[j - 2] >>> 17) | (w[j - 2] << 15)) ^
323
+ ((w[j - 2] >>> 19) | (w[j - 2] << 13)) ^
324
+ (w[j - 2] >>> 10);
325
+ w[j] = (w[j - 16] + s0 + w[j - 7] + s1) >>> 0;
326
+ }
327
+ a = hash[0], b = hash[1], c = hash[2], d = hash[3], e = hash[4], f = hash[5], g = hash[6], h = hash[7];
328
+ for (j = 0; j < 64; j++) {
329
+ S1 = ((e >>> 6) | (e << 26)) ^
330
+ ((e >>> 11) | (e << 21)) ^
331
+ ((e >>> 25) | (e << 7));
332
+ ch = (e & f) ^ (~e & g);
333
+ temp1 = (h + S1 + ch + k[j] + w[j]) >>> 0;
334
+ S0 = ((a >>> 2) | (a << 30)) ^
335
+ ((a >>> 13) | (a << 19)) ^
336
+ ((a >>> 22) | (a << 10));
337
+ maj = (a & b) ^ (a & c) ^ (b & c);
338
+ temp2 = (S0 + maj) >>> 0;
339
+ h = g;
340
+ g = f;
341
+ f = e;
342
+ e = (d + temp1) >>> 0;
343
+ d = c;
344
+ c = b;
345
+ b = a;
346
+ a = (temp1 + temp2) >>> 0;
347
+ }
348
+ hash[0] = (hash[0] + a) >>> 0;
349
+ hash[1] = (hash[1] + b) >>> 0;
350
+ hash[2] = (hash[2] + c) >>> 0;
351
+ hash[3] = (hash[3] + d) >>> 0;
352
+ hash[4] = (hash[4] + e) >>> 0;
353
+ hash[5] = (hash[5] + f) >>> 0;
354
+ hash[6] = (hash[6] + g) >>> 0;
355
+ hash[7] = (hash[7] + h) >>> 0;
356
+ }
357
+ result = new Uint8Array(32);
358
+ for (i = 0; i < 8; i++)
359
+ new DataView(result.buffer).setUint32(i * 4, hash[i], false);
360
+ return [2 /*return*/, result.buffer];
361
+ });
362
+ }); };
363
+ // Create the polyfilled subtle object
364
+ var polyfillSubtle = {
365
+ digest: function (algorithm, data) { return __awaiter(void 0, void 0, void 0, function () {
366
+ var alg;
367
+ return __generator(this, function (_a) {
368
+ alg = typeof algorithm === "string"
369
+ ? algorithm
370
+ : algorithm.name;
371
+ if (alg === "SHA-256")
372
+ return [2 /*return*/, sha256_1(data)];
373
+ throw new Error("Unsupported algorithm: ".concat(alg));
374
+ });
375
+ }); },
376
+ };
377
+ // Set the polyfilled subtle object
378
+ window.crypto.subtle = polyfillSubtle;
379
+ // Polyfill randomUUID
380
+ if (!window.crypto.randomUUID) {
381
+ window.crypto.randomUUID =
382
+ function () {
383
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
384
+ var r = (Math.random() * 16) | 0;
385
+ var v = c === "x" ? r : (r & 0x3) | 0x8;
386
+ return v.toString(16);
387
+ });
388
+ };
389
+ }
390
+ console.log("Crypto polyfill applied (native crypto.subtle not available)");
391
+ }
392
+
393
+ var setCookie = function (name, value, days) {
394
+ if (days === void 0) { days = 1; }
252
395
  var expires = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
396
+ console.log("Auth Cookie Expires >>>", { name: name, value: value, expires: expires });
253
397
  document.cookie = "".concat(name, "=").concat(encodeURIComponent(value), "; expires=").concat(expires, "; path=/; samesite=Lax");
254
398
  };
255
- var getCookie$1 = function (name) {
399
+ var getCookie = function (name) {
256
400
  var _a;
257
401
  return ((_a = document.cookie
258
402
  .split("; ")
@@ -263,23 +407,24 @@ var getCookie$1 = function (name) {
263
407
  .split("=")[1])
264
408
  : null;
265
409
  };
266
- var deleteCookie$1 = function (name) {
410
+ var deleteCookie = function (name) {
267
411
  document.cookie = name + "=; Max-Age=-99999999; path=/";
268
412
  };
269
413
 
270
414
  function useCAMSMSALAuth(options) {
271
415
  var _this = this;
272
- var storageKey = options.storageKey || "CAMS-MSAL-AUTH-SDK";
273
- var _a = useMsal(), instance = _a.instance, inProgress = _a.inProgress, accounts = _a.accounts;
416
+ var optStorageKey = options.storageKey, optScopes = options.scopes, prompt = options.prompt, appCode = options.appCode, MFAEndpoint = options.MFAEndpoint, _a = options.activeCookiePeriod, activeCookiePeriod = _a === void 0 ? 1 : _a;
417
+ var storageKey = optStorageKey || "CAMS-MSAL-AUTH-SDK";
418
+ var _b = useMsal(), instance = _b.instance, inProgress = _b.inProgress, accounts = _b.accounts;
274
419
  var account = useAccount(accounts[0] || {});
275
- var _b = useState(null), error = _b[0], setError = _b[1];
276
- var _c = useState(""), idToken = _c[0], setIdToken = _c[1];
277
- var _d = useState(""), accessToken = _d[0], setAccessToken = _d[1];
278
- var _e = useState(null), mfaAuthenticator = _e[0], setMfaAuthenticator = _e[1];
279
- var _f = useState(false), requiresMFA = _f[0], setRequiresMFA = _f[1];
420
+ var _c = useState(null), error = _c[0], setError = _c[1];
421
+ var _d = useState(""), idToken = _d[0], setIdToken = _d[1];
422
+ var _e = useState(""), accessToken = _e[0], setAccessToken = _e[1];
423
+ var _f = useState(null), mfaAuthenticator = _f[0], setMfaAuthenticator = _f[1];
424
+ var _g = useState(false), requiresMFA = _g[0], setRequiresMFA = _g[1];
280
425
  var isLoading = inProgress !== InteractionStatus.None;
281
426
  var isAuthenticated = !!account && !!accessToken && !requiresMFA;
282
- var scopes = options.scopes || ["openid", "profile", "email"];
427
+ var scopes = optScopes || ["openid", "profile", "email"];
283
428
  var isTokenValid = function (token) {
284
429
  try {
285
430
  var payload = JSON.parse(atob(token.split(".")[1]));
@@ -303,15 +448,14 @@ function useCAMSMSALAuth(options) {
303
448
  var mfaConfig = {
304
449
  accessToken: accessToken_1,
305
450
  idToken: idToken_1,
306
- appCode: options.appCode,
451
+ appCode: appCode,
307
452
  provider: "MSAL",
308
- apiEndpoint: options.MFAEndpoint,
453
+ apiEndpoint: MFAEndpoint,
309
454
  };
310
455
  var authenticator = new CAMSMFAAuthenticator(mfaConfig);
311
456
  setMfaAuthenticator(authenticator);
312
457
  setRequiresMFA(true);
313
458
  }
314
- Logger.debug("App Code", { ">>>": options.appCode });
315
459
  }
316
460
  else {
317
461
  localStorage.removeItem(storageKey);
@@ -353,22 +497,26 @@ function useCAMSMSALAuth(options) {
353
497
  // };
354
498
  // handleRedirect();
355
499
  // }, []);
356
- var login = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
500
+ var login = useCallback(function () { return __awaiter$1(_this, void 0, void 0, function () {
357
501
  var response, mfaConfig, authenticator, err_1, camsError_1, camsError;
358
- var _a, _b, _c, _d;
359
- return __generator(this, function (_e) {
360
- switch (_e.label) {
502
+ var _a;
503
+ return __generator$1(this, function (_b) {
504
+ switch (_b.label) {
361
505
  case 0:
506
+ if (inProgress !== InteractionStatus.None) {
507
+ Logger.warn("Authentication already in progress, ignoring duplicate call");
508
+ return [2 /*return*/];
509
+ }
362
510
  setError(null);
363
- _e.label = 1;
511
+ _b.label = 1;
364
512
  case 1:
365
- _e.trys.push([1, 3, , 4]);
513
+ _b.trys.push([1, 3, , 4]);
366
514
  return [4 /*yield*/, instance.loginPopup({
367
515
  scopes: scopes,
368
- prompt: options.prompt || "login",
516
+ prompt: prompt || "login",
369
517
  })];
370
518
  case 2:
371
- response = _e.sent();
519
+ response = _b.sent();
372
520
  console.log("Login Token response:", {
373
521
  accessToken: response.accessToken,
374
522
  idToken: response.idToken,
@@ -378,9 +526,9 @@ function useCAMSMSALAuth(options) {
378
526
  mfaConfig = {
379
527
  accessToken: response.accessToken,
380
528
  idToken: response.idToken,
381
- appCode: options.appCode,
529
+ appCode: appCode,
382
530
  provider: "MSAL",
383
- apiEndpoint: options.MFAEndpoint,
531
+ apiEndpoint: MFAEndpoint,
384
532
  };
385
533
  authenticator = new CAMSMFAAuthenticator(mfaConfig);
386
534
  setMfaAuthenticator(authenticator);
@@ -394,10 +542,14 @@ function useCAMSMSALAuth(options) {
394
542
  idToken: response.idToken,
395
543
  }));
396
544
  }
397
- (_a = options.onAuthSuccess) === null || _a === void 0 ? void 0 : _a.call(options, response.accessToken);
398
545
  return [3 /*break*/, 4];
399
546
  case 3:
400
- err_1 = _e.sent();
547
+ err_1 = _b.sent();
548
+ // Handle interaction_in_progress error
549
+ if (err_1.errorCode === "interaction_in_progress") {
550
+ Logger.warn("Interaction already in progress, please wait");
551
+ return [2 /*return*/];
552
+ }
401
553
  // Handle user cancellation gracefully
402
554
  if (err_1.errorCode === "user_cancelled") {
403
555
  Logger.error("User cancelled login");
@@ -406,22 +558,28 @@ function useCAMSMSALAuth(options) {
406
558
  }
407
559
  // If popup is blocked
408
560
  if (err_1.errorCode === "popup_window_error" ||
409
- ((_b = err_1.message) === null || _b === void 0 ? void 0 : _b.includes("popup"))) {
561
+ ((_a = err_1.message) === null || _a === void 0 ? void 0 : _a.includes("popup"))) {
410
562
  camsError_1 = new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again.");
411
563
  setError(camsError_1);
412
- (_c = options.onAuthError) === null || _c === void 0 ? void 0 : _c.call(options, camsError_1);
413
564
  return [2 /*return*/];
414
565
  }
415
566
  camsError = new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "Login failed: " + err_1.message || err_1);
416
567
  setError(camsError);
417
- (_d = options.onAuthError) === null || _d === void 0 ? void 0 : _d.call(options, camsError);
418
568
  return [3 /*break*/, 4];
419
569
  case 4: return [2 /*return*/];
420
570
  }
421
571
  });
422
- }); }, [instance, scopes, options]);
423
- var completeMFA = useCallback(function (data) { return __awaiter(_this, void 0, void 0, function () {
424
- return __generator(this, function (_a) {
572
+ }); }, [
573
+ instance,
574
+ scopes,
575
+ prompt,
576
+ appCode,
577
+ MFAEndpoint,
578
+ storageKey,
579
+ inProgress,
580
+ ]);
581
+ var completeMFA = useCallback(function (data) { return __awaiter$1(_this, void 0, void 0, function () {
582
+ return __generator$1(this, function (_a) {
425
583
  if (!mfaAuthenticator) {
426
584
  throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "MFA Authenticator not initialized");
427
585
  }
@@ -435,7 +593,7 @@ function useCAMSMSALAuth(options) {
435
593
  accessToken: accessToken,
436
594
  idToken: idToken,
437
595
  }));
438
- setCookie$1("CAMS-MSAL-AUTH-SDK-PROFILE", JSON.stringify({ type: "AUTH_SUCCESS", userProfile: __assign({}, data) }), 1);
596
+ setCookie("CAMS-MSAL-AUTH-SDK-PROFILE", JSON.stringify({ type: "AUTH_SUCCESS", userProfile: __assign({}, data) }), activeCookiePeriod);
439
597
  setRequiresMFA(false);
440
598
  // Set requiresMFA to false after storage update
441
599
  Logger.debug("MFA completed successfully, storage updated", {
@@ -454,9 +612,9 @@ function useCAMSMSALAuth(options) {
454
612
  }
455
613
  return [2 /*return*/];
456
614
  });
457
- }); }, [mfaAuthenticator, accessToken, idToken, storageKey]);
458
- var sendEmailOTP = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
459
- return __generator(this, function (_a) {
615
+ }); }, [mfaAuthenticator, accessToken, idToken, storageKey, activeCookiePeriod]);
616
+ var sendEmailOTP = useCallback(function () { return __awaiter$1(_this, void 0, void 0, function () {
617
+ return __generator$1(this, function (_a) {
460
618
  switch (_a.label) {
461
619
  case 0:
462
620
  if (!mfaAuthenticator) {
@@ -467,9 +625,9 @@ function useCAMSMSALAuth(options) {
467
625
  }
468
626
  });
469
627
  }); }, [mfaAuthenticator]);
470
- var logout = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
628
+ var logout = useCallback(function () { return __awaiter$1(_this, void 0, void 0, function () {
471
629
  var err_2, camsError;
472
- return __generator(this, function (_a) {
630
+ return __generator$1(this, function (_a) {
473
631
  switch (_a.label) {
474
632
  case 0:
475
633
  _a.trys.push([0, 2, , 3]);
@@ -505,12 +663,13 @@ function useCAMSMSALAuth(options) {
505
663
  error: error,
506
664
  idToken: idToken,
507
665
  accessToken: accessToken,
508
- appCode: options.appCode,
666
+ appCode: appCode,
509
667
  mfaAuthenticator: mfaAuthenticator,
510
668
  requiresMFA: requiresMFA,
511
669
  completeMFA: completeMFA,
512
670
  sendEmailOTP: sendEmailOTP,
513
671
  setRequiresMFA: setRequiresMFA,
672
+ activeCookiePeriod: activeCookiePeriod,
514
673
  };
515
674
  }
516
675
 
@@ -553,10 +712,10 @@ function arrayBufferToBase64url(buffer) {
553
712
  * @returns A promise that resolves to a JSON-serializable representation of the PublicKeyCredential.
554
713
  */
555
714
  function register(options) {
556
- return __awaiter(this, void 0, void 0, function () {
715
+ return __awaiter$1(this, void 0, void 0, function () {
557
716
  var createOptions, credential, publicKeyCredential, attestationResponse, transports, err_1;
558
717
  var _a, _b, _c, _d, _e, _f, _g, _h, _j;
559
- return __generator(this, function (_k) {
718
+ return __generator$1(this, function (_k) {
560
719
  switch (_k.label) {
561
720
  case 0:
562
721
  _k.trys.push([0, 2, , 3]);
@@ -614,10 +773,10 @@ function register(options) {
614
773
  * @returns A promise that resolves to a JSON-serializable representation of the PublicKeyCredential.
615
774
  */
616
775
  function authenticate(options) {
617
- return __awaiter(this, void 0, void 0, function () {
776
+ return __awaiter$1(this, void 0, void 0, function () {
618
777
  var getOptions, credential, publicKeyCredential, assertionResponse;
619
778
  var _a;
620
- return __generator(this, function (_b) {
779
+ return __generator$1(this, function (_b) {
621
780
  switch (_b.label) {
622
781
  case 0:
623
782
  getOptions = __assign(__assign({}, options), { challenge: base64urlToArrayBuffer(options.challenge), allowCredentials: (_a = options.allowCredentials) === null || _a === void 0 ? void 0 : _a.map(function (cred) { return (__assign(__assign({}, cred), { id: base64urlToArrayBuffer(cred.id) })); }) });
@@ -1090,7 +1249,7 @@ function ProtectedRoute(_a) {
1090
1249
  var children = _a.children, fallback = _a.fallback, redirectTo = _a.redirectTo;
1091
1250
  var _b = useCAMSContext$1(), isAuthenticated = _b.isAuthenticated, isLoading = _b.isLoading;
1092
1251
  if (isLoading) {
1093
- return fallback || jsxRuntimeExports.jsx("div", { children: "Loading..." });
1252
+ return fallback || jsxRuntimeExports.jsx("div", { className: 'h-screen flex items-center justify-center', children: "Loading..." });
1094
1253
  }
1095
1254
  if (!isAuthenticated) {
1096
1255
  if (redirectTo && typeof window !== 'undefined') {
@@ -1103,24 +1262,6 @@ function ProtectedRoute(_a) {
1103
1262
  }
1104
1263
 
1105
1264
  var CAMSMSALContext = createContext(null);
1106
- var setCookie = function (name, value, days) {
1107
- var expires = new Date(Date.now() + days * 864e5).toUTCString();
1108
- document.cookie = "".concat(name, "=").concat(encodeURIComponent(value), "; expires=").concat(expires, "; path=/; samesite=Lax");
1109
- };
1110
- var getCookie = function (name) {
1111
- var _a;
1112
- return ((_a = document.cookie
1113
- .split("; ")
1114
- .find(function (row) { return row.startsWith(name + "="); })) === null || _a === void 0 ? void 0 : _a.split("=")[1])
1115
- ? decodeURIComponent(document.cookie
1116
- .split("; ")
1117
- .find(function (row) { return row.startsWith(name + "="); })
1118
- .split("=")[1])
1119
- : null;
1120
- };
1121
- var deleteCookie = function (name) {
1122
- document.cookie = name + "=; Max-Age=-99999999; path=/";
1123
- };
1124
1265
  var isTokenValid = function (token) {
1125
1266
  try {
1126
1267
  var payload = JSON.parse(atob(token.split(".")[1]));
@@ -1169,7 +1310,7 @@ function CAMSMSALProviderInner(_a) {
1169
1310
  localStorage.setItem(auth.storageKey, JSON.stringify({
1170
1311
  accessToken: auth.accessToken,
1171
1312
  idToken: auth.idToken,
1172
- appCode: auth.appCode
1313
+ appCode: auth.appCode,
1173
1314
  }));
1174
1315
  }
1175
1316
  }, [auth.accessToken, auth.idToken, auth.storageKey]);
@@ -1185,8 +1326,8 @@ function CAMSMSALProviderInner(_a) {
1185
1326
  }
1186
1327
  }, [userProfile, profileStorageKey]);
1187
1328
  // Enhanced logout that also clears profile
1188
- var enhancedLogout = function () { return __awaiter(_this, void 0, void 0, function () {
1189
- return __generator(this, function (_a) {
1329
+ var enhancedLogout = function () { return __awaiter$1(_this, void 0, void 0, function () {
1330
+ return __generator$1(this, function (_a) {
1190
1331
  switch (_a.label) {
1191
1332
  case 0: return [4 /*yield*/, auth.logout()];
1192
1333
  case 1:
@@ -1203,7 +1344,12 @@ function CAMSMSALProviderInner(_a) {
1203
1344
  return (jsxRuntimeExports.jsx(CAMSMSALContext.Provider, { value: value, children: children }));
1204
1345
  }
1205
1346
  function CAMSMSALProvider(props) {
1347
+ var _a;
1206
1348
  var msalConfig = props.msalConfig, msalInstance = props.msalInstance;
1349
+ // Ensure crypto is available before creating MSAL instance
1350
+ if (typeof window !== "undefined" && !((_a = window.crypto) === null || _a === void 0 ? void 0 : _a.subtle)) {
1351
+ throw new Error("Crypto API not available. Polyfill failed to load.");
1352
+ }
1207
1353
  var instance = msalInstance || new PublicClientApplication(msalConfig);
1208
1354
  return (jsxRuntimeExports.jsx(MsalProvider, { instance: instance, children: jsxRuntimeExports.jsx(CAMSMSALProviderInner, __assign({}, props)) }));
1209
1355
  }
@@ -1253,7 +1399,7 @@ function CAMSProviderCore(props) {
1253
1399
  if (typeof window === "undefined")
1254
1400
  return null;
1255
1401
  try {
1256
- var storedProfile = getCookie$1(profileStorageKey);
1402
+ var storedProfile = getCookie(profileStorageKey);
1257
1403
  return storedProfile ? JSON.parse(storedProfile) : null;
1258
1404
  }
1259
1405
  catch (_a) {
@@ -1263,7 +1409,7 @@ function CAMSProviderCore(props) {
1263
1409
  var _a = useState(getInitialProfile), userProfile = _a[0], setUserProfile = _a[1];
1264
1410
  useEffect(function () {
1265
1411
  if (typeof window !== "undefined") {
1266
- var storedProfile = getCookie$1(profileStorageKey);
1412
+ var storedProfile = getCookie(profileStorageKey);
1267
1413
  if (storedProfile) {
1268
1414
  try {
1269
1415
  setUserProfile(JSON.parse(storedProfile));
@@ -1275,47 +1421,41 @@ function CAMSProviderCore(props) {
1275
1421
  useEffect(function () {
1276
1422
  if (typeof window !== "undefined") {
1277
1423
  if (userProfile) {
1278
- setCookie$1(profileStorageKey, JSON.stringify(userProfile), 1);
1424
+ setCookie(profileStorageKey, JSON.stringify(userProfile), 1);
1279
1425
  }
1280
1426
  else {
1281
- deleteCookie$1(profileStorageKey);
1427
+ deleteCookie(profileStorageKey);
1282
1428
  }
1283
1429
  }
1284
1430
  }, [userProfile, profileStorageKey]);
1285
- var enhancedLogout = function () { return __awaiter(_this, void 0, void 0, function () {
1286
- return __generator(this, function (_a) {
1431
+ var enhancedLogout = function () { return __awaiter$1(_this, void 0, void 0, function () {
1432
+ return __generator$1(this, function (_a) {
1287
1433
  switch (_a.label) {
1288
1434
  case 0: return [4 /*yield*/, auth.logout()];
1289
1435
  case 1:
1290
1436
  _a.sent();
1291
1437
  setUserProfile(null);
1292
1438
  if (typeof window !== "undefined") {
1293
- deleteCookie$1(profileStorageKey);
1439
+ deleteCookie(profileStorageKey);
1294
1440
  }
1295
1441
  return [2 /*return*/];
1296
1442
  }
1297
1443
  });
1298
1444
  }); };
1299
- // Handle MFA completion for MSAL mode
1300
1445
  useEffect(function () {
1301
1446
  if (mode === "MSAL" &&
1302
1447
  "requiresMFA" in auth &&
1303
1448
  !auth.requiresMFA &&
1304
1449
  auth.isAuthenticated) {
1305
- // MFA completed, extract profile from localStorage
1306
1450
  var storedData = localStorage.getItem(auth.storageKey);
1307
1451
  if (storedData) {
1308
1452
  try {
1309
1453
  var parsed = JSON.parse(storedData);
1310
- console.log("Parsed storage data:", parsed);
1311
1454
  if (parsed.userProfile) {
1312
- console.log("Setting user profile:", parsed.userProfile);
1313
1455
  setUserProfile(parsed.userProfile);
1314
1456
  }
1315
1457
  }
1316
- catch (e) {
1317
- console.error("Error parsing stored data:", e);
1318
- }
1458
+ catch (_a) { }
1319
1459
  }
1320
1460
  }
1321
1461
  }, [
@@ -1326,22 +1466,27 @@ function CAMSProviderCore(props) {
1326
1466
  userProfile,
1327
1467
  ]);
1328
1468
  var value = useMemo(function () {
1329
- return (__assign(__assign({}, auth), { logout: enhancedLogout, userProfile: userProfile, setUserProfile: setUserProfile, authMode: mode }));
1330
- }, [auth, userProfile, mode]);
1469
+ auth.logout; var authRest = __rest(auth, ["logout"]);
1470
+ return __assign(__assign({}, authRest), { logout: enhancedLogout, userProfile: userProfile, setUserProfile: setUserProfile, authMode: mode, onAuthSuccess: mode === "MSAL" ? props.onAuthSuccess : undefined, onAuthError: mode === "MSAL" ? props.onAuthError : undefined });
1471
+ }, [auth, userProfile, mode, props]);
1331
1472
  return jsxRuntimeExports.jsx(CAMSContext.Provider, { value: value, children: children });
1332
1473
  }
1333
1474
  function UnifiedCAMSProvider(props) {
1475
+ var _a;
1334
1476
  // Validate appCode is a valid GUID
1335
1477
  var appCodeValidation = GuidSchema.safeParse(props.appCode);
1336
1478
  if (!appCodeValidation.success) {
1337
- throw new Error("Invalid appCode: ".concat(appCodeValidation.error.issues[0].message));
1479
+ throw new Error("Invalid CAS APP CODE: ".concat(appCodeValidation.error.issues[0].message));
1338
1480
  }
1339
1481
  if (props.mode === "MSAL") {
1340
1482
  var msalConfig = props.msalConfig, msalInstance = props.msalInstance;
1483
+ if (typeof window !== "undefined" && !((_a = window.crypto) === null || _a === void 0 ? void 0 : _a.subtle)) {
1484
+ throw new Error("Crypto API not available. Polyfill failed to load.");
1485
+ }
1341
1486
  var instance = msalInstance || new PublicClientApplication(msalConfig);
1342
1487
  return (jsxRuntimeExports.jsx(MsalProvider, { instance: instance, children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
1343
1488
  }
1344
- return (jsxRuntimeExports.jsx(ClientOnly, { fallback: jsxRuntimeExports.jsx("div", { children: "Loading..." }), children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
1489
+ return (jsxRuntimeExports.jsx(ClientOnly, { fallback: jsxRuntimeExports.jsx("div", { className: 'h-screen flex items-center justify-center', children: "Loading..." }), children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
1345
1490
  }
1346
1491
  // Backward compatibility exports
1347
1492
  var CAMSProvider = function (props) { return (jsxRuntimeExports.jsx(UnifiedCAMSProvider, __assign({}, props, { mode: "REGULAR" }))); };
@@ -1670,39 +1815,9 @@ function DialogTitle(_a) {
1670
1815
 
1671
1816
  var a="container_f782f4",i="inner_37f4c9",c="bar_409d0f";const r=({size:r=35,color:l="black",speed:d=1,stroke:o=3.5})=>jsxRuntimeExports.jsx("div",{className:a,style:{"--uib-size":r+"px","--uib-color":l,"--uib-speed":d+"s","--uib-stroke":o+"px"},children:jsxRuntimeExports.jsxs("div",{className:i,children:[jsxRuntimeExports.jsx("div",{className:c}),jsxRuntimeExports.jsx("div",{className:c}),jsxRuntimeExports.jsx("div",{className:c}),jsxRuntimeExports.jsx("div",{className:c})]})});
1672
1817
 
1673
- function styleInject(css, ref) {
1674
- if ( ref === void 0 ) ref = {};
1675
- var insertAt = ref.insertAt;
1676
-
1677
- if (typeof document === 'undefined') { return; }
1678
-
1679
- var head = document.head || document.getElementsByTagName('head')[0];
1680
- var style = document.createElement('style');
1681
- style.type = 'text/css';
1682
-
1683
- if (insertAt === 'top') {
1684
- if (head.firstChild) {
1685
- head.insertBefore(style, head.firstChild);
1686
- } else {
1687
- head.appendChild(style);
1688
- }
1689
- } else {
1690
- head.appendChild(style);
1691
- }
1692
-
1693
- if (style.styleSheet) {
1694
- style.styleSheet.cssText = css;
1695
- } else {
1696
- style.appendChild(document.createTextNode(css));
1697
- }
1698
- }
1699
-
1700
- var css_248z = ".container_f782f4 {\n flex-shrink: 0;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n height: calc(var(--uib-size) * 0.9);\n width: var(--uib-size);\n}\n\n.inner_37f4c9 {\n display: flex;\n align-items: center;\n justify-content: space-between;\n width: var(--uib-size);\n height: calc(var(--uib-size) * 0.9);\n}\n\n.bar_409d0f {\n width: var(--uib-stroke);\n height: 100%;\n background-color: var(--uib-color);\n transition: background-color 0.3s ease;\n}\n\n.bar_409d0f:nth-child(1) {\n animation: grow_ca6a4e var(--uib-speed) ease-in-out calc(var(--uib-speed) * -0.45) infinite;\n}\n\n.bar_409d0f:nth-child(2) {\n animation: grow_ca6a4e var(--uib-speed) ease-in-out calc(var(--uib-speed) * -0.3) infinite;\n}\n\n.bar_409d0f:nth-child(3) {\n animation: grow_ca6a4e var(--uib-speed) ease-in-out calc(var(--uib-speed) * -0.15) infinite;\n}\n\n.bar_409d0f:nth-child(4) {\n animation: grow_ca6a4e var(--uib-speed) ease-in-out infinite;\n}\n\n@keyframes grow_ca6a4e {\n 0%, 100% {\n transform: scaleY(0.3);\n }\n 50% {\n transform: scaleY(1);\n }\n}";
1701
- styleInject(css_248z);
1702
-
1703
1818
  var LoadingSpinner = function (_a) {
1704
1819
  var loadingText = _a.loadingText;
1705
- return (jsxRuntimeExports.jsxs("div", { className: "flex flex-col justify-center items-center", children: [jsxRuntimeExports.jsx("script", { type: "module", defer: true, src: "https://cdn.jsdelivr.net/npm/ldrs/dist/auto/waveform.js" }), jsxRuntimeExports.jsx(r, { size: "35", stroke: "3.5", speed: "1", color: "green" }), loadingText && (jsxRuntimeExports.jsx("p", { className: "text-center font-semibold mt-3", children: "Loading..." }))] }));
1820
+ return (jsxRuntimeExports.jsxs("div", { className: "flex flex-col justify-center items-center h-full w-full py-10", children: [jsxRuntimeExports.jsx("script", { type: "module", defer: true, src: "https://cdn.jsdelivr.net/npm/ldrs/dist/auto/waveform.js" }), jsxRuntimeExports.jsx(r, { size: "35", stroke: "3.5", speed: "1", color: "green" }), loadingText && (jsxRuntimeExports.jsx("p", { className: "text-center font-semibold mt-3", children: "Loading..." }))] }));
1706
1821
  };
1707
1822
 
1708
1823
  var AuthSuccessAnimation = function (_a) {
@@ -1754,15 +1869,36 @@ var APIHeaders = {
1754
1869
  "X-API-VERSION": "1.0",
1755
1870
  };
1756
1871
 
1872
+ // Creates an Axios instance with a base URL determined by the environment (production or development).
1873
+ var axiosInstance = axios.create({
1874
+ httpsAgent: new https.Agent({ rejectUnauthorized: false }),
1875
+ headers: __assign({ "Content-Type": "application/json" }, APIHeaders),
1876
+ });
1877
+ // Intercepts outgoing requests to add authorization token, version header, and timeout settings.
1878
+ axiosInstance.interceptors.request.use(function (config) {
1879
+ var _a;
1880
+ config.timeout = Number((_a = process.env.NEXT_PUBLIC_API_TIMEOUT) !== null && _a !== void 0 ? _a : 605000);
1881
+ config.timeoutErrorMessage = "Operation Timed Out"; // Custom error message for timeouts.
1882
+ return config; // Returns the modified request configuration.
1883
+ }, function (axiosError) {
1884
+ var _a, _b;
1885
+ // Handles request errors.
1886
+ return {
1887
+ status: (_a = axiosError.response) === null || _a === void 0 ? void 0 : _a.status, // Extracts HTTP status from the error response.
1888
+ message: axiosError.message, // Extracts the error message.
1889
+ data: (_b = axiosError.response) === null || _b === void 0 ? void 0 : _b.data, // Extracts response data from the error.
1890
+ };
1891
+ });
1892
+
1757
1893
  var MAX_ATTEMPTS = 3;
1758
1894
  var useOTPHandler = function (_a) {
1759
1895
  var provider = _a.provider, accessToken = _a.accessToken, idToken = _a.idToken, appCode = _a.appCode, authenticationType = _a.authenticationType, MFAEndpoint = _a.MFAEndpoint, onAuthComplete = _a.onAuthComplete;
1760
1896
  var _b = useState(false), loading = _b[0], setLoading = _b[1];
1761
1897
  var _c = useState(0), attemptCount = _c[0], setAttemptCount = _c[1];
1762
1898
  var _d = useState(false), isMaxAttemptsReached = _d[0], setIsMaxAttemptsReached = _d[1];
1763
- var handleSubmitOTP = useMemo(function () { return function (authenticationValue) { return __awaiter(void 0, void 0, void 0, function () {
1899
+ var handleSubmitOTP = useMemo(function () { return function (authenticationValue) { return __awaiter$1(void 0, void 0, void 0, function () {
1764
1900
  var currentAttempt, response, error_1, currentAttempt;
1765
- return __generator(this, function (_a) {
1901
+ return __generator$1(this, function (_a) {
1766
1902
  switch (_a.label) {
1767
1903
  case 0:
1768
1904
  if (isMaxAttemptsReached) {
@@ -1779,16 +1915,13 @@ var useOTPHandler = function (_a) {
1779
1915
  setAttemptCount(currentAttempt);
1780
1916
  if (authenticationType === null)
1781
1917
  return [2 /*return*/, false];
1782
- return [4 /*yield*/, axios.post(MFAEndpoint || "/api/auth/verify-mfa", {
1918
+ return [4 /*yield*/, axiosInstance.post(MFAEndpoint || "/api/auth/verify-mfa", {
1783
1919
  provider: provider,
1784
1920
  accessToken: accessToken,
1785
1921
  idToken: idToken,
1786
1922
  authenticationType: authenticationType,
1787
1923
  MFACode: authenticationValue,
1788
1924
  appCode: appCode,
1789
- }, {
1790
- headers: APIHeaders,
1791
- timeout: 605000,
1792
1925
  })];
1793
1926
  case 2:
1794
1927
  response = (_a.sent()).data;
@@ -1855,23 +1988,20 @@ var useCredentialsHandler = function (onAuthComplete) {
1855
1988
  var _b = useState(0), attemptCount = _b[0], setAttemptCount = _b[1];
1856
1989
  var _c = useState(false), isMaxAttemptsReached = _c[0], setIsMaxAttemptsReached = _c[1];
1857
1990
  var handleSubmitCredentials = useMemo(function () {
1858
- return function (CredAuthEndpoint, credentials, appCode) { return __awaiter(void 0, void 0, void 0, function () {
1991
+ return function (CredAuthEndpoint, credentials, appCode) { return __awaiter$1(void 0, void 0, void 0, function () {
1859
1992
  var currentAttempt, response, error_2, currentAttempt;
1860
- return __generator(this, function (_a) {
1993
+ return __generator$1(this, function (_a) {
1861
1994
  switch (_a.label) {
1862
1995
  case 0:
1863
1996
  _a.trys.push([0, 2, 3, 4]);
1864
1997
  setLoading(true);
1865
1998
  currentAttempt = attemptCount + 1;
1866
1999
  setAttemptCount(currentAttempt);
1867
- return [4 /*yield*/, axios.post(CredAuthEndpoint, {
2000
+ return [4 /*yield*/, axiosInstance.post(CredAuthEndpoint, {
1868
2001
  username: credentials.username,
1869
2002
  password: credentials.password,
1870
2003
  MFACode: credentials.MFACode,
1871
2004
  appCode: appCode,
1872
- }, {
1873
- headers: APIHeaders,
1874
- timeout: 605000,
1875
2005
  })];
1876
2006
  case 1:
1877
2007
  response = (_a.sent()).data;
@@ -1932,23 +2062,21 @@ var MFAOptions = function (_a) {
1932
2062
  var context = useCAMSContext();
1933
2063
  var _f = context.authMode === "MSAL" && "sendEmailOTP" in context
1934
2064
  ? context
1935
- : { sendEmailOTP: null, completeMFA: null, logout: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
2065
+ : { sendEmailOTP: null, completeMFA: null, logout: function () { return __awaiter$1(void 0, void 0, void 0, function () { return __generator$1(this, function (_a) {
1936
2066
  return [2 /*return*/];
1937
2067
  }); }); } }, sendEmailOTP = _f.sendEmailOTP, completeMFA = _f.completeMFA, logout = _f.logout;
1938
2068
  var accessToken = context.authMode === "MSAL" ? context.accessToken : "";
1939
2069
  var idToken = context.authMode === "MSAL" ? context.idToken : "";
1940
2070
  var authenticate = useWebAuthn().authenticate;
1941
- var handleFIDOLogin = function () { return __awaiter(void 0, void 0, void 0, function () {
2071
+ var handleFIDOLogin = function () { return __awaiter$1(void 0, void 0, void 0, function () {
1942
2072
  var options, assertionResponse, error_1;
1943
- return __generator(this, function (_a) {
2073
+ return __generator$1(this, function (_a) {
1944
2074
  switch (_a.label) {
1945
2075
  case 0:
1946
2076
  _a.trys.push([0, 4, , 5]);
1947
2077
  // 1. Fetch authentication challenge from your server
1948
2078
  console.log("Requesting authentication challenge from server...");
1949
- return [4 /*yield*/, axios.post(MFAEndpoints.RetrieveAuthChallenge, {}, {
1950
- headers: APIHeaders,
1951
- })];
2079
+ return [4 /*yield*/, axiosInstance.post(MFAEndpoints.RetrieveAuthChallenge, {})];
1952
2080
  case 1:
1953
2081
  options = (_a.sent()).data;
1954
2082
  console.log("Received challenge:", options);
@@ -1960,9 +2088,7 @@ var MFAOptions = function (_a) {
1960
2088
  console.log("Authentication assertion received from client:", assertionResponse);
1961
2089
  // 3. Send the assertion back to the server for verification
1962
2090
  console.log("Sending assertion to server for verification...");
1963
- return [4 /*yield*/, axios.post(MFAEndpoints.AuthChallengeVerify, assertionResponse, {
1964
- headers: APIHeaders
1965
- })];
2091
+ return [4 /*yield*/, axiosInstance.post(MFAEndpoints.AuthChallengeVerify, assertionResponse)];
1966
2092
  case 3:
1967
2093
  _a.sent();
1968
2094
  toast.success("🔑 Sign-in successful!");
@@ -2024,12 +2150,12 @@ var MFAOptions = function (_a) {
2024
2150
  }
2025
2151
  var content = jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, {});
2026
2152
  if (!authType) {
2027
- content = (jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 text-center mb-6", children: "Choose your preferred authentication method:" }), jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-3", children: [jsxRuntimeExports.jsxs(Button, { variant: "outline", className: "w-full flex items-center justify-start gap-3 p-4 h-auto border-2 hover:border-[#506f4a] hover:bg-[#506f4a]/5 transition-all", onClick: function () { return __awaiter(void 0, void 0, void 0, function () {
2153
+ content = (jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [jsxRuntimeExports.jsx("p", { className: "text-sm text-gray-600 text-center mb-6", children: "Choose your preferred authentication method:" }), jsxRuntimeExports.jsxs("div", { className: "flex flex-col gap-3", children: [jsxRuntimeExports.jsxs(Button, { variant: "outline", className: "w-full flex items-center justify-start gap-3 p-4 h-auto border-2 hover:border-[#506f4a] hover:bg-[#506f4a]/5 transition-all", onClick: function () { return __awaiter$1(void 0, void 0, void 0, function () {
2028
2154
  var success;
2029
- return __generator(this, function (_a) {
2155
+ return __generator$1(this, function (_a) {
2030
2156
  switch (_a.label) {
2031
2157
  case 0:
2032
- resetAttempts();
2158
+ // resetAttempts();
2033
2159
  setAuthType("EmailOTP");
2034
2160
  setOtpVisible(true);
2035
2161
  if (!sendEmailOTP) return [3 /*break*/, 2];
@@ -2046,7 +2172,6 @@ var MFAOptions = function (_a) {
2046
2172
  }
2047
2173
  });
2048
2174
  }); }, children: [jsxRuntimeExports.jsx(Mail, { className: "w-5 h-5" }), jsxRuntimeExports.jsxs("div", { className: "text-left", children: [jsxRuntimeExports.jsx("div", { className: "font-medium", children: "Email OTP" }), jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: "Send code to your email" })] })] }), jsxRuntimeExports.jsxs(Button, { variant: "outline", className: "w-full flex items-center justify-start gap-3 p-4 h-auto border-2 hover:border-[#506f4a] hover:bg-[#506f4a]/5 transition-all", onClick: function () {
2049
- resetAttempts();
2050
2175
  setAuthType("AuthenticatorCode");
2051
2176
  setOtpVisible(true);
2052
2177
  }, children: [jsxRuntimeExports.jsx("img", { src: MicrosoftAuthenticatorImg, alt: "Authenticator", className: "rounded-full", width: 24, height: 24, onError: function () { return jsxRuntimeExports.jsx(Shield, {}); } }), jsxRuntimeExports.jsxs("div", { className: "text-left", children: [jsxRuntimeExports.jsx("div", { className: "font-medium", children: "Authenticator App" }), jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: "Use Authenticator App" })] })] }), usePassKey && (jsxRuntimeExports.jsxs(Button, { variant: "outline", className: "w-full flex items-center justify-start gap-3 p-4 h-auto border-2 hover:border-[#506f4a] hover:bg-[#506f4a]/5 transition-all",
@@ -2055,7 +2180,7 @@ var MFAOptions = function (_a) {
2055
2180
  // setAuthType("AuthenticatorCode");
2056
2181
  // setOtpVisible(true);
2057
2182
  // }}
2058
- onClick: handleFIDOLogin, disabled: context.isLoading, children: [jsxRuntimeExports.jsx(Button, { className: "w-full flex items-center justify-center cursor-pointer bg-[#506f4a] hover:bg-[#506f4a] rounded-lg border border-transparent px-5 py-8 text-base font-medium transition-colors duration-250", children: jsxRuntimeExports.jsx("span", { children: "Sign In " }) }), jsxRuntimeExports.jsx(KeyIcon, { className: "w-16 h-16 text-[#506f4a]" }), jsxRuntimeExports.jsxs("div", { className: "text-left", children: [jsxRuntimeExports.jsx("div", { className: "font-medium", children: "Continue with Passkey" }), jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: "Passkey" })] })] }))] })] }));
2183
+ onClick: handleFIDOLogin, disabled: context.isLoading, children: [jsxRuntimeExports.jsx(KeyIcon, { className: "text-[#506f4a]", size: 48 }), jsxRuntimeExports.jsxs("div", { className: "text-left", children: [jsxRuntimeExports.jsx("div", { className: "font-medium", children: "Continue with Passkey" }), jsxRuntimeExports.jsx("div", { className: "text-sm text-gray-500", children: "Passkey" })] })] }))] })] }));
2059
2184
  }
2060
2185
  else if (authType === "EmailOTP") {
2061
2186
  content = (jsxRuntimeExports.jsx(Dialog, { open: otpVisible, onOpenChange: function () {
@@ -2098,16 +2223,16 @@ var ADLoginModal = function (_a) {
2098
2223
  resolver: a$1(credentialsSchema),
2099
2224
  defaultValues: { username: "", password: "" },
2100
2225
  });
2101
- var handleCredentialsSubmit = function (values) { return __awaiter(void 0, void 0, void 0, function () {
2102
- return __generator(this, function (_a) {
2226
+ var handleCredentialsSubmit = function (values) { return __awaiter$1(void 0, void 0, void 0, function () {
2227
+ return __generator$1(this, function (_a) {
2103
2228
  setCredentials(values);
2104
2229
  setStep("mfa");
2105
2230
  return [2 /*return*/];
2106
2231
  });
2107
2232
  }); };
2108
- var handleMFASubmit = function (code) { return __awaiter(void 0, void 0, void 0, function () {
2233
+ var handleMFASubmit = function (code) { return __awaiter$1(void 0, void 0, void 0, function () {
2109
2234
  var error_1;
2110
- return __generator(this, function (_a) {
2235
+ return __generator$1(this, function (_a) {
2111
2236
  switch (_a.label) {
2112
2237
  case 0:
2113
2238
  setIsLoading(true);
@@ -2168,8 +2293,8 @@ var DefaultLoginPage = function (_a) {
2168
2293
  var login = context.login, isLoading = context.isLoading, authMode = context.authMode;
2169
2294
  var _b = useState(false), showADModal = _b[0], setShowADModal = _b[1];
2170
2295
  var register = useWebAuthn().register;
2171
- var _c = useCredentialsHandler(function (state, data) { return __awaiter(void 0, void 0, void 0, function () {
2172
- return __generator(this, function (_a) {
2296
+ var _c = useCredentialsHandler(function (state, data) { return __awaiter$1(void 0, void 0, void 0, function () {
2297
+ return __generator$1(this, function (_a) {
2173
2298
  console.log(data);
2174
2299
  if (state && data) {
2175
2300
  context.isAuthenticated = true;
@@ -2183,6 +2308,10 @@ var DefaultLoginPage = function (_a) {
2183
2308
  });
2184
2309
  }); }), handleSubmitCredentials = _c.handleSubmitCredentials, isCredAuthLoading = _c.loading, setIsCredAuthLoading = _c.setLoading;
2185
2310
  var handleMSALLogin = function () {
2311
+ if (typeof window !== "undefined" && !window.crypto) {
2312
+ toast.error("Crypto API not available. Please use a modern browser.");
2313
+ return;
2314
+ }
2186
2315
  if (authMode === "MSAL") {
2187
2316
  login();
2188
2317
  }
@@ -2191,17 +2320,15 @@ var DefaultLoginPage = function (_a) {
2191
2320
  console.warn("Regular CAMS login requires configuration");
2192
2321
  }
2193
2322
  };
2194
- var handleRegister = function (data) { return __awaiter(void 0, void 0, void 0, function () {
2323
+ var handleRegister = function (data) { return __awaiter$1(void 0, void 0, void 0, function () {
2195
2324
  var options, attestationResponse, error_1;
2196
- return __generator(this, function (_a) {
2325
+ return __generator$1(this, function (_a) {
2197
2326
  switch (_a.label) {
2198
2327
  case 0:
2199
2328
  _a.trys.push([0, 4, , 5]);
2200
2329
  // 1. Fetch challenge from your server
2201
2330
  console.log("Requesting registration challenge from server...");
2202
- return [4 /*yield*/, axios.post(MFAEndpoints.RegisterNewChallenge, __assign({}, data), {
2203
- headers: APIHeaders,
2204
- })];
2331
+ return [4 /*yield*/, axiosInstance.post(MFAEndpoints.RegisterNewChallenge, __assign({}, data))];
2205
2332
  case 1:
2206
2333
  options = (_a.sent()).data;
2207
2334
  console.log("Received challenge:", options);
@@ -2213,9 +2340,7 @@ var DefaultLoginPage = function (_a) {
2213
2340
  console.log("Passkey created on client:", attestationResponse);
2214
2341
  // 3. Send the response back to the server for verification
2215
2342
  console.log("Sending attestation to server for verification...");
2216
- return [4 /*yield*/, axios.post(MFAEndpoints.RegisterVerify + "?username=".concat(data.username), attestationResponse, {
2217
- headers: APIHeaders
2218
- })];
2343
+ return [4 /*yield*/, axiosInstance.post(MFAEndpoints.RegisterVerify + "?username=".concat(data.username), attestationResponse)];
2219
2344
  case 3:
2220
2345
  _a.sent();
2221
2346
  toast.success("✅ Registration successful! Passkey created.");
@@ -2229,15 +2354,15 @@ var DefaultLoginPage = function (_a) {
2229
2354
  }
2230
2355
  });
2231
2356
  }); };
2232
- return (jsxRuntimeExports.jsxs("main", { className: "min-h-screen bg-gray-50", children: [jsxRuntimeExports.jsx(motion.div, { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 }, transition: { duration: 0.5 }, children: jsxRuntimeExports.jsx("div", { className: "flex h-screen items-center justify-center", children: jsxRuntimeExports.jsxs(motion.div, { variants: cardVariants, initial: "hidden", animate: "visible", exit: "exit", className: "w-full max-w-md p-6 space-y-4 bg-gray-50 rounded-2xl shadow-2xl --dark:bg-gray-800", children: [jsxRuntimeExports.jsxs(CardHeader, { className: "text-center space-y-3", children: [jsxRuntimeExports.jsx("div", { className: "w-full flex items-center justify-center", children: jsxRuntimeExports.jsx("img", { src: NIBSSLogo, alt: "NIBSS Logo", width: 265, height: 265 }) }), jsxRuntimeExports.jsx(CardTitle, { className: "text-3xl font-bold --text-gray-900 --dark:text-white", children: "NIBSS CAMS" }), jsxRuntimeExports.jsx(CardTitle, { className: "text-gray-500 dark:text-gray-400 font-bold text-lg", children: "Centralized Authentication" })] }), jsxRuntimeExports.jsxs(CardAction, { className: "w-full flex flex-col items-center justify-center text-center text-gray-500 dark:text-gray-400 mb-6", children: [jsxRuntimeExports.jsx("img", { src: AuthLogo, alt: "Auth Logo", width: 365, height: 365 }), "Kindly use the below identity providers to authenticate"] }), jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [jsxRuntimeExports.jsxs(Button
2357
+ return (jsxRuntimeExports.jsxs("main", { className: "min-h-screen bg-gray-50", children: [jsxRuntimeExports.jsx(motion.div, { initial: { opacity: 0 }, animate: { opacity: 1 }, exit: { opacity: 0 }, transition: { duration: 0.5 }, children: jsxRuntimeExports.jsx("div", { className: "flex h-screen items-center justify-center", children: jsxRuntimeExports.jsxs(motion.div, { variants: cardVariants, initial: "hidden", animate: "visible", exit: "exit", className: "w-full max-w-md p-6 space-y-4 bg-gray-50 rounded-2xl shadow-2xl --dark:bg-gray-800", children: [jsxRuntimeExports.jsxs(CardHeader, { className: "text-center space-y-3", children: [jsxRuntimeExports.jsx("div", { className: "w-full flex items-center justify-center", children: jsxRuntimeExports.jsx("img", { src: NIBSSLogo, alt: "NIBSS Logo", width: 265, height: 265 }) }), jsxRuntimeExports.jsx(CardTitle, { className: "text-3xl font-bold --text-gray-900 --dark:text-white", children: "NIBSS CAMS" }), jsxRuntimeExports.jsx(CardTitle, { className: "text-gray-500 dark:text-gray-400 font-bold text-lg", children: "Centralized Authentication" })] }), jsxRuntimeExports.jsxs(CardAction, { className: "w-full flex flex-col items-center justify-center text-center text-gray-500 dark:text-gray-400 mb-8", children: [jsxRuntimeExports.jsx("img", { src: AuthLogo, alt: "Auth Logo", width: 365, height: 365 }), "Use Below Identity Providers To Authenticate"] }), jsxRuntimeExports.jsxs("div", { className: "space-y-4", children: [jsxRuntimeExports.jsxs(Button
2233
2358
  // variant="outline"
2234
2359
  , {
2235
2360
  // variant="outline"
2236
2361
  className: "w-full flex items-center justify-center cursor-pointer bg-[#506f4a] hover:bg-[#506f4a] rounded-lg border border-transparent px-5 py-8 text-base font-medium transition-colors duration-250", onClick: handleMSALLogin, disabled: isLoading, children: [jsxRuntimeExports.jsx("img", { src: MicrosoftLogo, alt: "Microsoft Logo", width: 35, height: 35 }), jsxRuntimeExports.jsx("span", { className: "ml-2", children: isLoading ? "Logging in..." : "Sign in with Microsoft" })] }), useADLogin && (jsxRuntimeExports.jsxs(Button, { className: "w-full flex items-center justify-center cursor-pointer bg-[#506f4a] hover:bg-[#506f4a] rounded-lg border border-transparent px-5 py-8 text-base font-medium transition-colors duration-250", onClick: function () { return setShowADModal(true); }, disabled: isLoading, children: [jsxRuntimeExports.jsx(KeyIcon, { className: "text-[#506f4a]", size: 64 }), jsxRuntimeExports.jsx("span", { children: isLoading
2237
2362
  ? "Logging in..."
2238
- : "Sign in with ActiveDirectory" })] })), usePassKey && (jsxRuntimeExports.jsxs(Button, { className: "w-full flex items-center justify-center cursor-pointer bg-[#506f4a] hover:bg-[#506f4a] rounded-lg border border-transparent px-5 py-8 text-base font-medium transition-colors duration-250", onClick: function () { return handleRegister(PassKeysRegisterProps); }, disabled: isLoading, children: [jsxRuntimeExports.jsx(KeyIcon, { className: "text-[#506f4a]", size: 64 }), jsxRuntimeExports.jsx("span", { children: "Create a Passkey" })] }))] }), jsxRuntimeExports.jsxs(CardFooter, { className: "flex items-center justify-center mt-6 space-x-2 text-gray-400 text-sm", children: [jsxRuntimeExports.jsx(ShieldCheck, { className: "w-4 h-4 text-[#506f4a] pulse-glow" }), jsxRuntimeExports.jsx("span", { children: "Powered By NIBSS" })] })] }) }) }, "landing"), jsxRuntimeExports.jsx(ADLoginModal, { open: showADModal, onOpenChange: setShowADModal, isLoading: isCredAuthLoading, setIsLoading: setIsCredAuthLoading, onLogin: function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
2363
+ : "Sign in with ActiveDirectory" })] })), usePassKey && (jsxRuntimeExports.jsxs(Button, { className: "w-full flex items-center justify-center cursor-pointer bg-[#506f4a] hover:bg-[#506f4a] rounded-lg border border-transparent px-5 py-8 text-base font-medium transition-colors duration-250", onClick: function () { return handleRegister(PassKeysRegisterProps); }, disabled: isLoading, children: [jsxRuntimeExports.jsx(KeyIcon, { className: "text-[#506f4a]", size: 64 }), jsxRuntimeExports.jsx("span", { children: "Create a Passkey" })] }))] }), jsxRuntimeExports.jsxs(CardFooter, { className: "flex items-center justify-center mt-6 space-x-2 text-gray-400 text-sm", children: [jsxRuntimeExports.jsx(ShieldCheck, { className: "w-4 h-4 text-[#506f4a] pulse-glow" }), jsxRuntimeExports.jsx("span", { children: "Powered By NIBSS" })] })] }) }) }, "landing"), jsxRuntimeExports.jsx(ADLoginModal, { open: showADModal, onOpenChange: setShowADModal, isLoading: isCredAuthLoading, setIsLoading: setIsCredAuthLoading, onLogin: function (_a) { return __awaiter$1(void 0, [_a], void 0, function (_b) {
2239
2364
  var username = _b.username, password = _b.password, MFACode = _b.MFACode;
2240
- return __generator(this, function (_c) {
2365
+ return __generator$1(this, function (_c) {
2241
2366
  // Implement your AD login logic here
2242
2367
  console.log("AD Login:", { username: username, password: password, MFACode: MFACode });
2243
2368
  // Example: await adLoginService(username, password, mfaCode);
@@ -2260,11 +2385,11 @@ var MFAEndpointsSchema = z$1.object({
2260
2385
  AuthChallengeVerify: z$1.url("MFA AuthChallengeVerify must be a valid URL"),
2261
2386
  });
2262
2387
  var MFAGate = function (_a) {
2263
- var children = _a.children, _b = _a.fallback, fallback = _b === void 0 ? jsxRuntimeExports.jsx(LoadingSpinner, {}) : _b,
2388
+ var children = _a.children, _b = _a.fallback, fallback = _b === void 0 ? jsxRuntimeExports.jsx("div", { className: 'h-screen flex items-center justify-center', children: jsxRuntimeExports.jsx(LoadingSpinner, {}) }) : _b,
2264
2389
  // loginComponent: LoginComponent = DefaultLoginPage,
2265
2390
  _c = _a.usePassKey,
2266
2391
  // loginComponent: LoginComponent = DefaultLoginPage,
2267
- usePassKey = _c === void 0 ? false : _c, _d = _a.useADLogin, useADLogin = _d === void 0 ? false : _d, CredentialsAuthEndpoint = _a.CredentialsAuthEndpoint, PassKeysRegisterProps = _a.PassKeysRegisterProps, MFAEndpoints = _a.MFAEndpoints;
2392
+ usePassKey = _c === void 0 ? false : _c, _d = _a.useADLogin, useADLogin = _d === void 0 ? false : _d, CredentialsAuthEndpoint = _a.CredentialsAuthEndpoint, PassKeysRegisterProps = _a.PassKeysRegisterProps, MFAEndpoints = _a.MFAEndpoints, requiresMFA = _a.requiresMFA, onAuthSuccess = _a.onAuthSuccess, onAuthError = _a.onAuthError;
2268
2393
  var context = useCAMSContext();
2269
2394
  var validatedMFAEndpoints = useMemo(function () {
2270
2395
  var parsed = MFAEndpointsSchema.safeParse(MFAEndpoints);
@@ -2275,20 +2400,35 @@ var MFAGate = function (_a) {
2275
2400
  return parsed.data;
2276
2401
  }, [MFAEndpoints]);
2277
2402
  var handleComplete = useCallback(function (success) {
2278
- if (!success)
2403
+ var _a;
2404
+ if (success && context.authMode === "MSAL") {
2405
+ var tokens = {
2406
+ accessToken: context.accessToken,
2407
+ idToken: context.idToken,
2408
+ };
2409
+ onAuthSuccess === null || onAuthSuccess === void 0 ? void 0 : onAuthSuccess(tokens);
2410
+ (_a = context.onAuthSuccess) === null || _a === void 0 ? void 0 : _a.call(context, tokens);
2411
+ }
2412
+ else if (!success) {
2279
2413
  Logger.error("MFA authentication failed");
2280
- }, []);
2281
- var handleAuthFailed = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
2282
- return __generator(this, function (_a) {
2283
- switch (_a.label) {
2284
- case 0: return [4 /*yield*/, context.logout()];
2414
+ }
2415
+ }, [context, onAuthSuccess]);
2416
+ var handleAuthFailed = useCallback(function () { return __awaiter$1(void 0, void 0, void 0, function () {
2417
+ var _a;
2418
+ return __generator$1(this, function (_b) {
2419
+ switch (_b.label) {
2420
+ case 0:
2421
+ if (context.authMode === "MSAL" && context.error) {
2422
+ onAuthError === null || onAuthError === void 0 ? void 0 : onAuthError(context.error);
2423
+ (_a = context.onAuthError) === null || _a === void 0 ? void 0 : _a.call(context, context.error);
2424
+ }
2425
+ return [4 /*yield*/, context.logout()];
2285
2426
  case 1:
2286
- _a.sent();
2427
+ _b.sent();
2287
2428
  return [2 /*return*/];
2288
2429
  }
2289
2430
  });
2290
- }); }, [context.logout]);
2291
- Logger.debug("MFA Endpoint >>>", { MFAEndpoints: MFAEndpoints });
2431
+ }); }, [context, onAuthError]);
2292
2432
  if (useADLogin && !CredentialsAuthEndpoint)
2293
2433
  return jsxRuntimeExports.jsx(ErrorFallback, { message: "Invalid AD Login Configuration." });
2294
2434
  if (!validatedMFAEndpoints)
@@ -2297,10 +2437,11 @@ var MFAGate = function (_a) {
2297
2437
  return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
2298
2438
  if (context.isLoading)
2299
2439
  return fallback;
2300
- if (context.requiresMFA) {
2301
- return (jsxRuntimeExports.jsx(MFAOptions, { MFAEndpoints: validatedMFAEndpoints, usePassKey: usePassKey, onComplete: handleComplete, onAuthFailed: handleAuthFailed }));
2302
- }
2303
2440
  if (!context.isAuthenticated) {
2441
+ var shouldRequireMFA = requiresMFA !== null && requiresMFA !== void 0 ? requiresMFA : context.requiresMFA;
2442
+ if (shouldRequireMFA && context.accessToken) {
2443
+ return (jsxRuntimeExports.jsx(MFAOptions, { MFAEndpoints: validatedMFAEndpoints, usePassKey: usePassKey, onComplete: handleComplete, onAuthFailed: handleAuthFailed }));
2444
+ }
2304
2445
  return (jsxRuntimeExports.jsx(DefaultLoginPage, { usePassKey: usePassKey, useADLogin: useADLogin, MFAEndpoints: MFAEndpoints, PassKeysRegisterProps: PassKeysRegisterProps, CredentialsAuthEndpoint: CredentialsAuthEndpoint }));
2305
2446
  }
2306
2447
  return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });