added force publish option for admins

This commit is contained in:
PhilReact 2024-12-16 14:00:43 +02:00
parent d77b6caed4
commit 4c4ee5b1d7
5 changed files with 269 additions and 155 deletions

View File

@ -27,7 +27,8 @@ export const AdminSpace = ({
myAddress,
hide,
defaultThread,
setDefaultThread
setDefaultThread,
setIsForceShowCreationKeyPopup
}) => {
const { rootHeight } = useContext(MyContext);
const [isMoved, setIsMoved] = useState(false);
@ -59,7 +60,7 @@ export const AdminSpace = ({
justifyContent: 'center',
paddingTop: '25px'
}}><Typography>Sorry, this space is only for Admins.</Typography></Box>}
{isAdmin && <AdminSpaceInner adminsWithNames={adminsWithNames} selectedGroup={selectedGroup} />}
{isAdmin && <AdminSpaceInner setIsForceShowCreationKeyPopup={setIsForceShowCreationKeyPopup} adminsWithNames={adminsWithNames} selectedGroup={selectedGroup} />}
</div>
);

View File

@ -1,19 +1,27 @@
import React, { useCallback, useContext, useEffect, useState } from 'react'
import { MyContext, getArbitraryEndpointReact, getBaseApiReact } from '../../App';
import { Box, Button, Typography } from '@mui/material';
import { decryptResource, validateSecretKey } from '../Group/Group';
import { getFee } from '../../background';
import { base64ToUint8Array } from '../../qdn/encryption/group-encryption';
import { uint8ArrayToObject } from '../../backgroundFunctions/encryption';
import { formatTimestampForum } from '../../utils/time';
import { Spacer } from '../../common/Spacer';
import React, { useCallback, useContext, useEffect, useState } from "react";
import {
MyContext,
getArbitraryEndpointReact,
getBaseApiReact,
} from "../../App";
import { Box, Button, Typography } from "@mui/material";
import {
decryptResource,
getPublishesFromAdmins,
validateSecretKey,
} from "../Group/Group";
import { getFee } from "../../background";
import { base64ToUint8Array } from "../../qdn/encryption/group-encryption";
import { uint8ArrayToObject } from "../../backgroundFunctions/encryption";
import { formatTimestampForum } from "../../utils/time";
import { Spacer } from "../../common/Spacer";
export const getPublishesFromAdminsAdminSpace = async (admins: string[], groupId) => {
const queryString = admins.map((name) => `name=${name}`).join("&");
const url = `${getBaseApiReact()}${getArbitraryEndpointReact()}?mode=ALL&service=DOCUMENT_PRIVATE&identifier=admins-symmetric-qchat-group-${
export const getPublishesFromAdminsAdminSpace = async (
admins: string[],
groupId
}&exactmatchnames=true&limit=0&reverse=true&${queryString}&prefix=true`;
) => {
const queryString = admins.map((name) => `name=${name}`).join("&");
const url = `${getBaseApiReact()}${getArbitraryEndpointReact()}?mode=ALL&service=DOCUMENT_PRIVATE&identifier=admins-symmetric-qchat-group-${groupId}&exactmatchnames=true&limit=0&reverse=true&${queryString}&prefix=true`;
const response = await fetch(url);
if (!response.ok) {
throw new Error("network error");
@ -21,8 +29,7 @@ export const getPublishesFromAdminsAdminSpace = async (admins: string[], groupId
const adminData = await response.json();
const filterId = adminData.filter(
(data: any) =>
data.identifier === `admins-symmetric-qchat-group-${groupId}`
(data: any) => data.identifier === `admins-symmetric-qchat-group-${groupId}`
);
if (filterId?.length === 0) {
return false;
@ -39,27 +46,40 @@ export const getPublishesFromAdminsAdminSpace = async (admins: string[], groupId
return sortedData[0];
};
export const AdminSpaceInner = ({selectedGroup, adminsWithNames}) => {
const [adminGroupSecretKey, setAdminGroupSecretKey] = useState(null)
const [isFetchingAdminGroupSecretKey, setIsFetchingAdminGroupSecretKey] = useState(true)
const [adminGroupSecretKeyPublishDetails, setAdminGroupSecretKeyPublishDetails] = useState(null)
const [isLoadingPublishKey, setIsLoadingPublishKey] = useState(false)
const { show, setTxList, setInfoSnackCustom,
setOpenSnackGlobal } = useContext(MyContext);
export const AdminSpaceInner = ({
selectedGroup,
adminsWithNames,
setIsForceShowCreationKeyPopup,
}) => {
const [adminGroupSecretKey, setAdminGroupSecretKey] = useState(null);
const [isFetchingAdminGroupSecretKey, setIsFetchingAdminGroupSecretKey] =
useState(true);
const [isFetchingGroupSecretKey, setIsFetchingGroupSecretKey] =
useState(true);
const [
adminGroupSecretKeyPublishDetails,
setAdminGroupSecretKeyPublishDetails,
] = useState(null);
const [groupSecretKeyPublishDetails, setGroupSecretKeyPublishDetails] =
useState(null);
const [isLoadingPublishKey, setIsLoadingPublishKey] = useState(false);
const { show, setTxList, setInfoSnackCustom, setOpenSnackGlobal } =
useContext(MyContext);
const getAdminGroupSecretKey = useCallback(async () => {
try {
if(!selectedGroup) return
const getLatestPublish = await getPublishesFromAdminsAdminSpace(adminsWithNames.map((admin)=> admin?.name), selectedGroup)
if(getLatestPublish === false) return
if (!selectedGroup) return;
const getLatestPublish = await getPublishesFromAdminsAdminSpace(
adminsWithNames.map((admin) => admin?.name),
selectedGroup
);
if (getLatestPublish === false) return;
let data;
const res = await fetch(
`${getBaseApiReact()}/arbitrary/DOCUMENT_PRIVATE/${getLatestPublish.name}/${
getLatestPublish.identifier
}?encoding=base64`
`${getBaseApiReact()}/arbitrary/DOCUMENT_PRIVATE/${
getLatestPublish.name
}/${getLatestPublish.identifier}?encoding=base64`
);
data = await res.text();
@ -68,39 +88,53 @@ export const AdminSpaceInner = ({selectedGroup, adminsWithNames}) => {
const decryptedKeyToObject = uint8ArrayToObject(dataint8Array);
if (!validateSecretKey(decryptedKeyToObject))
throw new Error("SecretKey is not valid");
setAdminGroupSecretKey(decryptedKeyToObject)
setAdminGroupSecretKeyPublishDetails(getLatestPublish)
setAdminGroupSecretKey(decryptedKeyToObject);
setAdminGroupSecretKeyPublishDetails(getLatestPublish);
} catch (error) {
} finally {
setIsFetchingAdminGroupSecretKey(false)
setIsFetchingAdminGroupSecretKey(false);
}
}, [adminsWithNames, selectedGroup])
}, [adminsWithNames, selectedGroup]);
const getGroupSecretKey = useCallback(async () => {
try {
if (!selectedGroup) return;
const getLatestPublish = await getPublishesFromAdmins(
adminsWithNames.map((admin) => admin?.name),
selectedGroup
);
if (getLatestPublish === false) setGroupSecretKeyPublishDetails(false);
setGroupSecretKeyPublishDetails(getLatestPublish);
} catch (error) {
} finally {
setIsFetchingGroupSecretKey(false);
}
}, [adminsWithNames, selectedGroup]);
const createCommonSecretForAdmins = async () => {
try {
const fee = await getFee('ARBITRARY')
const fee = await getFee("ARBITRARY");
await show({
message: "Would you like to perform an ARBITRARY transaction?",
publishFee: fee.fee + ' QORT'
})
setIsLoadingPublishKey(true)
publishFee: fee.fee + " QORT",
});
setIsLoadingPublishKey(true);
window.sendMessage("encryptAndPublishSymmetricKeyGroupChatForAdmins", {
window
.sendMessage("encryptAndPublishSymmetricKeyGroupChatForAdmins", {
groupId: selectedGroup,
previousData: null,
admins: adminsWithNames
admins: adminsWithNames,
})
.then((response) => {
if (!response?.error) {
setInfoSnackCustom({
type: "success",
message: "Successfully re-encrypted secret key. It may take a couple of minutes for the changes to propagate. Refresh the group in 5 mins.",
message:
"Successfully re-encrypted secret key. It may take a couple of minutes for the changes to propagate. Refresh the group in 5 mins.",
});
setOpenSnackGlobal(true);
return
return;
}
setInfoSnackCustom({
type: "error",
@ -115,36 +149,100 @@ export const AdminSpaceInner = ({selectedGroup, adminsWithNames}) => {
});
setOpenSnackGlobal(true);
});
} catch (error) {}
};
} catch (error) {
}
}
useEffect(() => {
getAdminGroupSecretKey()
}, [getAdminGroupSecretKey]);
getAdminGroupSecretKey();
getGroupSecretKey();
}, [getAdminGroupSecretKey, getGroupSecretKey]);
return (
<Box sx={{
width: '100%',
display: 'flex',
flexDirection: 'column',
padding: '10px'
}}>
<Box
sx={{
width: "100%",
display: "flex",
flexDirection: "column",
padding: "10px",
alignItems: 'center'
}}
>
<Typography sx={{
fontSize: '14px'
}}>Reminder: After publishing the key, it will take a couple of minutes for it to appear. Please just wait.</Typography>
<Spacer height="25px" />
<Box sx={{
display: 'flex',
flexDirection: 'column',
gap: '20px',
width: '300px',
maxWidth: '90%'
}}>
{isFetchingAdminGroupSecretKey && <Typography>Fetching Admins secret keys</Typography>}
{!isFetchingAdminGroupSecretKey && !adminGroupSecretKey && <Typography>No secret key published yet</Typography>}
{adminGroupSecretKeyPublishDetails && (
<Typography>Last encryption date: {formatTimestampForum(adminGroupSecretKeyPublishDetails?.updated || adminGroupSecretKeyPublishDetails?.created)}</Typography>
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: "20px",
width: "300px",
maxWidth: "90%",
padding: '10px',
border: '1px solid gray',
borderRadius: '6px'
}}
>
{isFetchingGroupSecretKey && (
<Typography>Fetching Group secret key publishes</Typography>
)}
<Button onClick={createCommonSecretForAdmins} variant="contained">Publish admin secret key</Button>
{!isFetchingGroupSecretKey &&
groupSecretKeyPublishDetails === false && (
<Typography>No secret key published yet</Typography>
)}
{groupSecretKeyPublishDetails && (
<Typography>
Last encryption date:{" "}
{formatTimestampForum(
groupSecretKeyPublishDetails?.updated ||
groupSecretKeyPublishDetails?.created
)}{" "}
{` by ${groupSecretKeyPublishDetails?.name}`}
</Typography>
)}
<Button disabled={isFetchingGroupSecretKey} onClick={setIsForceShowCreationKeyPopup} variant="contained">
Publish group secret key
</Button>
<Spacer height="20px" />
<Typography sx={{
fontSize: '14px'
}}>This key is to encrypt GROUP related content. This is the only one used in this UI as of now. All group members will be able to see content encrypted with this key.</Typography>
</Box>
<Spacer height="25px" />
<Box
sx={{
display: "flex",
flexDirection: "column",
gap: "20px",
width: "300px",
maxWidth: "90%",
padding: '10px',
border: '1px solid gray',
borderRadius: '6px'
}}
>
{isFetchingAdminGroupSecretKey && (
<Typography>Fetching Admins secret key</Typography>
)}
{!isFetchingAdminGroupSecretKey && !adminGroupSecretKey && (
<Typography>No secret key published yet</Typography>
)}
{adminGroupSecretKeyPublishDetails && (
<Typography>
Last encryption date:{" "}
{formatTimestampForum(
adminGroupSecretKeyPublishDetails?.updated ||
adminGroupSecretKeyPublishDetails?.created
)}
</Typography>
)}
<Button disabled={isFetchingAdminGroupSecretKey} onClick={createCommonSecretForAdmins} variant="contained">
Publish admin secret key
</Button>
<Spacer height="20px" />
<Typography sx={{
fontSize: '14px'
}}>This key is to encrypt ADMIN related content. Only admins would see content encrypted with it.</Typography>
</Box>
</Box>
)
}
);
};

