@nibssplc/cams-sdk-react 0.0.1-beta.75 → 0.0.1-beta.77

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
@@ -2,8 +2,8 @@ import * as React from 'react';
2
2
  import React__default, { useState, useRef, useEffect, useCallback, createContext, useContext, useMemo } from 'react';
3
3
  import { isPopupWindow, initializePopupAuth, CAMSSessionManager, CAMSMFAAuthenticator, Logger, CAMSError, CAMSErrorType } from '@nibssplc/cams-sdk';
4
4
  export * from '@nibssplc/cams-sdk';
5
- import { useMsal, useAccount, MsalProvider } from '@azure/msal-react';
6
- import { InteractionStatus, PublicClientApplication } from '@azure/msal-browser';
5
+ import { MsalProvider, useMsal, useAccount } from '@azure/msal-react';
6
+ import { PublicClientApplication, InteractionStatus } from '@azure/msal-browser';
7
7
  import z$1, { z } from 'zod';
8
8
  import { OTPInput, OTPInputContext, REGEXP_ONLY_DIGITS } from 'input-otp';
9
9
  import { RectangleEllipsis, XIcon, CheckCircle, Mail, Shield, ShieldCheck, ShieldClose } from 'lucide-react';
@@ -236,322 +236,18 @@ function useCAMSAuth(options) {
236
236
  };
237
237
  }
238
238
 
239
- function useCAMSMSALAuth(options) {
240
- var _this = this;
241
- var storageKey = options.storageKey || "CAMS-MSAL-AUTH-SDK";
242
- var _a = useMsal(), instance = _a.instance, inProgress = _a.inProgress, accounts = _a.accounts;
243
- var account = useAccount(accounts[0] || {});
244
- var _b = useState(null), error = _b[0], setError = _b[1];
245
- var _c = useState(""), idToken = _c[0], setIdToken = _c[1];
246
- var _d = useState(""), accessToken = _d[0], setAccessToken = _d[1];
247
- var _e = useState(null), mfaAuthenticator = _e[0], setMfaAuthenticator = _e[1];
248
- var _f = useState(false), requiresMFA = _f[0], setRequiresMFA = _f[1];
249
- var isLoading = inProgress !== InteractionStatus.None;
250
- var isAuthenticated = !!account && !!accessToken && !requiresMFA;
251
- var scopes = options.scopes || ["openid", "profile", "email"];
252
- var isTokenValid = function (token) {
253
- try {
254
- var payload = JSON.parse(atob(token.split(".")[1]));
255
- return payload.exp * 1000 > Date.now();
256
- }
257
- catch (_a) {
258
- return false;
259
- }
260
- };
261
- useEffect(function () {
262
- if (typeof window !== "undefined" && !accessToken) {
263
- var stored = localStorage.getItem(storageKey);
264
- if (stored) {
265
- try {
266
- var _a = JSON.parse(stored), accessToken_1 = _a.accessToken, idToken_1 = _a.idToken, storedRequiresMFA = _a.requiresMFA, storedIsAuthenticated = _a.isAuthenticated;
267
- if (accessToken_1 && isTokenValid(accessToken_1)) {
268
- setAccessToken(accessToken_1);
269
- setIdToken(idToken_1);
270
- // Restore MFA state
271
- if (storedRequiresMFA && !storedIsAuthenticated) {
272
- var mfaConfig = {
273
- accessToken: accessToken_1,
274
- idToken: idToken_1,
275
- appCode: options.appCode,
276
- provider: "MSAL",
277
- apiEndpoint: options.MFAEndpoint,
278
- };
279
- var authenticator = new CAMSMFAAuthenticator(mfaConfig);
280
- setMfaAuthenticator(authenticator);
281
- setRequiresMFA(true);
282
- }
283
- Logger.debug("App Code", { ">>>": options.appCode });
284
- }
285
- else {
286
- localStorage.removeItem(storageKey);
287
- }
288
- }
289
- catch (_b) { }
290
- }
291
- else if (account) {
292
- // Storage cleared but MSAL account exists - clear MSAL state
293
- instance.logoutRedirect().catch(function () { });
294
- }
295
- }
296
- }, [accessToken, account, instance, options.storageKey]);
297
- // useEffect(() => {
298
- // const handleRedirect = async () => {
299
- // try {
300
- // const response = await instance.handleRedirectPromise();
301
- // if (response) {
302
- // const account = response.account;
303
- // instance.setActiveA ccount(account);
304
- // const tokenResponse = await instance.acq uireTokenSilent({
305
- // scopes,
306
- // account,
307
- // });
308
- // setToken(tokenResponse.accessToken);
309
- // setAccessToken(tokenResponse.accessToken);
310
- // setIdToken(tokenResponse.idTo ken);
311
- // options.onAuthSuccess?.(tokenR esponse.accessToken);
312
- // if (
313
- // typeof window !== "undefined" &&
314
- // process.env.NODE_ENV !== "test"
315
- // ) {
316
- // window.location.href = options.mfaUrl!;
317
- // }
318
- // }
319
- // } catch (err) {
320
- // console.error("Redirect handling failed:", err);
321
- // }
322
- // };
323
- // handleRedirect();
324
- // }, []);
325
- var login = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
326
- var response, mfaConfig, authenticator, err_1, camsError_1, camsError;
327
- var _a, _b, _c, _d;
328
- return __generator(this, function (_e) {
329
- switch (_e.label) {
330
- case 0:
331
- setError(null);
332
- _e.label = 1;
333
- case 1:
334
- _e.trys.push([1, 3, , 4]);
335
- return [4 /*yield*/, instance.loginPopup({
336
- scopes: scopes,
337
- prompt: options.prompt || "login",
338
- })];
339
- case 2:
340
- response = _e.sent();
341
- console.log("Login Token response:", {
342
- accessToken: response.accessToken,
343
- idToken: response.idToken,
344
- });
345
- setAccessToken(response.accessToken);
346
- setIdToken(response.idToken);
347
- mfaConfig = {
348
- accessToken: response.accessToken,
349
- idToken: response.idToken,
350
- appCode: options.appCode,
351
- provider: "MSAL",
352
- apiEndpoint: options.MFAEndpoint,
353
- };
354
- authenticator = new CAMSMFAAuthenticator(mfaConfig);
355
- setMfaAuthenticator(authenticator);
356
- setRequiresMFA(true);
357
- // Don't persist as authenticated until MFA is complete
358
- if (typeof window !== "undefined") {
359
- localStorage.setItem(storageKey, JSON.stringify({
360
- isAuthenticated: false,
361
- requiresMFA: true,
362
- accessToken: response.accessToken,
363
- idToken: response.idToken,
364
- }));
365
- }
366
- (_a = options.onAuthSuccess) === null || _a === void 0 ? void 0 : _a.call(options, response.accessToken);
367
- return [3 /*break*/, 4];
368
- case 3:
369
- err_1 = _e.sent();
370
- // Handle user cancellation gracefully
371
- if (err_1.errorCode === "user_cancelled") {
372
- Logger.error("User cancelled login");
373
- setError(null); // Don't treat cancellation as an error
374
- return [2 /*return*/];
375
- }
376
- // If popup is blocked
377
- if (err_1.errorCode === "popup_window_error" ||
378
- ((_b = err_1.message) === null || _b === void 0 ? void 0 : _b.includes("popup"))) {
379
- camsError_1 = new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again.");
380
- setError(camsError_1);
381
- (_c = options.onAuthError) === null || _c === void 0 ? void 0 : _c.call(options, camsError_1);
382
- return [2 /*return*/];
383
- }
384
- camsError = new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "Login failed: " + err_1.message || err_1);
385
- setError(camsError);
386
- (_d = options.onAuthError) === null || _d === void 0 ? void 0 : _d.call(options, camsError);
387
- return [3 /*break*/, 4];
388
- case 4: return [2 /*return*/];
389
- }
390
- });
391
- }); }, [instance, scopes, options]);
392
- var completeMFA = useCallback(function (code, type) { return __awaiter(_this, void 0, void 0, function () {
393
- var mfaResponse, error_1;
394
- return __generator(this, function (_a) {
395
- switch (_a.label) {
396
- case 0:
397
- if (!mfaAuthenticator) {
398
- throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "MFA Authenticator not initialized");
399
- }
400
- _a.label = 1;
401
- case 1:
402
- _a.trys.push([1, 3, , 4]);
403
- return [4 /*yield*/, mfaAuthenticator.verifyOTP(code, type)];
404
- case 2:
405
- mfaResponse = _a.sent();
406
- if (mfaResponse.isAuthenticated) {
407
- // Update storage with complete authentication BEFORE setting state
408
- if (typeof window !== "undefined") {
409
- localStorage.setItem(storageKey, JSON.stringify({
410
- isAuthenticated: true,
411
- requiresMFA: false,
412
- accessToken: accessToken,
413
- idToken: idToken,
414
- userProfile: mfaResponse,
415
- }));
416
- Logger.info("MFA completed successfully, storage updated", {
417
- accessToken: accessToken,
418
- idToken: idToken,
419
- isAuthenticated: isAuthenticated,
420
- requiresMFA: requiresMFA,
421
- });
422
- }
423
- // Set requiresMFA to false after storage update
424
- setRequiresMFA(false);
425
- Logger.debug("MFA completed successfully, requiresMFA set to false");
426
- }
427
- return [2 /*return*/, mfaResponse];
428
- case 3:
429
- error_1 = _a.sent();
430
- setError(error_1);
431
- throw error_1;
432
- case 4: return [2 /*return*/];
433
- }
434
- });
435
- }); }, [mfaAuthenticator, accessToken, idToken, storageKey, requiresMFA]);
436
- var sendEmailOTP = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
437
- return __generator(this, function (_a) {
438
- switch (_a.label) {
439
- case 0:
440
- if (!mfaAuthenticator) {
441
- return [2 /*return*/, false];
442
- }
443
- return [4 /*yield*/, mfaAuthenticator.sendEmailOTP()];
444
- case 1: return [2 /*return*/, _a.sent()];
445
- }
446
- });
447
- }); }, [mfaAuthenticator]);
448
- var logout = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
449
- var err_2, camsError;
450
- return __generator(this, function (_a) {
451
- switch (_a.label) {
452
- case 0:
453
- _a.trys.push([0, 2, , 3]);
454
- Logger.info("Logging User Out");
455
- return [4 /*yield*/, instance.logoutRedirect()];
456
- case 1:
457
- _a.sent();
458
- setAccessToken("");
459
- setIdToken("");
460
- setError(null);
461
- setMfaAuthenticator(null);
462
- setRequiresMFA(false);
463
- if (typeof window !== "undefined") {
464
- localStorage.removeItem(storageKey);
465
- }
466
- return [3 /*break*/, 3];
467
- case 2:
468
- err_2 = _a.sent();
469
- camsError = new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "Logout failed: " + err_2);
470
- setError(camsError);
471
- return [3 /*break*/, 3];
472
- case 3: return [2 /*return*/];
473
- }
474
- });
475
- }); }, [instance, storageKey]);
476
- return {
477
- login: login,
478
- logout: logout,
479
- storageKey: storageKey,
480
- isAuthenticated: isAuthenticated,
481
- isLoading: isLoading,
482
- error: error,
483
- idToken: idToken,
484
- accessToken: accessToken,
485
- appCode: options.appCode,
486
- mfaAuthenticator: mfaAuthenticator,
487
- requiresMFA: requiresMFA,
488
- completeMFA: completeMFA,
489
- sendEmailOTP: sendEmailOTP,
490
- };
491
- }
239
+ var jsxRuntime = {exports: {}};
240
+
241
+ var reactJsxRuntime_production = {};
492
242
 
