Merge branch 'main' into issue16

This commit is contained in:
b 2024-05-14 15:09:09 +00:00
commit 7c2b8dc53e
20 changed files with 1420 additions and 863 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 app.sigit.io dist/* / surfer put --token ${{ secrets.CLOUDRON_SURFER_TOKEN }} --server sigit.io dist/* /

13
package-lock.json generated
View File

@ -17,6 +17,7 @@
"@reduxjs/toolkit": "2.2.1", "@reduxjs/toolkit": "2.2.1",
"axios": "1.6.7", "axios": "1.6.7",
"crypto-hash": "3.0.0", "crypto-hash": "3.0.0",
"crypto-js": "^4.2.0",
"file-saver": "2.0.5", "file-saver": "2.0.5",
"jszip": "3.10.1", "jszip": "3.10.1",
"lodash": "4.17.21", "lodash": "4.17.21",
@ -31,6 +32,7 @@
"tseep": "1.2.1" "tseep": "1.2.1"
}, },
"devDependencies": { "devDependencies": {
"@types/crypto-js": "^4.2.2",
"@types/file-saver": "2.0.7", "@types/file-saver": "2.0.7",
"@types/lodash": "4.14.202", "@types/lodash": "4.14.202",
"@types/react": "^18.2.56", "@types/react": "^18.2.56",
@ -1938,6 +1940,12 @@
"@babel/types": "^7.20.7" "@babel/types": "^7.20.7"
} }
}, },
"node_modules/@types/crypto-js": {
"version": "4.2.2",
"resolved": "https://registry.npmjs.org/@types/crypto-js/-/crypto-js-4.2.2.tgz",
"integrity": "sha512-sDOLlVbHhXpAUAL0YHDUUwDZf3iN4Bwi4W6a0W0b+QcAezUbRtH4FVb+9J4h+XFPW7l/gQ9F8qC7P+Ec4k8QVQ==",
"dev": true
},
"node_modules/@types/estree": { "node_modules/@types/estree": {
"version": "1.0.5", "version": "1.0.5",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.5.tgz",
@ -2630,6 +2638,11 @@
"url": "https://github.com/sponsors/sindresorhus" "url": "https://github.com/sponsors/sindresorhus"
} }
}, },
"node_modules/crypto-js": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/crypto-js/-/crypto-js-4.2.0.tgz",
"integrity": "sha512-KALDyEYgpY+Rlob/iriUtjV6d5Eq+Y191A5g4UqLAi8CyGP9N1+FdVbkc1SxKc2r4YAYqG8JzO2KGL+AizD70Q=="
},
"node_modules/csstype": { "node_modules/csstype": {
"version": "3.1.3", "version": "3.1.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz",

View File

@ -3,11 +3,12 @@
"private": true, "private": true,
"version": "0.0.0", "version": "0.0.0",
"type": "module", "type": "module",
"homepage": "https://app.sigit.io/", "homepage": "https://sigit.io/",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"build": "tsc && vite build", "build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"lint:fix": "eslint . --fix --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
@ -20,6 +21,7 @@
"@reduxjs/toolkit": "2.2.1", "@reduxjs/toolkit": "2.2.1",
"axios": "1.6.7", "axios": "1.6.7",
"crypto-hash": "3.0.0", "crypto-hash": "3.0.0",
"crypto-js": "^4.2.0",
"file-saver": "2.0.5", "file-saver": "2.0.5",
"jszip": "3.10.1", "jszip": "3.10.1",
"lodash": "4.17.21", "lodash": "4.17.21",
@ -34,6 +36,7 @@
"tseep": "1.2.1" "tseep": "1.2.1"
}, },
"devDependencies": { "devDependencies": {
"@types/crypto-js": "^4.2.2",
"@types/file-saver": "2.0.7", "@types/file-saver": "2.0.7",
"@types/lodash": "4.14.202", "@types/lodash": "4.14.202",
"@types/react": "^18.2.56", "@types/react": "^18.2.56",

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

@ -8,6 +8,7 @@ import styles from './style.module.scss'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { useSearchParams } from 'react-router-dom' import { useSearchParams } from 'react-router-dom'
import axios from 'axios' import axios from 'axios'
import { DecryptionError } from '../../types/errors/DecryptionError'
export const DecryptZip = () => { export const DecryptZip = () => {
const [searchParams] = useSearchParams() const [searchParams] = useSearchParams()
@ -60,9 +61,10 @@ export const DecryptZip = () => {
const arrayBuffer = await decryptArrayBuffer( const arrayBuffer = await decryptArrayBuffer(
encryptedArrayBuffer, encryptedArrayBuffer,
encryptionKey encryptionKey
).catch((err) => { ).catch((err: DecryptionError) => {
console.log('err in decryption:>> ', err) console.log('err in decryption:>> ', err)
toast.error(err.message || 'An error occurred while decrypting file.')
toast.error(err.message)
setIsLoading(false) setIsLoading(false)
return null return null
}) })

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 (
<> <Box className={styles.container}>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />} <Button
<Box className={styles.container}> onClick={() => navigate(appPrivateRoutes.sign)}
<Typography component='label' variant='h6'> variant='contained'
Select signers and viewers >
</Typography> Sign
<Box className={styles.inputBlock}> </Button>
<TextField <Button variant='contained'>Verify</Button>
label='nip05 / npub' </Box>
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,33 +1,6 @@
@import '../../colors.scss';
.container { .container {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
color: $text-color; gap: 25px;
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,9 +1,13 @@
import ContentCopyIcon from '@mui/icons-material/ContentCopy' import ContentCopyIcon from '@mui/icons-material/ContentCopy'
import { import {
CircularProgress,
IconButton,
InputProps,
List, List,
ListItem, ListItem,
ListSubheader, ListSubheader,
TextField, TextField,
Tooltip,
Typography, Typography,
useTheme useTheme
} from '@mui/material' } from '@mui/material'
@ -22,6 +26,7 @@ import { Dispatch } from '../../store/store'
import { setMetadataEvent } from '../../store/actions' import { setMetadataEvent } from '../../store/actions'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import { LoginMethods } from '../../store/auth/types' import { LoginMethods } from '../../store/auth/types'
import { SmartToy } from '@mui/icons-material'
export const ProfilePage = () => { export const ProfilePage = () => {
const theme = useTheme() const theme = useTheme()
@ -38,6 +43,7 @@ export const ProfilePage = () => {
useState<NostrJoiningBlock | null>(null) useState<NostrJoiningBlock | null>(null)
const [profileMetadata, setProfileMetadata] = useState<ProfileMetadata>() const [profileMetadata, setProfileMetadata] = useState<ProfileMetadata>()
const [savingProfileMetadata, setSavingProfileMetadata] = useState(false) const [savingProfileMetadata, setSavingProfileMetadata] = useState(false)
const [avatarLoading, setAvatarLoading] = useState(false)
const metadataState = useSelector((state: State) => state.metadata) const metadataState = useSelector((state: State) => state.metadata)
const keys = useSelector((state: State) => state.auth?.keyPair) const keys = useSelector((state: State) => state.auth?.keyPair)
const { usersPubkey, loginMethod } = useSelector((state: State) => state.auth) const { usersPubkey, loginMethod } = useSelector((state: State) => state.auth)
@ -97,7 +103,9 @@ export const ProfilePage = () => {
if (metadataEvent) { if (metadataEvent) {
const metadataContent = const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent) metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent) setProfileMetadata(metadataContent) if (metadataContent) {
setProfileMetadata(metadataContent)
}
} }
setIsLoading(false) setIsLoading(false)
@ -111,7 +119,8 @@ export const ProfilePage = () => {
key: keyof ProfileMetadata, key: keyof ProfileMetadata,
label: string, label: string,
multiline = false, multiline = false,
rows = 1 rows = 1,
inputProps?: InputProps
) => ( ) => (
<ListItem sx={{ marginTop: 1 }}> <ListItem sx={{ marginTop: 1 }}>
<TextField <TextField
@ -123,6 +132,7 @@ export const ProfilePage = () => {
rows={rows} rows={rows}
className={styles.textField} className={styles.textField}
disabled={!isUsersOwnProfile} disabled={!isUsersOwnProfile}
InputProps={inputProps}
onChange={(event: React.ChangeEvent<HTMLInputElement>) => { onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
const { value } = event.target const { value } = event.target
@ -201,6 +211,39 @@ export const ProfilePage = () => {
setSavingProfileMetadata(false) setSavingProfileMetadata(false)
} }
const generateRobotAvatar = () => {
setAvatarLoading(true)
const robotAvatarLink = `https://robohash.org/${npub}.png?set=set3`
setProfileMetadata((prev) => ({
...prev,
picture: ''
}))
setTimeout(() => {
setProfileMetadata((prev) => ({
...prev,
picture: robotAvatarLink
}))
})
}
/**
*
* @returns robohash generate button, loading spinner or no button
*/
const robohashButton = () => {
if (profileMetadata?.picture?.includes('robohash')) return null
return <Tooltip title="Generate a robohash avatar">
{avatarLoading ? <CircularProgress style={{padding: 8}} size={22}/>
: <IconButton onClick={generateRobotAvatar}>
<SmartToy/>
</IconButton>}
</Tooltip>
}
return ( return (
<> <>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />} {isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
@ -236,10 +279,14 @@ export const ProfilePage = () => {
onError={(event: any) => { onError={(event: any) => {
event.target.src = placeholderAvatar event.target.src = placeholderAvatar
}} }}
onLoad={() => {
setAvatarLoading(false)
}}
className={styles.img} className={styles.img}
src={profileMetadata.picture || placeholderAvatar} src={profileMetadata.picture || placeholderAvatar}
alt='Profile Image' alt='Profile Image'
/> />
{nostrJoiningBlock && ( {nostrJoiningBlock && (
<Typography <Typography
sx={{ sx={{
@ -256,11 +303,16 @@ export const ProfilePage = () => {
)} )}
</ListItem> </ListItem>
{editItem('picture', 'Picture URL', undefined, undefined, {
endAdornment: robohashButton()
})}
{editItem('name', 'Username')} {editItem('name', 'Username')}
{editItem('display_name', 'Display Name')} {editItem('display_name', 'Display Name')}
{editItem('nip05', 'Nostr Address (nip05)')} {editItem('nip05', 'Nostr Address (nip05)')}
{editItem('lud16', 'Lightning Address (lud16)')} {editItem('lud16', 'Lightning Address (lud16)')}
{editItem('about', 'About', true, 4)} {editItem('about', 'About', true, 4)}
{editItem('website', 'Website')}
{isUsersOwnProfile && ( {isUsersOwnProfile && (
<> <>
{usersPubkey && {usersPubkey &&

View File

@ -1,192 +1,267 @@
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('')
}
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 handleDragOver = (event: React.DragEvent<HTMLDivElement>) => { const handleUserRoleChange = (role: UserRole, index: number) => {
event.preventDefault() setUsers((prevUsers) => {
setIsDraggingOver(true) // 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)
} 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
meta.signedEvents = { // create content for meta file
...meta.signedEvents, const meta = {
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2) signers: signers.map((signer) => signer.pubkey),
viewers: viewers.map((viewer) => viewer.pubkey),
fileHashes,
submittedBy: usersPubkey,
signedEvents: {
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
}
} }
const stringifiedMeta = JSON.stringify(meta, null, 2) try {
zip.file('meta.json', stringifiedMeta) const stringifiedMeta = JSON.stringify(meta, null, 2)
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(metaHashJson, null, 2))
} catch (err) {
console.error(err)
toast.error('An error occurred in converting meta json to string')
return
} }
zip.file('hashes.json', JSON.stringify(hashes, null, 2)) setLoadingSpinnerDesc('Generating zip file')
const arrayBuffer = await zip const arraybuffer = await zip
.generateAsync({ .generateAsync({
type: 'arraybuffer', type: 'arraybuffer',
compression: 'DEFLATE', compression: 'DEFLATE',
@ -201,13 +276,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 +303,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
await sendDM( if (signers.length > 0) {
fileUrl, await sendDM(
encryptionKey, fileUrl,
receiver, encryptionKey,
nostrController, signers[0].pubkey,
isNextSigner, nostrController,
setAuthUrl true,
) 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 +349,193 @@ 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 <MuiFileInput
className={styles.inputBlock} multiple
onDrop={handleDrop} placeholder='Choose Files'
onDragOver={handleDragOver} value={selectedFiles}
> onChange={(value) => handleSelectFiles(value)}
{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'
}
}}
/>
</Box>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}> <ul>
<Button onClick={handleSign} variant='contained'> {selectedFiles.map((file, index) => (
Sign <li key={index}>
</Button> <Typography component='label'>{file.name}</Typography>
</Box> <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>
<DisplayUser
users={users}
handleUserRoleChange={handleUserRoleChange}
handleRemoveUser={handleRemoveUser}
/>
<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,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 { }
position: absolute;
top: 0; .subHeader {
left: 0; border-bottom: 0.5px solid;
width: 100%; }
height: 100%;
background-color: rgba(255, 255, 255, 0.8); .tableCell {
z-index: 1; border-right: 1px solid rgba(224, 224, 224, 1);
display: flex;
justify-content: center; .user {
align-items: center; display: flex;
align-items: center;
gap: 10px;
.name {
text-align: center;
cursor: pointer;
}
} }
} }

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

@ -0,0 +1,795 @@
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

@ -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 />
} }
] ]

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

@ -0,0 +1,17 @@
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

@ -0,0 +1,20 @@
export class DecryptionError extends Error {
public message: string = ''
constructor(
public inputError: any
) {
super()
if (inputError.message.toLowerCase().includes('expected')) {
this.message = `The decryption key length or format is invalid.`
} else if (inputError.message.includes('The JWK "alg" member was inconsistent')) {
this.message = `The decryption key is invalid.`
} else {
this.message = inputError.message || 'An error occurred while decrypting file.'
}
this.name = 'DecryptionError'
Object.setPrototypeOf(this, DecryptionError.prototype)
}
}

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

@ -3,6 +3,7 @@ export interface ProfileMetadata {
display_name?: string display_name?: string
picture?: string picture?: string
about?: string about?: string
website?: string
nip05?: string nip05?: string
lud16?: string lud16?: string
} }

View File

@ -4,6 +4,7 @@ import {
stringToHex, stringToHex,
uint8ArrayToHexString uint8ArrayToHexString
} from '.' } from '.'
import { DecryptionError } from '../types/errors/DecryptionError'
const ENCRYPTION_ALGO_NAME = 'AES-GCM' const ENCRYPTION_ALGO_NAME = 'AES-GCM'
@ -63,14 +64,18 @@ export const decryptArrayBuffer = async (
encryptedData: ArrayBuffer, encryptedData: ArrayBuffer,
key: string key: string
) => { ) => {
const { cryptoKey, iv } = await importKey(key) try {
const { cryptoKey, iv } = await importKey(key)
// Decrypt the data
const decryptedData = await window.crypto.subtle.decrypt( // Decrypt the data
{ name: ENCRYPTION_ALGO_NAME, iv }, const decryptedData = await window.crypto.subtle.decrypt(
cryptoKey, { name: ENCRYPTION_ALGO_NAME, iv },
encryptedData cryptoKey,
) encryptedData
)
return decryptedData
return decryptedData
} catch (err) {
throw new DecryptionError(err)
}
} }

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}`
@ -88,7 +92,7 @@ export const sendDM = async (
const timeoutPromise = new Promise<never>((_, reject) => { const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => { setTimeout(() => {
reject(new Error('Timeout occurred')) reject(new Error('Timeout occurred'))
}, 15000) // Timeout duration = 15 seconds }, 60000) // Timeout duration = 60 seconds
}) })
// Encrypt the DM content, with timeout // Encrypt the DM content, with timeout
@ -171,14 +175,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
}, },
@ -188,9 +190,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) {