View File

@ -54,14 +54,14 @@ const [messageSize, setMessageSize] = useState(0)
const handleUpdateRef = useRef(null);
const getTimestampEnterChat = async () => {
const getTimestampEnterChat = async (selectedGroup) => {
try {
return new Promise((res, rej) => {
window.sendMessage("getTimestampEnterChat")
.then((response) => {
if (!response?.error) {
if(response && selectedGroup && response[selectedGroup]){
lastReadTimestamp.current = response[selectedGroup]
if(response && selectedGroup){
lastReadTimestamp.current = response[selectedGroup] || undefined
window.sendMessage("addTimestampEnterChat", {
timestamp: Date.now(),
groupId: selectedGroup
@ -89,8 +89,9 @@ const [messageSize, setMessageSize] = useState(0)
};
useEffect(()=> {
getTimestampEnterChat()
}, [])
if(!selectedGroup) return
getTimestampEnterChat(selectedGroup)
}, [selectedGroup])
@ -208,7 +209,9 @@ const [messageSize, setMessageSize] = useState(0)
const formatted = combineUIAndExtensionMsgs
.filter((rawItem) => !rawItem?.chatReference)
.map((item) => {
const additionalFields = item?.data === 'NDAwMQ==' ? {
text: "<p>First group key created.</p>"
} : {}
return {
...item,
id: item.signature,
@ -216,6 +219,7 @@ const [messageSize, setMessageSize] = useState(0)
repliedTo: item?.repliedTo || item?.decryptedData?.repliedTo,
unread: item?.sender === myAddress ? false : !!item?.chatReference ? false : true,
isNotEncrypted: !!item?.messageText,
...additionalFields
}
});
setMessages((prev) => [...prev, ...formatted]);
@ -287,10 +291,12 @@ const [messageSize, setMessageSize] = useState(0)
});
} else {
let firstUnreadFound = false;
console.log('combineUIAndExtensionMsgs', combineUIAndExtensionMsgs)
const formatted = combineUIAndExtensionMsgs
.filter((rawItem) => !rawItem?.chatReference)
.map((item) => {
const additionalFields = item?.data === 'NDAwMQ==' ? {
text: "<p>First group key created.</p>"
} : {}
const divide = lastReadTimestamp.current && !firstUnreadFound && item.timestamp > lastReadTimestamp.current && myAddress !== item?.sender;
if(divide){
@ -303,7 +309,8 @@ const [messageSize, setMessageSize] = useState(0)
repliedTo: item?.repliedTo || item?.decryptedData?.repliedTo,
isNotEncrypted: !!item?.messageText,
unread: false,
divide
divide,
...additionalFields
}
});
setMessages(formatted);

View File

@ -8,7 +8,7 @@ import { decryptResource, getGroupAdmins, validateSecretKey } from '../Group/Gro
import { base64ToUint8Array } from '../../qdn/encryption/group-encryption';
import { uint8ArrayToObject } from '../../backgroundFunctions/encryption';
export const CreateCommonSecret = ({groupId, secretKey, isOwner, myAddress, secretKeyDetails, userInfo, noSecretKey, setHideCommonKeyPopup}) => {
export const CreateCommonSecret = ({groupId, secretKey, isOwner, myAddress, secretKeyDetails, userInfo, noSecretKey, setHideCommonKeyPopup, setIsForceShowCreationKeyPopup}) => {
const { show, setTxList } = useContext(MyContext);
const [openSnack, setOpenSnack] = React.useState(false);
@ -131,6 +131,9 @@ export const CreateCommonSecret = ({groupId, secretKey, isOwner, myAddress, sec
]);
}
setIsLoading(false);
setTimeout(() => {
setIsForceShowCreationKeyPopup(false)
}, 1000);
})
.catch((error) => {
console.error("Failed to encrypt and publish symmetric key for group chat:", error.message || "An error occurred");
@ -173,6 +176,7 @@ export const CreateCommonSecret = ({groupId, secretKey, isOwner, myAddress, sec
}}>
<Button onClick={()=> {
setHideCommonKeyPopup(true)
setIsForceShowCreationKeyPopup(false)
}} size='small'>Hide</Button>
</Box>
<CustomizedSnackbars open={openSnack} setOpen={setOpenSnack} info={infoSnack} setInfo={setInfoSnack} />

View File

@ -432,7 +432,7 @@ export const Group = ({
const [appsModeDev, setAppsModeDev] = useState('home')
const [isOpenSideViewDirects, setIsOpenSideViewDirects] = useState(false)
const [isOpenSideViewGroups, setIsOpenSideViewGroups] = useState(false)
const [isForceShowCreationKeyPopup, setIsForceShowCreationKeyPopup] = useState(false)
const [groupsProperties, setGroupsProperties] = useState({})
@ -2360,8 +2360,11 @@ export const Group = ({
setDefaultThread={setDefaultThread}
isPrivate={isPrivate}
/>
<AdminSpace adminsWithNames={adminsWithNames} selectedGroup={selectedGroup?.groupId} myAddress={myAddress} userInfo={userInfo} hide={groupSection !== "adminSpace"} isAdmin={admins.includes(myAddress)}
{groupSection === "adminSpace" && (
<AdminSpace setIsForceShowCreationKeyPopup={setIsForceShowCreationKeyPopup} adminsWithNames={adminsWithNames} selectedGroup={selectedGroup?.groupId} myAddress={myAddress} userInfo={userInfo} hide={groupSection !== "adminSpace"} isAdmin={admins.includes(myAddress)}
/>
)}
</>
)}
@ -2374,11 +2377,11 @@ export const Group = ({
zIndex: 100,
}}
>
{isPrivate && admins.includes(myAddress) &&
{(isPrivate && admins.includes(myAddress) &&
shouldReEncrypt &&
triedToFetchSecretKey &&
!firstSecretKeyInCreation &&
!hideCommonKeyPopup && (
!hideCommonKeyPopup) || isForceShowCreationKeyPopup && (
<CreateCommonSecret
setHideCommonKeyPopup={setHideCommonKeyPopup}
groupId={selectedGroup?.groupId}
@ -2387,6 +2390,7 @@ export const Group = ({
myAddress={myAddress}
isOwner={groupOwner?.owner === myAddress}
userInfo={userInfo}
setIsForceShowCreationKeyPopup={setIsForceShowCreationKeyPopup}
noSecretKey={
admins.includes(myAddress) &&
!secretKey &&