493
243
  /**
494
- * Hook for handling authentication in popup windows
495
- * This should be used by the popup app to complete authentication
496
- */
497
- function useCAMSPopupAuth(options) {
498
- if (options === void 0) { options = {}; }
499
- var _a = options.storageKey, storageKey = _a === void 0 ? "CAMS-SDK" : _a, targetOrigin = options.targetOrigin, onAuthComplete = options.onAuthComplete, onAuthError = options.onAuthError;
500
- useEffect(function () {
501
- if (typeof window === "undefined" || !isPopupWindow())
502
- return;
503
- // Initialize popup auth handler
504
- initializePopupAuth(targetOrigin);
505
- // Set up global handlers for the popup app
506
- var globalHandlers = window.__CAMS_POPUP_AUTH__;
507
- if (globalHandlers) {
508
- var originalCompleteAuth_1 = globalHandlers.completeAuth;
509
- var originalErrorAuth_1 = globalHandlers.errorAuth;
510
- globalHandlers.completeAuth = function (profile) {
511
- onAuthComplete === null || onAuthComplete === void 0 ? void 0 : onAuthComplete(profile);
512
- originalCompleteAuth_1(profile);
513
- };
514
- globalHandlers.errorAuth = function (error) {
515
- onAuthError === null || onAuthError === void 0 ? void 0 : onAuthError(error);
516
- originalErrorAuth_1(error);
517
- };
518
- }
519
- }, [targetOrigin, onAuthComplete, onAuthError]);
520
- var completeAuth = useCallback(function (profile) {
521
- if (!isPopupWindow()) {
522
- console.warn("completeAuth called outside of popup window");
523
- return;
524
- }
525
- var sessionManager = new CAMSSessionManager(localStorage, storageKey);
526
- sessionManager.completePopupAuth(profile, targetOrigin);
527
- }, [storageKey, targetOrigin]);
528
- var errorAuth = useCallback(function (error) {
529
- if (!isPopupWindow()) {
530
- console.warn("errorAuth called outside of popup window");
531
- return;
532
- }
533
- var sessionManager = new CAMSSessionManager(localStorage, storageKey);
534
- sessionManager.errorPopupAuth(error, targetOrigin);
535
- }, [storageKey, targetOrigin]);
536
- return {
537
- completeAuth: completeAuth,
538
- errorAuth: errorAuth,
539
- isPopup: isPopupWindow(),
540
- };
541
- }
542
-
543
- var jsxRuntime = {exports: {}};
544
-
545
- var reactJsxRuntime_production = {};
546
-
547
- /**
548
- * @license React
549
- * react-jsx-runtime.production.js
550
- *
551
- * Copyright (c) Meta Platforms, Inc. and affiliates.
552
- *
553
- * This source code is licensed under the MIT license found in the
554
- * LICENSE file in the root directory of this source tree.
244
+ * @license React
245
+ * react-jsx-runtime.production.js
246
+ *
247
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
248
+ *
249
+ * This source code is licensed under the MIT license found in the
250
+ * LICENSE file in the root directory of this source tree.
555
251
  */
