feat: add uuid to restrict broadcast to other tabs

This commit is contained in:
yassinedorbozgithub 2025-01-29 12:56:07 +01:00
parent 34e10fa8aa
commit e3d113470b
9 changed files with 139 additions and 27 deletions

View File

@ -22,6 +22,7 @@ import { useLogout } from "@/hooks/entities/auth-hooks";
import { useApiClient } from "@/hooks/useApiClient";
import { CURRENT_USER_KEY, PUBLIC_PATHS } from "@/hooks/useAuth";
import { useBroadcastChannel } from "@/hooks/useBroadcastChannel";
import { useTabUuid } from "@/hooks/useTabUuid";
import { useTranslate } from "@/hooks/useTranslate";
import { RouterType } from "@/services/types";
import { IUser } from "@/types/user.types";
@ -108,8 +109,11 @@ export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => {
setIsReady(true);
}, []);
const tabUuidRef = useTabUuid();
const tabUuid = tabUuidRef.current;
useBroadcastChannel("session", (e) => {
if (e.data === "logout") {
if (e.data.value === "logout" && e.data.uuid !== tabUuid) {
router.reload();
}
});

View File

@ -23,6 +23,7 @@ import { useFind } from "../crud/useFind";
import { useApiClient } from "../useApiClient";
import { CURRENT_USER_KEY, useAuth, useLogoutRedirection } from "../useAuth";
import { useBroadcastChannel } from "../useBroadcastChannel";
import { useTabUuid } from "../useTabUuid";
import { useToast } from "../useToast";
import { useTranslate } from "../useTranslate";
@ -60,6 +61,8 @@ export const useLogout = (
const { toast } = useToast();
const { t } = useTranslate();
const broadcastLogoutAcrossTabs = useBroadcastChannel("session");
const tabUuidRef = useTabUuid();
const tabUuid = tabUuidRef.current;
return useMutation({
...options,
@ -70,7 +73,10 @@ export const useLogout = (
},
onSuccess: async () => {
queryClient.removeQueries([CURRENT_USER_KEY]);
broadcastLogoutAcrossTabs("logout");
broadcastLogoutAcrossTabs({
value: "logout",
uuid: tabUuid || "",
});
await logoutRedirection();
toast.success(t("message.logout_success"));
},

View File

@ -8,13 +8,10 @@
import * as React from "react";
export type BroadcastChannelData =
| string
| number
| boolean
| Record<string, unknown>
| undefined
| null;
export type BroadcastChannelData = {
uuid: string;
value: string | number | boolean | Record<string, unknown> | undefined | null;
};
/**
* React hook to create and manage a Broadcast Channel across multiple browser windows.
@ -24,10 +21,12 @@ export type BroadcastChannelData =
* @param handleMessageError [optional] Callback to handle the event generated when `error` is received.
* @returns A function to send/post message on the channel.
*/
export function useBroadcastChannel<T extends BroadcastChannelData = string>(
export function useBroadcastChannel<
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
handleMessage?: (event: MessageEvent) => void,
handleMessageError?: (event: MessageEvent) => void,
handleMessage?: (event: MessageEvent<T>) => void,
handleMessageError?: (event: MessageEvent<T>) => void,
): (data: T) => void {
const channelRef = React.useRef<BroadcastChannel | null>(
typeof window !== "undefined" && "BroadcastChannel" in window
@ -52,7 +51,9 @@ export function useBroadcastChannel<T extends BroadcastChannelData = string>(
* @param initialState Initial state.
* @returns Tuple of state and setter for the state.
*/
export function useBroadcastState<T extends BroadcastChannelData = string>(
export function useBroadcastState<
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
initialState: T,
): [T, React.Dispatch<React.SetStateAction<T>>, boolean] {

View File

@ -0,0 +1,30 @@
/*
* 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, useRef } from "react";
import { generateId } from "@/utils/generateId";
export const useTabUuid = (key: string = "tab_uuid") => {
const tabUuidRef = useRef<string | null>(null);
useEffect(() => {
const storedUuid = sessionStorage.getItem(key);
if (storedUuid) {
tabUuidRef.current = storedUuid;
} else {
const newUuid = generateId();
sessionStorage.setItem(key, newUuid);
tabUuidRef.current = newUuid;
}
}, []);
return tabUuidRef;
};

View File

@ -8,13 +8,10 @@
import * as React from "react";
export type BroadcastChannelData =
| string
| number
| boolean
| Record<string, unknown>
| undefined
| null;
export type BroadcastChannelData = {
uuid: string;
value: string | number | boolean | Record<string, unknown> | undefined | null;
};
/**
* React hook to create and manage a Broadcast Channel across multiple browser windows.
@ -24,10 +21,12 @@ export type BroadcastChannelData =
* @param handleMessageError [optional] Callback to handle the event generated when `error` is received.
* @returns A function to send/post message on the channel.
*/
export function useBroadcastChannel<T extends BroadcastChannelData = string>(
export function useBroadcastChannel<
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
handleMessage?: (event: MessageEvent) => void,
handleMessageError?: (event: MessageEvent) => void,
handleMessage?: (event: MessageEvent<T>) => void,
handleMessageError?: (event: MessageEvent<T>) => void,
): (data: T) => void {
const channelRef = React.useRef<BroadcastChannel | null>(
typeof window !== "undefined" && "BroadcastChannel" in window
@ -52,7 +51,9 @@ export function useBroadcastChannel<T extends BroadcastChannelData = string>(
* @param initialState Initial state.
* @returns Tuple of state and setter for the state.
*/
export function useBroadcastState<T extends BroadcastChannelData = string>(
export function useBroadcastState<
T extends BroadcastChannelData = BroadcastChannelData,
>(
channelName: string,
initialState: T,
): [T, React.Dispatch<React.SetStateAction<T>>, boolean] {

View File

@ -0,0 +1,30 @@
/*
* 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, useRef } from "react";
import { generateId } from "../utils/generateId";
export const useTabUuid = (key: string = "tab_uuid") => {
const tabUuidRef = useRef<string | null>(null);
useEffect(() => {
const storedUuid = sessionStorage.getItem(key);
if (storedUuid) {
tabUuidRef.current = storedUuid;
} else {
const newUuid = generateId();
sessionStorage.setItem(key, newUuid);
tabUuidRef.current = newUuid;
}
}, []);
return tabUuidRef;
};

View File

@ -17,6 +17,7 @@ import React, {
} from "react";
import { useBroadcastChannel } from "../hooks/useBroadcastChannel";
import { useTabUuid } from "../hooks/useTabUuid";
import { StdEventType } from "../types/chat-io-messages.types";
import {
Direction,
@ -269,7 +270,7 @@ const ChatProvider: React.FC<{
content_type: QuickReplyType.text,
text: qr.title,
payload: qr.payload,
}) as ISuggestion,
} as ISuggestion),
),
);
} else {
@ -452,9 +453,11 @@ const ChatProvider: React.FC<{
setMessage,
handleSubscription,
};
const tabUuidRef = useTabUuid();
const tabUuid = tabUuidRef.current;
useBroadcastChannel("session", (e) => {
if (e.data === "logout") {
useBroadcastChannel("session", ({ data }) => {
if (data.value === "logout" && data.uuid !== tabUuid) {
socketCtx.socket.disconnect();
}
});

View 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);
});
};

View 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);