Compare commits

..

No commits in common. "c5ad828dca814e5f10ea0f915f5de84d948aa29f" and "a1f096018c4fb2e8ad573437f29afe547e9b665a" have entirely different histories.

14 changed files with 844 additions and 1305 deletions

View File

@ -29,4 +29,4 @@ jobs:
- name: Release Build - name: Release Build
run: | run: |
npm -g install cloudron-surfer npm -g install cloudron-surfer
surfer put --token ${{ secrets.CLOUDRON_SURFER_TOKEN }} --server sigit.io dist/* / surfer put --token ${{ secrets.CLOUDRON_SURFER_TOKEN }} --server app.sigit.io dist/* /

View File

@ -3,7 +3,7 @@
"private": true, "private": true,
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
"homepage": "https://sigit.io/", "homepage": "https://app.sigit.io/",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc && vite build", "build": "tsc && vite build",

View File

@ -1,9 +1,13 @@
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'
@ -15,10 +19,14 @@ 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, useNavigate } from 'react-router-dom' import { Link, useLocation, 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 { appPublicRoutes, getProfileRoute } from '../../routes' import {
appPrivateRoutes,
appPublicRoutes,
getProfileRoute
} from '../../routes'
import { import {
clearAuthToken, clearAuthToken,
saveNsecBunkerDelegatedKey, saveNsecBunkerDelegatedKey,
@ -26,14 +34,20 @@ 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)
@ -52,10 +66,18 @@ 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))
@ -89,8 +111,116 @@ 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 className={styles.logoWrapper}> <Box sx={{ display: { xs: 'none', md: 'flex' } }}>
<img src='/logo.png' alt='Logo' onClick={() => navigate('/')} /> <Box className={styles.logoWrapper}>
<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,20 +1,489 @@
import { Box, Button } from '@mui/material' import { Clear } from '@mui/icons-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'
import { appPrivateRoutes } from '../../routes' enum SelectionType {
signer = 'Signer',
viewer = 'Viewer'
}
export const HomePage = () => { export const HomePage = () => {
const navigate = useNavigate() const [inputValue, setInputValue] = useState('')
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 (
<Box className={styles.container}> <>
<Button {isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
onClick={() => navigate(appPrivateRoutes.sign)} <Box className={styles.container}>
variant='contained' <Typography component='label' variant='h6'>
> Select signers and viewers
Sign </Typography>
</Button> <Box className={styles.inputBlock}>
<Button variant='contained'>Verify</Button> <TextField
</Box> 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
disabled={!inputValue}
onClick={handleAddClick}
variant='contained'
>
Add
</Button>
</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,6 +1,33 @@
@import '../../colors.scss';
.container { .container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
gap: 25px; color: $text-color;
margin-top: 10px;
.inputBlock {
display: flex;
flex-direction: column;
gap: 25px;
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,267 +1,192 @@
import { Clear } from '@mui/icons-material' import { Box, Button, Typography } from '@mui/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 { useEffect, useState } from 'react' import { 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 { MetadataController, NostrController } from '../../controllers' import styles from './style.module.scss'
import { getProfileRoute } from '../../routes' import JSZip from 'jszip'
import { ProfileMetadata, User, UserRole } from '../../types' import { toast } from 'react-toastify'
import { import {
encryptArrayBuffer, encryptArrayBuffer,
generateEncryptionKey, generateEncryptionKey,
getHash, getHash,
hexToNpub, parseJson,
pubToHex, readContentOfZipEntry,
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 handleAddUser = async () => { const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
setError(undefined) event.preventDefault()
setIsDraggingOver(false)
const addUser = (pubkey: string) => { const file = event.dataTransfer.files[0]
setUsers((prev) => { if (file.type === 'application/zip') setSelectedFile(file)
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('')
}
if (userInput.startsWith('npub')) {
const pubkey = await pubToHex(userInput)
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) => { const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
setUsers((prevUsers) => { event.preventDefault()
// Create a shallow copy of the previous state setIsDraggingOver(true)
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 (users.length === 0) { if (!selectedFile) return
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)
// generating file hashes // create generate hashes for all entries in files folder of zipArchive
for (const file of selectedFiles) { // these hashes can be used to verify the originality of files
const arraybuffer = await file.arrayBuffer().catch((err) => { for (const fileName of fileNames) {
console.log( const filePath = `files/${fileName}`
`err while getting arrayBuffer of file ${file.name} :>> `, const arrayBuffer = await readContentOfZipEntry(
err zip,
) filePath,
toast.error( 'arraybuffer'
err.message || `err while getting arrayBuffer of file ${file.name}` )
)
return null
})
if (!arraybuffer) return if (!arrayBuffer) {
setIsLoading(false)
const hash = await getHash(arraybuffer) return
}
const hash = await getHash(arrayBuffer)
if (!hash) { if (!hash) {
setIsLoading(false) setIsLoading(false)
return return
} }
fileHashes[file.name] = hash fileHashes[fileName] = hash
} }
const zip = new JSZip() // 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
// zipping files // if current user is the last signer, then send DMs to all viewers
selectedFiles.forEach((file) => { if (isLastSigner) {
zip.file(`files/${file.name}`, file) for (const viewer of meta.viewers) {
}) await signAndSendToNext(zip, meta, hashes, viewer, fileHashes, false)
}
} else {
const nextSigner = meta.signers[signerIndex + 1]
const signers = users.filter((user) => user.role === UserRole.signer) await signAndSendToNext(zip, meta, hashes, nextSigner, fileHashes, true)
const viewers = users.filter((user) => user.role === UserRole.viewer) }
setIsLoading(false)
}
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
// create content for meta file meta.signedEvents = {
const meta = { ...meta.signedEvents,
signers: signers.map((signer) => signer.pubkey), [signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
viewers: viewers.map((viewer) => viewer.pubkey),
fileHashes,
submittedBy: usersPubkey,
signedEvents: {
[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
const metaHashJson = { hashes = {
[usersPubkey!]: metaHash ...hashes,
} [usersPubkey!]: metaHash
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
} }
setLoadingSpinnerDesc('Generating zip file') zip.file('hashes.json', JSON.stringify(hashes, null, 2))
const arraybuffer = await zip const arrayBuffer = await zip
.generateAsync({ .generateAsync({
type: 'arraybuffer', type: 'arraybuffer',
compression: 'DEFLATE', compression: 'DEFLATE',
@ -276,13 +201,13 @@ export const SignPage = () => {
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
) )
@ -303,34 +228,17 @@ export const SignPage = () => {
if (!fileUrl) return if (!fileUrl) return
setLoadingSpinnerDesc('Sending DM to signers/viewers') setLoadingSpinnerDesc(
`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) {
@ -349,193 +257,37 @@ export const SignPage = () => {
{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 files Select decrypted zip file
</Typography> </Typography>
<MuiFileInput <Box
multiple className={styles.inputBlock}
placeholder='Choose Files' onDrop={handleDrop}
value={selectedFiles} onDragOver={handleDragOver}
onChange={(value) => handleSelectFiles(value)} >
/> {isDraggingOver && (
<Box className={styles.fileDragOver}>
<ul> <Typography variant='body1'>Drop file here</Typography>
{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>
</Select>
</FormControl>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button
disabled={!userInput}
onClick={handleAddUser}
variant='contained'
>
Add
</Button>
</Box>
</Box> </Box>
<DisplayUser )}
users={users} <MuiFileInput
handleUserRoleChange={handleUserRoleChange} placeholder='Drop file here, or click to select'
handleRemoveUser={handleRemoveUser} value={selectedFile}
/> onChange={(value) => setSelectedFile(value)}
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}> InputProps={{
<Button onClick={handleSign} variant='contained'> inputProps: {
Sign accept: '.zip'
</Button> }
</Box> }}
</> />
)} </Box>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleSign} variant='contained'>
Sign
</Button>
</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>
</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,28 +6,22 @@
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;
} }
}
.subHeader { .fileDragOver {
border-bottom: 0.5px solid; position: absolute;
} top: 0;
left: 0;
.tableCell { width: 100%;
border-right: 1px solid rgba(224, 224, 224, 1); height: 100%;
background-color: rgba(255, 255, 255, 0.8);
.user { z-index: 1;
display: flex; display: flex;
justify-content: center;
align-items: center; align-items: center;
gap: 10px;
.name {
text-align: center;
cursor: pointer;
}
} }
} }

View File

@ -1,795 +0,0 @@
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(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 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} />
)}
{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) => {
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === signer) !== -1) return prev
return [
...prev,
{
pubkey: signer,
role: UserRole.signer
}
]
})
})
meta.viewers.forEach((viewer) => {
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === viewer) !== -1) return prev
return [
...prev,
{
pubkey: viewer,
role: UserRole.viewer
}
]
})
})
}, [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.signer) {
// 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 = 'Awaiting Signature'
}
}
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

@ -1,18 +0,0 @@
.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 { VerifyPage } from '../pages/verify' import { SignDocument } from '../pages/sign'
export const appPrivateRoutes = { export const appPrivateRoutes = {
homePage: '/', homePage: '/',
sign: '/sign', decryptZip: '/decrypt',
verify: '/verify' sign: '/sign'
} }
export const appPublicRoutes = { export const appPublicRoutes = {
@ -45,11 +45,11 @@ export const privateRoutes = [
element: <HomePage /> element: <HomePage />
}, },
{ {
path: appPrivateRoutes.sign, path: appPrivateRoutes.decryptZip,
element: <SignPage /> element: <DecryptZip />
}, },
{ {
path: appPrivateRoutes.verify, path: appPrivateRoutes.sign,
element: <VerifyPage /> element: <SignDocument />
} }
] ]

View File

@ -1,17 +0,0 @@
export enum UserRole {
signer = 'Signer',
viewer = 'Viewer'
}
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,4 +1,3 @@
export * from './core'
export * from './nostr' export * from './nostr'
export * from './profile' export * from './profile'
export * from './zip' export * from './zip'

View File

@ -75,11 +75,7 @@ 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}/#${ const decryptionUrl = `${window.location.origin}/#${appPrivateRoutes.decryptZip}?file=${encodeURIComponent(fileUrl)}&key=${encodeURIComponent(encryptionKey)}`
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}`
@ -170,12 +166,14 @@ 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
}, },
@ -185,9 +183,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 = <T>(content: string): Promise<T> => { export const parseJson = (content: string): Promise<any> => {
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) as T const json = JSON.parse(content)
// Resolve the promise with the parsed JSON object // Resolve the promise with the parsed JSON object
resolve(json) resolve(json)
} catch (error) { } catch (error) {