@civic/auth 0.11.7 → 0.11.8-beta.1
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/CHANGELOG.md +7 -0
- package/dist/reactjs/components/SignOutButton.d.ts.map +1 -1
- package/dist/reactjs/components/SignOutButton.js +6 -1
- package/dist/reactjs/components/SignOutButton.js.map +1 -1
- package/dist/reactjs/components/UserButton.d.ts.map +1 -1
- package/dist/reactjs/components/UserButton.js +21 -6
- package/dist/reactjs/components/UserButton.js.map +1 -1
- package/dist/shared/version.d.ts +1 -1
- package/dist/shared/version.d.ts.map +1 -1
- package/dist/shared/version.js +1 -1
- package/dist/shared/version.js.map +1 -1
- package/dist/vanillajs/auth/handlers/MessageHandler.d.ts +9 -0
- package/dist/vanillajs/auth/handlers/MessageHandler.d.ts.map +1 -1
- package/dist/vanillajs/auth/handlers/MessageHandler.js +30 -0
- package/dist/vanillajs/auth/handlers/MessageHandler.js.map +1 -1
- package/dist/vanillajs/auth/types/AuthTypes.d.ts +10 -0
- package/dist/vanillajs/auth/types/AuthTypes.d.ts.map +1 -1
- package/dist/vanillajs/auth/types/AuthTypes.js.map +1 -1
- package/dist/vanillajs/iframe/IframeManager.d.ts +41 -1
- package/dist/vanillajs/iframe/IframeManager.d.ts.map +1 -1
- package/dist/vanillajs/iframe/IframeManager.js +81 -7
- package/dist/vanillajs/iframe/IframeManager.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,10 @@
|
|
|
1
|
+
# 0.11.8 - Comprehensive loading states and UX improvements
|
|
2
|
+
- Added loading states to all auth buttons (SignInButton, SignOutButton, UserButton) with consistent visual feedback
|
|
3
|
+
- Fixed logout flickering by showing "Logging out..." state and preventing premature transition to "Log in"
|
|
4
|
+
- Fixed initial page load flicker by properly handling AUTHENTICATING and isLoading states
|
|
5
|
+
- Added visual indicators during loading: "Loading...", "Logging in...", "Logging out..." text with reduced opacity and wait cursor
|
|
6
|
+
- Disabled buttons during auth transitions to prevent multiple clicks
|
|
7
|
+
|
|
1
8
|
# 0.11.7 - Add loading states to SignInButton
|
|
2
9
|
- Added visual feedback and disabled state to SignInButton during auth initialization, showing "Loading..." text and reduced opacity to prevent clicks before the auth system is ready
|
|
3
10
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SignOutButton.d.ts","sourceRoot":"","sources":["../../../src/reactjs/components/SignOutButton.tsx"],"names":[],"mappings":"AACA,OAAO,EAAoC,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAC7E,OAAO,EAAW,KAAK,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAQxE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAE9D,UAAU,kBAAkB;IAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClE,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;CACnC;AAED,QAAA,MAAM,aAAa,oDAMhB,kBAAkB,
|
|
1
|
+
{"version":3,"file":"SignOutButton.d.ts","sourceRoot":"","sources":["../../../src/reactjs/components/SignOutButton.tsx"],"names":[],"mappings":"AACA,OAAO,EAAoC,KAAK,aAAa,EAAE,MAAM,OAAO,CAAC;AAC7E,OAAO,EAAW,KAAK,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAQxE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAE9D,UAAU,kBAAkB;IAC1B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClE,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;CACnC;AAED,QAAA,MAAM,aAAa,oDAMhB,kBAAkB,qDAsEpB,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,CAAC"}
|
|
@@ -39,13 +39,18 @@ const SignOutButton = ({ className, style, onSignOut, config, theme = "auto", })
|
|
|
39
39
|
onSignOut?.({ error: error });
|
|
40
40
|
}
|
|
41
41
|
}, [signOut, onSignOut, config]);
|
|
42
|
+
const isSigningOut = authStatus === AuthStatus.SIGNING_OUT;
|
|
42
43
|
return (_jsx(CivicWrapper, { theme: theme, children: _jsx(Button, { css: {
|
|
43
44
|
justifyContent: "center",
|
|
45
|
+
cursor: isSigningOut ? "wait" : "pointer",
|
|
46
|
+
opacity: isSigningOut && userActionStarted ? 0.6 : 1,
|
|
44
47
|
}, className: className, style: style, onClick: () => {
|
|
48
|
+
if (isSigningOut)
|
|
49
|
+
return;
|
|
45
50
|
setUserActionStarted(true);
|
|
46
51
|
!shouldShowLoader(authStatus, effectiveDisplayMode) &&
|
|
47
52
|
handleSignOut();
|
|
48
|
-
}, children: _jsx(ButtonContentOrLoader, { authStatus: authStatus, displayMode: effectiveDisplayMode, userActionStarted: userActionStarted, children: "Log out" }) }) }));
|
|
53
|
+
}, children: _jsx(ButtonContentOrLoader, { authStatus: authStatus, displayMode: effectiveDisplayMode, userActionStarted: userActionStarted, children: isSigningOut ? "Logging out..." : "Log out" }) }) }));
|
|
49
54
|
};
|
|
50
55
|
export { SignOutButton };
|
|
51
56
|
//# sourceMappingURL=SignOutButton.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SignOutButton.js","sourceRoot":"","sources":["../../../src/reactjs/components/SignOutButton.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AACb,OAAO,EAAE,WAAW,EAAE,SAAS,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;IACH,CAAC,EAAE,CAAC,OAAO,EAAE,SAAS,EAAE,MAAM,CAAC,CAAC,CAAC;IAEjC,MAAM,YAAY,GAAG,UAAU,KAAK,UAAU,CAAC,WAAW,CAAC;IAE3D,OAAO,CACL,KAAC,YAAY,IAAC,KAAK,EAAE,KAAK,YACxB,KAAC,MAAM,IACL,GAAG,EAAE;gBACH,cAAc,EAAE,QAAQ;gBACxB,MAAM,EAAE,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS;gBACzC,OAAO,EAAE,YAAY,IAAI,iBAAiB,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;aACrD,EACD,SAAS,EAAE,SAAS,EACpB,KAAK,EAAE,KAAK,EACZ,OAAO,EAAE,GAAG,EAAE;gBACZ,IAAI,YAAY;oBAAE,OAAO;gBACzB,oBAAoB,CAAC,IAAI,CAAC,CAAC;gBAC3B,CAAC,gBAAgB,CAAC,UAAU,EAAE,oBAAoB,CAAC;oBACjD,aAAa,EAAE,CAAC;YACpB,CAAC,YAED,KAAC,qBAAqB,IACpB,UAAU,EAAE,UAAU,EACtB,WAAW,EAAE,oBAAoB,EACjC,iBAAiB,EAAE,iBAAiB,YAEnC,YAAY,CAAC,CAAC,CAAC,gBAAgB,CAAC,CAAC,CAAC,SAAS,GACtB,GACjB,GACI,CAChB,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,aAAa,EAAE,CAAC","sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useState, type CSSProperties } from \"react\";\nimport { useUser, type SignInConfig } from \"@/reactjs/hooks/useUser.js\";\nimport { ButtonContentOrLoader } from \"./ButtonContentOrLoader.js\";\nimport { AuthStatus } from \"@/types.js\";\nimport { shouldShowLoader } from \"./utils.js\";\nimport { useBfcacheHandler } from \"@/shared/hooks/useBfcacheHandler.js\";\nimport { GlobalAuthManager } from \"@/reactjs/core/GlobalAuthManager.js\";\nimport { Button } from \"./Button.js\";\nimport { CivicWrapper } from \"./CivicWrapper.js\";\nimport type { OnSignOutResponse } from \"@/vanillajs/index.js\";\n\ninterface SignOutButtonProps {\n className?: string;\n style?: CSSProperties;\n onSignOut?: (response: OnSignOutResponse) => void | Promise<void>;\n config?: SignInConfig;\n theme?: \"light\" | \"dark\" | \"auto\";\n}\n\nconst SignOutButton = ({\n className,\n style,\n onSignOut,\n config,\n theme = \"auto\",\n}: SignOutButtonProps) => {\n const { signOut, authStatus, displayMode } = useUser();\n const [userActionStarted, setUserActionStarted] = useState(false);\n\n // Handle bfcache restore events\n useBfcacheHandler(\n useCallback(() => {\n // Reset local component state\n setUserActionStarted(false);\n\n // Reset global auth state\n const authManager = GlobalAuthManager.getInstance();\n authManager?.resetOnBfcache();\n }, []),\n );\n\n // reset the userActionStarted state if the user logs out or aborts\n useEffect(() => {\n if (\n [AuthStatus.AUTHENTICATED, AuthStatus.UNAUTHENTICATED].includes(\n authStatus,\n )\n ) {\n setUserActionStarted(false);\n }\n }, [authStatus]);\n\n // Provide default displayMode if undefined\n const effectiveDisplayMode = displayMode || \"iframe\";\n\n const handleSignOut = useCallback(async () => {\n setUserActionStarted(true);\n try {\n await signOut(config);\n onSignOut?.({});\n } catch (error) {\n console.error(\"[SignOutButton] Sign out error:\", error);\n onSignOut?.({ error: error as Error });\n }\n }, [signOut, onSignOut, config]);\n\n const isSigningOut = authStatus === AuthStatus.SIGNING_OUT;\n\n return (\n <CivicWrapper theme={theme}>\n <Button\n css={{\n justifyContent: \"center\",\n cursor: isSigningOut ? \"wait\" : \"pointer\",\n opacity: isSigningOut && userActionStarted ? 0.6 : 1,\n }}\n className={className}\n style={style}\n onClick={() => {\n if (isSigningOut) return;\n setUserActionStarted(true);\n !shouldShowLoader(authStatus, effectiveDisplayMode) &&\n handleSignOut();\n }}\n >\n <ButtonContentOrLoader\n authStatus={authStatus}\n displayMode={effectiveDisplayMode}\n userActionStarted={userActionStarted}\n >\n {isSigningOut ? \"Logging out...\" : \"Log out\"}\n </ButtonContentOrLoader>\n </Button>\n </CivicWrapper>\n );\n};\n\nexport { SignOutButton };\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserButton.d.ts","sourceRoot":"","sources":["../../../src/reactjs/components/UserButton.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAW,KAAK,YAAY,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAc,EAKZ,KAAK,aAAa,EACnB,MAAM,OAAO,CAAC;AAMf,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AA6ChF,UAAU,eAAe;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,YAAY,CAAC,EAAE,aAAa,CAAC;IAC7B,mBAAmB,CAAC,EAAE,aAAa,CAAC;IACpC,QAAQ,CAAC,EAAE,CAAC,QAAQ,EAAE,gBAAgB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChE,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;CACnC;AAED,QAAA,MAAM,UAAU,4IAab,eAAe,
|
|
1
|
+
{"version":3,"file":"UserButton.d.ts","sourceRoot":"","sources":["../../../src/reactjs/components/UserButton.tsx"],"names":[],"mappings":"AAEA,OAAO,EAAW,KAAK,YAAY,EAAE,MAAM,4BAA4B,CAAC;AACxE,OAAc,EAKZ,KAAK,aAAa,EACnB,MAAM,OAAO,CAAC;AAMf,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AA6ChF,UAAU,eAAe;IACvB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,uBAAuB,CAAC,EAAE,MAAM,CAAC;IACjC,KAAK,CAAC,EAAE,aAAa,CAAC;IACtB,YAAY,CAAC,EAAE,aAAa,CAAC;IAC7B,mBAAmB,CAAC,EAAE,aAAa,CAAC;IACpC,QAAQ,CAAC,EAAE,CAAC,QAAQ,EAAE,gBAAgB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAChE,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,iBAAiB,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAClE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,KAAK,CAAC,EAAE,OAAO,GAAG,MAAM,GAAG,MAAM,CAAC;CACnC;AAED,QAAA,MAAM,UAAU,4IAab,eAAe,qDAuPjB,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,CAAC"}
|
|
@@ -21,7 +21,7 @@ const UserButton = ({ className, wrapperClassName, dropdownButtonClassName, styl
|
|
|
21
21
|
}, theme = "auto", }) => {
|
|
22
22
|
const [isOpen, setIsOpen] = useState(false);
|
|
23
23
|
const [buttonWidth, setButtonWidth] = useState(null);
|
|
24
|
-
const { user, signOut, authStatus, displayMode } = useUser();
|
|
24
|
+
const { user, signOut, authStatus, displayMode, isLoading } = useUser();
|
|
25
25
|
const buttonRef = useRef(null);
|
|
26
26
|
const dropdownRef = useRef(null);
|
|
27
27
|
const [userActionStarted, setUserActionStarted] = useState(false);
|
|
@@ -87,16 +87,26 @@ const UserButton = ({ className, wrapperClassName, dropdownButtonClassName, styl
|
|
|
87
87
|
window.removeEventListener("keydown", handleEscape);
|
|
88
88
|
};
|
|
89
89
|
}, [handleClickOutside, handleEscape, isOpen]);
|
|
90
|
-
if
|
|
90
|
+
// Show the user button if user is present OR if we're in a transitional auth state
|
|
91
|
+
// (to prevent flickering to "Log in" during logout or initial auth check)
|
|
92
|
+
if (user ||
|
|
93
|
+
authStatus === AuthStatus.SIGNING_OUT ||
|
|
94
|
+
authStatus === AuthStatus.AUTHENTICATING ||
|
|
95
|
+
isLoading) {
|
|
91
96
|
return (_jsxs(CivicWrapper, { css: { position: "relative", width: "auto" }, className: wrapperClassName, style: wrapperStyle, id: "civic-dropdown-container", theme: theme, children: [_jsx(Button, { ref: buttonRef, css: {
|
|
92
|
-
cursor: isAuthenticating
|
|
97
|
+
cursor: isAuthenticating ||
|
|
98
|
+
authStatus === AuthStatus.SIGNING_OUT ||
|
|
99
|
+
(isLoading && !user)
|
|
100
|
+
? "wait"
|
|
101
|
+
: "pointer",
|
|
93
102
|
minWidth: "10rem",
|
|
94
103
|
alignItems: "center",
|
|
95
104
|
paddingRight: "0.75rem",
|
|
96
105
|
}, className: className, style: style, onClick: () => {
|
|
106
|
+
if (authStatus === AuthStatus.SIGNING_OUT || (isLoading && !user))
|
|
107
|
+
return;
|
|
97
108
|
setUserActionStarted(true);
|
|
98
|
-
|
|
99
|
-
setIsOpen((isOpen) => !isOpen);
|
|
109
|
+
setIsOpen((isOpen) => !isOpen);
|
|
100
110
|
}, children: _jsxs(_Fragment, { children: [user?.picture ? (_jsx("span", { css: {
|
|
101
111
|
position: "relative",
|
|
102
112
|
display: "flex",
|
|
@@ -110,7 +120,12 @@ const UserButton = ({ className, wrapperClassName, dropdownButtonClassName, styl
|
|
|
110
120
|
height: "100%",
|
|
111
121
|
width: "100%",
|
|
112
122
|
objectFit: "cover",
|
|
113
|
-
}, src: user.picture, alt: user?.name || user?.email }) })) : (_jsx("span", { css: { display: "block" } })), _jsx(ButtonContentOrLoader, { authStatus: authStatus, displayMode: effectiveDisplayMode, userActionStarted: userActionStarted, children:
|
|
123
|
+
}, src: user.picture, alt: user?.name || user?.email }) })) : (_jsx("span", { css: { display: "block" } })), _jsx(ButtonContentOrLoader, { authStatus: authStatus, displayMode: effectiveDisplayMode, userActionStarted: userActionStarted, children: authStatus === AuthStatus.SIGNING_OUT
|
|
124
|
+
? "Logging out..."
|
|
125
|
+
: (authStatus === AuthStatus.AUTHENTICATING || isLoading) &&
|
|
126
|
+
!user
|
|
127
|
+
? "Loading..."
|
|
128
|
+
: user?.name || user?.email }), _jsx("span", { css: {
|
|
114
129
|
display: "block",
|
|
115
130
|
pointerEvents: "none",
|
|
116
131
|
visibility: shouldShowLoader(authStatus, effectiveDisplayMode)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"UserButton.js","sourceRoot":"","sources":["../../../src/reactjs/components/UserButton.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,OAAO,EAAqB,MAAM,4BAA4B,CAAC;AACxE,OAAO,KAAK,EAAE,EACZ,WAAW,EACX,SAAS,EACT,MAAM,EACN,QAAQ,GAET,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAExE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,MAAM,WAAW,GAAG,GAAG,EAAE,CAAC,CACxB,cACE,KAAK,EAAC,4BAA4B,EAClC,KAAK,EAAC,IAAI,EACV,MAAM,EAAC,IAAI,EACX,OAAO,EAAC,WAAW,EACnB,IAAI,EAAC,MAAM,EACX,MAAM,EAAC,cAAc,EACrB,WAAW,EAAC,GAAG,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AC7C;iCACF,EACD,SAAS,EAAE,uBAAuB,EAClC,KAAK,EAAE,mBAAmB,EAC1B,OAAO,EAAE,GAAG,EAAE;oCACZ,oBAAoB,CAAC,IAAI,CAAC,CAAC;oCAC3B,CAAC,gBAAgB,CAAC,UAAU,EAAE,oBAAoB,CAAC;wCACjD,aAAa,EAAE,CAAC;gCACpB,CAAC,wBAGM,GACN,GACF,GACD,IACO,CAChB,CAAC;IACJ,CAAC;IAED,OAAO,CACL,KAAC,YAAY,IACX,SAAS,EAAE,SAAS,EACpB,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE;YACrB,mBAAmB,EAAE,CAAC;YACtB,QAAQ,EAAE,CAAC,QAAQ,CAAC,CAAC;QACvB,CAAC,EACD,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,KAAK,EACZ,WAAW,EAAE,oBAAoB,EACjC,iBAAiB,EAAE,iBAAiB,EACpC,oBAAoB,EAAE,oBAAoB,EAC1C,gBAAgB,EAAE,gBAAgB,EAClC,mBAAmB,EAAE,mBAAmB,GACxC,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,CAAC","sourcesContent":["\"use client\";\n\nimport { useUser, type SignInConfig } from \"@/reactjs/hooks/useUser.js\";\nimport React, {\n useCallback,\n useEffect,\n useRef,\n useState,\n type CSSProperties,\n} from \"react\";\nimport { ButtonContentOrLoader } from \"./ButtonContentOrLoader.js\";\nimport { AuthStatus } from \"@/types.js\";\nimport { shouldShowLoader } from \"./utils.js\";\nimport { useBfcacheHandler } from \"@/shared/hooks/useBfcacheHandler.js\";\nimport { GlobalAuthManager } from \"@/reactjs/core/GlobalAuthManager.js\";\nimport type { OnSignInResponse, OnSignOutResponse } from \"@/vanillajs/index.js\";\nimport { CivicWrapper } from \"./CivicWrapper.js\";\nimport { Button } from \"./Button.js\";\nimport { SignInButton } from \"./SignInButton.js\";\n\nconst ChevronDown = () => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"lucide lucide-chevron-down\"\n css={{\n stroke: \"var(--icon-secondary)\",\n }}\n >\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n);\n\nconst ChevronUp = () => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"lucide lucide-chevron-up\"\n css={{\n stroke: \"var(--icon-secondary)\",\n }}\n >\n <path d=\"m18 15-6-6-6 6\" />\n </svg>\n);\n\ninterface UserButtonProps {\n className?: string;\n wrapperClassName?: string;\n dropdownButtonClassName?: string;\n style?: CSSProperties;\n wrapperStyle?: CSSProperties;\n dropdownButtonStyle?: CSSProperties;\n onSignIn?: (response: OnSignInResponse) => void | Promise<void>;\n onSignOut?: (response: OnSignOutResponse) => void | Promise<void>;\n loginUrl?: string;\n config?: SignInConfig;\n theme?: \"light\" | \"dark\" | \"auto\";\n}\n\nconst UserButton = ({\n className,\n wrapperClassName,\n dropdownButtonClassName,\n style,\n wrapperStyle,\n dropdownButtonStyle,\n onSignIn,\n onSignOut,\n config = {\n displayMode: \"iframe\",\n },\n theme = \"auto\",\n}: UserButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n const [buttonWidth, setButtonWidth] = useState<number | null>(null);\n const { user, signOut, authStatus, displayMode } = useUser();\n const buttonRef = useRef<HTMLButtonElement>(null);\n const dropdownRef = useRef<HTMLDivElement>(null);\n const [userActionStarted, setUserActionStarted] = useState(false);\n const [isAuthenticating, setIsAuthenticating] = useState(false);\n\n // Provide default displayMode if undefined\n const effectiveDisplayMode = displayMode || \"iframe\";\n\n // Handle bfcache restore events\n useBfcacheHandler(\n useCallback(() => {\n // Reset local component state\n setUserActionStarted(false);\n setIsAuthenticating(false);\n setIsOpen(false);\n\n // Reset global auth state\n const authManager = GlobalAuthManager.getInstance();\n authManager?.resetOnBfcache();\n }, []),\n );\n\n useEffect(() => {\n if (\n [AuthStatus.AUTHENTICATED, AuthStatus.UNAUTHENTICATED].includes(\n authStatus,\n )\n ) {\n setUserActionStarted(false);\n }\n }, [authStatus]);\n\n useEffect(() => {\n if (buttonRef.current) {\n setButtonWidth(buttonRef.current.offsetWidth);\n }\n }, [isOpen]);\n\n const handleClickOutside = useCallback((event: MouseEvent) => {\n const target = event.target as HTMLElement;\n\n if (\n buttonRef.current &&\n dropdownRef.current &&\n !buttonRef.current.contains(target) &&\n !dropdownRef.current.contains(target)\n ) {\n setIsOpen(false);\n }\n }, []);\n\n const handleSignOut = useCallback(async () => {\n setIsOpen(false);\n try {\n await signOut(config);\n onSignOut?.({});\n } catch (error) {\n console.error(\"[UserButton] Sign out error:\", error);\n onSignOut?.({ error: error as Error });\n }\n }, [signOut, onSignOut, config]);\n\n const handleCloseDropdown = useCallback(() => {\n setIsOpen(false);\n }, []);\n\n const handleEscape = useCallback((event: KeyboardEvent) => {\n if (event.key === \"Escape\") {\n setIsOpen(false);\n setIsAuthenticating(false);\n }\n }, []);\n\n useEffect(() => {\n if (isOpen) {\n window.addEventListener(\"click\", handleClickOutside);\n\n window.addEventListener(\"keydown\", handleEscape);\n }\n\n return () => {\n window.removeEventListener(\"click\", handleClickOutside);\n\n window.removeEventListener(\"keydown\", handleEscape);\n };\n }, [handleClickOutside, handleEscape, isOpen]);\n\n if (user) {\n return (\n <CivicWrapper\n css={{ position: \"relative\", width: \"auto\" }}\n className={wrapperClassName}\n style={wrapperStyle}\n id=\"civic-dropdown-container\"\n theme={theme}\n >\n <Button\n ref={buttonRef}\n css={{\n cursor: isAuthenticating ? \"wait\" : \"pointer\",\n minWidth: \"10rem\",\n alignItems: \"center\",\n paddingRight: \"0.75rem\",\n }}\n className={className}\n style={style}\n onClick={() => {\n setUserActionStarted(true);\n authStatus !== AuthStatus.SIGNING_OUT &&\n setIsOpen((isOpen) => !isOpen);\n }}\n >\n <>\n {user?.picture ? (\n <span\n css={{\n position: \"relative\",\n display: \"flex\",\n height: \"30px\",\n width: \"30px\",\n flexShrink: 0,\n overflow: \"hidden\",\n borderRadius: \"9999px\",\n margin: \"1px\",\n }}\n >\n <img\n css={{\n height: \"100%\",\n width: \"100%\",\n objectFit: \"cover\",\n }}\n src={user.picture}\n alt={user?.name || user?.email}\n />\n </span>\n ) : (\n <span css={{ display: \"block\" }} />\n )}\n\n <ButtonContentOrLoader\n authStatus={authStatus}\n displayMode={effectiveDisplayMode}\n userActionStarted={userActionStarted}\n >\n {user?.name || user?.email}\n </ButtonContentOrLoader>\n <span\n css={{\n display: \"block\",\n pointerEvents: \"none\",\n visibility: shouldShowLoader(authStatus, effectiveDisplayMode)\n ? \"hidden\"\n : \"visible\",\n }}\n >\n {isOpen ? <ChevronUp /> : <ChevronDown />}\n </span>\n </>\n </Button>\n <div\n ref={dropdownRef}\n css={\n isOpen\n ? {\n position: \"absolute\",\n left: 0,\n background: \"transparent\",\n width: buttonWidth || \"auto\",\n marginTop: \"4px\",\n borderRadius: \"9999px\",\n boxShadow:\n \"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)\",\n zIndex: 1000,\n }\n : { display: \"none\" }\n }\n >\n <ul css={{ listStyleType: \"none\", margin: 0, padding: 0 }}>\n <li>\n <Button\n css={{\n display: \"block\",\n width: \"100%\",\n height: \"34px\",\n color: \"var(--text-paragraph)\",\n backgroundColor: \"var(--background-tertiary)\",\n \"&:hover\": {\n backgroundColor: \"var(--background-neutral)\",\n },\n }}\n className={dropdownButtonClassName}\n style={dropdownButtonStyle}\n onClick={() => {\n setUserActionStarted(true);\n !shouldShowLoader(authStatus, effectiveDisplayMode) &&\n handleSignOut();\n }}\n >\n Log out\n </Button>\n </li>\n </ul>\n </div>\n </CivicWrapper>\n );\n }\n\n return (\n <SignInButton\n className={className}\n style={style}\n onSignIn={(response) => {\n handleCloseDropdown();\n onSignIn?.(response);\n }}\n config={config}\n theme={theme}\n displayMode={effectiveDisplayMode}\n userActionStarted={userActionStarted}\n setUserActionStarted={setUserActionStarted}\n isAuthenticating={isAuthenticating}\n setIsAuthenticating={setIsAuthenticating}\n />\n );\n};\n\nexport { UserButton };\n"]}
|
|
1
|
+
{"version":3,"file":"UserButton.js","sourceRoot":"","sources":["../../../src/reactjs/components/UserButton.tsx"],"names":[],"mappings":"AAAA,YAAY,CAAC;;AAEb,OAAO,EAAE,OAAO,EAAqB,MAAM,4BAA4B,CAAC;AACxE,OAAO,KAAK,EAAE,EACZ,WAAW,EACX,SAAS,EACT,MAAM,EACN,QAAQ,GAET,MAAM,OAAO,CAAC;AACf,OAAO,EAAE,qBAAqB,EAAE,MAAM,4BAA4B,CAAC;AACnE,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAC;AACxC,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AACxE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAExE,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AACrC,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,MAAM,WAAW,GAAG,GAAG,EAAE,CAAC,CACxB,cACE,KAAK,EAAC,4BAA4B,EAClC,KAAK,EAAC,IAAI,EACV,MAAM,EAAC,IAAI,EACX,OAAO,EAAC,WAAW,EACnB,IAAI,EAAC,MAAM,EACX,MAAM,EAAC,cAAc,EACrB,WAAW,EAAC,GAAG,EACf,aAAa,EAAC,OAAO,EACrB,cAAc,EAAC,OAAO,EACtB,SAAS,EAAC,4BAA4B,EACt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;yBACb;wBACH,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,YAGzB,aAAI,GAAG,EAAE,EAAE,aAAa,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,YACvD,uBACE,KAAC,MAAM,IACL,GAAG,EAAE;oCACH,OAAO,EAAE,OAAO;oCAChB,KAAK,EAAE,MAAM;oCACb,MAAM,EAAE,MAAM;oCACd,KAAK,EAAE,uBAAuB;oCAC9B,eAAe,EAAE,4BAA4B;oCAC7C,SAAS,EAAE;wCACT,eAAe,EAAE,2BAA2B;qCAC7C;iCACF,EACD,SAAS,EAAE,uBAAuB,EAClC,KAAK,EAAE,mBAAmB,EAC1B,OAAO,EAAE,GAAG,EAAE;oCACZ,oBAAoB,CAAC,IAAI,CAAC,CAAC;oCAC3B,CAAC,gBAAgB,CAAC,UAAU,EAAE,oBAAoB,CAAC;wCACjD,aAAa,EAAE,CAAC;gCACpB,CAAC,wBAGM,GACN,GACF,GACD,IACO,CAChB,CAAC;IACJ,CAAC;IAED,OAAO,CACL,KAAC,YAAY,IACX,SAAS,EAAE,SAAS,EACpB,KAAK,EAAE,KAAK,EACZ,QAAQ,EAAE,CAAC,QAAQ,EAAE,EAAE;YACrB,mBAAmB,EAAE,CAAC;YACtB,QAAQ,EAAE,CAAC,QAAQ,CAAC,CAAC;QACvB,CAAC,EACD,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,KAAK,EACZ,WAAW,EAAE,oBAAoB,EACjC,iBAAiB,EAAE,iBAAiB,EACpC,oBAAoB,EAAE,oBAAoB,EAC1C,gBAAgB,EAAE,gBAAgB,EAClC,mBAAmB,EAAE,mBAAmB,GACxC,CACH,CAAC;AACJ,CAAC,CAAC;AAEF,OAAO,EAAE,UAAU,EAAE,CAAC","sourcesContent":["\"use client\";\n\nimport { useUser, type SignInConfig } from \"@/reactjs/hooks/useUser.js\";\nimport React, {\n useCallback,\n useEffect,\n useRef,\n useState,\n type CSSProperties,\n} from \"react\";\nimport { ButtonContentOrLoader } from \"./ButtonContentOrLoader.js\";\nimport { AuthStatus } from \"@/types.js\";\nimport { shouldShowLoader } from \"./utils.js\";\nimport { useBfcacheHandler } from \"@/shared/hooks/useBfcacheHandler.js\";\nimport { GlobalAuthManager } from \"@/reactjs/core/GlobalAuthManager.js\";\nimport type { OnSignInResponse, OnSignOutResponse } from \"@/vanillajs/index.js\";\nimport { CivicWrapper } from \"./CivicWrapper.js\";\nimport { Button } from \"./Button.js\";\nimport { SignInButton } from \"./SignInButton.js\";\n\nconst ChevronDown = () => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"lucide lucide-chevron-down\"\n css={{\n stroke: \"var(--icon-secondary)\",\n }}\n >\n <path d=\"m6 9 6 6 6-6\" />\n </svg>\n);\n\nconst ChevronUp = () => (\n <svg\n xmlns=\"http://www.w3.org/2000/svg\"\n width=\"24\"\n height=\"24\"\n viewBox=\"0 0 24 24\"\n fill=\"none\"\n stroke=\"currentColor\"\n strokeWidth=\"2\"\n strokeLinecap=\"round\"\n strokeLinejoin=\"round\"\n className=\"lucide lucide-chevron-up\"\n css={{\n stroke: \"var(--icon-secondary)\",\n }}\n >\n <path d=\"m18 15-6-6-6 6\" />\n </svg>\n);\n\ninterface UserButtonProps {\n className?: string;\n wrapperClassName?: string;\n dropdownButtonClassName?: string;\n style?: CSSProperties;\n wrapperStyle?: CSSProperties;\n dropdownButtonStyle?: CSSProperties;\n onSignIn?: (response: OnSignInResponse) => void | Promise<void>;\n onSignOut?: (response: OnSignOutResponse) => void | Promise<void>;\n loginUrl?: string;\n config?: SignInConfig;\n theme?: \"light\" | \"dark\" | \"auto\";\n}\n\nconst UserButton = ({\n className,\n wrapperClassName,\n dropdownButtonClassName,\n style,\n wrapperStyle,\n dropdownButtonStyle,\n onSignIn,\n onSignOut,\n config = {\n displayMode: \"iframe\",\n },\n theme = \"auto\",\n}: UserButtonProps) => {\n const [isOpen, setIsOpen] = useState(false);\n const [buttonWidth, setButtonWidth] = useState<number | null>(null);\n const { user, signOut, authStatus, displayMode, isLoading } = useUser();\n const buttonRef = useRef<HTMLButtonElement>(null);\n const dropdownRef = useRef<HTMLDivElement>(null);\n const [userActionStarted, setUserActionStarted] = useState(false);\n const [isAuthenticating, setIsAuthenticating] = useState(false);\n\n // Provide default displayMode if undefined\n const effectiveDisplayMode = displayMode || \"iframe\";\n\n // Handle bfcache restore events\n useBfcacheHandler(\n useCallback(() => {\n // Reset local component state\n setUserActionStarted(false);\n setIsAuthenticating(false);\n setIsOpen(false);\n\n // Reset global auth state\n const authManager = GlobalAuthManager.getInstance();\n authManager?.resetOnBfcache();\n }, []),\n );\n\n useEffect(() => {\n if (\n [AuthStatus.AUTHENTICATED, AuthStatus.UNAUTHENTICATED].includes(\n authStatus,\n )\n ) {\n setUserActionStarted(false);\n }\n }, [authStatus]);\n\n useEffect(() => {\n if (buttonRef.current) {\n setButtonWidth(buttonRef.current.offsetWidth);\n }\n }, [isOpen]);\n\n const handleClickOutside = useCallback((event: MouseEvent) => {\n const target = event.target as HTMLElement;\n\n if (\n buttonRef.current &&\n dropdownRef.current &&\n !buttonRef.current.contains(target) &&\n !dropdownRef.current.contains(target)\n ) {\n setIsOpen(false);\n }\n }, []);\n\n const handleSignOut = useCallback(async () => {\n setIsOpen(false);\n try {\n await signOut(config);\n onSignOut?.({});\n } catch (error) {\n console.error(\"[UserButton] Sign out error:\", error);\n onSignOut?.({ error: error as Error });\n }\n }, [signOut, onSignOut, config]);\n\n const handleCloseDropdown = useCallback(() => {\n setIsOpen(false);\n }, []);\n\n const handleEscape = useCallback((event: KeyboardEvent) => {\n if (event.key === \"Escape\") {\n setIsOpen(false);\n setIsAuthenticating(false);\n }\n }, []);\n\n useEffect(() => {\n if (isOpen) {\n window.addEventListener(\"click\", handleClickOutside);\n\n window.addEventListener(\"keydown\", handleEscape);\n }\n\n return () => {\n window.removeEventListener(\"click\", handleClickOutside);\n\n window.removeEventListener(\"keydown\", handleEscape);\n };\n }, [handleClickOutside, handleEscape, isOpen]);\n\n // Show the user button if user is present OR if we're in a transitional auth state\n // (to prevent flickering to \"Log in\" during logout or initial auth check)\n if (\n user ||\n authStatus === AuthStatus.SIGNING_OUT ||\n authStatus === AuthStatus.AUTHENTICATING ||\n isLoading\n ) {\n return (\n <CivicWrapper\n css={{ position: \"relative\", width: \"auto\" }}\n className={wrapperClassName}\n style={wrapperStyle}\n id=\"civic-dropdown-container\"\n theme={theme}\n >\n <Button\n ref={buttonRef}\n css={{\n cursor:\n isAuthenticating ||\n authStatus === AuthStatus.SIGNING_OUT ||\n (isLoading && !user)\n ? \"wait\"\n : \"pointer\",\n minWidth: \"10rem\",\n alignItems: \"center\",\n paddingRight: \"0.75rem\",\n }}\n className={className}\n style={style}\n onClick={() => {\n if (authStatus === AuthStatus.SIGNING_OUT || (isLoading && !user))\n return;\n setUserActionStarted(true);\n setIsOpen((isOpen) => !isOpen);\n }}\n >\n <>\n {user?.picture ? (\n <span\n css={{\n position: \"relative\",\n display: \"flex\",\n height: \"30px\",\n width: \"30px\",\n flexShrink: 0,\n overflow: \"hidden\",\n borderRadius: \"9999px\",\n margin: \"1px\",\n }}\n >\n <img\n css={{\n height: \"100%\",\n width: \"100%\",\n objectFit: \"cover\",\n }}\n src={user.picture}\n alt={user?.name || user?.email}\n />\n </span>\n ) : (\n <span css={{ display: \"block\" }} />\n )}\n\n <ButtonContentOrLoader\n authStatus={authStatus}\n displayMode={effectiveDisplayMode}\n userActionStarted={userActionStarted}\n >\n {authStatus === AuthStatus.SIGNING_OUT\n ? \"Logging out...\"\n : (authStatus === AuthStatus.AUTHENTICATING || isLoading) &&\n !user\n ? \"Loading...\"\n : user?.name || user?.email}\n </ButtonContentOrLoader>\n <span\n css={{\n display: \"block\",\n pointerEvents: \"none\",\n visibility: shouldShowLoader(authStatus, effectiveDisplayMode)\n ? \"hidden\"\n : \"visible\",\n }}\n >\n {isOpen ? <ChevronUp /> : <ChevronDown />}\n </span>\n </>\n </Button>\n <div\n ref={dropdownRef}\n css={\n isOpen\n ? {\n position: \"absolute\",\n left: 0,\n background: \"transparent\",\n width: buttonWidth || \"auto\",\n marginTop: \"4px\",\n borderRadius: \"9999px\",\n boxShadow:\n \"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)\",\n zIndex: 1000,\n }\n : { display: \"none\" }\n }\n >\n <ul css={{ listStyleType: \"none\", margin: 0, padding: 0 }}>\n <li>\n <Button\n css={{\n display: \"block\",\n width: \"100%\",\n height: \"34px\",\n color: \"var(--text-paragraph)\",\n backgroundColor: \"var(--background-tertiary)\",\n \"&:hover\": {\n backgroundColor: \"var(--background-neutral)\",\n },\n }}\n className={dropdownButtonClassName}\n style={dropdownButtonStyle}\n onClick={() => {\n setUserActionStarted(true);\n !shouldShowLoader(authStatus, effectiveDisplayMode) &&\n handleSignOut();\n }}\n >\n Log out\n </Button>\n </li>\n </ul>\n </div>\n </CivicWrapper>\n );\n }\n\n return (\n <SignInButton\n className={className}\n style={style}\n onSignIn={(response) => {\n handleCloseDropdown();\n onSignIn?.(response);\n }}\n config={config}\n theme={theme}\n displayMode={effectiveDisplayMode}\n userActionStarted={userActionStarted}\n setUserActionStarted={setUserActionStarted}\n isAuthenticating={isAuthenticating}\n setIsAuthenticating={setIsAuthenticating}\n />\n );\n};\n\nexport { UserButton };\n"]}
|
package/dist/shared/version.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export declare const VERSION = "@civic/auth:0.11.
|
|
1
|
+
export declare const VERSION = "@civic/auth:0.11.8-beta.1";
|
|
2
2
|
//# sourceMappingURL=version.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/shared/version.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,
|
|
1
|
+
{"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../../src/shared/version.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,OAAO,8BAA8B,CAAC"}
|
package/dist/shared/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/shared/version.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAE/C,MAAM,CAAC,MAAM,OAAO,GAAG,
|
|
1
|
+
{"version":3,"file":"version.js","sourceRoot":"","sources":["../../src/shared/version.ts"],"names":[],"mappings":"AAAA,+CAA+C;AAE/C,MAAM,CAAC,MAAM,OAAO,GAAG,2BAA2B,CAAC","sourcesContent":["// This is an auto-generated file. Do not edit.\n\nexport const VERSION = \"@civic/auth:0.11.8-beta.1\";\n"]}
|
|
@@ -143,6 +143,15 @@ export declare class MessageHandler {
|
|
|
143
143
|
* @param message - The civicloginApp popup failure message to process
|
|
144
144
|
*/
|
|
145
145
|
private handlePopupFailure;
|
|
146
|
+
/**
|
|
147
|
+
* Handles design messages from civicloginApp.
|
|
148
|
+
*
|
|
149
|
+
* Processes design messages containing customer preferences like colorMode
|
|
150
|
+
* and forwards them to the appropriate handlers.
|
|
151
|
+
*
|
|
152
|
+
* @param data - The design message data payload
|
|
153
|
+
*/
|
|
154
|
+
private handleDesignMessage;
|
|
146
155
|
/**
|
|
147
156
|
* Handles unknown or unrecognized civicloginApp message types.
|
|
148
157
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MessageHandler.d.ts","sourceRoot":"","sources":["../../../../src/vanillajs/auth/handlers/MessageHandler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAIV,wBAAwB,
|
|
1
|
+
{"version":3,"file":"MessageHandler.d.ts","sourceRoot":"","sources":["../../../../src/vanillajs/auth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;;OAOG;IACI,aAAa,UAAW,YAAY,KAAG,IAAI,CAYhD;IAEF;;;;;;;;OAQG;IACH,OAAO,CAAC,kBAAkB;IAa1B;;;;;;;;;OASG;IACH,OAAO,CAAC,oBAAoB;IA6D5B;;;;;;;OAOG;IACH,OAAO,CAAC,kBAAkB;IAoC1B;;;;;;;;OAQG;IACH,OAAO,CAAC,sBAAsB;IAS9B;;;;;;;;OAQG;IACH,OAAO,CAAC,0BAA0B;IA8DlC;;;;;;;OAOG;IAEH,OAAO,CAAC,sBAAsB;IAc9B;;;;;;;OAOG;IACH,OAAO,CAAC,wBAAwB;IAoBhC;;;;;OAKG;IACH,OAAO,CAAC,8BAA8B;IAkBtC;;;;;;;;OAQG;IACH,OAAO,CAAC,kBAAkB;IA8B1B;;;;;;;OAOG;IACH,OAAO,CAAC,mBAAmB;IAsB3B;;;;;;;OAOG;IACH,OAAO,CAAC,iCAAiC;IAqBzC;;;;;;;;OAQG;IACH,OAAO,CAAC,sBAAsB;IAY9B;;;;;;;OAOG;IACH,OAAO,CAAC,0BAA0B;IAYlC;;;;;;;OAOG;IACH,OAAO,CAAC,yBAAyB;IAmCjC;;;;;;;OAOG;IACH,OAAO,CAAC,iBAAiB;IASzB;;;;;;;OAOG;IACH,OAAO,CAAC,eAAe;CAcxB"}
|
|
@@ -245,6 +245,7 @@ export class MessageHandler {
|
|
|
245
245
|
this.logger.debug("civicloginApp design message", {
|
|
246
246
|
data: message.data,
|
|
247
247
|
});
|
|
248
|
+
this.handleDesignMessage(message.data);
|
|
248
249
|
break;
|
|
249
250
|
case "auth_success_early":
|
|
250
251
|
this.logger.info("civicloginApp auth success early message", {
|
|
@@ -366,6 +367,35 @@ export class MessageHandler {
|
|
|
366
367
|
}
|
|
367
368
|
this.onPopupFailure(failedUrl);
|
|
368
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* Handles design messages from civicloginApp.
|
|
372
|
+
*
|
|
373
|
+
* Processes design messages containing customer preferences like colorMode
|
|
374
|
+
* and forwards them to the appropriate handlers.
|
|
375
|
+
*
|
|
376
|
+
* @param data - The design message data payload
|
|
377
|
+
*/
|
|
378
|
+
handleDesignMessage(data) {
|
|
379
|
+
if (!data) {
|
|
380
|
+
this.logger.debug("Design message received with no data");
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
// Handle colorMode preference
|
|
384
|
+
if (data.colorMode) {
|
|
385
|
+
const validColorModes = ["light", "dark", "auto"];
|
|
386
|
+
if (validColorModes.includes(data.colorMode)) {
|
|
387
|
+
this.logger.debug("Setting customer color mode", {
|
|
388
|
+
colorMode: data.colorMode,
|
|
389
|
+
});
|
|
390
|
+
IframeManager.handleLoginAppColorMode(data.colorMode);
|
|
391
|
+
}
|
|
392
|
+
else {
|
|
393
|
+
this.logger.debug("Invalid colorMode value received", {
|
|
394
|
+
colorMode: data.colorMode,
|
|
395
|
+
});
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
369
399
|
/**
|
|
370
400
|
* Handles unknown or unrecognized civicloginApp message types.
|
|
371
401
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"MessageHandler.js","sourceRoot":"","sources":["../../../../src/vanillajs/auth/handlers/MessageHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAQjD,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3E,OAAO,EAAE,YAAY,IAAI,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAapE;;;GAGG;AACH,MAAM,OAAO,cAAc;IACjB,MAAM,CAA2B;IACjC,MAAM,GAAG,cAAc,CAAC,iBAAiB,CAAC,CAAC;IAC3C,aAAa,CAAqB;IAClC,aAAa,CAA+B;IAC5C,WAAW,CAAyB;IACpC,cAAc,CAA+B;IAC7C,0BAA0B,GAChC,GAAG,EAAE;QACH,O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AC;oBACN,IAAI,CAAC,MAAM,CAAC,KAAK,CACf,4GAA4G,EAC5G;wBACE,IAAI,EAAE,OAAO;wBACb,WAAW,EAAE,OAAO,OAAO;wBAC3B,OAAO,EAAE,UAAU,EAAE,IAAI,IAAI,MAAM;wBACnC,WAAW,EAAE,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC,EAAE;qBACvD,CACF,CAAC;gBACJ,CAAC;QACL,CAAC;IACH,CAAC;IAED;;;;;;;OAOG;IACK,iBAAiB,CAAC,IAAiB;QACzC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,gBAAgB,EAAE;YACnD,MAAM,EAAE,yCAAyC;YACjD,IAAI;SACL,CAAC,CAAC;QACH,IAAI,CAAC,aAAa,CAAE,IAAI,EAAE,IAAmB,IAAI,EAAE,CAAC,CAAC;QACrD,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED;;;;;;;OAOG;IACK,eAAe,CAAC,IAAiB;QACvC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,EAAE;YAChD,MAAM,EAAE,uCAAuC;YAC/C,KAAK,EAAE,IAAI;SACZ,CAAC,CAAC;QAEH,MAAM,KAAK,GAAG,IAAI,cAAc,CAC9B,IAAI,EAAE,MAAM,IAAI,uCAAuC,EACvD,kBAAkB,CAAC,eAAe,CACnC,CAAC;QAEF,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;QACxB,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { AuthEvent } from \"../../types/index.js\";\nimport type { AuthResult } from \"../../types/index.js\";\nimport type {\n IframeMessage,\n AuthMessage,\n LoginAppMessage,\n ProcessedCivicAuthConfig,\n} from \"../types/AuthTypes.js\";\nimport { CivicAuthError, CivicAuthErrorCode } from \"../types/AuthTypes.js\";\nimport type { createLogger } from \"../../utils/logger.js\";\nimport { createLogger as createLoggerFn } from \"../../utils/logger.js\";\nimport { IframeManager } from \"@/vanillajs/iframe/IframeManager.js\";\n\nexport interface MessageHandlerConfig {\n config: ProcessedCivicAuthConfig;\n logger: ReturnType<typeof createLogger>;\n iframeElement?: HTMLIFrameElement;\n onAuthSuccess: (result: AuthResult) => void;\n onAuthError: (error: Error) => void;\n onPopupFailure: (failedUrl?: string) => void;\n onBrowserCorsFailsSilently: (failedUrl?: string) => Promise<void>;\n cleanup: () => void;\n}\n\n/**\n * MessageHandler - Handles postMessage communication and authentication flow logic\n * Processes messages from iframe, validates origins, and manages auth state transitions\n */\nexport class MessageHandler {\n private config: ProcessedCivicAuthConfig;\n private logger = createLoggerFn(\"message-handler\");\n private iframeElement?: HTMLIFrameElement;\n private onAuthSuccess: (result: AuthResult) => void;\n private onAuthError: (error: Error) => void;\n private onPopupFailure: (failedUrl?: string) => void;\n private onBrowserCorsFailsSilently: (failedUrl?: string) => Promise<void> =\n () => {\n return Promise.resolve(); // No-op by default, can be overridden\n };\n private cleanup: () => void;\n\n // Backend integration - custom expected origin\n private customExpectedOrigin?: string;\n\n constructor(handlerConfig: MessageHandlerConfig) {\n this.config = handlerConfig.config;\n this.iframeElement = handlerConfig.iframeElement;\n this.onAuthSuccess = handlerConfig.onAuthSuccess;\n this.onAuthError = handlerConfig.onAuthError;\n this.onPopupFailure = handlerConfig.onPopupFailure;\n this.onBrowserCorsFailsSilently = handlerConfig.onBrowserCorsFailsSilently;\n this.cleanup = handlerConfig.cleanup;\n }\n\n /**\n * Updates the iframe element reference used for message validation.\n *\n * This method allows updating the iframe element after the MessageHandler\n * has been instantiated, which is useful when the iframe is created\n * dynamically after the handler setup.\n *\n * @param iframeElement - The new iframe element to associate with this handler\n */\n public updateIframeElement(iframeElement: HTMLIFrameElement): void {\n this.iframeElement = iframeElement;\n }\n\n /**\n * Sets a custom expected origin for backend integration.\n *\n * This allows the MessageHandler to accept messages from a custom backend\n * origin instead of the default OAuth server origin.\n *\n * @param customLoginUrl - The custom login URL to derive the origin from\n */\n public setCustomExpectedOrigin(customLoginUrl: string): void {\n this.customExpectedOrigin = new URL(customLoginUrl).origin;\n this.logger.info(\"🔗 Custom expected origin set for backend integration\", {\n customExpectedOrigin: this.customExpectedOrigin,\n customLoginUrl,\n });\n }\n\n /**\n * Clears the custom expected origin and returns to OAuth server origin.\n */\n public clearCustomExpectedOrigin(): void {\n this.customExpectedOrigin = undefined;\n this.logger.info(\n \"🔗 Custom expected origin cleared, returning to OAuth server origin\",\n );\n }\n\n /**\n * Main message handler for processing postMessage events.\n *\n * Validates message origin and source, then routes valid messages to\n * appropriate handlers. This is the entry point for all iframe communication.\n *\n * @param event - The MessageEvent received from the iframe or other sources\n */\n public handleMessage = (event: MessageEvent): void => {\n // Use custom origin if set (for backend integration), otherwise use OAuth server origin\n const expectedOrigin =\n this.customExpectedOrigin ||\n new URL(this.config.oauthServerBaseUrl).origin;\n this.logIncomingMessage(event, expectedOrigin);\n\n if (!this.isValidMessageSource(event, expectedOrigin)) {\n return;\n }\n\n this.handleValidMessage(event);\n };\n\n /**\n * Logs incoming message details for debugging purposes.\n *\n * Provides comprehensive logging of message properties including origin,\n * source validation, and iframe state for troubleshooting communication issues.\n *\n * @param event - The MessageEvent to log\n * @param expectedOrigin - The expected origin for comparison\n */\n private logIncomingMessage(\n event: MessageEvent,\n expectedOrigin: string,\n ): void {\n this.logger.debug(\"Global window received message:\", {\n data: event.data,\n origin: event.origin,\n sourceProvided: !!event.source,\n iframeContentWindow: this.iframeElement?.contentWindow,\n expectedIframeOrigin: expectedOrigin,\n });\n }\n\n /**\n * Validates that a message comes from the expected origin and source.\n *\n * Performs security checks to ensure messages are only processed from\n * the configured OAuth server origin and the designated iframe element.\n *\n * @param event - The MessageEvent to validate\n * @param expectedOrigin - The expected origin URL for the message\n * @returns True if the message source and origin are valid, false otherwise\n */\n private isValidMessageSource(\n event: MessageEvent,\n expectedOrigin: string,\n ): boolean {\n // Check if message is from the iframe source\n const isValidSource = event.source === this.iframeElement?.contentWindow;\n\n // Build list of allowed origins\n const allowedOrigins = [expectedOrigin];\n\n // Add the actual iframe origin (to handle redirects)\n if (this.iframeElement?.src) {\n try {\n const actualIframeOrigin = new URL(this.iframeElement.src).origin;\n allowedOrigins.push(actualIframeOrigin);\n } catch {\n // ignore URL parsing errors\n }\n }\n\n if (this.config.oauthServerBaseUrl) {\n allowedOrigins.push(new URL(this.config.oauthServerBaseUrl).origin);\n }\n\n // Add the client app's own origin (same-origin) for messages sent after token exchange\n // This is needed when the iframe navigates to the client app's callback URL\n const clientOrigin = window.location.origin;\n if (!allowedOrigins.includes(clientOrigin)) {\n allowedOrigins.push(clientOrigin);\n }\n\n // Add common development login app origins for localhost\n const expectedUrl = new URL(expectedOrigin);\n if (expectedUrl.hostname === \"localhost\") {\n // For localhost, also allow common development ports\n allowedOrigins.push(\"http://localhost:3004\"); // default login-app port\n allowedOrigins.push(\"http://localhost:3001\"); // auth server port\n }\n\n const isValidOrigin = allowedOrigins.includes(event.origin);\n\n if (!isValidOrigin) {\n this.logger.warn(\"Ignored message from unexpected origin.\", {\n receivedOrigin: event.origin,\n expectedOrigin,\n allowedOrigins,\n iframeSrc: this.iframeElement?.src,\n });\n }\n\n if (!isValidSource) {\n this.logger.warn(\"Ignored message from unexpected source.\", {\n isSourceProvided: !!event.source,\n isIframeContentWindowAvailable: !!this.iframeElement?.contentWindow,\n iframeSrc: this.iframeElement?.src,\n });\n }\n\n return isValidOrigin && isValidSource;\n }\n\n /**\n * Processes messages that have passed origin and source validation.\n *\n * Routes validated messages to specific handlers based on message type,\n * including civicloginApp messages, iframe resizer messages, and standard auth messages.\n *\n * @param event - The validated MessageEvent to process\n */\n private handleValidMessage(event: MessageEvent): void {\n this.logger.info(\n \"Message from configured iframe source and origin received\",\n {\n data: event.data,\n iframeSrc: this.iframeElement?.src,\n },\n );\n\n const message = event.data as IframeMessage;\n\n this.logger.debug(\"Processing iframe message\", {\n messageType: typeof message,\n hasType: message && typeof message === \"object\" && \"type\" in message,\n hasSource: message && typeof message === \"object\" && \"source\" in message,\n messageKeys:\n message && typeof message === \"object\" ? Object.keys(message) : [],\n rawData: message,\n });\n\n // Handle civicloginApp messages\n if (this.isCivicLoginAppMessage(message)) {\n this.handleCivicLoginAppMessage(message);\n return;\n }\n\n // Handle iframe resizer messages\n if (this.isIframeResizerMessage(message)) {\n this.handleIframeResizerMessage(message);\n return;\n }\n\n // Handle standard auth messages\n this.handleStandardAuthMessage(message);\n }\n\n /**\n * Type guard to identify civicloginApp messages.\n *\n * Checks if a message object has the structure and source property\n * that identifies it as coming from the civicloginApp.\n *\n * @param message - The message object to check\n * @returns True if the message is a LoginAppMessage, false otherwise\n */\n private isCivicLoginAppMessage(message: unknown): message is LoginAppMessage {\n return (\n message !== null &&\n typeof message === \"object\" &&\n \"source\" in message &&\n (message as Record<string, unknown>).source === \"civicloginApp\"\n );\n }\n\n /**\n * Handles messages originating from the civicloginApp.\n *\n * Processes various civicloginApp message types including authentication errors,\n * popup failures, design updates, and other app-specific communications.\n * Validates client ID matches before processing.\n *\n * @param message - The validated civicloginApp message to process\n */\n private handleCivicLoginAppMessage(message: LoginAppMessage): void {\n this.logger.info(\"Received civicloginApp message\", {\n type: message.type,\n clientId: message.clientId,\n data: message.data,\n });\n\n // Validate clientId matches our config\n if (\n message.clientId !== this.config.clientId &&\n this.config.loginUrl === undefined\n ) {\n this.logger.warn(\"civicloginApp message clientId mismatch\", {\n received: message.clientId,\n expected: this.config.clientId,\n });\n return;\n }\n\n switch (message.type) {\n case \"auth_error\":\n case \"auth_error_try_again\":\n this.handleCivicLoginAppError(message);\n break;\n case \"generatePopupFailed\":\n this.handlePopupFailure(message);\n break;\n case \"browserCorsFailsSilently\":\n this.handleBrowserCorsFailsSilently(message);\n break;\n case \"design\":\n this.logger.debug(\"civicloginApp design message\", {\n data: message.data,\n });\n break;\n case \"auth_success_early\":\n this.logger.info(\"civicloginApp auth success early message\", {\n data: message.data,\n });\n this.handleAuthSuccessEarly(message);\n break;\n case \"auth_success\":\n this.logger.info(\"civicloginApp auth success message\", {\n data: message.data,\n });\n\n // Dispatch early auth success event for immediate modal closing\n\n // Still handle auth success normally (for callback processing)\n this.handleAuthSuccess({\n type: \"auth_success\",\n detail: \"Authentication successful\",\n data: message.data,\n });\n break;\n default:\n this.handleUnknownCivicLoginAppMessage(message);\n break;\n }\n }\n\n /**\n * Handles auth success early messages from civicloginApp.\n *\n * Processes auth_success_early messages, emits success events,\n * and triggers the success callback with authentication results.\n *\n * @param message - The civicloginApp auth success early message to process\n */\n\n private handleAuthSuccessEarly(message: LoginAppMessage): void {\n this.logger.info(\"civicloginApp auth success early message\", {\n data: message.data,\n });\n\n const earlySuccessEvent = new CustomEvent(\"civic-auth-success-early\", {\n detail: {\n clientId: message.clientId,\n data: message.data,\n },\n });\n window.dispatchEvent(earlySuccessEvent);\n }\n\n /**\n * Handles authentication error messages from civicloginApp.\n *\n * Processes auth_error and auth_error_try_again messages, creates\n * appropriate error objects, emits error events, and triggers cleanup.\n *\n * @param message - The civicloginApp error message to process\n */\n private handleCivicLoginAppError(message: LoginAppMessage): void {\n this.logger.error(\"civicloginApp authentication error\", {\n type: message.type,\n data: message.data,\n });\n\n const error = new CivicAuthError(\n `Login app error: ${message.type}`,\n CivicAuthErrorCode.INVALID_MESSAGE,\n );\n\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: error.message,\n error: message.data,\n });\n\n this.onAuthError(error);\n this.cleanup();\n }\n\n /**\n * Handle the case where we know in advance that the browser will not prompt the user to open\n * a popup and will fail silently instead. We want to handle this case gracefully by switching to redirect\n * mode if the iframe is in modal display mode. This will be done when the auth flow actually starts\n * @param message\n */\n private handleBrowserCorsFailsSilently(message: LoginAppMessage): void {\n const failedUrl = (message.data as Record<string, unknown> | undefined)\n ?.url as string | undefined;\n this.logger.warn(\"civicloginApp browser CORS fail silently\", {\n failedUrl,\n config: this.config,\n autoRedirect: this.config.autoRedirect,\n });\n if (\n this.config.displayMode === \"iframe\" &&\n this.config.iframeDisplayMode === \"modal\" &&\n this.config.autoRedirect !== false && // Add this check\n failedUrl\n ) {\n IframeManager.handleBrowserCorsFailsSilently(failedUrl);\n this.onBrowserCorsFailsSilently(failedUrl);\n }\n }\n /**\n * Handles popup generation failure messages from civicloginApp.\n *\n * Processes generatePopupFailed messages, extracts the failed URL,\n * emits appropriate events, and triggers the popup failure callback\n * to enable fallback authentication methods.\n *\n * @param message - The civicloginApp popup failure message to process\n */\n private handlePopupFailure(message: LoginAppMessage): void {\n this.logger.warn(\"civicloginApp popup generation failed\", {\n data: message.data,\n });\n\n const failedUrl = (message.data as Record<string, unknown> | undefined)\n ?.url as string | undefined;\n if (failedUrl) {\n this.logger.info(\"Popup failed for URL, considering fallback options\", {\n failedUrl,\n displayMode: this.config.displayMode,\n });\n\n this.config.events?.emit(AuthEvent.URL_CHANGE, {\n detail: \"Popup blocked by browser - switching to redirect mode\",\n url: failedUrl,\n source: \"login_app\",\n failedUrl,\n error: {\n type: \"popup_blocked\",\n failedUrl,\n suggestion:\n \"The browser blocked a popup window. Redirecting to complete authentication in a new page.\",\n },\n });\n }\n\n this.onPopupFailure(failedUrl);\n }\n\n /**\n * Handles unknown or unrecognized civicloginApp message types.\n *\n * Provides fallback handling for unexpected message types, with special\n * logic to detect potential success messages that don't match standard types.\n *\n * @param message - The unrecognized civicloginApp message to process\n */\n private handleUnknownCivicLoginAppMessage(message: LoginAppMessage): void {\n this.logger.debug(\"Unhandled civicloginApp message type\", {\n type: message.type,\n data: message.data,\n });\n\n // Check if this might be a success message with a different type\n if (message.type && message.type.toLowerCase().includes(\"success\")) {\n this.logger.info(\"Potential success message from civicloginApp\", {\n type: message.type,\n data: message.data,\n });\n\n this.handleAuthSuccess({\n type: \"auth_success\",\n detail: `civicloginApp success: ${message.type}`,\n data: message.data,\n });\n }\n }\n\n /**\n * Type guard to identify iframe resizer messages.\n *\n * Checks if a message is related to iframe resizing functionality,\n * including both civic-specific resize messages and iFrameResizerChild messages.\n *\n * @param message - The message object to check\n * @returns True if the message is an iframe resizer message, false otherwise\n */\n private isIframeResizerMessage(message: unknown): boolean {\n return (\n (message !== null &&\n typeof message === \"object\" &&\n \"type\" in message &&\n ((message as Record<string, unknown>).type === \"civic-iframe-resize\" ||\n (message as Record<string, unknown>).type ===\n \"civic-iframe-ready\")) ||\n (typeof message === \"string\" && message.includes(\"iFrameResizerChild\"))\n );\n }\n\n /**\n * Handles iframe resizer messages for dynamic iframe sizing.\n *\n * Processes messages related to iframe resizing, including height adjustments\n * and ready state notifications from the iframe resizer library.\n *\n * @param message - The iframe resizer message to process\n */\n private handleIframeResizerMessage(message: unknown): void {\n if (typeof message === \"string\") {\n this.logger.debug(\"Received iframe resizer child message\", { message });\n } else if (message && typeof message === \"object\" && message !== null) {\n const messageObj = message as Record<string, unknown>;\n this.logger.debug(\"Received iframe resizer message\", {\n type: messageObj.type,\n height: messageObj.height,\n });\n }\n }\n\n /**\n * Handles standard authentication messages.\n *\n * Processes auth_success and auth_error messages that follow the standard\n * authentication message format, routing them to appropriate success or error handlers.\n *\n * @param message - The standard auth message to process\n */\n private handleStandardAuthMessage(message: unknown): void {\n const messageObj =\n message && typeof message === \"object\" && message !== null\n ? (message as Record<string, unknown>)\n : null;\n const messageType = messageObj?.type;\n\n switch (messageType) {\n case \"auth_success\":\n this.handleAuthSuccess(message as AuthMessage);\n break;\n case \"auth_error\":\n this.handleAuthError(message as AuthMessage);\n break;\n default:\n // Check if this is a calculateSubFramePositioning message (expected and harmless)\n if (messageObj?.command === \"calculateSubFramePositioning\") {\n this.logger.debug(\"Received iframe positioning message (expected)\", {\n command: messageObj.command,\n hasSubFrameData: !!messageObj.subFrameData,\n });\n } else {\n this.logger.debug(\n \"Message from iframe did not match expected types (auth_success, auth_error, civicloginApp, iframe-resizer)\",\n {\n data: message,\n messageType: typeof message,\n hasType: messageObj?.type ?? \"none\",\n messageKeys: messageObj ? Object.keys(messageObj) : [],\n },\n );\n }\n }\n }\n\n /**\n * Handles successful authentication completion.\n *\n * Processes authentication success messages, emits success events,\n * triggers the success callback with authentication results, and performs cleanup.\n *\n * @param data - The authentication success message containing result data\n */\n private handleAuthSuccess(data: AuthMessage): void {\n this.config.events?.emit(AuthEvent.SIGN_IN_COMPLETE, {\n detail: \"Success signal received via postMessage\",\n data,\n });\n this.onAuthSuccess((data?.data as AuthResult) || {});\n this.cleanup();\n }\n\n /**\n * Handles authentication errors.\n *\n * Processes authentication error messages, creates appropriate error objects,\n * emits error events, triggers the error callback, and performs cleanup.\n *\n * @param data - The authentication error message containing error details\n */\n private handleAuthError(data: AuthMessage): void {\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Error signal received via postMessage\",\n error: data,\n });\n\n const error = new CivicAuthError(\n data?.detail || \"Error signal received via postMessage\",\n CivicAuthErrorCode.INVALID_MESSAGE,\n );\n\n this.onAuthError(error);\n this.cleanup();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"MessageHandler.js","sourceRoot":"","sources":["../../../../src/vanillajs/auth/handlers/MessageHandler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,sBAAsB,CAAC;AAUjD,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3E,OAAO,EAAE,YAAY,IAAI,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,EAAE,aAAa,EAAE,MAAM,qCAAqC,CAAC;AAapE;;;GAGG;AACH,MAAM,OAAO,cAAc;IACjB,MAAM,CAA2B;IACjC,MAAM,GAAG,cAAc,CAAC,iBAAiB,CAAC,CAAC;IAC3C,aAAa,CAAqB;IAClC,aAAa,CAA+B;IAC5C,WAAW,CAAyB;IACpC,cAAc,CAA+B;IAC7C,0BAA0B,GAChC,GAAG,EAAE;QACH,OAAO,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,sCAAsC;IAClE,CAAC,CAAC;IACI,OAAO,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Aa,CAAE,IAAI,EAAE,IAAmB,IAAI,EAAE,CAAC,CAAC;QACrD,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;IAED;;;;;;;OAOG;IACK,eAAe,CAAC,IAAiB;QACvC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC,aAAa,EAAE;YAChD,MAAM,EAAE,uCAAuC;YAC/C,KAAK,EAAE,IAAI;SACZ,CAAC,CAAC;QAEH,MAAM,KAAK,GAAG,IAAI,cAAc,CAC9B,IAAI,EAAE,MAAM,IAAI,uCAAuC,EACvD,kBAAkB,CAAC,eAAe,CACnC,CAAC;QAEF,IAAI,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC;QACxB,IAAI,CAAC,OAAO,EAAE,CAAC;IACjB,CAAC;CACF","sourcesContent":["import { AuthEvent } from \"../../types/index.js\";\nimport type { AuthResult } from \"../../types/index.js\";\nimport type {\n IframeMessage,\n AuthMessage,\n LoginAppMessage,\n ProcessedCivicAuthConfig,\n ColorMode,\n DesignMessageData,\n} from \"../types/AuthTypes.js\";\nimport { CivicAuthError, CivicAuthErrorCode } from \"../types/AuthTypes.js\";\nimport type { createLogger } from \"../../utils/logger.js\";\nimport { createLogger as createLoggerFn } from \"../../utils/logger.js\";\nimport { IframeManager } from \"@/vanillajs/iframe/IframeManager.js\";\n\nexport interface MessageHandlerConfig {\n config: ProcessedCivicAuthConfig;\n logger: ReturnType<typeof createLogger>;\n iframeElement?: HTMLIFrameElement;\n onAuthSuccess: (result: AuthResult) => void;\n onAuthError: (error: Error) => void;\n onPopupFailure: (failedUrl?: string) => void;\n onBrowserCorsFailsSilently: (failedUrl?: string) => Promise<void>;\n cleanup: () => void;\n}\n\n/**\n * MessageHandler - Handles postMessage communication and authentication flow logic\n * Processes messages from iframe, validates origins, and manages auth state transitions\n */\nexport class MessageHandler {\n private config: ProcessedCivicAuthConfig;\n private logger = createLoggerFn(\"message-handler\");\n private iframeElement?: HTMLIFrameElement;\n private onAuthSuccess: (result: AuthResult) => void;\n private onAuthError: (error: Error) => void;\n private onPopupFailure: (failedUrl?: string) => void;\n private onBrowserCorsFailsSilently: (failedUrl?: string) => Promise<void> =\n () => {\n return Promise.resolve(); // No-op by default, can be overridden\n };\n private cleanup: () => void;\n\n // Backend integration - custom expected origin\n private customExpectedOrigin?: string;\n\n constructor(handlerConfig: MessageHandlerConfig) {\n this.config = handlerConfig.config;\n this.iframeElement = handlerConfig.iframeElement;\n this.onAuthSuccess = handlerConfig.onAuthSuccess;\n this.onAuthError = handlerConfig.onAuthError;\n this.onPopupFailure = handlerConfig.onPopupFailure;\n this.onBrowserCorsFailsSilently = handlerConfig.onBrowserCorsFailsSilently;\n this.cleanup = handlerConfig.cleanup;\n }\n\n /**\n * Updates the iframe element reference used for message validation.\n *\n * This method allows updating the iframe element after the MessageHandler\n * has been instantiated, which is useful when the iframe is created\n * dynamically after the handler setup.\n *\n * @param iframeElement - The new iframe element to associate with this handler\n */\n public updateIframeElement(iframeElement: HTMLIFrameElement): void {\n this.iframeElement = iframeElement;\n }\n\n /**\n * Sets a custom expected origin for backend integration.\n *\n * This allows the MessageHandler to accept messages from a custom backend\n * origin instead of the default OAuth server origin.\n *\n * @param customLoginUrl - The custom login URL to derive the origin from\n */\n public setCustomExpectedOrigin(customLoginUrl: string): void {\n this.customExpectedOrigin = new URL(customLoginUrl).origin;\n this.logger.info(\"🔗 Custom expected origin set for backend integration\", {\n customExpectedOrigin: this.customExpectedOrigin,\n customLoginUrl,\n });\n }\n\n /**\n * Clears the custom expected origin and returns to OAuth server origin.\n */\n public clearCustomExpectedOrigin(): void {\n this.customExpectedOrigin = undefined;\n this.logger.info(\n \"🔗 Custom expected origin cleared, returning to OAuth server origin\",\n );\n }\n\n /**\n * Main message handler for processing postMessage events.\n *\n * Validates message origin and source, then routes valid messages to\n * appropriate handlers. This is the entry point for all iframe communication.\n *\n * @param event - The MessageEvent received from the iframe or other sources\n */\n public handleMessage = (event: MessageEvent): void => {\n // Use custom origin if set (for backend integration), otherwise use OAuth server origin\n const expectedOrigin =\n this.customExpectedOrigin ||\n new URL(this.config.oauthServerBaseUrl).origin;\n this.logIncomingMessage(event, expectedOrigin);\n\n if (!this.isValidMessageSource(event, expectedOrigin)) {\n return;\n }\n\n this.handleValidMessage(event);\n };\n\n /**\n * Logs incoming message details for debugging purposes.\n *\n * Provides comprehensive logging of message properties including origin,\n * source validation, and iframe state for troubleshooting communication issues.\n *\n * @param event - The MessageEvent to log\n * @param expectedOrigin - The expected origin for comparison\n */\n private logIncomingMessage(\n event: MessageEvent,\n expectedOrigin: string,\n ): void {\n this.logger.debug(\"Global window received message:\", {\n data: event.data,\n origin: event.origin,\n sourceProvided: !!event.source,\n iframeContentWindow: this.iframeElement?.contentWindow,\n expectedIframeOrigin: expectedOrigin,\n });\n }\n\n /**\n * Validates that a message comes from the expected origin and source.\n *\n * Performs security checks to ensure messages are only processed from\n * the configured OAuth server origin and the designated iframe element.\n *\n * @param event - The MessageEvent to validate\n * @param expectedOrigin - The expected origin URL for the message\n * @returns True if the message source and origin are valid, false otherwise\n */\n private isValidMessageSource(\n event: MessageEvent,\n expectedOrigin: string,\n ): boolean {\n // Check if message is from the iframe source\n const isValidSource = event.source === this.iframeElement?.contentWindow;\n\n // Build list of allowed origins\n const allowedOrigins = [expectedOrigin];\n\n // Add the actual iframe origin (to handle redirects)\n if (this.iframeElement?.src) {\n try {\n const actualIframeOrigin = new URL(this.iframeElement.src).origin;\n allowedOrigins.push(actualIframeOrigin);\n } catch {\n // ignore URL parsing errors\n }\n }\n\n if (this.config.oauthServerBaseUrl) {\n allowedOrigins.push(new URL(this.config.oauthServerBaseUrl).origin);\n }\n\n // Add the client app's own origin (same-origin) for messages sent after token exchange\n // This is needed when the iframe navigates to the client app's callback URL\n const clientOrigin = window.location.origin;\n if (!allowedOrigins.includes(clientOrigin)) {\n allowedOrigins.push(clientOrigin);\n }\n\n // Add common development login app origins for localhost\n const expectedUrl = new URL(expectedOrigin);\n if (expectedUrl.hostname === \"localhost\") {\n // For localhost, also allow common development ports\n allowedOrigins.push(\"http://localhost:3004\"); // default login-app port\n allowedOrigins.push(\"http://localhost:3001\"); // auth server port\n }\n\n const isValidOrigin = allowedOrigins.includes(event.origin);\n\n if (!isValidOrigin) {\n this.logger.warn(\"Ignored message from unexpected origin.\", {\n receivedOrigin: event.origin,\n expectedOrigin,\n allowedOrigins,\n iframeSrc: this.iframeElement?.src,\n });\n }\n\n if (!isValidSource) {\n this.logger.warn(\"Ignored message from unexpected source.\", {\n isSourceProvided: !!event.source,\n isIframeContentWindowAvailable: !!this.iframeElement?.contentWindow,\n iframeSrc: this.iframeElement?.src,\n });\n }\n\n return isValidOrigin && isValidSource;\n }\n\n /**\n * Processes messages that have passed origin and source validation.\n *\n * Routes validated messages to specific handlers based on message type,\n * including civicloginApp messages, iframe resizer messages, and standard auth messages.\n *\n * @param event - The validated MessageEvent to process\n */\n private handleValidMessage(event: MessageEvent): void {\n this.logger.info(\n \"Message from configured iframe source and origin received\",\n {\n data: event.data,\n iframeSrc: this.iframeElement?.src,\n },\n );\n\n const message = event.data as IframeMessage;\n\n this.logger.debug(\"Processing iframe message\", {\n messageType: typeof message,\n hasType: message && typeof message === \"object\" && \"type\" in message,\n hasSource: message && typeof message === \"object\" && \"source\" in message,\n messageKeys:\n message && typeof message === \"object\" ? Object.keys(message) : [],\n rawData: message,\n });\n\n // Handle civicloginApp messages\n if (this.isCivicLoginAppMessage(message)) {\n this.handleCivicLoginAppMessage(message);\n return;\n }\n\n // Handle iframe resizer messages\n if (this.isIframeResizerMessage(message)) {\n this.handleIframeResizerMessage(message);\n return;\n }\n\n // Handle standard auth messages\n this.handleStandardAuthMessage(message);\n }\n\n /**\n * Type guard to identify civicloginApp messages.\n *\n * Checks if a message object has the structure and source property\n * that identifies it as coming from the civicloginApp.\n *\n * @param message - The message object to check\n * @returns True if the message is a LoginAppMessage, false otherwise\n */\n private isCivicLoginAppMessage(message: unknown): message is LoginAppMessage {\n return (\n message !== null &&\n typeof message === \"object\" &&\n \"source\" in message &&\n (message as Record<string, unknown>).source === \"civicloginApp\"\n );\n }\n\n /**\n * Handles messages originating from the civicloginApp.\n *\n * Processes various civicloginApp message types including authentication errors,\n * popup failures, design updates, and other app-specific communications.\n * Validates client ID matches before processing.\n *\n * @param message - The validated civicloginApp message to process\n */\n private handleCivicLoginAppMessage(message: LoginAppMessage): void {\n this.logger.info(\"Received civicloginApp message\", {\n type: message.type,\n clientId: message.clientId,\n data: message.data,\n });\n\n // Validate clientId matches our config\n if (\n message.clientId !== this.config.clientId &&\n this.config.loginUrl === undefined\n ) {\n this.logger.warn(\"civicloginApp message clientId mismatch\", {\n received: message.clientId,\n expected: this.config.clientId,\n });\n return;\n }\n\n switch (message.type) {\n case \"auth_error\":\n case \"auth_error_try_again\":\n this.handleCivicLoginAppError(message);\n break;\n case \"generatePopupFailed\":\n this.handlePopupFailure(message);\n break;\n case \"browserCorsFailsSilently\":\n this.handleBrowserCorsFailsSilently(message);\n break;\n case \"design\":\n this.logger.debug(\"civicloginApp design message\", {\n data: message.data,\n });\n this.handleDesignMessage(message.data as DesignMessageData | undefined);\n break;\n case \"auth_success_early\":\n this.logger.info(\"civicloginApp auth success early message\", {\n data: message.data,\n });\n this.handleAuthSuccessEarly(message);\n break;\n case \"auth_success\":\n this.logger.info(\"civicloginApp auth success message\", {\n data: message.data,\n });\n\n // Dispatch early auth success event for immediate modal closing\n\n // Still handle auth success normally (for callback processing)\n this.handleAuthSuccess({\n type: \"auth_success\",\n detail: \"Authentication successful\",\n data: message.data,\n });\n break;\n default:\n this.handleUnknownCivicLoginAppMessage(message);\n break;\n }\n }\n\n /**\n * Handles auth success early messages from civicloginApp.\n *\n * Processes auth_success_early messages, emits success events,\n * and triggers the success callback with authentication results.\n *\n * @param message - The civicloginApp auth success early message to process\n */\n\n private handleAuthSuccessEarly(message: LoginAppMessage): void {\n this.logger.info(\"civicloginApp auth success early message\", {\n data: message.data,\n });\n\n const earlySuccessEvent = new CustomEvent(\"civic-auth-success-early\", {\n detail: {\n clientId: message.clientId,\n data: message.data,\n },\n });\n window.dispatchEvent(earlySuccessEvent);\n }\n\n /**\n * Handles authentication error messages from civicloginApp.\n *\n * Processes auth_error and auth_error_try_again messages, creates\n * appropriate error objects, emits error events, and triggers cleanup.\n *\n * @param message - The civicloginApp error message to process\n */\n private handleCivicLoginAppError(message: LoginAppMessage): void {\n this.logger.error(\"civicloginApp authentication error\", {\n type: message.type,\n data: message.data,\n });\n\n const error = new CivicAuthError(\n `Login app error: ${message.type}`,\n CivicAuthErrorCode.INVALID_MESSAGE,\n );\n\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: error.message,\n error: message.data,\n });\n\n this.onAuthError(error);\n this.cleanup();\n }\n\n /**\n * Handle the case where we know in advance that the browser will not prompt the user to open\n * a popup and will fail silently instead. We want to handle this case gracefully by switching to redirect\n * mode if the iframe is in modal display mode. This will be done when the auth flow actually starts\n * @param message\n */\n private handleBrowserCorsFailsSilently(message: LoginAppMessage): void {\n const failedUrl = (message.data as Record<string, unknown> | undefined)\n ?.url as string | undefined;\n this.logger.warn(\"civicloginApp browser CORS fail silently\", {\n failedUrl,\n config: this.config,\n autoRedirect: this.config.autoRedirect,\n });\n if (\n this.config.displayMode === \"iframe\" &&\n this.config.iframeDisplayMode === \"modal\" &&\n this.config.autoRedirect !== false && // Add this check\n failedUrl\n ) {\n IframeManager.handleBrowserCorsFailsSilently(failedUrl);\n this.onBrowserCorsFailsSilently(failedUrl);\n }\n }\n /**\n * Handles popup generation failure messages from civicloginApp.\n *\n * Processes generatePopupFailed messages, extracts the failed URL,\n * emits appropriate events, and triggers the popup failure callback\n * to enable fallback authentication methods.\n *\n * @param message - The civicloginApp popup failure message to process\n */\n private handlePopupFailure(message: LoginAppMessage): void {\n this.logger.warn(\"civicloginApp popup generation failed\", {\n data: message.data,\n });\n\n const failedUrl = (message.data as Record<string, unknown> | undefined)\n ?.url as string | undefined;\n if (failedUrl) {\n this.logger.info(\"Popup failed for URL, considering fallback options\", {\n failedUrl,\n displayMode: this.config.displayMode,\n });\n\n this.config.events?.emit(AuthEvent.URL_CHANGE, {\n detail: \"Popup blocked by browser - switching to redirect mode\",\n url: failedUrl,\n source: \"login_app\",\n failedUrl,\n error: {\n type: \"popup_blocked\",\n failedUrl,\n suggestion:\n \"The browser blocked a popup window. Redirecting to complete authentication in a new page.\",\n },\n });\n }\n\n this.onPopupFailure(failedUrl);\n }\n\n /**\n * Handles design messages from civicloginApp.\n *\n * Processes design messages containing customer preferences like colorMode\n * and forwards them to the appropriate handlers.\n *\n * @param data - The design message data payload\n */\n private handleDesignMessage(data: DesignMessageData | undefined): void {\n if (!data) {\n this.logger.debug(\"Design message received with no data\");\n return;\n }\n\n // Handle colorMode preference\n if (data.colorMode) {\n const validColorModes: ColorMode[] = [\"light\", \"dark\", \"auto\"];\n if (validColorModes.includes(data.colorMode)) {\n this.logger.debug(\"Setting customer color mode\", {\n colorMode: data.colorMode,\n });\n IframeManager.handleLoginAppColorMode(data.colorMode);\n } else {\n this.logger.debug(\"Invalid colorMode value received\", {\n colorMode: data.colorMode,\n });\n }\n }\n }\n\n /**\n * Handles unknown or unrecognized civicloginApp message types.\n *\n * Provides fallback handling for unexpected message types, with special\n * logic to detect potential success messages that don't match standard types.\n *\n * @param message - The unrecognized civicloginApp message to process\n */\n private handleUnknownCivicLoginAppMessage(message: LoginAppMessage): void {\n this.logger.debug(\"Unhandled civicloginApp message type\", {\n type: message.type,\n data: message.data,\n });\n\n // Check if this might be a success message with a different type\n if (message.type && message.type.toLowerCase().includes(\"success\")) {\n this.logger.info(\"Potential success message from civicloginApp\", {\n type: message.type,\n data: message.data,\n });\n\n this.handleAuthSuccess({\n type: \"auth_success\",\n detail: `civicloginApp success: ${message.type}`,\n data: message.data,\n });\n }\n }\n\n /**\n * Type guard to identify iframe resizer messages.\n *\n * Checks if a message is related to iframe resizing functionality,\n * including both civic-specific resize messages and iFrameResizerChild messages.\n *\n * @param message - The message object to check\n * @returns True if the message is an iframe resizer message, false otherwise\n */\n private isIframeResizerMessage(message: unknown): boolean {\n return (\n (message !== null &&\n typeof message === \"object\" &&\n \"type\" in message &&\n ((message as Record<string, unknown>).type === \"civic-iframe-resize\" ||\n (message as Record<string, unknown>).type ===\n \"civic-iframe-ready\")) ||\n (typeof message === \"string\" && message.includes(\"iFrameResizerChild\"))\n );\n }\n\n /**\n * Handles iframe resizer messages for dynamic iframe sizing.\n *\n * Processes messages related to iframe resizing, including height adjustments\n * and ready state notifications from the iframe resizer library.\n *\n * @param message - The iframe resizer message to process\n */\n private handleIframeResizerMessage(message: unknown): void {\n if (typeof message === \"string\") {\n this.logger.debug(\"Received iframe resizer child message\", { message });\n } else if (message && typeof message === \"object\" && message !== null) {\n const messageObj = message as Record<string, unknown>;\n this.logger.debug(\"Received iframe resizer message\", {\n type: messageObj.type,\n height: messageObj.height,\n });\n }\n }\n\n /**\n * Handles standard authentication messages.\n *\n * Processes auth_success and auth_error messages that follow the standard\n * authentication message format, routing them to appropriate success or error handlers.\n *\n * @param message - The standard auth message to process\n */\n private handleStandardAuthMessage(message: unknown): void {\n const messageObj =\n message && typeof message === \"object\" && message !== null\n ? (message as Record<string, unknown>)\n : null;\n const messageType = messageObj?.type;\n\n switch (messageType) {\n case \"auth_success\":\n this.handleAuthSuccess(message as AuthMessage);\n break;\n case \"auth_error\":\n this.handleAuthError(message as AuthMessage);\n break;\n default:\n // Check if this is a calculateSubFramePositioning message (expected and harmless)\n if (messageObj?.command === \"calculateSubFramePositioning\") {\n this.logger.debug(\"Received iframe positioning message (expected)\", {\n command: messageObj.command,\n hasSubFrameData: !!messageObj.subFrameData,\n });\n } else {\n this.logger.debug(\n \"Message from iframe did not match expected types (auth_success, auth_error, civicloginApp, iframe-resizer)\",\n {\n data: message,\n messageType: typeof message,\n hasType: messageObj?.type ?? \"none\",\n messageKeys: messageObj ? Object.keys(messageObj) : [],\n },\n );\n }\n }\n }\n\n /**\n * Handles successful authentication completion.\n *\n * Processes authentication success messages, emits success events,\n * triggers the success callback with authentication results, and performs cleanup.\n *\n * @param data - The authentication success message containing result data\n */\n private handleAuthSuccess(data: AuthMessage): void {\n this.config.events?.emit(AuthEvent.SIGN_IN_COMPLETE, {\n detail: \"Success signal received via postMessage\",\n data,\n });\n this.onAuthSuccess((data?.data as AuthResult) || {});\n this.cleanup();\n }\n\n /**\n * Handles authentication errors.\n *\n * Processes authentication error messages, creates appropriate error objects,\n * emits error events, triggers the error callback, and performs cleanup.\n *\n * @param data - The authentication error message containing error details\n */\n private handleAuthError(data: AuthMessage): void {\n this.config.events?.emit(AuthEvent.SIGN_IN_ERROR, {\n detail: \"Error signal received via postMessage\",\n error: data,\n });\n\n const error = new CivicAuthError(\n data?.detail || \"Error signal received via postMessage\",\n CivicAuthErrorCode.INVALID_MESSAGE,\n );\n\n this.onAuthError(error);\n this.cleanup();\n }\n}\n"]}
|
|
@@ -39,6 +39,16 @@ export declare const CIVIC_AUTH_CONSTANTS: {
|
|
|
39
39
|
readonly SUCCESS_SIGNAL_ID: "civic-auth-success-signal";
|
|
40
40
|
readonly ERROR_SIGNAL_ID: "civic-auth-error-signal";
|
|
41
41
|
};
|
|
42
|
+
/**
|
|
43
|
+
* Color mode preference for iframe background
|
|
44
|
+
*/
|
|
45
|
+
export type ColorMode = "light" | "dark" | "auto";
|
|
46
|
+
/**
|
|
47
|
+
* Data payload for design messages from login-app
|
|
48
|
+
*/
|
|
49
|
+
export interface DesignMessageData {
|
|
50
|
+
colorMode?: ColorMode;
|
|
51
|
+
}
|
|
42
52
|
/**
|
|
43
53
|
* Message types for postMessage communication
|
|
44
54
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthTypes.d.ts","sourceRoot":"","sources":["../../../../src/vanillajs/auth/types/AuthTypes.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,4BAA4B,CAAC;AACvE,OAAO,KAAK,EACV,WAAW,IAAI,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AAC;IACzB,WAAW,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,GAAG,CACA;IACE,yDAAyD;IACzD,QAAQ,EAAE,MAAM,CAAC;IACjB,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,GACD;IACE,gEAAgE;IAChE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,wFAAwF;IACxF,QAAQ,EAAE,MAAM,CAAC;CAClB,CACJ,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AuthTypes.js","sourceRoot":"","sources":["../../../../src/vanillajs/auth/types/AuthTypes.ts"],"names":[],"mappings":"AAgBA;;GAEG;AACH,MAAM,CAAN,IAAY,kBAkBX;AAlBD,WAAY,kBAAkB;IAC5B,yDAAmC,CAAA;IACnC,iDAA2B,CAAA;IAC3B,6EAAuD,CAAA;IACvD,iEAA2C,CAAA;IAC3C,mEAA6C,CAAA;IAC7C,6DAAuC,CAAA;IACvC,qEAA+C,CAAA;IAC/C,yDAAmC,CAAA;IACnC,qDAA+B,CAAA;IAC/B,qDAA+B,CAAA;IAC/B,uDAAiC,CAAA;IACjC,iEAA2C,CAAA;IAC3C,mEAA6C,CAAA;IAC7C,6DAAuC,CAAA;IACvC,qDAA+B,CAAA;IAC/B,2DAAqC,CAAA;IACrC,uDAAiC,CAAA;AACnC,CAAC,EAlBW,kBAAkB,KAAlB,kBAAkB,QAkB7B;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,MAAM,CAAC,CAAC,aAAa;AAEjE,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,iBAAiB,EAAE,mBAAmB;IACtC,4BAA4B;IAC5B,iBAAiB,EAAE,2BAA2B;IAC9C,eAAe,EAAE,yBAAyB;CAClC,CAAC;
|
|
1
|
+
{"version":3,"file":"AuthTypes.js","sourceRoot":"","sources":["../../../../src/vanillajs/auth/types/AuthTypes.ts"],"names":[],"mappings":"AAgBA;;GAEG;AACH,MAAM,CAAN,IAAY,kBAkBX;AAlBD,WAAY,kBAAkB;IAC5B,yDAAmC,CAAA;IACnC,iDAA2B,CAAA;IAC3B,6EAAuD,CAAA;IACvD,iEAA2C,CAAA;IAC3C,mEAA6C,CAAA;IAC7C,6DAAuC,CAAA;IACvC,qEAA+C,CAAA;IAC/C,yDAAmC,CAAA;IACnC,qDAA+B,CAAA;IAC/B,qDAA+B,CAAA;IAC/B,uDAAiC,CAAA;IACjC,iEAA2C,CAAA;IAC3C,mEAA6C,CAAA;IAC7C,6DAAuC,CAAA;IACvC,qDAA+B,CAAA;IAC/B,2DAAqC,CAAA;IACrC,uDAAiC,CAAA;AACnC,CAAC,EAlBW,kBAAkB,KAAlB,kBAAkB,QAkB7B;AAED;;GAEG;AACH,MAAM,CAAC,MAAM,4BAA4B,GAAG,MAAM,CAAC,CAAC,aAAa;AAEjE,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,iBAAiB,EAAE,mBAAmB;IACtC,4BAA4B;IAC5B,iBAAiB,EAAE,2BAA2B;IAC9C,eAAe,EAAE,yBAAyB;CAClC,CAAC;AA4CX,MAAM,OAAO,cAAe,SAAQ,KAAK;IAGrB;IAFlB,YACE,OAAe,EACC,IAAwB;QAExC,KAAK,CAAC,OAAO,CAAC,CAAC;QAFC,SAAI,GAAJ,IAAI,CAAoB;QAGxC,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF","sourcesContent":["import type { AuthenticationEvents } from \"../AuthenticationEvents.js\";\nimport type {\n DisplayMode as BaseDisplayMode,\n AuthStorage,\n FrameworkType,\n User,\n} from \"../../../types.js\";\nimport type { BackendEndpoints } from \"../../../server/config.js\";\n\n/**\n * Extended DisplayMode for VanillaJS that includes \"embedded\" option\n * This provides a cleaner API where users can simply use displayMode: \"embedded\"\n * instead of displayMode: \"iframe\" + iframeDisplayMode: \"embedded\"\n */\nexport type VanillaJSDisplayMode = BaseDisplayMode | \"embedded\";\n\n/**\n * Error codes for CivicAuth errors\n */\nexport enum CivicAuthErrorCode {\n CONFIG_REQUIRED = \"CONFIG_REQUIRED\",\n INIT_FAILED = \"INIT_FAILED\",\n ENDPOINTS_NOT_INITIALIZED = \"ENDPOINTS_NOT_INITIALIZED\",\n CONTAINER_NOT_FOUND = \"CONTAINER_NOT_FOUND\",\n AUTH_PROCESS_TIMEOUT = \"AUTH_PROCESS_TIMEOUT\",\n IFRAME_LOAD_ERROR = \"IFRAME_LOAD_ERROR\",\n IFRAME_PRELOAD_FAILED = \"IFRAME_PRELOAD_FAILED\",\n INVALID_MESSAGE = \"INVALID_MESSAGE\",\n LOGOUT_FAILED = \"LOGOUT_FAILED\",\n POPUP_BLOCKED = \"popup_blocked\",\n USER_CANCELLED = \"user_cancelled\",\n CONFIGURATION_ERROR = \"configuration_error\",\n TOKEN_REFRESH_FAILED = \"token_refresh_failed\",\n SESSION_NOT_FOUND = \"session_not_found\",\n STORAGE_ERROR = \"storage_error\",\n IFRAME_NOT_FOUND = \"iframe_not_found\",\n INTERNAL_ERROR = \"internal_error\",\n}\n\n/**\n * Constants for the auth client\n */\nexport const DEFAULT_AUTH_PROCESS_TIMEOUT = 600000; // 10 minutes\n\nexport const CIVIC_AUTH_CONSTANTS = {\n DEFAULT_IFRAME_ID: \"civic-auth-iframe\",\n DEFAULT_AUTH_PROCESS_TIMEOUT,\n SUCCESS_SIGNAL_ID: \"civic-auth-success-signal\",\n ERROR_SIGNAL_ID: \"civic-auth-error-signal\",\n} as const;\n\n/**\n * Color mode preference for iframe background\n */\nexport type ColorMode = \"light\" | \"dark\" | \"auto\";\n\n/**\n * Data payload for design messages from login-app\n */\nexport interface DesignMessageData {\n colorMode?: ColorMode;\n}\n\n/**\n * Message types for postMessage communication\n */\nexport type AuthMessageType = \"auth_success\" | \"auth_error\";\n\nexport interface AuthMessage {\n type: AuthMessageType;\n detail?: string;\n data?: unknown;\n error?: unknown;\n}\n\n/**\n * Login app message types for postMessage communication\n */\nexport interface LoginAppMessage {\n source: \"civicloginApp\";\n type: \"design\" | \"generatePopupFailed\" | \"auth_success\" | string;\n clientId: string;\n data?: unknown;\n}\n\n/**\n * Combined message type for all iframe communications\n */\nexport type IframeMessage =\n | AuthMessage\n | LoginAppMessage\n | Record<string, unknown>;\n\nexport class CivicAuthError extends Error {\n constructor(\n message: string,\n public readonly code: CivicAuthErrorCode,\n ) {\n super(message);\n this.name = \"CivicAuthError\";\n }\n}\n\n/**\n * Configuration options for the CivicAuth client\n * Uses discriminated union to make clientId optional when loginUrl is provided\n */\nexport type CivicAuthClientConfig = {\n /** URL to redirect to after authentication */\n redirectUrl?: string;\n /** URL to redirect to after logout - if not provided, will use redirectUrl */\n logoutRedirectUrl?: string;\n /** Base URL of the OAuth server */\n oauthServerBaseUrl?: string;\n /** Array of OAuth scopes to request */\n scopes?: string[];\n /** HTML element or element ID where the auth iframe will be mounted (required for embedded iframe mode) */\n targetContainerElement?: HTMLElement | string;\n /** Text signals for success and error states */\n textSignals?: {\n /** Text to display on successful authentication */\n success: string;\n /** Optional text to display on authentication error */\n error?: string;\n };\n /** Display mode for the authentication UI - VanillaJS supports \"embedded\" for simplified API */\n displayMode?: VanillaJSDisplayMode;\n /** Display mode for iframe rendering - modal (full-screen overlay) or embedded (within container) */\n iframeDisplayMode?: \"modal\" | \"embedded\";\n /**\n * Timeout duration in milliseconds for the entire authentication process.\n * If the authentication process takes longer than this duration, it will be cancelled\n * and an error will be thrown.\n * Note: This timeout is not applied to embedded iframe mode, where the iframe remains persistent.\n */\n authProcessTimeout?: number;\n /** Event handlers for authentication events */\n events?: AuthenticationEvents;\n /** Custom ID for the auth iframe */\n iframeId?: string;\n /** Custom storage adapter for auth state - uses shared AuthStorage interface */\n storageAdapter?: AuthStorage;\n /** OAuth nonce parameter for security */\n nonce?: string;\n /** Initial state for OAuth flow */\n initialState?: string;\n /** Logging configuration */\n logging?: LoggingConfig;\n /**\n * Custom backend endpoints configuration for backend integration\n * Only used when loginUrl is provided. Allows overriding default endpoints.\n */\n backendEndpoints?: BackendEndpoints;\n /** Framework being used (for analytics) - internal use only */\n framework?: FrameworkType;\n /** Whether to automatically preload the iframe for instant sign-in (defaults to true) */\n preloadIframe?: boolean;\n /** Whether to automatically switch to redirect mode when browser doesn't support iframe-based auth (defaults to true) */\n autoRedirect?: boolean;\n /** URL to redirect to after successful login - defaults to the page that initiated login */\n loginSuccessUrl?: string;\n /** Initial user data to avoid backend calls during authentication state checks.\n * - User object: user is authenticated\n * - null: explicitly no user (skip backend checks)\n * - undefined: unknown state (check backend)\n */\n initialUser?: User | null;\n /** Base path for application deployment - affects all URLs, redirects, and cookie paths when app is served from a subdirectory */\n basePath?: string;\n} & (\n | {\n /** OAuth client ID - required for standard OAuth flow */\n clientId: string;\n /** Custom login URL for backend integration - optional */\n loginUrl?: string;\n }\n | {\n /** OAuth client ID - optional when using backend integration */\n clientId?: string;\n /** Custom login URL for backend integration - required when clientId is not provided */\n loginUrl: string;\n }\n);\n\nexport interface LoggingConfig {\n enabled: boolean;\n namespace?: string;\n level?: \"debug\" | \"info\" | \"warn\" | \"error\";\n}\n\n/**\n * Internal configuration with all optional properties resolved to required ones.\n * Maintains the discriminated union structure for clientId/loginUrl\n */\nexport type ProcessedCivicAuthConfig = {\n redirectUrl: string;\n logoutRedirectUrl: string;\n oauthServerBaseUrl: string;\n scopes: string[];\n textSignals: {\n success: string;\n error?: string;\n };\n storageAdapter: AuthStorage;\n logging: LoggingConfig;\n displayMode: BaseDisplayMode; // Internal config uses base DisplayMode after processing\n authProcessTimeout: number;\n iframeId: string;\n prompt: string;\n nonce?: string;\n backendEndpoints?: BackendEndpoints;\n preloadIframe: boolean;\n autoRedirect: boolean;\n // targetContainerElement remains optional as it's not needed for all display modes\n targetContainerElement?: HTMLElement | string;\n iframeDisplayMode?: \"modal\" | \"embedded\";\n events?: AuthenticationEvents;\n initialState?: string;\n framework?: FrameworkType;\n loginSuccessUrl?: string;\n initialUser?: User | null;\n basePath?: string;\n} & (\n | {\n /** OAuth client ID - required for standard OAuth flow */\n clientId: string;\n /** Custom login URL for backend integration - optional */\n loginUrl?: string;\n }\n | {\n /** OAuth client ID - optional when using backend integration */\n clientId?: string;\n /** Custom login URL for backend integration - required when clientId is not provided */\n loginUrl: string;\n }\n);\n"]}
|