mirror of
https://github.com/hexastack/hexabot
synced 2025-06-26 18:27:28 +00:00
Merge pull request #635 from Hexastack/634-issue---logout-is-not-shared-cross-tabs
feat(frontend): add BroadcastChannel hook
This commit is contained in:
commit
bc156fcefe
@ -21,6 +21,7 @@ import { Progress } from "@/app-components/displays/Progress";
|
||||
import { useLogout } from "@/hooks/entities/auth-hooks";
|
||||
import { useApiClient } from "@/hooks/useApiClient";
|
||||
import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth";
|
||||
import { useSubscribeBroadcastChannel } from "@/hooks/useSubscribeBroadcastChannel";
|
||||
import { useTranslate } from "@/hooks/useTranslate";
|
||||
import { RouterType } from "@/services/types";
|
||||
import { IUser } from "@/types/user.types";
|
||||
@ -100,6 +101,14 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
|
||||
};
|
||||
const isAuthenticated = !!user;
|
||||
|
||||
useSubscribeBroadcastChannel("login", () => {
|
||||
router.reload();
|
||||
});
|
||||
|
||||
useSubscribeBroadcastChannel("logout", () => {
|
||||
router.reload();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const search = location.search;
|
||||
|
||||
|
147
frontend/src/contexts/broadcast-channel.context.tsx
Normal file
147
frontend/src/contexts/broadcast-channel.context.tsx
Normal file
@ -0,0 +1,147 @@
|
||||
/*
|
||||
* Copyright © 2025 Hexastack. All rights reserved.
|
||||
*
|
||||
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
|
||||
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
|
||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||
*/
|
||||
|
||||
import {
|
||||
createContext,
|
||||
FC,
|
||||
ReactNode,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
} from "react";
|
||||
|
||||
import { generateId } from "@/utils/generateId";
|
||||
|
||||
export enum EBCEvent {
|
||||
LOGIN = "login",
|
||||
LOGOUT = "logout",
|
||||
}
|
||||
|
||||
type BroadcastChannelPayload = {
|
||||
event: `${EBCEvent}`;
|
||||
data?: string | number | boolean | Record<string, unknown> | undefined | null;
|
||||
};
|
||||
|
||||
type BroadcastChannelData = {
|
||||
tabId: string;
|
||||
payload: BroadcastChannelPayload;
|
||||
};
|
||||
|
||||
interface IBroadcastChannelProps {
|
||||
channelName: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
interface IBroadcastChannelContext {
|
||||
subscribe: (
|
||||
event: `${EBCEvent}`,
|
||||
callback: (message: BroadcastChannelData) => void,
|
||||
) => void;
|
||||
postMessage: (payload: BroadcastChannelPayload) => void;
|
||||
}
|
||||
|
||||
const getOrCreateTabId = () => {
|
||||
let storedTabId = sessionStorage.getItem("tab_uuid");
|
||||
|
||||
if (storedTabId) {
|
||||
return storedTabId;
|
||||
}
|
||||
|
||||
storedTabId = generateId();
|
||||
sessionStorage.setItem("tab_uuid", storedTabId);
|
||||
|
||||
return storedTabId;
|
||||
};
|
||||
|
||||
export const BroadcastChannelContext = createContext<
|
||||
IBroadcastChannelContext | undefined
|
||||
>(undefined);
|
||||
|
||||
export const BroadcastChannelProvider: FC<IBroadcastChannelProps> = ({
|
||||
children,
|
||||
channelName,
|
||||
}) => {
|
||||
const channelRef = useRef<BroadcastChannel>(
|
||||
new BroadcastChannel(channelName),
|
||||
);
|
||||
const subscribersRef = useRef<
|
||||
Record<
|
||||
string,
|
||||
Array<Parameters<IBroadcastChannelContext["subscribe"]>["1"]>
|
||||
>
|
||||
>({});
|
||||
const tabUuid = getOrCreateTabId();
|
||||
|
||||
useEffect(() => {
|
||||
const handleMessage = ({ data }: MessageEvent<BroadcastChannelData>) => {
|
||||
const { tabId, payload } = data;
|
||||
|
||||
if (tabId === tabUuid) {
|
||||
return;
|
||||
}
|
||||
|
||||
subscribersRef.current[payload.event].forEach((callback) =>
|
||||
callback(data),
|
||||
);
|
||||
};
|
||||
|
||||
channelRef.current.addEventListener("message", handleMessage);
|
||||
|
||||
return () => {
|
||||
channelRef.current.removeEventListener("message", handleMessage);
|
||||
channelRef.current.close();
|
||||
};
|
||||
}, []);
|
||||
|
||||
const subscribe: IBroadcastChannelContext["subscribe"] = (
|
||||
event,
|
||||
callback,
|
||||
) => {
|
||||
subscribersRef.current[event] ??= [];
|
||||
subscribersRef.current[event].push(callback);
|
||||
|
||||
return () => {
|
||||
const index = subscribersRef.current[event].indexOf(callback);
|
||||
|
||||
if (index !== -1) {
|
||||
subscribersRef.current[event].splice(index, 1);
|
||||
}
|
||||
};
|
||||
};
|
||||
const postMessage: IBroadcastChannelContext["postMessage"] = (payload) => {
|
||||
channelRef.current.postMessage({
|
||||
tabId: tabUuid,
|
||||
payload,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<BroadcastChannelContext.Provider
|
||||
value={{
|
||||
subscribe,
|
||||
postMessage,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</BroadcastChannelContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useBroadcastChannel = () => {
|
||||
const context = useContext(BroadcastChannelContext);
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error(
|
||||
"useBroadcastChannel must be used within a BroadcastChannelProvider",
|
||||
);
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export default BroadcastChannelProvider;
|
@ -9,6 +9,7 @@
|
||||
import { useEffect } from "react";
|
||||
import { useMutation, useQuery, useQueryClient } from "react-query";
|
||||
|
||||
import { useBroadcastChannel } from "@/contexts/broadcast-channel.context";
|
||||
import { EntityType, TMutationOptions } from "@/services/types";
|
||||
import { ILoginAttributes } from "@/types/auth/login.types";
|
||||
import {
|
||||
@ -32,12 +33,17 @@ export const useLogin = (
|
||||
>,
|
||||
) => {
|
||||
const { apiClient } = useApiClient();
|
||||
const { postMessage } = useBroadcastChannel();
|
||||
|
||||
return useMutation({
|
||||
...options,
|
||||
async mutationFn(credentials) {
|
||||
return await apiClient.login(credentials);
|
||||
},
|
||||
onSuccess: (data, variables, context) => {
|
||||
options?.onSuccess?.(data, variables, context);
|
||||
postMessage({ event: "login" });
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
@ -58,6 +64,7 @@ export const useLogout = (
|
||||
const { logoutRedirection } = useLogoutRedirection();
|
||||
const { toast } = useToast();
|
||||
const { t } = useTranslate();
|
||||
const { postMessage } = useBroadcastChannel();
|
||||
|
||||
return useMutation({
|
||||
...options,
|
||||
@ -68,6 +75,7 @@ export const useLogout = (
|
||||
},
|
||||
onSuccess: async () => {
|
||||
queryClient.removeQueries([CURRENT_USER_KEY]);
|
||||
postMessage({ event: "logout" });
|
||||
await logoutRedirection();
|
||||
toast.success(t("message.logout_success"));
|
||||
},
|
||||
|
21
frontend/src/hooks/useSubscribeBroadcastChannel.ts
Normal file
21
frontend/src/hooks/useSubscribeBroadcastChannel.ts
Normal file
@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright © 2025 Hexastack. All rights reserved.
|
||||
*
|
||||
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
|
||||
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
|
||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||
*/
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useBroadcastChannel } from "@/contexts/broadcast-channel.context";
|
||||
|
||||
export const useSubscribeBroadcastChannel: ReturnType<
|
||||
typeof useBroadcastChannel
|
||||
>["subscribe"] = (...props) => {
|
||||
const { subscribe } = useBroadcastChannel();
|
||||
|
||||
useEffect(() => {
|
||||
subscribe(...props);
|
||||
}, [subscribe, ...props]);
|
||||
};
|
@ -19,6 +19,7 @@ import { ReactQueryDevtools } from "react-query/devtools";
|
||||
import { SnackbarCloseButton } from "@/app-components/displays/Toast/CloseButton";
|
||||
import { ApiClientProvider } from "@/contexts/apiClient.context";
|
||||
import { AuthProvider } from "@/contexts/auth.context";
|
||||
import BroadcastChannelProvider from "@/contexts/broadcast-channel.context";
|
||||
import { ConfigProvider } from "@/contexts/config.context";
|
||||
import { PermissionProvider } from "@/contexts/permission.context";
|
||||
import { SettingsProvider } from "@/contexts/setting.context";
|
||||
@ -83,6 +84,7 @@ const App = ({ Component, pageProps }: TAppPropsWithLayout) => {
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<CssBaseline />
|
||||
<ApiClientProvider>
|
||||
<BroadcastChannelProvider channelName="main-channel">
|
||||
<AuthProvider>
|
||||
<PermissionProvider>
|
||||
<SettingsProvider>
|
||||
@ -92,6 +94,7 @@ const App = ({ Component, pageProps }: TAppPropsWithLayout) => {
|
||||
</SettingsProvider>
|
||||
</PermissionProvider>
|
||||
</AuthProvider>
|
||||
</BroadcastChannelProvider>
|
||||
</ApiClientProvider>
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</QueryClientProvider>
|
||||
|
4
package-lock.json
generated
4
package-lock.json
generated
@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "hexabot",
|
||||
"version": "2.2.2",
|
||||
"version": "2.2.3",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "hexabot",
|
||||
"version": "2.2.2",
|
||||
"version": "2.2.3",
|
||||
"license": "AGPL-3.0-only",
|
||||
"workspaces": [
|
||||
"frontend",
|
||||
|
@ -10,6 +10,7 @@ import { PropsWithChildren } from "react";
|
||||
|
||||
import Launcher from "./components/Launcher";
|
||||
import UserSubscription from "./components/UserSubscription";
|
||||
import BroadcastChannelProvider from "./providers/BroadcastChannelProvider";
|
||||
import ChatProvider from "./providers/ChatProvider";
|
||||
import { ColorProvider } from "./providers/ColorProvider";
|
||||
import { ConfigProvider } from "./providers/ConfigProvider";
|
||||
@ -41,6 +42,7 @@ function UiChatWidget({
|
||||
<SocketProvider>
|
||||
<SettingsProvider>
|
||||
<ColorProvider>
|
||||
<BroadcastChannelProvider channelName="main-channel">
|
||||
<WidgetProvider defaultScreen="chat">
|
||||
<ChatProvider
|
||||
defaultConnectionState={ConnectionState.connected}
|
||||
@ -52,6 +54,7 @@ function UiChatWidget({
|
||||
/>
|
||||
</ChatProvider>
|
||||
</WidgetProvider>
|
||||
</BroadcastChannelProvider>
|
||||
</ColorProvider>
|
||||
</SettingsProvider>
|
||||
</SocketProvider>
|
||||
|
22
widget/src/hooks/useSubscribeBroadcastChannel.ts
Normal file
22
widget/src/hooks/useSubscribeBroadcastChannel.ts
Normal file
@ -0,0 +1,22 @@
|
||||
/*
|
||||
* Copyright © 2025 Hexastack. All rights reserved.
|
||||
*
|
||||
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
|
||||
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
|
||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||
*/
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
import { useBroadcastChannel } from "../providers/BroadcastChannelProvider";
|
||||
|
||||
export const useSubscribeBroadcastChannel: ReturnType<
|
||||
typeof useBroadcastChannel
|
||||
>["subscribe"] = (...props) => {
|
||||
const { subscribe } = useBroadcastChannel();
|
||||
|
||||
useEffect(() => {
|
||||
subscribe(...props);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [subscribe, ...props]);
|
||||
};
|
148
widget/src/providers/BroadcastChannelProvider.tsx
Normal file
148
widget/src/providers/BroadcastChannelProvider.tsx
Normal file
@ -0,0 +1,148 @@
|
||||
/*
|
||||
* Copyright © 2025 Hexastack. All rights reserved.
|
||||
*
|
||||
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
|
||||
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
|
||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||
*/
|
||||
|
||||
import {
|
||||
createContext,
|
||||
FC,
|
||||
ReactNode,
|
||||
useContext,
|
||||
useEffect,
|
||||
useRef,
|
||||
} from "react";
|
||||
|
||||
import { generateId } from "../utils/generateId";
|
||||
|
||||
export enum EBCEvent {
|
||||
LOGOUT = "logout",
|
||||
}
|
||||
|
||||
type BroadcastChannelPayload = {
|
||||
event: `${EBCEvent}`;
|
||||
data?: string | number | boolean | Record<string, unknown> | undefined | null;
|
||||
};
|
||||
|
||||
type BroadcastChannelData = {
|
||||
tabId: string;
|
||||
payload: BroadcastChannelPayload;
|
||||
};
|
||||
|
||||
interface IBroadcastChannelProps {
|
||||
channelName: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
interface IBroadcastChannelContext {
|
||||
subscribe: (
|
||||
event: `${EBCEvent}`,
|
||||
callback: (message: BroadcastChannelData) => void,
|
||||
) => void;
|
||||
postMessage: (payload: BroadcastChannelPayload) => void;
|
||||
}
|
||||
|
||||
const getOrCreateTabId = () => {
|
||||
let storedTabId = sessionStorage.getItem("tab_uuid");
|
||||
|
||||
if (storedTabId) {
|
||||
return storedTabId;
|
||||
}
|
||||
|
||||
storedTabId = generateId();
|
||||
sessionStorage.setItem("tab_uuid", storedTabId);
|
||||
|
||||
return storedTabId;
|
||||
};
|
||||
|
||||
export const BroadcastChannelContext = createContext<
|
||||
IBroadcastChannelContext | undefined
|
||||
>(undefined);
|
||||
|
||||
export const BroadcastChannelProvider: FC<IBroadcastChannelProps> = ({
|
||||
children,
|
||||
channelName,
|
||||
}) => {
|
||||
const channelRef = useRef<BroadcastChannel>(
|
||||
new BroadcastChannel(channelName),
|
||||
);
|
||||
const subscribersRef = useRef<
|
||||
Record<
|
||||
string,
|
||||
Array<Parameters<IBroadcastChannelContext["subscribe"]>["1"]>
|
||||
>
|
||||
>({});
|
||||
const tabUuid = getOrCreateTabId();
|
||||
|
||||
useEffect(() => {
|
||||
const handleMessage = ({ data }: MessageEvent<BroadcastChannelData>) => {
|
||||
const { tabId, payload } = data;
|
||||
|
||||
if (tabId === tabUuid) {
|
||||
return;
|
||||
}
|
||||
|
||||
subscribersRef.current[payload.event].forEach((callback) =>
|
||||
callback(data),
|
||||
);
|
||||
};
|
||||
|
||||
channelRef.current.addEventListener("message", handleMessage);
|
||||
|
||||
return () => {
|
||||
channelRef.current.removeEventListener("message", handleMessage);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
channelRef.current.close();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
const subscribe: IBroadcastChannelContext["subscribe"] = (
|
||||
event,
|
||||
callback,
|
||||
) => {
|
||||
subscribersRef.current[event] ??= [];
|
||||
subscribersRef.current[event].push(callback);
|
||||
|
||||
return () => {
|
||||
const index = subscribersRef.current[event].indexOf(callback);
|
||||
|
||||
if (index !== -1) {
|
||||
subscribersRef.current[event].splice(index, 1);
|
||||
}
|
||||
};
|
||||
};
|
||||
const postMessage: IBroadcastChannelContext["postMessage"] = (payload) => {
|
||||
channelRef.current.postMessage({
|
||||
tabId: tabUuid,
|
||||
payload,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<BroadcastChannelContext.Provider
|
||||
value={{
|
||||
subscribe,
|
||||
postMessage,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</BroadcastChannelContext.Provider>
|
||||
);
|
||||
};
|
||||
|
||||
export const useBroadcastChannel = () => {
|
||||
const context = useContext(BroadcastChannelContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error(
|
||||
"useBroadcastChannel must be used within a BroadcastChannelProvider",
|
||||
);
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
|
||||
export default BroadcastChannelProvider;
|
@ -6,7 +6,6 @@
|
||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||
*/
|
||||
|
||||
|
||||
import React, {
|
||||
createContext,
|
||||
ReactNode,
|
||||
@ -17,6 +16,7 @@ import React, {
|
||||
useState,
|
||||
} from "react";
|
||||
|
||||
import { useSubscribeBroadcastChannel } from "../hooks/useSubscribeBroadcastChannel";
|
||||
import { StdEventType } from "../types/chat-io-messages.types";
|
||||
import {
|
||||
Direction,
|
||||
@ -385,6 +385,10 @@ const ChatProvider: React.FC<{
|
||||
}
|
||||
}, [syncState, isOpen]);
|
||||
|
||||
useSubscribeBroadcastChannel("logout", () => {
|
||||
socketCtx.socket.disconnect();
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (screen === "chat" && connectionState === ConnectionState.connected) {
|
||||
handleSubscription();
|
||||
|
21
widget/src/utils/generateId.ts
Normal file
21
widget/src/utils/generateId.ts
Normal file
@ -0,0 +1,21 @@
|
||||
/*
|
||||
* Copyright © 2025 Hexastack. All rights reserved.
|
||||
*
|
||||
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
|
||||
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
|
||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||
*/
|
||||
|
||||
|
||||
import { getRandom } from "./safeRandom";
|
||||
|
||||
export const generateId = () => {
|
||||
const d =
|
||||
typeof performance === "undefined" ? Date.now() : performance.now() * 1000;
|
||||
|
||||
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
||||
const r = (getRandom() * 16 + d) % 16 | 0;
|
||||
|
||||
return (c == "x" ? r : (r & 0x3) | 0x8).toString(16);
|
||||
});
|
||||
};
|
16
widget/src/utils/safeRandom.ts
Normal file
16
widget/src/utils/safeRandom.ts
Normal file
@ -0,0 +1,16 @@
|
||||
/*
|
||||
* Copyright © 2025 Hexastack. All rights reserved.
|
||||
*
|
||||
* Licensed under the GNU Affero General Public License v3.0 (AGPLv3) with the following additional terms:
|
||||
* 1. The name "Hexabot" is a trademark of Hexastack. You may not use this name in derivative works without express written permission.
|
||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Return a cryptographically secure random value between 0 and 1
|
||||
*
|
||||
* @returns A cryptographically secure random value between 0 and 1
|
||||
*/
|
||||
export const getRandom = (): number =>
|
||||
window.crypto.getRandomValues(new Uint32Array(1))[0] * Math.pow(2, -32);
|
Loading…
Reference in New Issue
Block a user