import { Box, Button, IconButton, List, ListItem, ListSubheader, Table, TableBody, TableCell, TableHead, TableRow, TextField, Tooltip, Typography, useTheme } from '@mui/material' import axios from 'axios' import saveAs from 'file-saver' import JSZip from 'jszip' import _ from 'lodash' import { MuiFileInput } from 'mui-file-input' import { Event, verifyEvent } from 'nostr-tools' import { useEffect, useState } from 'react' import { useSelector } from 'react-redux' import { useNavigate, useSearchParams } from 'react-router-dom' import { toast } from 'react-toastify' import { LoadingSpinner } from '../../components/LoadingSpinner' import { UserComponent } from '../../components/username' import { MetadataController, NostrController } from '../../controllers' import { appPrivateRoutes } from '../../routes' import { State } from '../../store/rootReducer' import { CreateSignatureEventContent, Meta, ProfileMetadata, SignedEventContent, User, UserRole } from '../../types' import { decryptArrayBuffer, encryptArrayBuffer, generateEncryptionKey, getHash, hexToNpub, parseJson, npubToHex, readContentOfZipEntry, sendDM, shorten, signEventForMetaFile, uploadToFileStorage } from '../../utils' import styles from './style.module.scss' import { Cancel, CheckCircle, Download, HourglassTop } from '@mui/icons-material' enum SignedStatus { Fully_Signed, User_Is_Next_Signer, User_Is_Not_Next_Signer } export const SignPage = () => { const navigate = useNavigate() const [searchParams, setSearchParams] = useSearchParams() const [displayInput, setDisplayInput] = useState(false) const [selectedFile, setSelectedFile] = useState(null) const [encryptionKey, setEncryptionKey] = useState('') const [zip, setZip] = useState() const [isLoading, setIsLoading] = useState(true) const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [meta, setMeta] = useState(null) const [signedStatus, setSignedStatus] = useState() const [submittedBy, setSubmittedBy] = useState() const [signers, setSigners] = useState<`npub1${string}`[]>([]) const [viewers, setViewers] = useState<`npub1${string}`[]>([]) const [creatorFileHashes, setCreatorFileHashes] = useState<{ [key: string]: string }>({}) const [currentFileHashes, setCurrentFileHashes] = useState<{ [key: string]: string | null }>({}) const [signedBy, setSignedBy] = useState<`npub1${string}`[]>([]) const [nextSinger, setNextSinger] = useState() const usersPubkey = useSelector((state: State) => state.auth.usersPubkey) const [authUrl, setAuthUrl] = useState() const nostrController = NostrController.getInstance() useEffect(() => { if (zip) { const generateCurrentFileHashes = async () => { const fileHashes: { [key: string]: string | null } = {} const fileNames = Object.values(zip.files) .filter((entry) => entry.name.startsWith('files/') && !entry.dir) .map((entry) => entry.name) // generate hashes for all entries in files folder of zipArchive // these hashes can be used to verify the originality of files for (const fileName of fileNames) { const arrayBuffer = await readContentOfZipEntry( zip, fileName, 'arraybuffer' ) if (arrayBuffer) { const hash = await getHash(arrayBuffer) if (hash) { fileHashes[fileName.replace(/^files\//, '')] = hash } } else { fileHashes[fileName.replace(/^files\//, '')] = null } } setCurrentFileHashes(fileHashes) } generateCurrentFileHashes() } }, [zip]) useEffect(() => { if (signers.length > 0) { // check if all signers have signed then its fully signed if (signers.every((signer) => signedBy.includes(signer))) { setSignedStatus(SignedStatus.Fully_Signed) } else { for (const signer of signers) { if (!signedBy.includes(signer)) { // signers in meta.json are in npub1 format // so, convert it to hex before setting to nextSigner setNextSinger(npubToHex(signer)!) const usersNpub = hexToNpub(usersPubkey!) if (signer === usersNpub) { // logged in user is the next signer setSignedStatus(SignedStatus.User_Is_Next_Signer) } else { setSignedStatus(SignedStatus.User_Is_Not_Next_Signer) } break } } } } else { // there's no signer just viewers. So its fully signed setSignedStatus(SignedStatus.Fully_Signed) } }, [signers, signedBy, usersPubkey]) useEffect(() => { const fileUrl = searchParams.get('file') const key = searchParams.get('key') if (fileUrl && key) { setIsLoading(true) setLoadingSpinnerDesc('Fetching file from file server') axios .get(fileUrl, { responseType: 'arraybuffer' }) .then((res) => { const fileName = fileUrl.split('/').pop() const file = new File([res.data], fileName!) decrypt(file, decodeURIComponent(key)).then((arrayBuffer) => { if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer) }) }) .catch((err) => { console.error(`error occurred in getting file from ${fileUrl}`, err) toast.error( err.message || `error occurred in getting file from ${fileUrl}` ) }) .finally(() => { setIsLoading(false) }) } else { setIsLoading(false) setDisplayInput(true) } }, [searchParams]) const decrypt = async (file: File, key: string) => { setLoadingSpinnerDesc('Decrypting file') const encryptedArrayBuffer = await file.arrayBuffer() const arrayBuffer = await decryptArrayBuffer(encryptedArrayBuffer, key) .catch((err) => { console.log('err in decryption:>> ', err) toast.error(err.message || 'An error occurred in decrypting file.') return null }) .finally(() => { setIsLoading(false) }) return arrayBuffer } const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => { const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip') setLoadingSpinnerDesc('Parsing zip file') const zip = await JSZip.loadAsync(decryptedZipFile).catch((err) => { console.log('err in loading zip file :>> ', err) toast.error(err.message || 'An error occurred in loading zip file.') return null }) if (!zip) return setZip(zip) setLoadingSpinnerDesc('Parsing meta.json') const metaFileContent = await readContentOfZipEntry( zip, 'meta.json', 'string' ) if (!metaFileContent) { setIsLoading(false) return } const parsedMetaJson = await parseJson(metaFileContent).catch( (err) => { console.log('err in parsing the content of meta.json :>> ', err) toast.error( err.message || 'error occurred in parsing the content of meta.json' ) setIsLoading(false) return null } ) if (!parsedMetaJson) return const createSignatureEvent = await parseJson( parsedMetaJson.createSignature ).catch((err) => { console.log('err in parsing the createSignature event:>> ', err) toast.error( err.message || 'error occurred in parsing the create signature event' ) setIsLoading(false) return null }) if (!createSignatureEvent) return const isValidCreateSignature = verifyEvent(createSignatureEvent) if (!isValidCreateSignature) { toast.error('Create signature is invalid') setIsLoading(false) return } const createSignatureContent = await parseJson( createSignatureEvent.content ).catch((err) => { console.log( `err in parsing the createSignature event's content :>> `, err ) toast.error( err.message || `error occurred in parsing the create signature event's content` ) setIsLoading(false) return null }) if (!createSignatureContent) return setSigners(createSignatureContent.signers) setViewers(createSignatureContent.viewers) setCreatorFileHashes(createSignatureContent.fileHashes) setSubmittedBy(createSignatureEvent.pubkey) setSignedBy(Object.keys(parsedMetaJson.docSignatures) as `npub1${string}`[]) setMeta(parsedMetaJson) } const handleDecrypt = async () => { if (!selectedFile || !encryptionKey) return setIsLoading(true) const arrayBuffer = await decrypt( selectedFile, decodeURIComponent(encryptionKey) ) if (!arrayBuffer) return handleDecryptedArrayBuffer(arrayBuffer) } const handleSign = async () => { if (!zip || !meta) return setIsLoading(true) setLoadingSpinnerDesc('parsing hashes.json file') const hashesFileContent = await readContentOfZipEntry( zip, 'hashes.json', 'string' ) if (!hashesFileContent) { setIsLoading(false) return } let hashes = await parseJson(hashesFileContent).catch((err) => { console.log('err in parsing the content of hashes.json :>> ', err) toast.error( err.message || 'error occurred in parsing the content of hashes.json' ) setIsLoading(false) return null }) if (!hashes) return setLoadingSpinnerDesc('Generating hashes for files') setLoadingSpinnerDesc('Signing nostr event') const prevSig = getPrevSignersSig(hexToNpub(usersPubkey!)) if (!prevSig) return const signedEvent = await signEventForMetaFile( JSON.stringify({ prevSig }), nostrController, setIsLoading ) if (!signedEvent) return const metaCopy = _.cloneDeep(meta) metaCopy.docSignatures = { ...metaCopy.docSignatures, [hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2) } const stringifiedMeta = JSON.stringify(metaCopy, null, 2) zip.file('meta.json', stringifiedMeta) const metaHash = await getHash(stringifiedMeta) if (!metaHash) return hashes = { ...hashes, [usersPubkey!]: metaHash } zip.file('hashes.json', JSON.stringify(hashes, null, 2)) const arrayBuffer = await zip .generateAsync({ type: 'arraybuffer', compression: 'DEFLATE', compressionOptions: { level: 6 } }) .catch((err) => { console.log('err in zip:>> ', err) setIsLoading(false) toast.error(err.message || 'Error occurred in generating zip file') return null }) if (!arrayBuffer) return const key = await generateEncryptionKey() setLoadingSpinnerDesc('Encrypting zip file') const encryptedArrayBuffer = await encryptArrayBuffer(arrayBuffer, key) const blob = new Blob([encryptedArrayBuffer]) setLoadingSpinnerDesc('Uploading zip file to file storage.') const fileUrl = await uploadToFileStorage(blob, nostrController) .then((url) => { toast.success('zip file uploaded to file storage') return url }) .catch((err) => { console.log('err in upload:>> ', err) setIsLoading(false) toast.error(err.message || 'Error occurred in uploading zip file') return null }) if (!fileUrl) return // check if the current user is the last signer const usersNpub = hexToNpub(usersPubkey!) const lastSignerIndex = signers.length - 1 const signerIndex = signers.indexOf(usersNpub) const isLastSigner = signerIndex === lastSignerIndex // if current user is the last signer, then send DMs to all signers and viewers if (isLastSigner) { const userSet = new Set<`npub1${string}`>() if (submittedBy) { userSet.add(hexToNpub(submittedBy)) } signers.forEach((signer) => { userSet.add(signer) }) viewers.forEach((viewer) => { userSet.add(viewer) }) const users = Array.from(userSet) for (const user of users) { // todo: execute in parallel await sendDM( fileUrl, key, npubToHex(user)!, nostrController, false, setAuthUrl ) } } else { const nextSigner = signers[signerIndex + 1] await sendDM( fileUrl, key, npubToHex(nextSigner)!, nostrController, true, setAuthUrl ) } setIsLoading(false) // update search params with updated file url and encryption key setSearchParams({ file: fileUrl, key: key }) } const handleExport = async () => { if (!meta || !zip || !usersPubkey) return const usersNpub = hexToNpub(usersPubkey) if ( !signers.includes(usersNpub) && !viewers.includes(usersNpub) && submittedBy !== usersNpub ) return setIsLoading(true) setLoadingSpinnerDesc('Signing nostr event') const prevSig = await getLastSignersSig() if (!prevSig) return const signedEvent = await signEventForMetaFile( JSON.stringify({ prevSig }), nostrController, setIsLoading ) if (!signedEvent) return const exportSignature = JSON.stringify(signedEvent, null, 2) const stringifiedMeta = JSON.stringify( { ...meta, exportSignature }, null, 2 ) zip.file('meta.json', stringifiedMeta) const arrayBuffer = await zip .generateAsync({ type: 'arraybuffer', compression: 'DEFLATE', compressionOptions: { level: 6 } }) .catch((err) => { console.log('err in zip:>> ', err) setIsLoading(false) toast.error(err.message || 'Error occurred in generating zip file') return null }) if (!arrayBuffer) return const blob = new Blob([arrayBuffer]) saveAs(blob, 'exported.zip') setIsLoading(false) navigate(appPrivateRoutes.verify) } /** * This function accepts an npub of a signer and return the signature of its previous signer. * This prevSig will be used in the content of the provided signer's signedEvent */ const getPrevSignersSig = (npub: string) => { if (!meta) return null // if user is first signer then use creator's signature if (signers[0] === npub) { try { const createSignatureEvent: Event = JSON.parse(meta.createSignature) return createSignatureEvent.sig } catch (error) { return null } } // find the index of signer const currentSignerIndex = signers.findIndex((signer) => signer === npub) // return null if could not found user in signer's list if (currentSignerIndex === -1) return null // find prev signer const prevSigner = signers[currentSignerIndex - 1] // get the signature of prev signer try { const prevSignersEvent: Event = JSON.parse(meta.docSignatures[prevSigner]) return prevSignersEvent.sig } catch (error) { return null } } /** * This function returns the signature of last signer * It will be used in the content of export signature's signedEvent */ const getLastSignersSig = () => { if (!meta) return null // if there're no signers then use creator's signature if (signers.length === 0) { try { const createSignatureEvent: Event = JSON.parse(meta.createSignature) return createSignatureEvent.sig } catch (error) { return null } } // get last signer const lastSigner = signers[signers.length - 1] // get the signature of last signer try { const lastSignatureEvent: Event = JSON.parse( meta.docSignatures[lastSigner] ) return lastSignatureEvent.sig } catch (error) { return null } } if (authUrl) { return (