feat: update signing flow

This commit is contained in:
SwiftHawk 2024-05-14 14:27:05 +05:00
parent e479156270
commit 1f9954befd
12 changed files with 1336 additions and 846 deletions

View File

@ -1,13 +1,9 @@
import { Menu as MenuIcon } from '@mui/icons-material'
import { import {
AppBar as AppBarMui, AppBar as AppBarMui,
Box, Box,
Button, Button,
IconButton,
Menu, Menu,
MenuItem, MenuItem,
Tab,
Tabs,
Toolbar, Toolbar,
Typography Typography
} from '@mui/material' } from '@mui/material'
@ -19,14 +15,10 @@ import { State } from '../../store/rootReducer'
import { Dispatch } from '../../store/store' import { Dispatch } from '../../store/store'
import Username from '../username' import Username from '../username'
import { Link, useLocation, useNavigate } from 'react-router-dom' import { Link, useNavigate } from 'react-router-dom'
import nostrichAvatar from '../../assets/images/avatar.png' import nostrichAvatar from '../../assets/images/avatar.png'
import { NostrController } from '../../controllers' import { NostrController } from '../../controllers'
import { import { appPublicRoutes, getProfileRoute } from '../../routes'
appPrivateRoutes,
appPublicRoutes,
getProfileRoute
} from '../../routes'
import { import {
clearAuthToken, clearAuthToken,
saveNsecBunkerDelegatedKey, saveNsecBunkerDelegatedKey,
@ -34,20 +26,14 @@ import {
} from '../../utils' } from '../../utils'
import styles from './style.module.scss' import styles from './style.module.scss'
const validTabs = [appPrivateRoutes.homePage, appPrivateRoutes.decryptZip]
export const AppBar = () => { export const AppBar = () => {
const navigate = useNavigate() const navigate = useNavigate()
const { pathname } = useLocation()
const [tabValue, setTabValue] = useState(
validTabs.includes(pathname) ? pathname : '/'
)
const dispatch: Dispatch = useDispatch() const dispatch: Dispatch = useDispatch()
const [username, setUsername] = useState('') const [username, setUsername] = useState('')
const [userAvatar, setUserAvatar] = useState(nostrichAvatar) const [userAvatar, setUserAvatar] = useState(nostrichAvatar)
const [anchorElUser, setAnchorElUser] = useState<null | HTMLElement>(null) const [anchorElUser, setAnchorElUser] = useState<null | HTMLElement>(null)
const [anchorElNav, setAnchorElNav] = useState<null | HTMLElement>(null)
const authState = useSelector((state: State) => state.auth) const authState = useSelector((state: State) => state.auth)
const metadataState = useSelector((state: State) => state.metadata) const metadataState = useSelector((state: State) => state.metadata)
@ -66,18 +52,10 @@ export const AppBar = () => {
setAnchorElUser(event.currentTarget) setAnchorElUser(event.currentTarget)
} }
const handleOpenNavMenu = (event: React.MouseEvent<HTMLElement>) => {
setAnchorElNav(event.currentTarget)
}
const handleCloseUserMenu = () => { const handleCloseUserMenu = () => {
setAnchorElUser(null) setAnchorElUser(null)
} }
const handleCloseNavMenu = () => {
setAnchorElNav(null)
}
const handleProfile = () => { const handleProfile = () => {
const hexKey = authState?.usersPubkey const hexKey = authState?.usersPubkey
if (hexKey) navigate(getProfileRoute(hexKey)) if (hexKey) navigate(getProfileRoute(hexKey))
@ -111,116 +89,8 @@ export const AppBar = () => {
return ( return (
<AppBarMui position='fixed' className={styles.AppBar}> <AppBarMui position='fixed' className={styles.AppBar}>
<Toolbar className={styles.toolbar}> <Toolbar className={styles.toolbar}>
<Box sx={{ display: { xs: 'none', md: 'flex' } }}>
<Box className={styles.logoWrapper}> <Box className={styles.logoWrapper}>
<img src="/logo.png" alt='Logo' onClick={() => navigate('/')} /> <img src='/logo.png' alt='Logo' onClick={() => navigate('/')} />
</Box>
{isAuthenticated && (
<Tabs
indicatorColor='secondary'
value={tabValue}
onChange={(_, value) => setTabValue(value)}
>
<Tab
label='Home'
value={appPrivateRoutes.homePage}
to={appPrivateRoutes.homePage}
component={Link}
/>
<Tab
label='Decrypt Zip'
value={appPrivateRoutes.decryptZip}
to={appPrivateRoutes.decryptZip}
component={Link}
/>
<Tab
label='Sign Document'
value={appPrivateRoutes.sign}
to={appPrivateRoutes.sign}
component={Link}
/>
</Tabs>
)}
</Box>
<Box sx={{ flexGrow: 1, display: { xs: 'flex', md: 'none' } }}>
{!isAuthenticated && (
<Box className={styles.logoWrapper}>
<img
src="/logo.png"
alt='Logo'
onClick={() => navigate('/')}
/>
</Box>
)}
{isAuthenticated && (
<>
<IconButton
size='large'
onClick={handleOpenNavMenu}
color='primary'
>
<MenuIcon />
</IconButton>
<Menu
id='menu-appbar'
anchorEl={anchorElNav}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left'
}}
keepMounted
transformOrigin={{
vertical: 'top',
horizontal: 'left'
}}
open={!!anchorElNav}
onClose={handleCloseNavMenu}
sx={{
display: { xs: 'block', md: 'none' }
}}
>
<MenuItem sx={{ justifyContent: 'center' }}>
<Button
component={Link}
to={appPrivateRoutes.homePage}
onClick={handleCloseNavMenu}
variant='contained'
color='primary'
>
Home
</Button>
</MenuItem>
<MenuItem sx={{ justifyContent: 'center' }}>
<Button
component={Link}
to={appPrivateRoutes.decryptZip}
onClick={handleCloseNavMenu}
variant='contained'
color='primary'
>
Decrypt Zip
</Button>
</MenuItem>
<MenuItem sx={{ justifyContent: 'center' }}>
<Button
component={Link}
to={appPrivateRoutes.sign}
onClick={handleCloseNavMenu}
variant='contained'
color='primary'
>
Sign Document
</Button>
</MenuItem>
</Menu>
</>
)}
</Box> </Box>
<Box className={styles.rightSideBox}> <Box className={styles.rightSideBox}>

View File

@ -1,489 +1,20 @@
import { Clear } from '@mui/icons-material' import { Box, Button } from '@mui/material'
import {
Box,
Button,
FormControl,
IconButton,
InputLabel,
List,
ListItem,
ListSubheader,
MenuItem,
Select,
TextField,
Typography
} from '@mui/material'
import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input'
import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { Link } from 'react-router-dom'
import { toast } from 'react-toastify'
import placeholderAvatar from '../../assets/images/nostr-logo.jpg'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { MetadataController, NostrController } from '../../controllers'
import { getProfileRoute } from '../../routes'
import { State } from '../../store/rootReducer'
import { ProfileMetadata } from '../../types'
import {
encryptArrayBuffer,
generateEncryptionKey,
getHash,
pubToHex,
queryNip05,
sendDM,
shorten,
signEventForMetaFile,
uploadToFileStorage
} from '../../utils'
import styles from './style.module.scss' import styles from './style.module.scss'
import { useNavigate } from 'react-router-dom'
enum SelectionType { import { appPrivateRoutes } from '../../routes'
signer = 'Signer',
viewer = 'Viewer'
}
export const HomePage = () => { export const HomePage = () => {
const [inputValue, setInputValue] = useState('') const navigate = useNavigate()
const [type, setType] = useState<SelectionType>(SelectionType.signer)
const [error, setError] = useState<string>()
const [signers, setSigners] = useState<string[]>([])
const [viewers, setViewers] = useState<string[]>([])
const [selectedFiles, setSelectedFiles] = useState<File[]>([])
const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [authUrl, setAuthUrl] = useState<string>()
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const nostrController = NostrController.getInstance()
const handleAddClick = async () => {
setError(undefined)
const addPubkey = (pubkey: string) => {
const addElement = (prev: string[]) => {
// if key is already in the list just return that
if (prev.includes(pubkey)) return prev
return [...prev, pubkey]
}
if (type === SelectionType.signer) {
setSigners(addElement)
} else {
setViewers(addElement)
}
}
if (inputValue.startsWith('npub')) {
const pubkey = await pubToHex(inputValue)
if (pubkey) {
addPubkey(pubkey)
setInputValue('')
} else {
setError('Provided npub is not valid. Please enter correct npub.')
}
return
}
if (inputValue.includes('@')) {
setIsLoading(true)
setLoadingSpinnerDesc('Querying for nip05')
const nip05Profile = await queryNip05(inputValue)
.catch((err) => {
console.error(`error occurred in querying nip05: ${inputValue}`, err)
return null
})
.finally(() => {
setIsLoading(false)
setLoadingSpinnerDesc('')
})
if (nip05Profile) {
const pubkey = nip05Profile.pubkey
addPubkey(pubkey)
setInputValue('')
} else {
setError('Provided nip05 is not valid. Please enter correct nip05.')
}
return
}
setError('Invalid input! Make sure to provide correct npub or nip05.')
}
const handleRemove = (pubkey: string, selectionType: SelectionType) => {
if (selectionType === SelectionType.signer) {
setSigners((prev) => prev.filter((signer) => signer !== pubkey))
} else {
setViewers((prev) => prev.filter((viewer) => viewer !== pubkey))
}
}
const handleSelectFiles = (files: File[]) => {
setSelectedFiles((prev) => {
const prevFileNames = prev.map((file) => file.name)
const newFiles = files.filter(
(file) => !prevFileNames.includes(file.name)
)
return [...prev, ...newFiles]
})
}
const handleRemoveFile = (fileToRemove: File) => {
setSelectedFiles((prevFiles) =>
prevFiles.filter((file) => file.name !== fileToRemove.name)
)
}
const handleSubmit = async () => {
if (signers.length === 0) {
toast.error('No signer is provided. At least provide one signer.')
return
}
if (viewers.length === 0) {
toast.error('No viewer is provided. At least provide one viewer.')
return
}
if (selectedFiles.length === 0) {
toast.error('No file is provided. At least provide one file.')
return
}
setIsLoading(true)
setLoadingSpinnerDesc('Generating hashes for files')
const fileHashes: { [key: string]: string } = {}
for (const file of selectedFiles) {
const arraybuffer = await file.arrayBuffer().catch((err) => {
console.log(
`err while getting arrayBuffer of file ${file.name} :>> `,
err
)
toast.error(
err.message || `err while getting arrayBuffer of file ${file.name}`
)
return null
})
if (!arraybuffer) return
const hash = await getHash(arraybuffer)
if (!hash) {
setIsLoading(false)
return
}
fileHashes[file.name] = hash
}
const zip = new JSZip()
selectedFiles.forEach((file) => {
zip.file(`files/${file.name}`, file)
})
setLoadingSpinnerDesc('Signing nostr event')
const signedEvent = await signEventForMetaFile(
signers[0],
fileHashes,
nostrController,
setIsLoading
)
if (!signedEvent) return
const meta = {
signers,
viewers,
fileHashes,
submittedBy: usersPubkey,
signedEvents: {
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
}
}
try {
const stringifiedMeta = JSON.stringify(meta, null, 2)
zip.file('meta.json', stringifiedMeta)
const metaHash = await getHash(stringifiedMeta)
if (!metaHash) return
const metaHashJson = {
[usersPubkey!]: metaHash
}
zip.file('hashes.json', JSON.stringify(metaHashJson, null, 2))
} catch (err) {
toast.error('An error occurred in converting meta json to string')
}
setLoadingSpinnerDesc('Generating zip file')
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 encryptionKey = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer(
arraybuffer,
encryptionKey
)
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
setLoadingSpinnerDesc('Sending DM to first signer')
await sendDM(
fileUrl,
encryptionKey,
signers[0],
nostrController,
true,
setAuthUrl
)
setIsLoading(false)
}
if (authUrl) {
return (
<iframe
title='Nsecbunker auth'
src={authUrl}
width='100%'
height='500px'
/>
)
}
return ( return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}> <Box className={styles.container}>
<Typography component='label' variant='h6'>
Select signers and viewers
</Typography>
<Box className={styles.inputBlock}>
<TextField
label='nip05 / npub'
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
helperText={error}
error={!!error}
/>
<FormControl fullWidth>
<InputLabel id='select-type-label'>Type</InputLabel>
<Select
labelId='select-type-label'
id='demo-simple-select'
value={type}
label='Type'
onChange={(e) => setType(e.target.value as SelectionType)}
>
<MenuItem value={SelectionType.signer}>
{SelectionType.signer}
</MenuItem>
<MenuItem value={SelectionType.viewer}>
{SelectionType.viewer}
</MenuItem>
</Select>
</FormControl>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button <Button
disabled={!inputValue} onClick={() => navigate(appPrivateRoutes.sign)}
onClick={handleAddClick}
variant='contained' variant='contained'
> >
Add Sign
</Button> </Button>
<Button variant='contained'>Verify</Button>
</Box> </Box>
</Box>
<Typography component='label' variant='h6'>
Select files
</Typography>
<MuiFileInput
multiple
placeholder='Choose Files'
value={selectedFiles}
onChange={(value) => handleSelectFiles(value)}
/>
<ul>
{selectedFiles.map((file, index) => (
<li key={index}>
<Typography component='label'>{file.name}</Typography>
<IconButton onClick={() => handleRemoveFile(file)}>
<Clear style={{ color: 'red' }} />{' '}
</IconButton>
</li>
))}
</ul>
{signers.length > 0 && (
<List
sx={{
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader
sx={{
paddingBottom: 1,
paddingTop: 1,
fontSize: '1.5rem'
}}
className={styles.subHeader}
>
Signers
</ListSubheader>
}
>
{signers.map((signer, index) => (
<DisplaySignerOrViewer
key={`signer-${index}`}
pubkey={signer}
remove={() => handleRemove(signer, SelectionType.signer)}
/>
))}
</List>
)}
{viewers.length > 0 && (
<List
sx={{
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader
sx={{
paddingBottom: 1,
paddingTop: 1,
fontSize: '1.5rem'
}}
className={styles.subHeader}
>
Viewers
</ListSubheader>
}
>
{viewers.map((viewer, index) => (
<DisplaySignerOrViewer
key={`viewer-${index}`}
pubkey={viewer}
remove={() => handleRemove(viewer, SelectionType.viewer)}
/>
))}
</List>
)}
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleSubmit} variant='contained'>
Submit
</Button>
</Box>
</Box>
</>
)
}
type DisplaySignerOrViewerProps = {
pubkey: string
remove: () => void
}
const DisplaySignerOrViewer = ({
pubkey,
remove
}: DisplaySignerOrViewerProps) => {
const [metadata, setMetadata] = useState<ProfileMetadata>()
useEffect(() => {
const getMetadata = async (pubkey: string) => {
const metadataController = new MetadataController()
const metadataEvent = await metadataController
.findMetadata(pubkey)
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${pubkey}`,
err
)
return null
})
if (metadataEvent) {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent) setMetadata(metadataContent)
}
}
getMetadata(pubkey)
}, [pubkey])
const imageLoadError = (event: any) => {
event.target.src = placeholderAvatar
}
return (
<ListItem sx={{ marginTop: 1 }} className={styles.listItem}>
<img
onError={imageLoadError}
src={metadata?.picture || placeholderAvatar}
alt='Profile Image'
className={styles.img}
/>
<Link to={getProfileRoute(pubkey)}>
<Typography component='label' className={styles.name}>
{metadata?.display_name || metadata?.name || shorten(pubkey)}
</Typography>
</Link>
<IconButton onClick={remove}>
<Clear style={{ color: 'red' }} />
</IconButton>
</ListItem>
) )
} }

View File

@ -1,33 +1,6 @@
@import '../../colors.scss';
.container { .container {
display: flex;
flex-direction: column;
color: $text-color;
.inputBlock {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 25px; gap: 25px;
margin-top: 10px; margin-top: 10px;
} }
}
.subHeader {
border-bottom: 0.5px solid;
}
.listItem {
display: flex;
align-items: center;
justify-content: space-between !important;
.img {
max-width: 100px;
}
.name {
text-align: center;
cursor: pointer;
}
}

View File

@ -1,192 +1,271 @@
import { Box, Button, Typography } from '@mui/material' import { Clear } from '@mui/icons-material'
import {
Box,
Button,
FormControl,
IconButton,
InputLabel,
MenuItem,
Paper,
Select,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
TextField,
Tooltip,
Typography
} from '@mui/material'
import { MuiFileInput } from 'mui-file-input' import { MuiFileInput } from 'mui-file-input'
import { useState } from 'react' import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import placeholderAvatar from '../../assets/images/nostr-logo.jpg'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import styles from './style.module.scss' import { MetadataController, NostrController } from '../../controllers'
import JSZip from 'jszip' import { getProfileRoute } from '../../routes'
import { toast } from 'react-toastify' import { ProfileMetadata, User, UserRole } from '../../types'
import { import {
encryptArrayBuffer, encryptArrayBuffer,
generateEncryptionKey, generateEncryptionKey,
getHash, getHash,
parseJson, hexToNpub,
readContentOfZipEntry, pubToHex,
queryNip05,
sendDM, sendDM,
shorten,
signEventForMetaFile, signEventForMetaFile,
uploadToFileStorage uploadToFileStorage
} from '../../utils' } from '../../utils'
import styles from './style.module.scss'
import { toast } from 'react-toastify'
import JSZip from 'jszip'
import { useSelector } from 'react-redux' import { useSelector } from 'react-redux'
import { State } from '../../store/rootReducer' import { State } from '../../store/rootReducer'
import { NostrController } from '../../controllers'
export const SignDocument = () => {
const [selectedFile, setSelectedFile] = useState<File | null>(null)
export const SignPage = () => {
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [isDraggingOver, setIsDraggingOver] = useState(false)
const [authUrl, setAuthUrl] = useState<string>() const [authUrl, setAuthUrl] = useState<string>()
const [selectedFiles, setSelectedFiles] = useState<File[]>([])
const [displayUserInput, setDisplayUserInput] = useState(false)
const [userInput, setUserInput] = useState('')
const [userRole, setUserRole] = useState<UserRole>(UserRole.signer)
const [error, setError] = useState<string>()
const [users, setUsers] = useState<User[]>([])
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey) const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const nostrController = NostrController.getInstance() const nostrController = NostrController.getInstance()
const handleDrop = (event: React.DragEvent<HTMLDivElement>) => { const handleAddUser = async () => {
event.preventDefault() setError(undefined)
setIsDraggingOver(false)
const file = event.dataTransfer.files[0] const addUser = (pubkey: string) => {
if (file.type === 'application/zip') setSelectedFile(file) setUsers((prev) => {
const existingUserIndex = prev.findIndex(
(user) => user.pubkey === pubkey
)
// add new
if (existingUserIndex === -1)
return [...prev, { pubkey, role: userRole }]
const existingUser = prev[existingUserIndex]
// return existing
if (existingUser.role === userRole) return prev
// change user role
const updatedUsers = [...prev]
const updatedUser = { ...updatedUsers[existingUserIndex] }
updatedUser.role = userRole
updatedUsers[existingUserIndex] = updatedUser
return updatedUsers
})
setUserInput('')
} }
const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => { if (userInput.startsWith('npub')) {
event.preventDefault() const pubkey = await pubToHex(userInput)
setIsDraggingOver(true) if (pubkey) {
addUser(pubkey)
setUserInput('')
} else {
setError('Provided npub is not valid. Please enter correct npub.')
}
return
}
if (userInput.includes('@')) {
setIsLoading(true)
setLoadingSpinnerDesc('Querying for nip05')
const nip05Profile = await queryNip05(userInput)
.catch((err) => {
console.error(`error occurred in querying nip05: ${userInput}`, err)
return null
})
.finally(() => {
setIsLoading(false)
setLoadingSpinnerDesc('')
})
if (nip05Profile) {
const pubkey = nip05Profile.pubkey
addUser(pubkey)
setUserInput('')
} else {
setError('Provided nip05 is not valid. Please enter correct nip05.')
}
return
}
setError('Invalid input! Make sure to provide correct npub or nip05.')
}
const handleUserRoleChange = (role: UserRole, index: number) => {
setUsers((prevUsers) => {
// Create a shallow copy of the previous state
const updatedUsers = [...prevUsers]
// Create a shallow copy of the user object at the specified index
const updatedUser = { ...updatedUsers[index] }
// Update the role property of the copied user object
updatedUser.role = role
// Update the user object at the specified index in the copied array
updatedUsers[index] = updatedUser
// Return the updated array
return updatedUsers
})
}
const handleRemoveUser = (pubkey: string) => {
setUsers((prev) => prev.filter((user) => user.pubkey !== pubkey))
}
const handleSelectFiles = (files: File[]) => {
setDisplayUserInput(true)
setSelectedFiles((prev) => {
const prevFileNames = prev.map((file) => file.name)
const newFiles = files.filter(
(file) => !prevFileNames.includes(file.name)
)
return [...prev, ...newFiles]
})
}
const handleRemoveFile = (fileToRemove: File) => {
setSelectedFiles((prevFiles) =>
prevFiles.filter((file) => file.name !== fileToRemove.name)
)
} }
const handleSign = async () => { const handleSign = async () => {
if (!selectedFile) return if (users.length === 0) {
toast.error(
'No signer/viewer is provided. At least add one signer or viewer.'
)
return
}
if (selectedFiles.length === 0) {
toast.error('No file is selected. Select at least 1 file')
return
}
setIsLoading(true) setIsLoading(true)
setLoadingSpinnerDesc('Parsing zip file')
const zip = await JSZip.loadAsync(selectedFile).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
setLoadingSpinnerDesc('Parsing meta.json')
const metaFileContent = await readContentOfZipEntry(
zip,
'meta.json',
'string'
)
if (!metaFileContent) {
setIsLoading(false)
return
}
const meta = 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
})
const hashesFileContent = await readContentOfZipEntry(
zip,
'hashes.json',
'string'
)
if (!hashesFileContent) {
setIsLoading(false)
return
}
const 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('Generating hashes for files')
const fileHashes: { [key: string]: string } = {} const fileHashes: { [key: string]: string } = {}
const fileNames = Object.keys(meta.fileHashes)
// create generate hashes for all entries in files folder of zipArchive // generating file hashes
// these hashes can be used to verify the originality of files for (const file of selectedFiles) {
for (const fileName of fileNames) { const arraybuffer = await file.arrayBuffer().catch((err) => {
const filePath = `files/${fileName}` console.log(
const arrayBuffer = await readContentOfZipEntry( `err while getting arrayBuffer of file ${file.name} :>> `,
zip, err
filePath,
'arraybuffer'
) )
toast.error(
err.message || `err while getting arrayBuffer of file ${file.name}`
)
return null
})
if (!arrayBuffer) { if (!arraybuffer) return
setIsLoading(false)
return const hash = await getHash(arraybuffer)
}
const hash = await getHash(arrayBuffer)
if (!hash) { if (!hash) {
setIsLoading(false) setIsLoading(false)
return return
} }
fileHashes[fileName] = hash fileHashes[file.name] = hash
} }
// check if the current user is the last signer const zip = new JSZip()
const lastSignerIndex = meta.signers.length - 1
const signerIndex = meta.signers.indexOf(usersPubkey)
const isLastSigner = signerIndex === lastSignerIndex
// if current user is the last signer, then send DMs to all viewers // zipping files
if (isLastSigner) { selectedFiles.forEach((file) => {
for (const viewer of meta.viewers) { zip.file(`files/${file.name}`, file)
await signAndSendToNext(zip, meta, hashes, viewer, fileHashes, false) })
}
} else {
const nextSigner = meta.signers[signerIndex + 1]
await signAndSendToNext(zip, meta, hashes, nextSigner, fileHashes, true) const signers = users.filter(
} (user) => user.role === UserRole.signer || user.role === UserRole.both
)
setIsLoading(false) const viewers = users.filter(
} (user) => user.role === UserRole.viewer || user.role === UserRole.both
)
const signAndSendToNext = async (
zip: JSZip,
meta: any,
hashes: any,
receiver: string,
fileHashes: {
[key: string]: string
},
isNextSigner: boolean
) => {
setLoadingSpinnerDesc('Signing nostr event for meta file')
setLoadingSpinnerDesc('Signing nostr event')
const signedEvent = await signEventForMetaFile( const signedEvent = await signEventForMetaFile(
receiver,
fileHashes, fileHashes,
nostrController, nostrController,
setIsLoading setIsLoading
) )
if (!signedEvent) return if (!signedEvent) return
meta.signedEvents = { // create content for meta file
...meta.signedEvents, const meta = {
signers: signers.map((signer) => signer.pubkey),
viewers: viewers.map((viewer) => viewer.pubkey),
fileHashes,
submittedBy: usersPubkey,
signedEvents: {
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2) [signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
} }
}
try {
const stringifiedMeta = JSON.stringify(meta, null, 2) const stringifiedMeta = JSON.stringify(meta, null, 2)
zip.file('meta.json', stringifiedMeta) zip.file('meta.json', stringifiedMeta)
const metaHash = await getHash(stringifiedMeta) const metaHash = await getHash(stringifiedMeta)
if (!metaHash) return if (!metaHash) return
hashes = { const metaHashJson = {
...hashes,
[usersPubkey!]: metaHash [usersPubkey!]: metaHash
} }
zip.file('hashes.json', JSON.stringify(hashes, null, 2)) zip.file('hashes.json', JSON.stringify(metaHashJson, null, 2))
} catch (err) {
console.error(err)
toast.error('An error occurred in converting meta json to string')
return
}
const arrayBuffer = await zip setLoadingSpinnerDesc('Generating zip file')
const arraybuffer = await zip
.generateAsync({ .generateAsync({
type: 'arraybuffer', type: 'arraybuffer',
compression: 'DEFLATE', compression: 'DEFLATE',
@ -201,13 +280,13 @@ export const SignDocument = () => {
return null return null
}) })
if (!arrayBuffer) return if (!arraybuffer) return
const encryptionKey = await generateEncryptionKey() const encryptionKey = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file') setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer( const encryptedArrayBuffer = await encryptArrayBuffer(
arrayBuffer, arraybuffer,
encryptionKey encryptionKey
) )
@ -228,17 +307,34 @@ export const SignDocument = () => {
if (!fileUrl) return if (!fileUrl) return
setLoadingSpinnerDesc( setLoadingSpinnerDesc('Sending DM to signers/viewers')
`Sending DM to next ${isNextSigner ? 'signer' : 'viewer'}`
) // send DM to first signer if exists
if (signers.length > 0) {
await sendDM( await sendDM(
fileUrl, fileUrl,
encryptionKey, encryptionKey,
receiver, signers[0].pubkey,
nostrController, nostrController,
isNextSigner, true,
setAuthUrl setAuthUrl
) )
} else {
// send DM to all viewers if no signer
for (const viewer of viewers) {
// todo: execute in parallel
await sendDM(
fileUrl,
encryptionKey,
viewer.pubkey,
nostrController,
false,
setAuthUrl
)
}
}
setIsLoading(false)
} }
if (authUrl) { if (authUrl) {
@ -257,37 +353,195 @@ export const SignDocument = () => {
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />} {isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}> <Box className={styles.container}>
<Typography component='label' variant='h6'> <Typography component='label' variant='h6'>
Select decrypted zip file Select files
</Typography> </Typography>
<Box
className={styles.inputBlock}
onDrop={handleDrop}
onDragOver={handleDragOver}
>
{isDraggingOver && (
<Box className={styles.fileDragOver}>
<Typography variant='body1'>Drop file here</Typography>
</Box>
)}
<MuiFileInput <MuiFileInput
placeholder='Drop file here, or click to select' multiple
value={selectedFile} placeholder='Choose Files'
onChange={(value) => setSelectedFile(value)} value={selectedFiles}
InputProps={{ onChange={(value) => handleSelectFiles(value)}
inputProps: {
accept: '.zip'
}
}}
/> />
</Box>
<ul>
{selectedFiles.map((file, index) => (
<li key={index}>
<Typography component='label'>{file.name}</Typography>
<IconButton onClick={() => handleRemoveFile(file)}>
<Clear style={{ color: 'red' }} />{' '}
</IconButton>
</li>
))}
</ul>
{displayUserInput && (
<>
<Typography component='label' variant='h6'>
Select signers and viewers
</Typography>
<Box className={styles.inputBlock}>
<TextField
label='nip05 / npub'
value={userInput}
onChange={(e) => setUserInput(e.target.value)}
helperText={error}
error={!!error}
/>
<FormControl fullWidth>
<InputLabel id='select-role-label'>Role</InputLabel>
<Select
labelId='select-role-label'
id='demo-simple-select'
value={userRole}
label='Role'
onChange={(e) => setUserRole(e.target.value as UserRole)}
>
<MenuItem value={UserRole.signer}>{UserRole.signer}</MenuItem>
<MenuItem value={UserRole.viewer}>{UserRole.viewer}</MenuItem>
<MenuItem value={UserRole.both}>{UserRole.both}</MenuItem>
</Select>
</FormControl>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button
disabled={!userInput}
onClick={handleAddUser}
variant='contained'
>
Add
</Button>
</Box>
</Box>
<DisplayUser
users={users}
handleUserRoleChange={handleUserRoleChange}
handleRemoveUser={handleRemoveUser}
/>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}> <Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleSign} variant='contained'> <Button onClick={handleSign} variant='contained'>
Sign Sign
</Button> </Button>
</Box> </Box>
</>
)}
</Box> </Box>
</> </>
) )
} }
type DisplayUsersProps = {
users: User[]
handleUserRoleChange: (role: UserRole, index: number) => void
handleRemoveUser: (pubkey: string) => void
}
const DisplayUser = ({
users,
handleUserRoleChange,
handleRemoveUser
}: DisplayUsersProps) => {
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
useEffect(() => {
users.forEach((user) => {
if (!(user.pubkey in metadata)) {
const metadataController = new MetadataController()
metadataController
.findMetadata(user.pubkey)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[user.pubkey]: metadataContent
}))
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user.pubkey}`,
err
)
})
}
})
}, [users])
const imageLoadError = (event: any) => {
event.target.src = placeholderAvatar
}
return (
<TableContainer component={Paper} elevation={3} sx={{ marginTop: '20px' }}>
<Table>
<TableHead>
<TableRow>
<TableCell className={styles.tableCell}>User</TableCell>
<TableCell className={styles.tableCell}>Role</TableCell>
<TableCell>Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map((user, index) => {
const userMeta = metadata[user.pubkey]
const npub = hexToNpub(user.pubkey)
const roboUrl = `https://robohash.org/${npub}.png?set=set3`
return (
<TableRow key={index}>
<TableCell className={styles.tableCell}>
<Box className={styles.user}>
<img
onError={imageLoadError}
src={userMeta?.picture || roboUrl}
alt='Profile Image'
className='profile-image'
style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${user.pubkey.substring(0, 6)}`
}}
/>
<Link to={getProfileRoute(user.pubkey)}>
<Typography component='label' className={styles.name}>
{userMeta?.display_name ||
userMeta?.name ||
shorten(npub)}
</Typography>
</Link>
</Box>
</TableCell>
<TableCell className={styles.tableCell}>
<Select
fullWidth
value={user.role}
onChange={(e) =>
handleUserRoleChange(e.target.value as UserRole, index)
}
>
<MenuItem value={UserRole.signer}>
{UserRole.signer}
</MenuItem>
<MenuItem value={UserRole.viewer}>
{UserRole.viewer}
</MenuItem>
<MenuItem value={UserRole.both}>{UserRole.both}</MenuItem>
</Select>
</TableCell>
<TableCell>
<Tooltip title='Remove User' arrow>
<IconButton onClick={() => handleRemoveUser(user.pubkey)}>
<Clear style={{ color: 'red' }} />
</IconButton>
</Tooltip>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</TableContainer>
)
}

View File

@ -6,22 +6,28 @@
color: $text-color; color: $text-color;
.inputBlock { .inputBlock {
position: relative;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 25px; gap: 25px;
margin-top: 10px;
}
} }
.fileDragOver { .subHeader {
position: absolute; border-bottom: 0.5px solid;
top: 0; }
left: 0;
width: 100%; .tableCell {
height: 100%; border-right: 1px solid rgba(224, 224, 224, 1);
background-color: rgba(255, 255, 255, 0.8);
z-index: 1; .user {
display: flex; display: flex;
justify-content: center;
align-items: center; align-items: center;
gap: 10px;
.name {
text-align: center;
cursor: pointer;
}
} }
} }

817
src/pages/verify/index.tsx Normal file
View File

@ -0,0 +1,817 @@
import {
Box,
Button,
List,
ListItem,
ListSubheader,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
TextField,
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 { EventTemplate } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { Link, useSearchParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import placeholderAvatar from '../../assets/images/nostr-logo.jpg'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { MetadataController, NostrController } from '../../controllers'
import { getProfileRoute } from '../../routes'
import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import {
decryptArrayBuffer,
encryptArrayBuffer,
generateEncryptionKey,
getHash,
hexToNpub,
parseJson,
readContentOfZipEntry,
sendDM,
shorten,
signEventForMetaFile,
uploadToFileStorage
} from '../../utils'
import styles from './style.module.scss'
enum SignedStatus {
Fully_Signed,
User_Is_Next_Signer,
User_Is_Not_Next_Signer
}
export const VerifyPage = () => {
const [searchParams] = useSearchParams()
const [displayInput, setDisplayInput] = useState(false)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [encryptionKey, setEncryptionKey] = useState('')
const [zip, setZip] = useState<JSZip>()
const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [isDraggingOver, setIsDraggingOver] = useState(false)
const [meta, setMeta] = useState<Meta | null>(null)
const [signedStatus, setSignedStatus] = useState<SignedStatus>()
const [nextSinger, setNextSinger] = useState<string>()
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const [authUrl, setAuthUrl] = useState<string>()
const nostrController = NostrController.getInstance()
useEffect(() => {
if (meta) {
setDisplayInput(false)
// get list of users who have signed
const signedBy = Object.keys(meta.signedEvents)
if (meta.signers.length > 0) {
// check if all signers have signed then its fully signed
if (meta.signers.every((signer) => signedBy.includes(signer))) {
setSignedStatus(SignedStatus.Fully_Signed)
} else {
for (const signer of meta.signers) {
if (!signedBy.includes(signer)) {
setNextSinger(signer)
if (signer === usersPubkey) {
// 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)
}
}
}, [meta, 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, 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<Meta>(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 || !encryptionKey) return
setIsLoading(true)
const arrayBuffer = await decrypt(selectedFile, encryptionKey)
if (!arrayBuffer) return
handleDecryptedArrayBuffer(arrayBuffer)
}
const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault()
setIsDraggingOver(false)
const file = event.dataTransfer.files[0]
if (file.type === 'application/zip') setSelectedFile(file)
}
const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault()
setIsDraggingOver(true)
}
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')
const fileHashes: { [key: string]: string } = {}
const fileNames = Object.keys(meta.fileHashes)
// 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 filePath = `files/${fileName}`
const arrayBuffer = await readContentOfZipEntry(
zip,
filePath,
'arraybuffer'
)
if (!arrayBuffer) {
setIsLoading(false)
return
}
const hash = await getHash(arrayBuffer)
if (!hash) {
setIsLoading(false)
return
}
fileHashes[fileName] = hash
}
setLoadingSpinnerDesc('Signing nostr event')
const signedEvent = await signEventForMetaFile(
fileHashes,
nostrController,
setIsLoading
)
if (!signedEvent) return
const metaCopy = _.cloneDeep(meta)
metaCopy.signedEvents = {
...metaCopy.signedEvents,
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
}
const stringifiedMeta = JSON.stringify(meta, 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 encryptionKey = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer(
arrayBuffer,
encryptionKey
)
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 lastSignerIndex = meta.signers.length - 1
const signerIndex = meta.signers.indexOf(usersPubkey!)
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<string>()
userSet.add(meta.submittedBy)
meta.signers.forEach((signer) => {
userSet.add(signer)
})
meta.viewers.forEach((viewer) => {
userSet.add(viewer)
})
const users = Array.from(userSet)
for (const user of users) {
// todo: execute in parallel
await sendDM(
fileUrl,
encryptionKey,
user,
nostrController,
false,
setAuthUrl
)
}
} else {
const nextSigner = meta.signers[signerIndex + 1]
await sendDM(
fileUrl,
encryptionKey,
nextSigner,
nostrController,
false,
setAuthUrl
)
}
setIsLoading(false)
}
const handleExport = async () => {
if (!meta || !zip || !usersPubkey) return
if (
!meta.signers.includes(usersPubkey) &&
!meta.viewers.includes(usersPubkey) &&
meta.submittedBy !== usersPubkey
)
return
setIsLoading(true)
setLoadingSpinnerDesc('Signing nostr event')
const event: EventTemplate = {
kind: 1,
content: '',
created_at: Math.floor(Date.now() / 1000), // Current timestamp
tags: []
}
// Sign the event
const signedEvent = await nostrController.signEvent(event).catch((err) => {
console.error(err)
toast.error(err.message || 'Error occurred in signing nostr event')
setIsLoading(false) // Set loading state to false
return null
})
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)
}
if (authUrl) {
return (
<iframe
title='Nsecbunker auth'
src={authUrl}
width='100%'
height='500px'
/>
)
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}>
{displayInput && (
<>
<Typography component='label' variant='h6'>
Select sigit file
</Typography>
<Box
className={styles.inputBlock}
onDrop={handleDrop}
onDragOver={handleDragOver}
>
{isDraggingOver && (
<Box className={styles.fileDragOver}>
<Typography variant='body1'>Drop file here</Typography>
</Box>
)}
<MuiFileInput
placeholder='Drop file here, or click to select'
value={selectedFile}
onChange={(value) => setSelectedFile(value)}
InputProps={{
inputProps: {
accept: '.zip'
}
}}
/>
{selectedFile && (
<TextField
label='Encryption Key'
variant='outlined'
value={encryptionKey}
onChange={(e) => setEncryptionKey(e.target.value)}
/>
)}
</Box>
{selectedFile && encryptionKey && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleDecrypt} variant='contained'>
Decrypt
</Button>
</Box>
)}
</>
)}
{meta && signedStatus === SignedStatus.Fully_Signed && (
<>
<DisplayMeta meta={meta} nextSigner={nextSinger} />
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant='contained'>
Export
</Button>
</Box>
</>
)}
{meta && signedStatus === SignedStatus.User_Is_Not_Next_Signer && (
<>
<DisplayMeta meta={meta} nextSigner={nextSinger} />
<Typography component='h6'>
Awaiting signature by {hexToNpub(nextSinger)}
</Typography>
</>
)}
{meta && signedStatus === SignedStatus.User_Is_Next_Signer && (
<>
<DisplayMeta meta={meta} nextSigner={nextSinger} />
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleSign} variant='contained'>
Sign
</Button>
</Box>
</>
)}
</Box>
</>
)
}
type DisplayMetaProps = {
meta: Meta
nextSigner?: string
}
const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
const theme = useTheme()
const textColor = theme.palette.getContrastText(
theme.palette.background.paper
)
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
const [users, setUsers] = useState<User[]>([])
useEffect(() => {
meta.signers.forEach((signer) => {
const userRole = meta.viewers.includes(signer)
? UserRole.both
: UserRole.signer
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === signer) !== -1) return prev
return [
...prev,
{
pubkey: signer,
role: userRole
}
]
})
})
meta.viewers.forEach((viewer) => {
const userRole = meta.signers.includes(viewer)
? UserRole.both
: UserRole.viewer
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === viewer) !== -1) return prev
return [
...prev,
{
pubkey: viewer,
role: userRole
}
]
})
})
}, [meta])
useEffect(() => {
const metadataController = new MetadataController()
metadataController
.findMetadata(meta.submittedBy)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[meta.submittedBy]: metadataContent
}))
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${meta.submittedBy}`,
err
)
})
users.forEach((user) => {
if (!(user.pubkey in metadata)) {
metadataController
.findMetadata(user.pubkey)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[user.pubkey]: metadataContent
}))
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user.pubkey}`,
err
)
})
}
})
}, [users, meta.submittedBy])
const imageLoadError = (event: any) => {
event.target.src = placeholderAvatar
}
const getRoboImageUrl = (pubkey: string) => {
const npub = hexToNpub(pubkey)
return `https://robohash.org/${npub}.png?set=set3`
}
return (
<List
sx={{
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader
sx={{
borderBottom: '0.5px solid',
paddingBottom: 1,
paddingTop: 1,
fontSize: '1.5rem'
}}
className={styles.subHeader}
>
Meta Info
</ListSubheader>
}
>
<ListItem
sx={{
marginTop: 1,
gap: '15px'
}}
>
<Typography variant='h6' sx={{ color: textColor }}>
Submitted By
</Typography>
<Box className={styles.user}>
<img
onError={imageLoadError}
src={
metadata[meta.submittedBy]?.picture ||
getRoboImageUrl(meta.submittedBy)
}
alt='Profile Image'
className='profile-image'
style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${meta.submittedBy.substring(0, 6)}`
}}
/>
<Link to={getProfileRoute(meta.submittedBy)}>
<Typography component='label' className={styles.name}>
{metadata[meta.submittedBy]?.display_name ||
metadata[meta.submittedBy]?.name ||
shorten(hexToNpub(meta.submittedBy))}
</Typography>
</Link>
</Box>
</ListItem>
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant='h6' sx={{ color: textColor }}>
Files
</Typography>
<ul>
{Object.keys(meta.fileHashes).map((file, index) => (
<li key={index} style={{ color: textColor }}>
{file}
</li>
))}
</ul>
</ListItem>
<ListItem sx={{ marginTop: 1 }}>
<Table>
<TableHead>
<TableRow>
<TableCell className={styles.tableCell}>User</TableCell>
<TableCell className={styles.tableCell}>Role</TableCell>
<TableCell>Signed Status</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map((user, index) => {
const userMeta = metadata[user.pubkey]
const npub = hexToNpub(user.pubkey)
const roboUrl = `https://robohash.org/${npub}.png?set=set3`
let signedStatus = '-'
if (user.role === UserRole.viewer) {
signedStatus = '-'
} else if (
user.role === UserRole.signer ||
user.role === UserRole.both
) {
// check if user has signed the document
if (user.pubkey in meta.signedEvents) {
signedStatus = 'Signed'
}
// check if user is the next signer
else if (user.pubkey === nextSigner) {
signedStatus === 'Next Singer'
}
// if none of the above condition is true then it means user's signature is pending
else {
signedStatus === 'Pending'
}
}
return (
<TableRow key={index}>
<TableCell className={styles.tableCell}>
<Box className={styles.user}>
<img
onError={imageLoadError}
src={userMeta?.picture || roboUrl}
alt='Profile Image'
className='profile-image'
style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${user.pubkey.substring(0, 6)}`
}}
/>
<Link to={getProfileRoute(user.pubkey)}>
<Typography component='label' className={styles.name}>
{userMeta?.display_name ||
userMeta?.name ||
shorten(npub)}
</Typography>
</Link>
</Box>
</TableCell>
<TableCell className={styles.tableCell}>
{user.role}
</TableCell>
<TableCell>{signedStatus}</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</ListItem>
</List>
)
}

View File

@ -0,0 +1,18 @@
.user {
display: flex;
align-items: center;
gap: 10px;
.name {
text-align: center;
cursor: pointer;
}
}
.tableCell {
border-right: 1px solid rgba(224, 224, 224, 1);
.user {
@extend .user;
}
}

View File

@ -1,15 +1,15 @@
import { DecryptZip } from '../pages/decrypt'
import { HomePage } from '../pages/home' import { HomePage } from '../pages/home'
import { SignPage } from '../pages/sign'
import { LandingPage } from '../pages/landing/LandingPage' import { LandingPage } from '../pages/landing/LandingPage'
import { Login } from '../pages/login' import { Login } from '../pages/login'
import { ProfilePage } from '../pages/profile' import { ProfilePage } from '../pages/profile'
import { hexToNpub } from '../utils' import { hexToNpub } from '../utils'
import { SignDocument } from '../pages/sign' import { VerifyPage } from '../pages/verify'
export const appPrivateRoutes = { export const appPrivateRoutes = {
homePage: '/', homePage: '/',
decryptZip: '/decrypt', sign: '/sign',
sign: '/sign' verify: '/verify'
} }
export const appPublicRoutes = { export const appPublicRoutes = {
@ -45,11 +45,11 @@ export const privateRoutes = [
element: <HomePage /> element: <HomePage />
}, },
{ {
path: appPrivateRoutes.decryptZip, path: appPrivateRoutes.sign,
element: <DecryptZip /> element: <SignPage />
}, },
{ {
path: appPrivateRoutes.sign, path: appPrivateRoutes.verify,
element: <SignDocument /> element: <VerifyPage />
} }
] ]

18
src/types/core.ts Normal file
View File

@ -0,0 +1,18 @@
export enum UserRole {
signer = 'Signer',
viewer = 'Viewer',
both = 'Both'
}
export interface User {
pubkey: string
role: UserRole
}
export interface Meta {
signers: string[]
viewers: string[]
fileHashes: { [key: string]: string }
submittedBy: string
signedEvents: { [key: string]: string }
}

View File

@ -1,3 +1,4 @@
export * from './core'
export * from './nostr' export * from './nostr'
export * from './profile' export * from './profile'
export * from './zip' export * from './zip'

View File

@ -75,7 +75,11 @@ export const sendDM = async (
? 'Your signature is requested on the document below!' ? 'Your signature is requested on the document below!'
: 'You have received a signed document.' : 'You have received a signed document.'
const decryptionUrl = `${window.location.origin}/#${appPrivateRoutes.decryptZip}?file=${encodeURIComponent(fileUrl)}&key=${encodeURIComponent(encryptionKey)}` const decryptionUrl = `${window.location.origin}/#${
appPrivateRoutes.verify
}?file=${encodeURIComponent(fileUrl)}&key=${encodeURIComponent(
encryptionKey
)}`
const content = `${initialLine}\n\n${decryptionUrl}\n\nDirect download${fileUrl}` const content = `${initialLine}\n\n${decryptionUrl}\n\nDirect download${fileUrl}`
@ -166,14 +170,12 @@ export const sendDM = async (
/** /**
* Signs an event for a meta.json file. * Signs an event for a meta.json file.
* @param receiver The recipient's public key.
* @param fileHashes Object containing file hashes. * @param fileHashes Object containing file hashes.
* @param nostrController The NostrController instance for signing the event. * @param nostrController The NostrController instance for signing the event.
* @param setIsLoading Function to set loading state in the component. * @param setIsLoading Function to set loading state in the component.
* @returns A Promise resolving to the signed event, or null if signing fails. * @returns A Promise resolving to the signed event, or null if signing fails.
*/ */
export const signEventForMetaFile = async ( export const signEventForMetaFile = async (
receiver: string,
fileHashes: { fileHashes: {
[key: string]: string [key: string]: string
}, },
@ -183,9 +185,9 @@ export const signEventForMetaFile = async (
// Construct the event metadata for the meta file // Construct the event metadata for the meta file
const event: EventTemplate = { const event: EventTemplate = {
kind: 1, // Event type for meta file kind: 1, // Event type for meta file
tags: [['r', receiver]], // Tag with recipient's public key
content: JSON.stringify(fileHashes), // Convert file hashes to JSON string content: JSON.stringify(fileHashes), // Convert file hashes to JSON string
created_at: Math.floor(Date.now() / 1000) // Current timestamp created_at: Math.floor(Date.now() / 1000), // Current timestamp
tags: []
} }
// Sign the event // Sign the event

View File

@ -65,11 +65,11 @@ export const hexStringToUint8Array = (hexString: string) => {
* @param content The JSON content to parse. * @param content The JSON content to parse.
* @returns A Promise that resolves to the parsed JSON object. * @returns A Promise that resolves to the parsed JSON object.
*/ */
export const parseJson = (content: string): Promise<any> => { export const parseJson = <T>(content: string): Promise<T> => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
try { try {
// Attempt to parse the JSON content // Attempt to parse the JSON content
const json = JSON.parse(content) const json = JSON.parse(content) as T
// Resolve the promise with the parsed JSON object // Resolve the promise with the parsed JSON object
resolve(json) resolve(json)
} catch (error) { } catch (error) {