556
252
 
557
253
  var hasRequiredReactJsxRuntime_production;
@@ -951,17 +647,464 @@ function requireReactJsxRuntime_development () {
951
647
  return reactJsxRuntime_development;
952
648
  }
953
649
 
954
- if (process.env.NODE_ENV === 'production') {
955
- jsxRuntime.exports = requireReactJsxRuntime_production();
956
- } else {
957
- jsxRuntime.exports = requireReactJsxRuntime_development();
650
+ if (process.env.NODE_ENV === 'production') {
651
+ jsxRuntime.exports = requireReactJsxRuntime_production();
652
+ } else {
653
+ jsxRuntime.exports = requireReactJsxRuntime_development();
654
+ }
655
+
656
+ var jsxRuntimeExports = jsxRuntime.exports;
657
+
658
+ var CAMSContext$1 = createContext(null);
659
+ function useCAMSContext$1() {
660
+ var context = useContext(CAMSContext$1);
661
+ if (!context) {
662
+ throw new Error("useCAMSContext must be used within a UnifiedCAMSProvider");
663
+ }
664
+ return context;
665
+ }
666
+
667
+ var ClientOnly = function (_a) {
668
+ var children = _a.children, _b = _a.fallback, fallback = _b === void 0 ? null : _b;
669
+ var _c = useState(false), hasMounted = _c[0], setHasMounted = _c[1];
670
+ useEffect(function () {
671
+ setHasMounted(true);
672
+ }, []);
673
+ if (!hasMounted) {
674
+ return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: fallback });
675
+ }
676
+ return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
677
+ };
678
+
679
+ var GuidSchema = z.uuid("appCode must be a valid GUID");
680
+ var setCookie$1 = function (name, value, days) {
681
+ if (days === void 0) { days = 1; }
682
+ var expires = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
683
+ document.cookie = "".concat(name, "=").concat(encodeURIComponent(value), "; expires=").concat(expires, "; path=/; samesite=Lax");
684
+ };
685
+ var getCookie$1 = function (name) {
686
+ var _a;
687
+ return ((_a = document.cookie
688
+ .split("; ")
689
+ .find(function (row) { return row.startsWith(name + "="); })) === null || _a === void 0 ? void 0 : _a.split("=")[1])
690
+ ? decodeURIComponent(document.cookie
691
+ .split("; ")
692
+ .find(function (row) { return row.startsWith(name + "="); })
693
+ .split("=")[1])
694
+ : null;
695
+ };
696
+ var deleteCookie$1 = function (name) {
697
+ document.cookie = name + "=; Max-Age=-99999999; path=/";
698
+ };
699
+ function CAMSProviderCore(props) {
700
+ var _this = this;
701
+ var children = props.children, mode = props.mode, appCode = props.appCode;
702
+ // Always call both hooks to satisfy Rules of Hooks
703
+ var regularAuth = useCAMSAuth(mode === "REGULAR"
704
+ ? __assign(__assign({}, props), { appCode: appCode })
705
+ : { appCode: "" });
706
+ var msalAuth = useCAMSMSALAuth(mode === "MSAL"
707
+ ? __assign(__assign({}, props), { appCode: appCode })
708
+ : { appCode: "" });
709
+ var auth = mode === "REGULAR" ? regularAuth : msalAuth;
710
+ var profileStorageKey = "".concat(auth.storageKey, "-PROFILE");
711
+ var getInitialProfile = function () {
712
+ if (typeof window === "undefined")
713
+ return null;
714
+ try {
715
+ var storedProfile = getCookie$1(profileStorageKey);
716
+ return storedProfile ? JSON.parse(storedProfile) : null;
717
+ }
718
+ catch (_a) {
719
+ return null;
720
+ }
721
+ };
722
+ var _a = useState(getInitialProfile), userProfile = _a[0], setUserProfile = _a[1];
723
+ useEffect(function () {
724
+ if (typeof window !== "undefined") {
725
+ var storedProfile = getCookie$1(profileStorageKey);
726
+ if (storedProfile) {
727
+ try {
728
+ setUserProfile(JSON.parse(storedProfile));
729
+ }
730
+ catch (_a) { }
731
+ }
732
+ }
733
+ }, [profileStorageKey]);
734
+ useEffect(function () {
735
+ if (typeof window !== "undefined") {
736
+ if (userProfile) {
737
+ setCookie$1(profileStorageKey, JSON.stringify(userProfile), 1);
738
+ }
739
+ else {
740
+ deleteCookie$1(profileStorageKey);
741
+ }
742
+ }
743
+ }, [userProfile, profileStorageKey]);
744
+ var enhancedLogout = function () { return __awaiter(_this, void 0, void 0, function () {
745
+ return __generator(this, function (_a) {
746
+ switch (_a.label) {
747
+ case 0: return [4 /*yield*/, auth.logout()];
748
+ case 1:
749
+ _a.sent();
750
+ setUserProfile(null);
751
+ if (typeof window !== "undefined") {
752
+ deleteCookie$1(profileStorageKey);
753
+ }
754
+ return [2 /*return*/];
755
+ }
756
+ });
757
+ }); };
758
+ // Handle MFA completion for MSAL mode
759
+ useEffect(function () {
760
+ if (mode === "MSAL" &&
761
+ "requiresMFA" in auth &&
762
+ !auth.requiresMFA &&
763
+ auth.isAuthenticated) {
764
+ // MFA completed, extract profile from localStorage
765
+ var storedData = localStorage.getItem(auth.storageKey);
766
+ console.log("MFA Complete - Checking for profile:", storedData);
767
+ if (storedData) {
768
+ try {
769
+ var parsed = JSON.parse(storedData);
770
+ console.log("Parsed storage data:", parsed);
771
+ if (parsed.userProfile) {
772
+ console.log("Setting user profile:", parsed.userProfile);
773
+ setUserProfile(parsed.userProfile);
774
+ }
775
+ }
776
+ catch (e) {
777
+ console.error("Error parsing stored data:", e);
778
+ }
779
+ }
780
+ }
781
+ }, [
782
+ mode,
783
+ "requiresMFA" in auth ? auth.requiresMFA : false,
784
+ auth.isAuthenticated,
785
+ auth.storageKey,
786
+ userProfile,
787
+ ]);
788
+ var value = useMemo(function () {
789
+ return (__assign(__assign({}, auth), { logout: enhancedLogout, userProfile: userProfile, setUserProfile: setUserProfile, authMode: mode }));
790
+ }, [auth, userProfile, mode]);
791
+ return jsxRuntimeExports.jsx(CAMSContext$1.Provider, { value: value, children: children });
792
+ }
793
+ function UnifiedCAMSProvider(props) {
794
+ // Validate appCode is a valid GUID
795
+ var appCodeValidation = GuidSchema.safeParse(props.appCode);
796
+ if (!appCodeValidation.success) {
797
+ throw new Error("Invalid appCode: ".concat(appCodeValidation.error.issues[0].message));
798
+ }
799
+ if (props.mode === "MSAL") {
800
+ var msalConfig = props.msalConfig, msalInstance = props.msalInstance;
801
+ var instance = msalInstance || new PublicClientApplication(msalConfig);
802
+ return (jsxRuntimeExports.jsx(MsalProvider, { instance: instance, children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
803
+ }
804
+ return (jsxRuntimeExports.jsx(ClientOnly, { fallback: jsxRuntimeExports.jsx("div", { children: "Loading..." }), children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
805
+ }
806
+ // Backward compatibility exports
807
+ var CAMSProvider = function (props) { return (jsxRuntimeExports.jsx(UnifiedCAMSProvider, __assign({}, props, { mode: "REGULAR" }))); };
808
+
809
+ function useCAMSMSALAuth(options) {
810
+ var _this = this;
811
+ var storageKey = options.storageKey || "CAMS-MSAL-AUTH-SDK";
812
+ var _a = useMsal(), instance = _a.instance, inProgress = _a.inProgress, accounts = _a.accounts;
813
+ var account = useAccount(accounts[0] || {});
814
+ var _b = useState(null), error = _b[0], setError = _b[1];
815
+ var _c = useState(""), idToken = _c[0], setIdToken = _c[1];
816
+ var _d = useState(""), accessToken = _d[0], setAccessToken = _d[1];
817
+ var _e = useState(null), mfaAuthenticator = _e[0], setMfaAuthenticator = _e[1];
818
+ var _f = useState(false), requiresMFA = _f[0], setRequiresMFA = _f[1];
819
+ var isLoading = inProgress !== InteractionStatus.None;
820
+ var isAuthenticated = !!account && !!accessToken && !requiresMFA;
821
+ var scopes = options.scopes || ["openid", "profile", "email"];
822
+ var isTokenValid = function (token) {
823
+ try {
824
+ var payload = JSON.parse(atob(token.split(".")[1]));
825
+ return payload.exp * 1000 > Date.now();
826
+ }
827
+ catch (_a) {
828
+ return false;
829
+ }
830
+ };
831
+ useEffect(function () {
832
+ if (typeof window !== "undefined" && !accessToken) {
833
+ var stored = localStorage.getItem(storageKey);
834
+ if (stored) {
835
+ try {
836
+ var _a = JSON.parse(stored), accessToken_1 = _a.accessToken, idToken_1 = _a.idToken, storedRequiresMFA = _a.requiresMFA, storedIsAuthenticated = _a.isAuthenticated;
837
+ if (accessToken_1 && isTokenValid(accessToken_1)) {
838
+ setAccessToken(accessToken_1);
839
+ setIdToken(idToken_1);
840
+ // Restore MFA state
841
+ if (storedRequiresMFA && !storedIsAuthenticated) {
842
+ var mfaConfig = {
843
+ accessToken: accessToken_1,
844
+ idToken: idToken_1,
845
+ appCode: options.appCode,
846
+ provider: "MSAL",
847
+ apiEndpoint: options.MFAEndpoint,
848
+ };
849
+ var authenticator = new CAMSMFAAuthenticator(mfaConfig);
850
+ setMfaAuthenticator(authenticator);
851
+ setRequiresMFA(true);
852
+ }
853
+ Logger.debug("App Code", { ">>>": options.appCode });
854
+ }
855
+ else {
856
+ localStorage.removeItem(storageKey);
857
+ }
858
+ }
859
+ catch (_b) { }
860
+ }
861
+ else if (account) {
862
+ // Storage cleared but MSAL account exists - clear MSAL state
863
+ instance.logoutRedirect().catch(function () { });
864
+ }
865
+ }
866
+ }, [accessToken, account, instance, options.storageKey]);
867
+ // useEffect(() => {
868
+ // const handleRedirect = async () => {
869
+ // try {
870
+ // const response = await instance.handleRedirectPromise();
871
+ // if (response) {
872
+ // const account = response.account;
873
+ // instance.setActiveA ccount(account);
874
+ // const tokenResponse = await instance.acq uireTokenSilent({
875
+ // scopes,
876
+ // account,
877
+ // });
878
+ // setToken(tokenResponse.accessToken);
879
+ // setAccessToken(tokenResponse.accessToken);
880
+ // setIdToken(tokenResponse.idTo ken);
881
+ // options.onAuthSuccess?.(tokenR esponse.accessToken);
882
+ // if (
883
+ // typeof window !== "undefined" &&
884
+ // process.env.NODE_ENV !== "test"
885
+ // ) {
886
+ // window.location.href = options.mfaUrl!;
887
+ // }
888
+ // }
889
+ // } catch (err) {
890
+ // console.error("Redirect handling failed:", err);
891
+ // }
892
+ // };
893
+ // handleRedirect();
894
+ // }, []);
895
+ var login = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
896
+ var response, mfaConfig, authenticator, err_1, camsError_1, camsError;
897
+ var _a, _b, _c, _d;
898
+ return __generator(this, function (_e) {
899
+ switch (_e.label) {
900
+ case 0:
901
+ setError(null);
902
+ _e.label = 1;
903
+ case 1:
904
+ _e.trys.push([1, 3, , 4]);
905
+ return [4 /*yield*/, instance.loginPopup({
906
+ scopes: scopes,
907
+ prompt: options.prompt || "login",
908
+ })];
909
+ case 2:
910
+ response = _e.sent();
911
+ console.log("Login Token response:", {
912
+ accessToken: response.accessToken,
913
+ idToken: response.idToken,
914
+ });
915
+ setAccessToken(response.accessToken);
916
+ setIdToken(response.idToken);
917
+ mfaConfig = {
918
+ accessToken: response.accessToken,
919
+ idToken: response.idToken,
920
+ appCode: options.appCode,
921
+ provider: "MSAL",
922
+ apiEndpoint: options.MFAEndpoint,
923
+ };
924
+ authenticator = new CAMSMFAAuthenticator(mfaConfig);
925
+ setMfaAuthenticator(authenticator);
926
+ setRequiresMFA(true);
927
+ // Don't persist as authenticated until MFA is complete
928
+ if (typeof window !== "undefined") {
929
+ localStorage.setItem(storageKey, JSON.stringify({
930
+ isAuthenticated: false,
931
+ requiresMFA: true,
932
+ accessToken: response.accessToken,
933
+ idToken: response.idToken,
934
+ }));
935
+ }
936
+ (_a = options.onAuthSuccess) === null || _a === void 0 ? void 0 : _a.call(options, response.accessToken);
937
+ return [3 /*break*/, 4];
938
+ case 3:
939
+ err_1 = _e.sent();
940
+ // Handle user cancellation gracefully
941
+ if (err_1.errorCode === "user_cancelled") {
942
+ Logger.error("User cancelled login");
943
+ setError(null); // Don't treat cancellation as an error
944
+ return [2 /*return*/];
945
+ }
946
+ // If popup is blocked
947
+ if (err_1.errorCode === "popup_window_error" ||
948
+ ((_b = err_1.message) === null || _b === void 0 ? void 0 : _b.includes("popup"))) {
949
+ camsError_1 = new CAMSError(CAMSErrorType.POPUP_BLOCKED, "Popup blocked by browser. Please allow popups and try again.");
950
+ setError(camsError_1);
951
+ (_c = options.onAuthError) === null || _c === void 0 ? void 0 : _c.call(options, camsError_1);
952
+ return [2 /*return*/];
953
+ }
954
+ camsError = new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "Login failed: " + err_1.message || err_1);
955
+ setError(camsError);
956
+ (_d = options.onAuthError) === null || _d === void 0 ? void 0 : _d.call(options, camsError);
957
+ return [3 /*break*/, 4];
958
+ case 4: return [2 /*return*/];
959
+ }
960
+ });
961
+ }); }, [instance, scopes, options]);
962
+ var completeMFA = useCallback(function (data) { return __awaiter(_this, void 0, void 0, function () {
963
+ return __generator(this, function (_a) {
964
+ if (!mfaAuthenticator) {
965
+ throw new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "MFA Authenticator not initialized");
966
+ }
967
+ Logger.info("Completed MFA.. Setting State");
968
+ try {
969
+ // Update storage with complete authentication BEFORE setting state
970
+ if (typeof window !== "undefined") {
971
+ localStorage.setItem(storageKey, JSON.stringify({
972
+ isAuthenticated: true,
973
+ requiresMFA: false,
974
+ accessToken: accessToken,
975
+ idToken: idToken,
976
+ }));
977
+ setCookie$1("CAMS-MSAL-AUTH-SDK-PROFILE", JSON.stringify({ type: "AUTH_SUCCESS", userProfile: __assign({}, data) }), 1);
978
+ setRequiresMFA(false);
979
+ // Set requiresMFA to false after storage update
980
+ Logger.debug("MFA completed successfully, storage updated", {
981
+ accessToken: accessToken,
982
+ idToken: idToken,
983
+ isAuthenticated: true,
984
+ requiresMFA: false,
985
+ });
986
+ }
987
+ Logger.debug("MFA completed successfully, requiresMFA set to false");
988
+ return [2 /*return*/, data];
989
+ }
990
+ catch (error) {
991
+ setError(error);
992
+ throw error;
993
+ }
994
+ return [2 /*return*/];
995
+ });
996
+ }); }, [mfaAuthenticator, accessToken, idToken, storageKey]);
997
+ var sendEmailOTP = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
998
+ return __generator(this, function (_a) {
999
+ switch (_a.label) {
1000
+ case 0:
1001
+ if (!mfaAuthenticator) {
1002
+ return [2 /*return*/, false];
1003
+ }
1004
+ return [4 /*yield*/, mfaAuthenticator.sendEmailOTP()];
1005
+ case 1: return [2 /*return*/, _a.sent()];
1006
+ }
1007
+ });
1008
+ }); }, [mfaAuthenticator]);
1009
+ var logout = useCallback(function () { return __awaiter(_this, void 0, void 0, function () {
1010
+ var err_2, camsError;
1011
+ return __generator(this, function (_a) {
1012
+ switch (_a.label) {
1013
+ case 0:
1014
+ _a.trys.push([0, 2, , 3]);
1015
+ Logger.info("Logging User Out");
1016
+ return [4 /*yield*/, instance.logoutRedirect()];
1017
+ case 1:
1018
+ _a.sent();
1019
+ setAccessToken("");
1020
+ setIdToken("");
1021
+ setError(null);
1022
+ setMfaAuthenticator(null);
1023
+ setRequiresMFA(false);
1024
+ if (typeof window !== "undefined") {
1025
+ localStorage.removeItem(storageKey);
1026
+ }
1027
+ return [3 /*break*/, 3];
1028
+ case 2:
1029
+ err_2 = _a.sent();
1030
+ camsError = new CAMSError(CAMSErrorType.API_VALIDATION_ERROR, "Logout failed: " + err_2);
1031
+ setError(camsError);
1032
+ return [3 /*break*/, 3];
1033
+ case 3: return [2 /*return*/];
1034
+ }
1035
+ });
1036
+ }); }, [instance, storageKey]);
1037
+ return {
1038
+ login: login,
1039
+ logout: logout,
1040
+ storageKey: storageKey,
1041
+ isAuthenticated: isAuthenticated,
1042
+ isLoading: isLoading,
1043
+ error: error,
1044
+ idToken: idToken,
1045
+ accessToken: accessToken,
1046
+ appCode: options.appCode,
1047
+ mfaAuthenticator: mfaAuthenticator,
1048
+ requiresMFA: requiresMFA,
1049
+ completeMFA: completeMFA,
1050
+ sendEmailOTP: sendEmailOTP,
1051
+ setRequiresMFA: setRequiresMFA,
1052
+ };
1053
+ }
1054
+
1055
+ /**
1056
+ * Hook for handling authentication in popup windows
1057
+ * This should be used by the popup app to complete authentication
1058
+ */
1059
+ function useCAMSPopupAuth(options) {
1060
+ if (options === void 0) { options = {}; }
1061
+ var _a = options.storageKey, storageKey = _a === void 0 ? "CAMS-SDK" : _a, targetOrigin = options.targetOrigin, onAuthComplete = options.onAuthComplete, onAuthError = options.onAuthError;
1062
+ useEffect(function () {
1063
+ if (typeof window === "undefined" || !isPopupWindow())
1064
+ return;
1065
+ // Initialize popup auth handler
1066
+ initializePopupAuth(targetOrigin);
1067
+ // Set up global handlers for the popup app
1068
+ var globalHandlers = window.__CAMS_POPUP_AUTH__;
1069
+ if (globalHandlers) {
1070
+ var originalCompleteAuth_1 = globalHandlers.completeAuth;
1071
+ var originalErrorAuth_1 = globalHandlers.errorAuth;
1072
+ globalHandlers.completeAuth = function (profile) {
1073
+ onAuthComplete === null || onAuthComplete === void 0 ? void 0 : onAuthComplete(profile);
1074
+ originalCompleteAuth_1(profile);
1075
+ };
1076
+ globalHandlers.errorAuth = function (error) {
1077
+ onAuthError === null || onAuthError === void 0 ? void 0 : onAuthError(error);
1078
+ originalErrorAuth_1(error);
1079
+ };
1080
+ }
1081
+ }, [targetOrigin, onAuthComplete, onAuthError]);
1082
+ var completeAuth = useCallback(function (profile) {
1083
+ if (!isPopupWindow()) {
1084
+ console.warn("completeAuth called outside of popup window");
1085
+ return;
1086
+ }
1087
+ var sessionManager = new CAMSSessionManager(localStorage, storageKey);
1088
+ sessionManager.completePopupAuth(profile, targetOrigin);
1089
+ }, [storageKey, targetOrigin]);
1090
+ var errorAuth = useCallback(function (error) {
1091
+ if (!isPopupWindow()) {
1092
+ console.warn("errorAuth called outside of popup window");
1093
+ return;
1094
+ }
1095
+ var sessionManager = new CAMSSessionManager(localStorage, storageKey);
1096
+ sessionManager.errorPopupAuth(error, targetOrigin);
1097
+ }, [storageKey, targetOrigin]);
1098
+ return {
1099
+ completeAuth: completeAuth,
1100
+ errorAuth: errorAuth,
1101
+ isPopup: isPopupWindow(),
1102
+ };
958
1103
  }
