import { Box, Button, Typography } 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 { useLocation, useNavigate } from 'react-router-dom' import { toast } from 'react-toastify' import { LoadingSpinner } from '../../components/LoadingSpinner' import { NostrController } from '../../controllers' import { appPublicRoutes } from '../../routes' import { State } from '../../store/rootReducer' import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types' import { decryptArrayBuffer, encryptArrayBuffer, extractZipUrlAndEncryptionKey, generateEncryptionKey, generateKeysFile, getHash, hexToNpub, isOnline, loadZip, now, npubToHex, parseJson, readContentOfZipEntry, sendNotification, signEventForMetaFile, updateUsersAppData } from '../../utils' import { DisplayMeta } from './internal/displayMeta' import styles from './style.module.scss' import { PdfFile } from '../../types/drawing.ts' import { convertToPdfFile } from '../../utils/pdf.ts' import PdfView from '../../components/PDFView' import { CurrentUserMark, Mark, MarkConfig } from '../../types/mark.ts' import MarkFormField from './MarkFormField.tsx' import { getLastSignersSig } from '../../utils/sign.ts' enum SignedStatus { Fully_Signed, User_Is_Next_Signer, User_Is_Not_Next_Signer } export const SignPage = () => { const navigate = useNavigate() const location = useLocation() /** * uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains keys.json * arrayBuffer will be received in navigation from create page in offline mode * meta will be received in navigation from create & home page in online mode */ const { meta: metaInNavState, arrayBuffer: decryptedArrayBuffer, uploadedZip } = location.state || {} const [displayInput, setDisplayInput] = useState(false) const [selectedFile, setSelectedFile] = useState(null) const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({}) 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 [marks, setMarks] = useState([]) 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() // This state variable indicates whether the logged-in user is a signer, a creator, or neither. const [isSignerOrCreator, setIsSignerOrCreator] = useState(false) const usersPubkey = useSelector((state: State) => state.auth.usersPubkey) const [authUrl, setAuthUrl] = useState() const nostrController = NostrController.getInstance() const [currentUserMark, setCurrentUserMark] = useState(null); const [currentUserMarks, setCurrentUserMarks] = useState([]); const [currentMarkValue, setCurrentMarkValue] = useState(''); const [isMarksCompleted, setIsMarksCompleted] = useState(false); 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) } // Determine and set the status of the user if (submittedBy && usersPubkey && submittedBy === usersPubkey) { // If the submission was made by the user, set the status to true setIsSignerOrCreator(true) } else if (usersPubkey) { // Convert the user's public key from hex to npub format const usersNpub = hexToNpub(usersPubkey) if (signers.includes(usersNpub)) { // If the user's npub is in the list of signers, set the status to true setIsSignerOrCreator(true) } } }, [signers, signedBy, usersPubkey, submittedBy]) useEffect(() => { const handleUpdatedMeta = async (meta: Meta) => { const createSignatureEvent = await parseJson( meta.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) setMarks(createSignatureContent.markConfig); console.log('createSignatureContent markConfig', createSignatureContent); if (usersPubkey) { console.log('this runs behind users pubkey'); const curMarks = getCurrentUserMarks(createSignatureContent.markConfig, usersPubkey) if (curMarks.length === 0) { setIsMarksCompleted(true) } else { const nextMark = findNextIncompleteMark(curMarks) if (!nextMark) { setIsMarksCompleted(true) } else { setCurrentUserMark(nextMark) setIsMarksCompleted(false) } setCurrentUserMarks(curMarks) } } setSignedBy(Object.keys(meta.docSignatures) as `npub1${string}`[]) } if (meta) { handleUpdatedMeta(meta) } }, [meta]) useEffect(() => { if (metaInNavState) { const processSigit = async () => { setIsLoading(true) setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta') const res = await extractZipUrlAndEncryptionKey(metaInNavState) if (!res) { setIsLoading(false) return } const { zipUrl, encryptionKey } = res setLoadingSpinnerDesc('Fetching file from file server') axios .get(zipUrl, { responseType: 'arraybuffer' }) .then((res) => { handleArrayBufferFromBlossom(res.data, encryptionKey) setMeta(metaInNavState) console.log('meta in nav state: ', metaInNavState) }) .catch((err) => { console.error(`error occurred in getting file from ${zipUrl}`, err) toast.error( err.message || `error occurred in getting file from ${zipUrl}` ) }) .finally(() => { setIsLoading(false) }) } processSigit() } else if (decryptedArrayBuffer) { handleDecryptedArrayBuffer(decryptedArrayBuffer).finally(() => setIsLoading(false) ) } else if (uploadedZip) { decrypt(uploadedZip) .then((arrayBuffer) => { if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer) }) .catch((err) => { console.error(`error occurred in decryption`, err) toast.error(err.message || `error occurred in decryption`) }) .finally(() => { setIsLoading(false) }) } else { setIsLoading(false) setDisplayInput(true) } }, [decryptedArrayBuffer, uploadedZip, metaInNavState]) const handleArrayBufferFromBlossom = async ( arrayBuffer: ArrayBuffer, encryptionKey: string ) => { // array buffer returned from blossom is encrypted. // So, first decrypt it const decrypted = await decryptArrayBuffer( arrayBuffer, encryptionKey ).catch((err) => { console.log('err in decryption:>> ', err) toast.error(err.message || 'An error occurred in decrypting file.') setIsLoading(false) return null }) if (!decrypted) return const zip = await loadZip(decrypted) if (!zip) { setIsLoading(false) return } const files: { [filename: string]: PdfFile } = {} const fileHashes: { [key: string]: string | null } = {} const fileNames = Object.values(zip.files).map((entry) => entry.name) // generate hashes for all files in 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) { files[fileName] = await convertToPdfFile(arrayBuffer, fileName); const hash = await getHash(arrayBuffer) if (hash) { fileHashes[fileName] = hash } } else { fileHashes[fileName] = null } } console.log('processed files: ', files); setFiles(files) setCurrentFileHashes(fileHashes) } const parseKeysJson = async (zip: JSZip) => { const keysFileContent = await readContentOfZipEntry( zip, 'keys.json', 'string' ) if (!keysFileContent) return null const parsedJSON = await parseJson<{ sender: string; keys: string[] }>( keysFileContent ).catch((err) => { console.log(`Error parsing content of keys.json:`, err) toast.error(err.message || `Error parsing content of keys.json`) return null }) return parsedJSON } const decrypt = async (file: File) => { setLoadingSpinnerDesc('Decrypting file') const zip = await loadZip(file); if (!zip) return const parsedKeysJson = await parseKeysJson(zip) if (!parsedKeysJson) return const encryptedArrayBuffer = await readContentOfZipEntry( zip, 'compressed.sigit', 'arraybuffer' ) if (!encryptedArrayBuffer) return const { keys, sender } = parsedKeysJson for (const key of keys) { // Set up event listener for authentication event nostrController.on('nsecbunker-auth', (url) => { setAuthUrl(url) }) // Set up timeout promise to handle encryption timeout const timeoutPromise = new Promise((_, reject) => { setTimeout(() => { reject(new Error('Timeout occurred')) }, 60000) // Timeout duration = 60 seconds }) // decrypt the encryptionKey, with timeout const encryptionKey = await Promise.race([ nostrController.nip04Decrypt(sender, key), timeoutPromise ]) .then((res) => { return res }) .catch((err) => { console.log('err :>> ', err) return null }) .finally(() => { setAuthUrl(undefined) // Clear authentication URL }) // Return if encryption failed if (!encryptionKey) continue const arrayBuffer = await decryptArrayBuffer( encryptedArrayBuffer, encryptionKey ) .catch((err) => { console.log('err in decryption:>> ', err) return null }) .finally(() => { setIsLoading(false) }) if (arrayBuffer) return arrayBuffer } return null } const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => { const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip') setLoadingSpinnerDesc('Parsing zip file') const zip = await loadZip(decryptedZipFile) if (!zip) return const files: { [filename: string]: PdfFile } = {} const fileHashes: { [key: string]: string | null } = {} const fileNames = Object.values(zip.files) .filter((entry) => entry.name.startsWith('files/') && !entry.dir) .map((entry) => entry.name) .map((entry) => entry.replace(/^files\//, '')) // 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) { files[fileName] = await convertToPdfFile(arrayBuffer, fileName); const hash = await getHash(arrayBuffer) if (hash) { fileHashes[fileName] = hash } } else { fileHashes[fileName] = null } } console.log('processed files: ', files); setFiles(files) setCurrentFileHashes(fileHashes) setDisplayInput(false) 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 } ) setMeta(parsedMetaJson) } const handleDecrypt = async () => { if (!selectedFile) return setIsLoading(true) const arrayBuffer = await decrypt(selectedFile) if (!arrayBuffer) return handleDecryptedArrayBuffer(arrayBuffer) } const handleSign = async () => { if (Object.entries(files).length === 0 || !meta) return setIsLoading(true) setLoadingSpinnerDesc('Signing nostr event') const prevSig = getPrevSignersSig(hexToNpub(usersPubkey!)) if (!prevSig) return const marks = getSignerMarksForMeta() if (!marks) return const signedEvent = await signEventForMeta({ prevSig, marks }) if (!signedEvent) return const updatedMeta = updateMetaSignatures(meta, signedEvent) if (await isOnline()) { await handleOnlineFlow(updatedMeta) } else { setMeta(updatedMeta) setIsLoading(false) } } // Sign the event for the meta file const signEventForMeta = async (signerContent: { prevSig: string, marks: Mark[] }) => { return await signEventForMetaFile( JSON.stringify(signerContent), nostrController, setIsLoading ) } const getSignerMarksForMeta = (): Mark[] | undefined => { if (currentUserMarks.length === 0) return; return currentUserMarks.map(( { mark }: CurrentUserMark) => mark); } const handleMarkClick = (id: number) => { const nextMark = currentUserMarks.find(mark => mark.mark.id === id) setCurrentUserMark(nextMark!) setCurrentMarkValue(nextMark?.mark.value || "") } const getMarkConfigPerUser = (markConfig: MarkConfig) => { if (!usersPubkey) return; return markConfig[hexToNpub(usersPubkey)]; } const handleChange = (event: any) => setCurrentMarkValue(event.target.value); const handleSubmit = (event: any) => { event.preventDefault(); if (!currentMarkValue || !currentUserMark) return; const curMark = { ...currentUserMark.mark, value: currentMarkValue }; const indexToUpdate = marks.findIndex(mark => mark.id === curMark.id); const updatedMarks: Mark[] = [ ...marks.slice(0, indexToUpdate), curMark, ...marks.slice(indexToUpdate + 1) ]; setMarks(updatedMarks) setCurrentMarkValue("") const updatedCurUserMarks = getCurrentUserMarks(updatedMarks, usersPubkey!) console.log('updatedCurUserMarks: ', updatedCurUserMarks) setCurrentUserMarks(updatedCurUserMarks) const nextMark = findNextIncompleteMark(updatedCurUserMarks) console.log('next mark: ', nextMark) if (!nextMark) { setCurrentUserMark(null) setIsMarksCompleted(true) } else { setCurrentUserMark(nextMark) setIsMarksCompleted(false) } } const findNextIncompleteMark = (usersMarks: CurrentUserMark[]): CurrentUserMark | undefined => { return usersMarks.find(mark => !mark.isCompleted); } // Update the meta signatures const updateMetaSignatures = (meta: Meta, signedEvent: SignedEvent): Meta => { const metaCopy = _.cloneDeep(meta) metaCopy.docSignatures = { ...metaCopy.docSignatures, [hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2) } metaCopy.modifiedAt = now() console.log('meta copy: ', metaCopy); return metaCopy } // create final zip file const createFinalZipFile = async ( encryptedArrayBuffer: ArrayBuffer, encryptionKey: string ): Promise => { // Get the current timestamp in seconds const unixNow = now() const blob = new Blob([encryptedArrayBuffer]) // Create a File object with the Blob data const file = new File([blob], `compressed.sigit`, { type: 'application/sigit' }) const isLastSigner = checkIsLastSigner(signers) const userSet = new Set() if (isLastSigner) { if (submittedBy) { userSet.add(submittedBy) } signers.forEach((signer) => { userSet.add(npubToHex(signer)!) }) viewers.forEach((viewer) => { userSet.add(npubToHex(viewer)!) }) } else { const usersNpub = hexToNpub(usersPubkey!) const signerIndex = signers.indexOf(usersNpub) const nextSigner = signers[signerIndex + 1] userSet.add(npubToHex(nextSigner)!) } const keysFileContent = await generateKeysFile( Array.from(userSet), encryptionKey ) if (!keysFileContent) return null const zip = new JSZip() zip.file(`compressed.sigit`, file) zip.file('keys.json', keysFileContent) const arraybuffer = await zip .generateAsync({ type: 'arraybuffer', compression: 'DEFLATE', compressionOptions: { level: 6 } }) .catch(handleZipError) if (!arraybuffer) return null const finalZipFile = new File( [new Blob([arraybuffer])], `${unixNow}.sigit.zip`, { type: 'application/zip' } ) return finalZipFile } // Handle errors during zip file generation const handleZipError = (err: any) => { console.log('Error in zip:>> ', err) setIsLoading(false) toast.error(err.message || 'Error occurred in generating zip file') return null } // Handle the online flow: update users app data and send notifications const handleOnlineFlow = async (meta: Meta) => { setLoadingSpinnerDesc('Updating users app data') const updatedEvent = await updateUsersAppData(meta) if (!updatedEvent) { setIsLoading(false) return } const userSet = new Set<`npub1${string}`>() if (submittedBy && submittedBy !== usersPubkey) { userSet.add(hexToNpub(submittedBy)) } const usersNpub = hexToNpub(usersPubkey!) const isLastSigner = checkIsLastSigner(signers) if (isLastSigner) { signers.forEach((signer) => { if (signer !== usersNpub) { userSet.add(signer) } }) viewers.forEach((viewer) => { userSet.add(viewer) }) } else { const currentSignerIndex = signers.indexOf(usersNpub) const prevSigners = signers.slice(0, currentSignerIndex) prevSigners.forEach((signer) => { userSet.add(signer) }) const nextSigner = signers[currentSignerIndex + 1] userSet.add(nextSigner) } setLoadingSpinnerDesc('Sending notifications') const users = Array.from(userSet) const promises = users.map((user) => sendNotification(npubToHex(user)!, meta) ) await Promise.all(promises) .then(() => { toast.success('Notifications sent successfully') console.log('meta: ', meta); setMeta(meta) }) .catch(() => { toast.error('Failed to publish notifications') }) setIsLoading(false) } // Check if the current user is the last signer const checkIsLastSigner = (signers: string[]): boolean => { const usersNpub = hexToNpub(usersPubkey!) const lastSignerIndex = signers.length - 1 const signerIndex = signers.indexOf(usersNpub) return signerIndex === lastSignerIndex } const handleExport = async () => { if (Object.entries(files).length === 0 || !meta || !usersPubkey) return const usersNpub = hexToNpub(usersPubkey) if ( !signers.includes(usersNpub) && !viewers.includes(usersNpub) && submittedBy !== usersNpub ) return setIsLoading(true) setLoadingSpinnerDesc('Signing nostr event') if (!meta) return; const prevSig = getLastSignersSig(meta, signers) 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 ) const zip = new JSZip() zip.file('meta.json', stringifiedMeta) Object.entries(files).forEach(([fileName, arrayBuffer]) => { zip.file(`files/${fileName}`, arrayBuffer) }) 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]) const unixNow = now() saveAs(blob, `exported-${unixNow}.sigit.zip`) setIsLoading(false) navigate(appPublicRoutes.verify) } const getCurrentUserMarks = (marks: Mark[], pubkey: string): CurrentUserMark[] => { console.log('marks: ', marks); const filteredMarks = marks .filter(mark => mark.npub === hexToNpub(pubkey)) const currentMarks = filteredMarks .map((mark, index, arr) => { return { mark, isLast: isLast(index, arr), isCompleted: !!mark.value } }) console.log('current marks: ', currentMarks) return currentMarks; } const isLast = (index: number, arr: any[]) => (index === (arr.length -1)) const handleExportSigit = async () => { if (Object.entries(files).length === 0 || !meta) return const zip = new JSZip() const stringifiedMeta = JSON.stringify(meta, null, 2) zip.file('meta.json', stringifiedMeta) Object.entries(files).forEach(([fileName, arrayBuffer]) => { zip.file(`files/${fileName}`, arrayBuffer) }) 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 finalZipFile = await createFinalZipFile(encryptedArrayBuffer, key) if (!finalZipFile) return const unixNow = now() saveAs(finalZipFile, `exported-${unixNow}.sigit.zip`) } /** * 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 } } if (authUrl) { return (