959
1104
 
960
- var jsxRuntimeExports = jsxRuntime.exports;
961
-
962
- var CAMSContext$1 = createContext(null);
963
- function useCAMSContext$1() {
964
- var context = useContext(CAMSContext$1);
1105
+ var CAMSContext = createContext(null);
1106
+ function useCAMSContext() {
1107
+ var context = useContext(CAMSContext);
965
1108
  if (!context) {
966
1109
  throw new Error('useCAMSContext must be used within a CAMSProvider');
967
1110
  }
@@ -970,7 +1113,7 @@ function useCAMSContext$1() {
970
1113
 
971
1114
  function ProtectedRoute(_a) {
972
1115
  var children = _a.children, fallback = _a.fallback, redirectTo = _a.redirectTo;
973
- var _b = useCAMSContext$1(), isAuthenticated = _b.isAuthenticated, isLoading = _b.isLoading;
1116
+ var _b = useCAMSContext(), isAuthenticated = _b.isAuthenticated, isLoading = _b.isLoading;
974
1117
  if (isLoading) {
975
1118
  return fallback || jsxRuntimeExports.jsx("div", { children: "Loading..." });
976
1119
  }
@@ -985,11 +1128,11 @@ function ProtectedRoute(_a) {
985
1128
  }
986
1129
 
987
1130
  var CAMSMSALContext = createContext(null);
988
- var setCookie$1 = function (name, value, days) {
1131
+ var setCookie = function (name, value, days) {
989
1132
  var expires = new Date(Date.now() + days * 864e5).toUTCString();
990
1133
  document.cookie = "".concat(name, "=").concat(encodeURIComponent(value), "; expires=").concat(expires, "; path=/; samesite=Lax");
991
1134
  };
992
- var getCookie$1 = function (name) {
1135
+ var getCookie = function (name) {
993
1136
  var _a;
994
1137
  return ((_a = document.cookie
995
1138
  .split("; ")
@@ -1000,7 +1143,7 @@ var getCookie$1 = function (name) {
1000
1143
  .split("=")[1])
1001
1144
  : null;
1002
1145
  };
1003
- var deleteCookie$1 = function (name) {
1146
+ var deleteCookie = function (name) {
1004
1147
  document.cookie = name + "=; Max-Age=-99999999; path=/";
1005
1148
  };
1006
1149
  var isTokenValid = function (token) {
@@ -1022,7 +1165,7 @@ function CAMSMSALProviderInner(_a) {
1022
1165
  return null;
1023
1166
  }
1024
1167
  try {
1025
- var storedProfile = getCookie$1(profileStorageKey);
1168
+ var storedProfile = getCookie(profileStorageKey);
1026
1169
  return storedProfile ? JSON.parse(storedProfile) : null;
1027
1170
  }
1028
1171
  catch (_a) {
@@ -1034,7 +1177,7 @@ function CAMSMSALProviderInner(_a) {
1034
1177
  useEffect(function () {
1035
1178
  if (typeof window !== "undefined") {
1036
1179
  // const storedProfile = localStorage.get Item(profileStorageKey);
1037
- var storedProfile = getCookie$1(profileStorageKey);
1180
+ var storedProfile = getCookie(profileStorageKey);
1038
1181
  if (storedProfile) {
1039
1182
  try {
1040
1183
  setUserProfile(JSON.parse(storedProfile));
@@ -1059,10 +1202,10 @@ function CAMSMSALProviderInner(_a) {
1059
1202
  useEffect(function () {
1060
1203
  if (typeof window !== "undefined") {
1061
1204
  if (userProfile) {
1062
- setCookie$1(profileStorageKey, JSON.stringify(userProfile), 1); // Store for 1 day
1205
+ setCookie(profileStorageKey, JSON.stringify(userProfile), 1); // Store for 1 day
1063
1206
  }
1064
1207
  else {
1065
- deleteCookie$1(profileStorageKey);
1208
+ deleteCookie(profileStorageKey);
1066
1209
  }
1067
1210
  }
1068
1211
  }, [userProfile, profileStorageKey]);
@@ -1075,7 +1218,7 @@ function CAMSMSALProviderInner(_a) {
1075
1218
  _a.sent();
1076
1219
  setUserProfile(null);
1077
1220
  if (typeof window !== "undefined") {
1078
- deleteCookie$1(profileStorageKey);
1221
+ deleteCookie(profileStorageKey);
1079
1222
  }
1080
1223
  return [2 /*return*/];
1081
1224
  }
@@ -1097,156 +1240,6 @@ function useCAMSMSALContext() {
1097
1240
  return context;
1098
1241
  }
1099
1242
 
1100
- var ClientOnly = function (_a) {
1101
- var children = _a.children, _b = _a.fallback, fallback = _b === void 0 ? null : _b;
1102
- var _c = useState(false), hasMounted = _c[0], setHasMounted = _c[1];
1103
- useEffect(function () {
1104
- setHasMounted(true);
1105
- }, []);
1106
- if (!hasMounted) {
1107
- return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: fallback });
1108
- }
1109
- return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
1110
- };
1111
-
1112
- var CAMSContext = createContext(null);
1113
- function useCAMSContext() {
1114
- var context = useContext(CAMSContext);
1115
- if (!context) {
1116
- throw new Error("useCAMSContext must be used within a UnifiedCAMSProvider");
1117
- }
1118
- return context;
1119
- }
1120
-
1121
- var GuidSchema = z.uuid("appCode must be a valid GUID");
1122
- var setCookie = function (name, value, days) {
1123
- var expires = new Date(Date.now() + days * 24 * 60 * 60 * 1000).toUTCString();
1124
- document.cookie = "".concat(name, "=").concat(encodeURIComponent(value), "; expires=").concat(expires, "; path=/; samesite=Lax");
1125
- };
1126
- var getCookie = function (name) {
1127
- var _a;
1128
- return ((_a = document.cookie
1129
- .split("; ")
1130
- .find(function (row) { return row.startsWith(name + "="); })) === null || _a === void 0 ? void 0 : _a.split("=")[1])
1131
- ? decodeURIComponent(document.cookie
1132
- .split("; ")
1133
- .find(function (row) { return row.startsWith(name + "="); })
1134
- .split("=")[1])
1135
- : null;
1136
- };
1137
- var deleteCookie = function (name) {
1138
- document.cookie = name + "=; Max-Age=-99999999; path=/";
1139
- };
1140
- function CAMSProviderCore(props) {
1141
- var _this = this;
1142
- var children = props.children, mode = props.mode, appCode = props.appCode;
1143
- // Always call both hooks to satisfy Rules of Hooks
1144
- var regularAuth = useCAMSAuth(mode === "REGULAR"
1145
- ? __assign(__assign({}, props), { appCode: appCode })
1146
- : { appCode: "" });
1147
- var msalAuth = useCAMSMSALAuth(mode === "MSAL"
1148
- ? __assign(__assign({}, props), { appCode: appCode })
1149
- : { appCode: "" });
1150
- var auth = mode === "REGULAR" ? regularAuth : msalAuth;
1151
- var profileStorageKey = "".concat(auth.storageKey, "-PROFILE");
1152
- var getInitialProfile = function () {
1153
- if (typeof window === "undefined")
1154
- return null;
1155
- try {
1156
- var storedProfile = getCookie(profileStorageKey);
1157
- return storedProfile ? JSON.parse(storedProfile) : null;
1158
- }
1159
- catch (_a) {
1160
- return null;
1161
- }
1162
- };
1163
- var _a = useState(getInitialProfile), userProfile = _a[0], setUserProfile = _a[1];
1164
- useEffect(function () {
1165
- if (typeof window !== "undefined") {
1166
- var storedProfile = getCookie(profileStorageKey);
1167
- if (storedProfile) {
1168
- try {
1169
- setUserProfile(JSON.parse(storedProfile));
1170
- }
1171
- catch (_a) { }
1172
- }
1173
- }
1174
- }, [profileStorageKey]);
1175
- useEffect(function () {
1176
- if (typeof window !== "undefined") {
1177
- if (userProfile) {
1178
- setCookie(profileStorageKey, JSON.stringify(userProfile), 1);
1179
- }
1180
- else {
1181
- deleteCookie(profileStorageKey);
1182
- }
1183
- }
1184
- }, [userProfile, profileStorageKey]);
1185
- var enhancedLogout = function () { return __awaiter(_this, void 0, void 0, function () {
1186
- return __generator(this, function (_a) {
1187
- switch (_a.label) {
1188
- case 0: return [4 /*yield*/, auth.logout()];
1189
- case 1:
1190
- _a.sent();
1191
- setUserProfile(null);
1192
- if (typeof window !== "undefined") {
1193
- deleteCookie(profileStorageKey);
1194
- }
1195
- return [2 /*return*/];
1196
- }
1197
- });
1198
- }); };
1199
- // Handle MFA completion for MSAL mode
1200
- useEffect(function () {
1201
- if (mode === "MSAL" &&
1202
- "requiresMFA" in auth &&
1203
- !auth.requiresMFA &&
1204
- auth.isAuthenticated) {
1205
- // MFA completed, extract profile from localStorage
1206
- var storedData = localStorage.getItem(auth.storageKey);
1207
- console.log("MFA Complete - Checking for profile:", storedData);
1208
- if (storedData) {
1209
- try {
1210
- var parsed = JSON.parse(storedData);
1211
- console.log("Parsed storage data:", parsed);
1212
- if (parsed.userProfile) {
1213
- console.log("Setting user profile:", parsed.userProfile);
1214
- setUserProfile(parsed.userProfile);
1215
- }
1216
- }
1217
- catch (e) {
1218
- console.error("Error parsing stored data:", e);
1219
- }
1220
- }
1221
- }
1222
- }, [
1223
- mode,
1224
- "requiresMFA" in auth ? auth.requiresMFA : false,
1225
- auth.isAuthenticated,
1226
- auth.storageKey,
1227
- userProfile,
1228
- ]);
1229
- var value = useMemo(function () {
1230
- return (__assign(__assign({}, auth), { logout: enhancedLogout, userProfile: userProfile, setUserProfile: setUserProfile, authMode: mode }));
1231
- }, [auth, userProfile, mode]);
1232
- return jsxRuntimeExports.jsx(CAMSContext.Provider, { value: value, children: children });
1233
- }
1234
- function UnifiedCAMSProvider(props) {
1235
- // Validate appCode is a valid GUID
1236
- var appCodeValidation = GuidSchema.safeParse(props.appCode);
1237
- if (!appCodeValidation.success) {
1238
- throw new Error("Invalid appCode: ".concat(appCodeValidation.error.issues[0].message));
1239
- }
1240
- if (props.mode === "MSAL") {
1241
- var msalConfig = props.msalConfig, msalInstance = props.msalInstance;
1242
- var instance = msalInstance || new PublicClientApplication(msalConfig);
1243
- return (jsxRuntimeExports.jsx(MsalProvider, { instance: instance, children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
1244
- }
1245
- return (jsxRuntimeExports.jsx(ClientOnly, { fallback: jsxRuntimeExports.jsx("div", { children: "Loading..." }), children: jsxRuntimeExports.jsx(CAMSProviderCore, __assign({}, props)) }));
1246
- }
1247
- // Backward compatibility exports
1248
- var CAMSProvider = function (props) { return (jsxRuntimeExports.jsx(UnifiedCAMSProvider, __assign({}, props, { mode: "REGULAR" }))); };
1249
-
1250
1243
  /** A special constant with type `never` */
1251
1244
  function $constructor(name, initializer, params) {
1252
1245
  function init(inst, def) {
@@ -1746,8 +1739,8 @@ var MFAOptions = function (_a) {
1746
1739
  var _d = useState(false), otpVisible = _d[0], setOtpVisible = _d[1];
1747
1740
  var _e = useState(false), showSuccessAnimation = _e[0], setShowSuccessAnimation = _e[1];
1748
1741
  var _f = useState(null), authType = _f[0], setAuthType = _f[1];
1749
- var _g = useState(""), lastOTPCode = _g[0], setLastOTPCode = _g[1];
1750
- var context = useCAMSContext();
1742
+ var _g = useState(""); _g[0]; var setLastOTPCode = _g[1];
1743
+ var context = useCAMSContext$1();
1751
1744
  var _h = context.authMode === "MSAL" && "sendEmailOTP" in context
1752
1745
  ? context
1753
1746
  : { sendEmailOTP: null, completeMFA: null, logout: function () { return __awaiter(void 0, void 0, void 0, function () { return __generator(this, function (_a) {
@@ -1763,10 +1756,12 @@ var MFAOptions = function (_a) {
1763
1756
  authenticationType: authType,
1764
1757
  MFAEndpoint: MFAEndpoint,
1765
1758
  onAuthComplete: function (state, data) {
1759
+ console.log("Completed Auth. Handling MFA", state);
1766
1760
  if (state) {
1767
1761
  // Call completeMFA to update context state
1768
- if (completeMFA && authType && lastOTPCode) {
1769
- completeMFA(lastOTPCode, authType).catch(function (error) {
1762
+ if (completeMFA && data) {
1763
+ console.log("IN Complete MFA Block. Handling MFA", data);
1764
+ completeMFA(data).catch(function (error) {
1770
1765
  console.error("Failed to complete MFA:", error);
1771
1766
  });
1772
1767
  }
@@ -1782,7 +1777,7 @@ var MFAOptions = function (_a) {
1782
1777
  onAuthFailed === null || onAuthFailed === void 0 ? void 0 : onAuthFailed();
1783
1778
  onComplete === null || onComplete === void 0 ? void 0 : onComplete(false);
1784
1779
  });
1785
- }, 1000);
1780
+ }, 3000);
1786
1781
  }
1787
1782
  }
1788
1783
  },
@@ -1854,7 +1849,7 @@ var AuthLogo = "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2
1854
1849
  var MicrosoftLogo = "data:image/svg+xml,%3Csvg%20width%3D%2225%22%20height%3D%2225%22%20viewBox%3D%220%200%2025%2025%22%20fill%3D%22none%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%3E%3Cg%20id%3D%22microsoft_svgrepo.com%22%3E%3Cpath%20id%3D%22Vector%22%20d%3D%22M20.75%2013.25H13.25V20.75H20.75V13.25Z%22%20fill%3D%22%23FEBA08%22%2F%3E%3Cpath%20id%3D%22Vector_2%22%20d%3D%22M11.75%2013.25H4.25V20.75H11.75V13.25Z%22%20fill%3D%22%2305A6F0%22%2F%3E%3Cpath%20id%3D%22Vector_3%22%20d%3D%22M20.75%204.25H13.25V11.75H20.75V4.25Z%22%20fill%3D%22%2380BC06%22%2F%3E%3Cpath%20id%3D%22Vector_4%22%20d%3D%22M11.75%204.25H4.25V11.75H11.75V4.25Z%22%20fill%3D%22%23F25325%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E";
1855
1850
 
1856
1851
  var DefaultLoginPage = function () {
1857
- var context = useCAMSContext();
1852
+ var context = useCAMSContext$1();
1858
1853
  var login = context.login, isLoading = context.isLoading, authMode = context.authMode;
1859
1854
  var handleLogin = function () {
1860
1855
  if (authMode === "MSAL") {
@@ -1882,44 +1877,52 @@ var DefaultLoginPage = function () {
1882
1877
  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: handleLogin, disabled: isLoading, children: [jsxRuntimeExports.jsx("img", { src: MicrosoftLogo, alt: "Microsoft Logo", width: 35, height: 35 }), jsxRuntimeExports.jsx("span", { children: isLoading ? 'Logging in...' : "Sign in with Microsoft" })] }) }), 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") }));
1883
1878
  };
1884
1879
 
1880
+ var ErrorFallback = function (_a) {
1881
+ var message = _a.message;
1882
+ return (jsxRuntimeExports.jsx("div", { className: "flex items-center justify-center min-h-screen bg-gray-50", children: jsxRuntimeExports.jsxs("div", { className: "bg-white p-6 rounded-lg shadow-lg border border-red-200 max-w-md", children: [jsxRuntimeExports.jsxs("div", { className: "flex items-center gap-3 mb-2", children: [jsxRuntimeExports.jsx("svg", { className: "w-6 h-6 text-red-500", fill: "none", stroke: "currentColor", viewBox: "0 0 24 24", children: jsxRuntimeExports.jsx("path", { strokeLinecap: "round", strokeLinejoin: "round", strokeWidth: 2, d: "M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" }) }), jsxRuntimeExports.jsx("h2", { className: "text-lg font-semibold text-gray-900", children: "Configuration Error" })] }), jsxRuntimeExports.jsx("p", { className: "text-red-600", children: message })] }) }));
1883
+ };
1884
+
1885
1885
  var MFAEndpointUrlSchema = z$1.url("MFAEndpoint must be a valid URL");
1886
1886
  var MFAGate = function (_a) {
1887
- var children = _a.children, fallback = _a.fallback, LoginComponent = _a.loginComponent, MFAEndpoint = _a.MFAEndpoint;
1888
- var context = useCAMSContext();
1889
- var urlValidation = MFAEndpointUrlSchema.safeParse(MFAEndpoint);
1890
- if (!urlValidation.success) {
1891
- throw new Error("Invalid MFAEndpoint: ".concat(urlValidation.error.issues[0].message));
1892
- }
1887
+ var children = _a.children, _b = _a.fallback, fallback = _b === void 0 ? jsxRuntimeExports.jsx(LoadingSpinner, {}) : _b, _c = _a.loginComponent, LoginComponent = _c === void 0 ? DefaultLoginPage : _c, MFAEndpoint = _a.MFAEndpoint;
1888
+ var context = useCAMSContext$1();
1889
+ var validatedMFAEndpoint = useMemo(function () {
1890
+ var parsed = MFAEndpointUrlSchema.safeParse(MFAEndpoint);
1891
+ if (!parsed.success) {
1892
+ Logger.error("Invalid MFAEndpoint", parsed.error);
1893
+ return null;
1894
+ }
1895
+ return parsed.data;
1896
+ }, [MFAEndpoint]);
1897
+ var handleComplete = useCallback(function (success) {
1898
+ if (!success)
1899
+ Logger.error("MFA authentication failed");
1900
+ }, []);
1901
+ var handleAuthFailed = useCallback(function () { return __awaiter(void 0, void 0, void 0, function () {
1902
+ return __generator(this, function (_a) {
1903
+ switch (_a.label) {
1904
+ case 0: return [4 /*yield*/, context.logout()];
1905
+ case 1:
1906
+ _a.sent();
1907
+ return [2 /*return*/];
1908
+ }
1909
+ });
1910
+ }); }, [context.logout]);
1893
1911
  Logger.debug("MFA Endpoint >>>", { MFAEndpoint: MFAEndpoint });
1894
- // Only apply MFA gate for MSAL mode
1895
- if (context.authMode !== "MSAL") {
1912
+ if (!validatedMFAEndpoint)
1913
+ return jsxRuntimeExports.jsx(ErrorFallback, { message: "Invalid MFA configuration." });
1914
+ if (context.authMode !== "MSAL")
1896
1915
  return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
1916
+ if (context.isLoading)
1917
+ return fallback;
1918
+ if (context.requiresMFA) {
1919
+ return (jsxRuntimeExports.jsx(MFAOptions, { MFAEndpoint: validatedMFAEndpoint, onComplete: handleComplete, onAuthFailed: handleAuthFailed }));
1897
1920
  }
1898
- var requiresMFA = context.requiresMFA, isAuthenticated = context.isAuthenticated, isLoading = context.isLoading;
1899
- if (isLoading) {
1900
- return fallback || jsxRuntimeExports.jsx("div", { className: "flex h-dvh items-center justify-center", children: "Loading..." });
1901
- }
1902
- if (requiresMFA) {
1903
- return (jsxRuntimeExports.jsx(MFAOptions, { MFAEndpoint: MFAEndpoint, onComplete: function (success) {
1904
- if (!success) {
1905
- console.error("MFA authentication failed");
1906
- }
1907
- }, onAuthFailed: function () { return __awaiter(void 0, void 0, void 0, function () {
1908
- return __generator(this, function (_a) {
1909
- switch (_a.label) {
1910
- case 0: return [4 /*yield*/, context.logout()];
1911
- case 1:
1912
- _a.sent();
1913
- return [2 /*return*/];
1914
- }
1915
- });
1916
- }); } }));
1917
- }
1918
- if (!isAuthenticated) {
1919
- return LoginComponent ? jsxRuntimeExports.jsx(LoginComponent, {}) : jsxRuntimeExports.jsx(DefaultLoginPage, {});
1921
+ if (!context.isAuthenticated) {
1922
+ return jsxRuntimeExports.jsx(LoginComponent, {});
1920
1923
  }
1921
1924
  return jsxRuntimeExports.jsx(jsxRuntimeExports.Fragment, { children: children });
1922
1925
  };
1923
1926
 
1924
- export { CAMSMSALProvider, CAMSProvider, ClientOnly, DefaultLoginPage as LoginButton, MFAGate, MFAOptions, ProtectedRoute, UnifiedCAMSProvider, useCAMSAuth, useCAMSContext, useCAMSMSALAuth, useCAMSMSALContext, useCAMSPopupAuth };
1927
+ export { CAMSMSALProvider, CAMSProvider, ClientOnly, DefaultLoginPage as LoginButton, MFAGate, MFAOptions, ProtectedRoute, UnifiedCAMSProvider, setCookie$1 as setCookie, useCAMSAuth, useCAMSContext$1 as useCAMSContext, useCAMSMSALAuth, useCAMSMSALContext, useCAMSPopupAuth };
1925
1928
  //# sourceMappingURL=index.esm.js.map