store-sigits and update working flow #116

Merged
b merged 18 commits from store-sigits into staging 2024-07-11 11:42:19 +00:00
17 changed files with 1042 additions and 501 deletions
Showing only changes of commit d4c50dabaf - Show all commits

View File

@ -46,7 +46,6 @@ export class MetadataController extends EventEmitter {
const pool = new SimplePool() const pool = new SimplePool()
// todo: use nostrController to get event
// Try to get the metadata event from a special relay (wss://purplepag.es) // Try to get the metadata event from a special relay (wss://purplepag.es)
const metadataEvent = await pool const metadataEvent = await pool
.get([this.specialMetadataRelay], eventFilter) .get([this.specialMetadataRelay], eventFilter)
@ -62,14 +61,17 @@ export class MetadataController extends EventEmitter {
verifyEvent(metadataEvent) // Verify the event's authenticity verifyEvent(metadataEvent) // Verify the event's authenticity
) { ) {
// If there's no current event or the new metadata event is more recent // If there's no current event or the new metadata event is more recent
if (!currentEvent || metadataEvent.created_at > currentEvent.created_at) { if (
!currentEvent ||
metadataEvent.created_at >= currentEvent.created_at
) {
// Handle the new metadata event // Handle the new metadata event
this.handleNewMetadataEvent(metadataEvent) this.handleNewMetadataEvent(metadataEvent)
return metadataEvent
}
} }
// todo use nostr controller to find event from connected relays return metadataEvent
}
// If no valid metadata event is found from the special relay, get the most popular relays // If no valid metadata event is found from the special relay, get the most popular relays
const mostPopularRelays = await this.nostrController.getMostPopularRelays() const mostPopularRelays = await this.nostrController.getMostPopularRelays()
@ -125,11 +127,11 @@ export class MetadataController extends EventEmitter {
// If cached metadata is found, check its validity // If cached metadata is found, check its validity
if (cachedMetadataEvent) { if (cachedMetadataEvent) {
const oneDayInMS = 24 * 60 * 60 * 1000 // Number of milliseconds in one day const oneWeekInMS = 7 * 24 * 60 * 60 * 1000 // Number of milliseconds in one week
// Check if the cached metadata is older than one day // Check if the cached metadata is older than one week
if (Date.now() - cachedMetadataEvent.cachedAt > oneDayInMS) { if (Date.now() - cachedMetadataEvent.cachedAt > oneWeekInMS) {
// If older than one day, find the metadata from relays in background // If older than one week, find the metadata from relays in background
this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event) this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event)
} }

View File

@ -1,30 +1,40 @@
import { Box } from '@mui/material' import { Box } from '@mui/material'
import Container from '@mui/material/Container' import Container from '@mui/material/Container'
import { Event, kinds } from 'nostr-tools'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux' import { useDispatch, useSelector } from 'react-redux'
import { Outlet } from 'react-router-dom' import { Outlet } from 'react-router-dom'
import { AppBar } from '../components/AppBar/AppBar' import { AppBar } from '../components/AppBar/AppBar'
import { restoreState, setAuthState, setMetadataEvent } from '../store/actions' import { LoadingSpinner } from '../components/LoadingSpinner'
import { MetadataController, NostrController } from '../controllers'
import {
restoreState,
setAuthState,
setMetadataEvent,
updateUserAppData
} from '../store/actions'
import { LoginMethods } from '../store/auth/types'
import { State } from '../store/rootReducer'
import { Dispatch } from '../store/store'
import { setUserRobotImage } from '../store/userRobotImage/action'
import { import {
clearAuthToken, clearAuthToken,
clearState, clearState,
getRoboHashPicture, getRoboHashPicture,
getUsersAppData,
loadState, loadState,
saveNsecBunkerDelegatedKey, saveNsecBunkerDelegatedKey,
subscribeForSigits subscribeForSigits
} from '../utils' } from '../utils'
import { LoadingSpinner } from '../components/LoadingSpinner' import { useAppSelector } from '../hooks'
import { Dispatch } from '../store/store' import { SubCloser } from 'nostr-tools/abstract-pool'
import { MetadataController, NostrController } from '../controllers'
import { LoginMethods } from '../store/auth/types'
import { setUserRobotImage } from '../store/userRobotImage/action'
import { State } from '../store/rootReducer'
import { Event, kinds } from 'nostr-tools'
export const MainLayout = () => { export const MainLayout = () => {
const dispatch: Dispatch = useDispatch() const dispatch: Dispatch = useDispatch()
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState(`Loading App`)
const authState = useSelector((state: State) => state.auth) const authState = useSelector((state: State) => state.auth)
const usersAppData = useAppSelector((state) => state.userAppData)
useEffect(() => { useEffect(() => {
const metadataController = new MetadataController() const metadataController = new MetadataController()
@ -84,11 +94,47 @@ export const MainLayout = () => {
metadataController.findMetadata(usersPubkey).then((metadataEvent) => { metadataController.findMetadata(usersPubkey).then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(metadataEvent) if (metadataEvent) handleMetadataEvent(metadataEvent)
}) })
setLoadingSpinnerDesc(`Fetching user's app data`)
getUsersAppData()
.then((appData) => {
if (appData) {
dispatch(updateUserAppData(appData))
}
})
.finally(() => setIsLoading(false))
} else {
setIsLoading(false)
}
} else {
setIsLoading(false)
}
}, [dispatch])
useEffect(() => {
let subCloser: SubCloser | null = null
if (authState.loggedIn && usersAppData) {
const pubkey = authState.usersPubkey || authState.keyPair?.public
if (pubkey) {
/**
* Sigit notifications are wrapped using nip 59 seal and gift wrap scheme.
* According to nip59 created_at for seal and gift wrap should be tweaked to thwart time-analysis attacks.
* For the above purpose created_at is set to random time upto 2 days in past
*/
subscribeForSigits(pubkey).then((res) => {
subCloser = res || null
})
} }
} }
setIsLoading(false) return () => {
}, [dispatch]) if (subCloser) {
subCloser.close()
}
}
}, [authState, usersAppData])
/** /**
* When authState change user logged in / or app reloaded * When authState change user logged in / or app reloaded
@ -101,13 +147,11 @@ export const MainLayout = () => {
if (pubkey) { if (pubkey) {
dispatch(setUserRobotImage(getRoboHashPicture(pubkey))) dispatch(setUserRobotImage(getRoboHashPicture(pubkey)))
subscribeForSigits(pubkey)
} }
} }
}, [authState]) }, [authState])
if (isLoading) return <LoadingSpinner desc="Loading App" /> if (isLoading) return <LoadingSpinner desc={loadingSpinnerDesc} />
return ( return (
<> <>

View File

@ -23,19 +23,23 @@ import saveAs from 'file-saver'
import JSZip from 'jszip' import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input' import { MuiFileInput } from 'mui-file-input'
import { Event, kinds } from 'nostr-tools' import { Event, kinds } from 'nostr-tools'
import { useEffect, useMemo, useRef, useState } from 'react' import { useEffect, useRef, useState } from 'react'
import { DndProvider, useDrag, useDrop } from 'react-dnd' import { DndProvider, useDrag, useDrop } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend' import { HTML5Backend } from 'react-dnd-html5-backend'
import { useSelector } from 'react-redux' import { useSelector } from 'react-redux'
import { useLocation, useNavigate } from 'react-router-dom' import { useLocation, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { v4 as uuidV4 } from 'uuid'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserComponent } from '../../components/username' import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers' import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer' import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types' import {
CreateSignatureEventContent,
Meta,
ProfileMetadata,
User,
UserRole
} from '../../types'
import { import {
encryptArrayBuffer, encryptArrayBuffer,
generateEncryptionKey, generateEncryptionKey,
@ -54,6 +58,7 @@ import {
uploadToFileStorage uploadToFileStorage
} from '../../utils' } from '../../utils'
import styles from './style.module.scss' import styles from './style.module.scss'
import { appPrivateRoutes } from '../../routes'
export const CreatePage = () => { export const CreatePage = () => {
const navigate = useNavigate() const navigate = useNavigate()
@ -83,10 +88,6 @@ export const CreatePage = () => {
setAuthUrl(url) setAuthUrl(url)
}) })
const uuid = useMemo(() => {
return uuidV4()
}, [])
useEffect(() => { useEffect(() => {
if (uploadedFile) { if (uploadedFile) {
setSelectedFiles([uploadedFile]) setSelectedFiles([uploadedFile])
@ -295,56 +296,6 @@ export const CreatePage = () => {
return fileHashes return fileHashes
} }
// initialize a zip file with the selected files and generate creator's signature
const initZipFileAndCreatorSignature = async (
encryptionKey: string,
fileHashes: {
[key: string]: string
}
): Promise<{ zip: JSZip; createSignature: string } | null> => {
const zip = new JSZip()
selectedFiles.forEach((file) => {
zip.file(`files/${file.name}`, file)
})
// generate key pairs for decryption
const pubkeys = users.map((user) => user.pubkey)
// also add creator in the list
if (pubkeys.includes(usersPubkey!)) {
pubkeys.push(usersPubkey!)
}
const keys = await generateKeys(pubkeys, encryptionKey)
const signers = users.filter((user) => user.role === UserRole.signer)
const viewers = users.filter((user) => user.role === UserRole.viewer)
setLoadingSpinnerDesc('Signing nostr event')
const createSignature = await signEventForMetaFile(
JSON.stringify({
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
fileHashes,
keys
}),
nostrController,
setIsLoading
)
if (!createSignature) return null
try {
return {
zip,
createSignature: JSON.stringify(createSignature, null, 2)
}
} catch (error) {
return null
}
}
// Handle errors during zip file generation // Handle errors during zip file generation
const handleZipError = (err: any) => { const handleZipError = (err: any) => {
console.log('Error in zip:>> ', err) console.log('Error in zip:>> ', err)
@ -377,7 +328,7 @@ export const CreatePage = () => {
return encryptArrayBuffer(arraybuffer, encryptionKey) return encryptArrayBuffer(arraybuffer, encryptionKey)
} }
// create final zip file // create final zip file for offline mode
const createFinalZipFile = async ( const createFinalZipFile = async (
encryptedArrayBuffer: ArrayBuffer, encryptedArrayBuffer: ArrayBuffer,
encryptionKey: string encryptionKey: string
@ -423,28 +374,6 @@ export const CreatePage = () => {
return finalZipFile return finalZipFile
} }
const handleOnlineFlow = async (
encryptedArrayBuffer: ArrayBuffer,
meta: Meta
) => {
const unixNow = now()
const blob = new Blob([encryptedArrayBuffer])
// Create a File object with the Blob data
const file = new File([blob], `compressed-${unixNow}.sigit`, {
type: 'application/sigit'
})
const fileUrl = await uploadFile(file)
if (!fileUrl) return
const updatedEvent = await updateUsersAppData(fileUrl, meta)
if (!updatedEvent) return
await sendDMs(fileUrl, meta)
navigate(appPrivateRoutes.sign, { state: { sigit: { fileUrl, meta } } })
}
// Handle errors during file upload // Handle errors during file upload
const handleUploadError = (err: any) => { const handleUploadError = (err: any) => {
console.log('Error in upload:>> ', err) console.log('Error in upload:>> ', err)
@ -454,13 +383,19 @@ export const CreatePage = () => {
} }
// Upload the file to the storage // Upload the file to the storage
const uploadFile = async (file: File): Promise<string | null> => { const uploadFile = async (
setIsLoading(true) arrayBuffer: ArrayBuffer
setLoadingSpinnerDesc('Uploading sigit to file storage.') ): Promise<string | null> => {
const unixNow = now()
const blob = new Blob([arrayBuffer])
// Create a File object with the Blob data
const file = new File([blob], `compressed-${unixNow}.sigit`, {
type: 'application/sigit'
})
const fileUrl = await uploadToFileStorage(file, nostrController) const fileUrl = await uploadToFileStorage(file, nostrController)
.then((url) => { .then((url) => {
toast.success('Sigit uploaded to file storage') toast.success('files.zip uploaded to file storage')
return url return url
}) })
.catch(handleUploadError) .catch(handleUploadError)
@ -468,24 +403,6 @@ export const CreatePage = () => {
return fileUrl return fileUrl
} }
// Send DMs to signers and viewers with the file URL
const sendDMs = async (fileUrl: string, meta: Meta) => {
setLoadingSpinnerDesc('Sending DM to signers/viewers')
const signers = users.filter((user) => user.role === UserRole.signer)
const viewers = users.filter((user) => user.role === UserRole.viewer)
const receivers =
signers.length > 0
? [signers[0].pubkey]
: viewers.map((viewer) => viewer.pubkey)
const promises = receivers.map((receiver) =>
sendNotification(receiver, meta, fileUrl)
)
await Promise.allSettled(promises)
}
// Manage offline scenarios for signing or viewing the file // Manage offline scenarios for signing or viewing the file
const handleOfflineFlow = async ( const handleOfflineFlow = async (
encryptedArrayBuffer: ArrayBuffer, encryptedArrayBuffer: ArrayBuffer,
@ -501,35 +418,185 @@ export const CreatePage = () => {
saveAs(finalZipFile, 'request.sigit.zip') saveAs(finalZipFile, 'request.sigit.zip')
} }
const generateFilesZip = async (): Promise<ArrayBuffer | null> => {
const zip = new JSZip()
selectedFiles.forEach((file) => {
zip.file(file.name, file)
})
const arraybuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
})
.catch(handleZipError)
return arraybuffer
}
const generateCreateSignature = async (
fileHashes: {
[key: string]: string
},
zipUrl: string
) => {
const signers = users.filter((user) => user.role === UserRole.signer)
const viewers = users.filter((user) => user.role === UserRole.viewer)
const content: CreateSignatureEventContent = {
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
fileHashes,
zipUrl,
title
}
setLoadingSpinnerDesc('Signing nostr event for create signature')
try {
const createSignature = await signEventForMetaFile(
JSON.stringify(content),
nostrController,
setIsLoading
)
if (!createSignature) return null
return JSON.stringify(createSignature, null, 2)
} catch (error) {
return null
}
}
// Send notifications to signers and viewers
const sendNotifications = (meta: Meta) => {
const signers = users.filter((user) => user.role === UserRole.signer)
const viewers = users.filter((user) => user.role === UserRole.viewer)
// no need to send notification to self so remove it from the list
const receivers = (
signers.length > 0
? [signers[0].pubkey]
: viewers.map((viewer) => viewer.pubkey)
).filter((receiver) => receiver !== usersPubkey)
const promises = receivers.map((receiver) =>
sendNotification(receiver, meta)
)
return promises
}
const handleCreate = async () => { const handleCreate = async () => {
if (!validateInputs()) return if (!validateInputs()) return
setIsLoading(true) setIsLoading(true)
setLoadingSpinnerDesc('Generating hashes for files') setLoadingSpinnerDesc('Generating file hashes')
const fileHashes = await generateFileHashes() const fileHashes = await generateFileHashes()
if (!fileHashes) return if (!fileHashes) {
setIsLoading(false)
return
}
setLoadingSpinnerDesc('Generating encryption key')
const encryptionKey = await generateEncryptionKey() const encryptionKey = await generateEncryptionKey()
const createZipResponse = await initZipFileAndCreatorSignature( if (await isOnline()) {
encryptionKey, setLoadingSpinnerDesc('generating files.zip')
fileHashes const arrayBuffer = await generateFilesZip()
if (!arrayBuffer) {
setIsLoading(false)
return
}
setLoadingSpinnerDesc('Encrypting files.zip')
const encryptedArrayBuffer = await encryptZipFile(
arrayBuffer,
encryptionKey
) )
if (!createZipResponse) return
const { zip, createSignature } = createZipResponse setLoadingSpinnerDesc('Uploading files.zip to file storage')
const fileUrl = await uploadFile(encryptedArrayBuffer)
if (!fileUrl) {
setIsLoading(false)
return
}
// create content for meta file setLoadingSpinnerDesc('Generating create signature')
const createSignature = await generateCreateSignature(fileHashes, fileUrl)
if (!createSignature) {
setIsLoading(false)
return
}
setLoadingSpinnerDesc('Generating keys for decryption')
// generate key pairs for decryption
const pubkeys = users.map((user) => user.pubkey)
// also add creator in the list
if (pubkeys.includes(usersPubkey!)) {
pubkeys.push(usersPubkey!)
}
const keys = await generateKeys(pubkeys, encryptionKey)
if (!keys) {
setIsLoading(false)
return
}
const meta: Meta = { const meta: Meta = {
uuid,
title,
modifiedAt: now(),
createSignature, createSignature,
keys,
modifiedAt: now(),
docSignatures: {} docSignatures: {}
} }
setLoadingSpinnerDesc('Generating zip file') setLoadingSpinnerDesc('Updating user app data')
const event = await updateUsersAppData(meta)
if (!event) {
setIsLoading(false)
return
}
setLoadingSpinnerDesc('Sending notifications to counterparties')
const promises = sendNotifications(meta)
await Promise.all(promises)
.then(() => {
toast.success('Notifications sent successfully')
})
.catch(() => {
toast.error('Failed to publish notifications')
})
navigate(appPrivateRoutes.sign, { state: { meta: meta } })
} else {
const zip = new JSZip()
selectedFiles.forEach((file) => {
zip.file(`files/${file.name}`, file)
})
setLoadingSpinnerDesc('Generating create signature')
const createSignature = await generateCreateSignature(fileHashes, '')
if (!createSignature) return
const meta: Meta = {
createSignature,
modifiedAt: now(),
docSignatures: {}
}
// add meta to zip
try {
const stringifiedMeta = JSON.stringify(meta, null, 2)
zip.file('meta.json', stringifiedMeta)
} catch (err) {
console.error(err)
toast.error('An error occurred in converting meta json to string')
return null
}
const arrayBuffer = await generateZipFile(zip) const arrayBuffer = await generateZipFile(zip)
if (!arrayBuffer) return if (!arrayBuffer) return
@ -540,10 +607,6 @@ export const CreatePage = () => {
encryptionKey encryptionKey
) )
if (await isOnline()) {
await handleOnlineFlow(encryptedArrayBuffer, meta)
} else {
// todo: fix offline flow
await handleOfflineFlow(encryptedArrayBuffer, encryptionKey) await handleOfflineFlow(encryptedArrayBuffer, encryptionKey)
} }
} }

View File

@ -1,59 +1,38 @@
import { Add, CalendarMonth, Description, Upload } from '@mui/icons-material' import { Add, CalendarMonth, Description, Upload } from '@mui/icons-material'
import { Box, Button, Tooltip, Typography } from '@mui/material' import { Box, Button, Tooltip, Typography } from '@mui/material'
import JSZip from 'jszip' import JSZip from 'jszip'
import { Event, kinds, verifyEvent } from 'nostr-tools'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react' import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { UserComponent } from '../../components/username'
import { MetadataController } from '../../controllers'
import { useAppSelector } from '../../hooks'
import { appPrivateRoutes, appPublicRoutes } from '../../routes' import { appPrivateRoutes, appPublicRoutes } from '../../routes'
import styles from './style.module.scss' import { CreateSignatureEventContent, Meta, ProfileMetadata } from '../../types'
import { MetadataController, NostrController } from '../../controllers'
import { import {
formatTimestamp, formatTimestamp,
getUsersAppData,
hexToNpub, hexToNpub,
npubToHex, npubToHex,
parseJson, parseJson,
shorten shorten
} from '../../utils' } from '../../utils'
import { LoadingSpinner } from '../../components/LoadingSpinner' import styles from './style.module.scss'
import {
CreateSignatureEventContent,
Meta,
ProfileMetadata,
Sigit
} from '../../types'
import { Event, kinds, verifyEvent } from 'nostr-tools'
import { UserComponent } from '../../components/username'
export const HomePage = () => { export const HomePage = () => {
const navigate = useNavigate() const navigate = useNavigate()
const fileInputRef = useRef<HTMLInputElement>(null) const fileInputRef = useRef<HTMLInputElement>(null)
const [isLoading, setIsLoading] = useState(true) const [sigits, setSigits] = useState<Meta[]>([])
const [loadingSpinnerDesc] = useState(`Finding user's app data`)
const [authUrl, setAuthUrl] = useState<string>()
const [sigits, setSigits] = useState<Sigit[]>([])
const [profiles, setProfiles] = useState<{ [key: string]: ProfileMetadata }>( const [profiles, setProfiles] = useState<{ [key: string]: ProfileMetadata }>(
{} {}
) )
const usersAppData = useAppSelector((state) => state.userAppData)
useEffect(() => { useEffect(() => {
const nostrController = NostrController.getInstance() if (usersAppData) {
// Set up event listener for authentication event setSigits(Object.values(usersAppData.sigits))
nostrController.on('nsecbunker-auth', (url) => {
setAuthUrl(url)
})
getUsersAppData()
.then((res) => {
if (res) {
setSigits(Object.values(res))
} }
}) }, [usersAppData])
.finally(() => {
setIsLoading(false)
})
}, [])
const handleUploadClick = () => { const handleUploadClick = () => {
if (fileInputRef.current) { if (fileInputRef.current) {
@ -101,20 +80,8 @@ export const HomePage = () => {
} }
} }
if (authUrl) {
return (
<iframe
title="Nsecbunker auth"
src={authUrl}
width="100%"
height="500px"
/>
)
}
return ( return (
<> <>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}> <Box className={styles.container}>
<Box className={styles.header}> <Box className={styles.header}>
<Typography variant="h3" className={styles.title}> <Typography variant="h3" className={styles.title}>
@ -180,10 +147,10 @@ export const HomePage = () => {
</Box> </Box>
</Box> </Box>
<Box className={styles.submissions}> <Box className={styles.submissions}>
{sigits.map((sigit) => ( {sigits.map((sigit, index) => (
<DisplaySigit <DisplaySigit
key={sigit.meta.uuid} key={`sigit-${index}`}
sigit={sigit} meta={sigit}
profiles={profiles} profiles={profiles}
setProfiles={setProfiles} setProfiles={setProfiles}
/> />
@ -195,22 +162,31 @@ export const HomePage = () => {
} }
type SigitProps = { type SigitProps = {
sigit: Sigit meta: Meta
profiles: { [key: string]: ProfileMetadata } profiles: { [key: string]: ProfileMetadata }
setProfiles: Dispatch<SetStateAction<{ [key: string]: ProfileMetadata }>> setProfiles: Dispatch<SetStateAction<{ [key: string]: ProfileMetadata }>>
} }
const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => { enum SignedStatus {
Partial = 'Partially Signed',
Complete = 'Completely Signed'
}
const DisplaySigit = ({ meta, profiles, setProfiles }: SigitProps) => {
const navigate = useNavigate() const navigate = useNavigate()
const [title, setTitle] = useState<string>()
const [createdAt, setCreatedAt] = useState('') const [createdAt, setCreatedAt] = useState('')
const [submittedBy, setSubmittedBy] = useState<string>() const [submittedBy, setSubmittedBy] = useState<string>()
const [signers, setSigners] = useState<`npub1${string}`[]>([]) const [signers, setSigners] = useState<`npub1${string}`[]>([])
const [signedStatus, setSignedStatus] = useState<SignedStatus>(
SignedStatus.Partial
)
useEffect(() => { useEffect(() => {
const extractInfo = async () => { const extractInfo = async () => {
const createSignatureEvent = await parseJson<Event>( const createSignatureEvent = await parseJson<Event>(
sigit.meta.createSignature meta.createSignature
).catch((err) => { ).catch((err) => {
console.log('err in parsing the createSignature event:>> ', err) console.log('err in parsing the createSignature event:>> ', err)
toast.error( toast.error(
@ -238,11 +214,20 @@ const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
if (!createSignatureContent) return if (!createSignatureContent) return
setTitle(createSignatureContent.title)
setSubmittedBy(createSignatureEvent.pubkey) setSubmittedBy(createSignatureEvent.pubkey)
setSigners(createSignatureContent.signers) setSigners(createSignatureContent.signers)
const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[]
const isCompletelySigned = createSignatureContent.signers.every(
(signer) => signedBy.includes(signer)
)
if (isCompletelySigned) {
setSignedStatus(SignedStatus.Complete)
}
} }
extractInfo() extractInfo()
}, [sigit]) }, [meta])
useEffect(() => { useEffect(() => {
const hexKeys: string[] = [] const hexKeys: string[] = []
@ -285,7 +270,11 @@ const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
}, [submittedBy, signers]) }, [submittedBy, signers])
const handleNavigation = () => { const handleNavigation = () => {
navigate(appPrivateRoutes.sign, { state: { sigit } }) if (signedStatus === SignedStatus.Complete) {
navigate(appPublicRoutes.verify, { state: { meta } })
} else {
navigate(appPrivateRoutes.sign, { state: { meta } })
}
} }
return ( return (
@ -314,7 +303,7 @@ const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
> >
<Typography variant="body1" className={styles.title}> <Typography variant="body1" className={styles.title}>
<Description /> <Description />
{sigit.meta.title} {title}
</Typography> </Typography>
{submittedBy && {submittedBy &&
(function () { (function () {
@ -344,7 +333,7 @@ const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
return ( return (
<DisplaySigner <DisplaySigner
key={signer} key={signer}
meta={sigit.meta} meta={meta}
profile={profile} profile={profile}
pubkey={pubkey} pubkey={pubkey}
/> />

View File

@ -13,16 +13,11 @@ import { LoadingSpinner } from '../../components/LoadingSpinner'
import { NostrController } from '../../controllers' import { NostrController } from '../../controllers'
import { appPublicRoutes } from '../../routes' import { appPublicRoutes } from '../../routes'
import { State } from '../../store/rootReducer' import { State } from '../../store/rootReducer'
import { import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types'
CreateSignatureEventContent,
Meta,
Sigit,
SignedEvent
} from '../../types'
import { import {
decryptArrayBuffer, decryptArrayBuffer,
encryptArrayBuffer, encryptArrayBuffer,
extractEncryptionKey, extractZipUrlAndEncryptionKey,
generateEncryptionKey, generateEncryptionKey,
generateKeysFile, generateKeysFile,
getHash, getHash,
@ -48,7 +43,7 @@ export const SignPage = () => {
const navigate = useNavigate() const navigate = useNavigate()
const location = useLocation() const location = useLocation()
const { const {
sigit, meta: metaInNavState,
arrayBuffer: decryptedArrayBuffer, arrayBuffer: decryptedArrayBuffer,
uploadedZip uploadedZip
} = location.state || {} } = location.state || {}
@ -57,12 +52,11 @@ export const SignPage = () => {
const [selectedFile, setSelectedFile] = useState<File | null>(null) const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [zip, setZip] = useState<JSZip>() const [files, setFiles] = useState<{ [filename: string]: ArrayBuffer }>({})
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [fileUrl, setFileUrl] = useState<string>()
const [meta, setMeta] = useState<Meta | null>(null) const [meta, setMeta] = useState<Meta | null>(null)
const [signedStatus, setSignedStatus] = useState<SignedStatus>() const [signedStatus, setSignedStatus] = useState<SignedStatus>()
@ -89,41 +83,6 @@ export const SignPage = () => {
const [authUrl, setAuthUrl] = useState<string>() const [authUrl, setAuthUrl] = useState<string>()
const nostrController = NostrController.getInstance() const nostrController = NostrController.getInstance()
useEffect(() => {
if (zip) {
const generateCurrentFileHashes = async () => {
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
.map((entry) => entry.name)
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
if (arrayBuffer) {
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName.replace(/^files\//, '')] = hash
}
} else {
fileHashes[fileName.replace(/^files\//, '')] = null
}
}
setCurrentFileHashes(fileHashes)
}
generateCurrentFileHashes()
}
}, [zip])
useEffect(() => { useEffect(() => {
if (signers.length > 0) { if (signers.length > 0) {
// check if all signers have signed then its fully signed // check if all signers have signed then its fully signed
@ -223,65 +182,32 @@ export const SignPage = () => {
}, [meta]) }, [meta])
useEffect(() => { useEffect(() => {
if (sigit) { if (metaInNavState) {
const processSigit = async () => { const processSigit = async () => {
setIsLoading(true) setIsLoading(true)
setLoadingSpinnerDesc( setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
'Extracting encryption key from creator signature'
)
const { fileUrl, meta } = sigit as Sigit const res = await extractZipUrlAndEncryptionKey(metaInNavState)
if (!res) {
const encryptionKey = await extractEncryptionKey(
meta.createSignature
).then(async (res) => {
if (!res) return null
const { sender, encryptedKey } = res
const decrypted = await nostrController
.nip04Decrypt(sender, encryptedKey)
.catch((err) => {
console.log('An error occurred in decrypting encryption key', err)
toast.error('An error occurred in decrypting encryption key')
return null
})
return decrypted
})
if (!encryptionKey) {
setIsLoading(false) setIsLoading(false)
return return
} }
const { zipUrl, encryptionKey } = res
setLoadingSpinnerDesc('Fetching file from file server') setLoadingSpinnerDesc('Fetching file from file server')
setFileUrl(fileUrl)
axios axios
.get(fileUrl, { .get(zipUrl, {
responseType: 'arraybuffer' responseType: 'arraybuffer'
}) })
.then(async (res) => { .then((res) => {
const fileName = fileUrl.split('/').pop() handleArrayBufferFromBlossom(res.data, encryptionKey)
const file = new File([res.data], fileName!) setMeta(metaInNavState)
const encryptedArrayBuffer = await file.arrayBuffer()
const arrayBuffer = await decryptArrayBuffer(
encryptedArrayBuffer,
encryptionKey
).catch((err) => {
console.log('err in decryption:>> ', err)
toast.error(
err.message || 'An error occurred in decrypting file.'
)
return null
})
if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer, meta)
}) })
.catch((err) => { .catch((err) => {
console.error(`error occurred in getting file from ${fileUrl}`, err) console.error(`error occurred in getting file from ${zipUrl}`, err)
toast.error( toast.error(
err.message || `error occurred in getting file from ${fileUrl}` err.message || `error occurred in getting file from ${zipUrl}`
) )
}) })
.finally(() => { .finally(() => {
@ -310,7 +236,63 @@ export const SignPage = () => {
setIsLoading(false) setIsLoading(false)
setDisplayInput(true) setDisplayInput(true)
} }
}, [decryptedArrayBuffer, uploadedZip]) }, [decryptedArrayBuffer, uploadedZip, metaInNavState])
const handleArrayBufferFromBlossom = async (
arrayBuffer: ArrayBuffer,
encryptionKey: string
) => {
// array buffer returned from blossom is encrypted.
// So, first decrypt it
const decrypted = await decryptArrayBuffer(
arrayBuffer,
encryptionKey
).catch((err) => {
console.log('err in decryption:>> ', err)
toast.error(err.message || 'An error occurred in decrypting file.')
setIsLoading(false)
return null
})
if (!decrypted) return
const zip = await JSZip.loadAsync(decrypted).catch((err) => {
console.log('err in loading zip file :>> ', err)
toast.error(err.message || 'An error occurred in loading zip file.')
setIsLoading(false)
return null
})
if (!zip) return
const files: { [filename: string]: ArrayBuffer } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files).map((entry) => entry.name)
// generate hashes for all files in zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
if (arrayBuffer) {
files[fileName] = arrayBuffer
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName] = hash
}
} else {
fileHashes[fileName] = null
}
}
setFiles(files)
setCurrentFileHashes(fileHashes)
}
const parseKeysJson = async (zip: JSZip) => { const parseKeysJson = async (zip: JSZip) => {
const keysFileContent = await readContentOfZipEntry( const keysFileContent = await readContentOfZipEntry(
@ -405,10 +387,7 @@ export const SignPage = () => {
return null return null
} }
const handleDecryptedArrayBuffer = async ( const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => {
arrayBuffer: ArrayBuffer,
meta?: Meta
) => {
const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip') const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip')
setLoadingSpinnerDesc('Parsing zip file') setLoadingSpinnerDesc('Parsing zip file')
@ -421,14 +400,39 @@ export const SignPage = () => {
if (!zip) return if (!zip) return
setZip(zip) const files: { [filename: string]: ArrayBuffer } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
.map((entry) => entry.name)
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (let fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
fileName = fileName.replace(/^files\//, '')
if (arrayBuffer) {
files[fileName] = arrayBuffer
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName] = hash
}
} else {
fileHashes[fileName] = null
}
}
setFiles(files)
setCurrentFileHashes(fileHashes)
setDisplayInput(false) setDisplayInput(false)
let parsedMetaJson: Meta | null = null
if (meta) {
parsedMetaJson = meta
} else {
setLoadingSpinnerDesc('Parsing meta.json') setLoadingSpinnerDesc('Parsing meta.json')
const metaFileContent = await readContentOfZipEntry( const metaFileContent = await readContentOfZipEntry(
@ -442,15 +446,16 @@ export const SignPage = () => {
return return
} }
parsedMetaJson = await parseJson<Meta>(metaFileContent).catch((err) => { const parsedMetaJson = await parseJson<Meta>(metaFileContent).catch(
(err) => {
console.log('err in parsing the content of meta.json :>> ', err) console.log('err in parsing the content of meta.json :>> ', err)
toast.error( toast.error(
err.message || 'error occurred in parsing the content of meta.json' err.message || 'error occurred in parsing the content of meta.json'
) )
setIsLoading(false) setIsLoading(false)
return null return null
})
} }
)
setMeta(parsedMetaJson) setMeta(parsedMetaJson)
} }
@ -467,7 +472,7 @@ export const SignPage = () => {
} }
const handleSign = async () => { const handleSign = async () => {
if (!zip || !meta) return if (Object.entries(files).length === 0 || !meta) return
setIsLoading(true) setIsLoading(true)
@ -480,13 +485,12 @@ export const SignPage = () => {
if (!signedEvent) return if (!signedEvent) return
const updatedMeta = updateMetaSignatures(meta, signedEvent) const updatedMeta = updateMetaSignatures(meta, signedEvent)
setMeta(updatedMeta)
if (await isOnline()) { if (await isOnline()) {
if (fileUrl) await handleOnlineFlow(fileUrl, updatedMeta) await handleOnlineFlow(updatedMeta)
} else { } else {
// todo: fix offline flow setMeta(updatedMeta)
// handleDecryptedArrayBuffer(arrayBuffer).finally(() => setIsLoading(false)) setIsLoading(false)
} }
} }
@ -585,31 +589,33 @@ export const SignPage = () => {
return null return null
} }
// Handle the online flow: upload file and send DMs // Handle the online flow: update users app data and send notifications
const handleOnlineFlow = async (fileUrl: string, meta: Meta) => { const handleOnlineFlow = async (meta: Meta) => {
setLoadingSpinnerDesc('Updating users app data') setLoadingSpinnerDesc('Updating users app data')
const updatedEvent = await updateUsersAppData(fileUrl, meta) const updatedEvent = await updateUsersAppData(meta)
if (!updatedEvent) { if (!updatedEvent) {
setIsLoading(false) setIsLoading(false)
return return
} }
const userSet = new Set<`npub1${string}`>() const userSet = new Set<`npub1${string}`>()
if (submittedBy) { if (submittedBy && submittedBy !== usersPubkey) {
userSet.add(hexToNpub(submittedBy)) userSet.add(hexToNpub(submittedBy))
} }
const usersNpub = hexToNpub(usersPubkey!)
const isLastSigner = checkIsLastSigner(signers) const isLastSigner = checkIsLastSigner(signers)
if (isLastSigner) { if (isLastSigner) {
signers.forEach((signer) => { signers.forEach((signer) => {
if (signer !== usersNpub) {
userSet.add(signer) userSet.add(signer)
}
}) })
viewers.forEach((viewer) => { viewers.forEach((viewer) => {
userSet.add(viewer) userSet.add(viewer)
}) })
} else { } else {
const usersNpub = hexToNpub(usersPubkey!)
const currentSignerIndex = signers.indexOf(usersNpub) const currentSignerIndex = signers.indexOf(usersNpub)
const prevSigners = signers.slice(0, currentSignerIndex) const prevSigners = signers.slice(0, currentSignerIndex)
@ -624,9 +630,16 @@ export const SignPage = () => {
setLoadingSpinnerDesc('Sending notifications') setLoadingSpinnerDesc('Sending notifications')
const users = Array.from(userSet) const users = Array.from(userSet)
const promises = users.map((user) => const promises = users.map((user) =>
sendNotification(npubToHex(user)!, meta, fileUrl) sendNotification(npubToHex(user)!, meta)
) )
await Promise.allSettled(promises) await Promise.all(promises)
.then(() => {
toast.success('Notifications sent successfully')
setMeta(meta)
})
.catch(() => {
toast.error('Failed to publish notifications')
})
setIsLoading(false) setIsLoading(false)
} }
@ -640,7 +653,7 @@ export const SignPage = () => {
} }
const handleExport = async () => { const handleExport = async () => {
if (!meta || !zip || !usersPubkey) return if (Object.entries(files).length === 0 || !meta || !usersPubkey) return
const usersNpub = hexToNpub(usersPubkey) const usersNpub = hexToNpub(usersPubkey)
if ( if (
@ -653,7 +666,7 @@ export const SignPage = () => {
setIsLoading(true) setIsLoading(true)
setLoadingSpinnerDesc('Signing nostr event') setLoadingSpinnerDesc('Signing nostr event')
const prevSig = await getLastSignersSig() const prevSig = getLastSignersSig()
if (!prevSig) return if (!prevSig) return
const signedEvent = await signEventForMetaFile( const signedEvent = await signEventForMetaFile(
@ -676,8 +689,15 @@ export const SignPage = () => {
null, null,
2 2
) )
const zip = new JSZip()
zip.file('meta.json', stringifiedMeta) zip.file('meta.json', stringifiedMeta)
Object.entries(files).forEach(([fileName, arrayBuffer]) => {
zip.file(`files/${fileName}`, arrayBuffer)
})
const arrayBuffer = await zip const arrayBuffer = await zip
.generateAsync({ .generateAsync({
type: 'arraybuffer', type: 'arraybuffer',
@ -705,7 +725,17 @@ export const SignPage = () => {
} }
const handleExportSigit = async () => { const handleExportSigit = async () => {
if (!zip) return if (Object.entries(files).length === 0 || !meta) return
const zip = new JSZip()
const stringifiedMeta = JSON.stringify(meta, null, 2)
zip.file('meta.json', stringifiedMeta)
Object.entries(files).forEach(([fileName, arrayBuffer]) => {
zip.file(`files/${fileName}`, arrayBuffer)
})
const arrayBuffer = await zip const arrayBuffer = await zip
.generateAsync({ .generateAsync({
@ -840,11 +870,11 @@ export const SignPage = () => {
</> </>
)} )}
{submittedBy && zip && meta && ( {submittedBy && Object.entries(files).length > 0 && meta && (
<> <>
<DisplayMeta <DisplayMeta
meta={meta} meta={meta}
zip={zip} files={files}
submittedBy={submittedBy} submittedBy={submittedBy}
signers={signers} signers={signers}
viewers={viewers} viewers={viewers}
@ -871,7 +901,6 @@ export const SignPage = () => {
</Box> </Box>
)} )}
{/* todo: In offline mode export sigit is not visible after last signer has signed*/}
{isSignerOrCreator && ( {isSignerOrCreator && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}> <Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExportSigit} variant="contained"> <Button onClick={handleExportSigit} variant="contained">

View File

@ -1,4 +1,3 @@
import JSZip from 'jszip'
import { import {
Meta, Meta,
ProfileMetadata, ProfileMetadata,
@ -33,18 +32,12 @@ import { useState, useEffect } from 'react'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { UserComponent } from '../../../components/username' import { UserComponent } from '../../../components/username'
import { MetadataController } from '../../../controllers' import { MetadataController } from '../../../controllers'
import { import { npubToHex, shorten, hexToNpub, parseJson } from '../../../utils'
npubToHex,
readContentOfZipEntry,
shorten,
hexToNpub,
parseJson
} from '../../../utils'
import styles from '../style.module.scss' import styles from '../style.module.scss'
type DisplayMetaProps = { type DisplayMetaProps = {
meta: Meta meta: Meta
zip: JSZip files: { [filename: string]: ArrayBuffer }
submittedBy: string submittedBy: string
signers: `npub1${string}`[] signers: `npub1${string}`[]
viewers: `npub1${string}`[] viewers: `npub1${string}`[]
@ -57,7 +50,7 @@ type DisplayMetaProps = {
export const DisplayMeta = ({ export const DisplayMeta = ({
meta, meta,
zip, files,
submittedBy, submittedBy,
signers, signers,
viewers, viewers,
@ -150,11 +143,7 @@ export const DisplayMeta = ({
}, [users, submittedBy]) }, [users, submittedBy])
const downloadFile = async (filename: string) => { const downloadFile = async (filename: string) => {
const arrayBuffer = await readContentOfZipEntry( const arrayBuffer = files[filename]
zip,
`files/${filename}`,
'arraybuffer'
)
if (!arrayBuffer) return if (!arrayBuffer) return
const blob = new Blob([arrayBuffer]) const blob = new Blob([arrayBuffer])

View File

@ -23,6 +23,8 @@ import {
SignedEventContent SignedEventContent
} from '../../types' } from '../../types'
import { import {
decryptArrayBuffer,
extractZipUrlAndEncryptionKey,
getHash, getHash,
hexToNpub, hexToNpub,
npubToHex, npubToHex,
@ -33,6 +35,7 @@ import {
import styles from './style.module.scss' import styles from './style.module.scss'
import { Cancel, CheckCircle } from '@mui/icons-material' import { Cancel, CheckCircle } from '@mui/icons-material'
import { useLocation } from 'react-router-dom' import { useLocation } from 'react-router-dom'
import axios from 'axios'
export const VerifyPage = () => { export const VerifyPage = () => {
const theme = useTheme() const theme = useTheme()
@ -41,13 +44,12 @@ export const VerifyPage = () => {
) )
const location = useLocation() const location = useLocation()
const { uploadedZip } = location.state || {} const { uploadedZip, meta: metaInNavState } = location.state || {}
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [selectedFile, setSelectedFile] = useState<File | null>(null) const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [zip, setZip] = useState<JSZip>()
const [meta, setMeta] = useState<Meta | null>(null) const [meta, setMeta] = useState<Meta | null>(null)
const [submittedBy, setSubmittedBy] = useState<string>() const [submittedBy, setSubmittedBy] = useState<string>()
@ -68,16 +70,60 @@ export const VerifyPage = () => {
useEffect(() => { useEffect(() => {
if (uploadedZip) { if (uploadedZip) {
setSelectedFile(uploadedZip) setSelectedFile(uploadedZip)
} } else if (metaInNavState) {
}, [uploadedZip]) const processSigit = async () => {
setIsLoading(true)
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
const res = await extractZipUrlAndEncryptionKey(metaInNavState)
if (!res) {
setIsLoading(false)
return
}
const {
zipUrl,
encryptionKey,
createSignatureEvent,
createSignatureContent
} = res
setLoadingSpinnerDesc('Fetching file from file server')
axios
.get(zipUrl, {
responseType: 'arraybuffer'
})
.then(async (res) => {
const fileName = zipUrl.split('/').pop()
const file = new File([res.data], fileName!)
const encryptedArrayBuffer = await file.arrayBuffer()
const arrayBuffer = await decryptArrayBuffer(
encryptedArrayBuffer,
encryptionKey
).catch((err) => {
console.log('err in decryption:>> ', err)
toast.error(
err.message || 'An error occurred in decrypting file.'
)
return null
})
if (arrayBuffer) {
const zip = await JSZip.loadAsync(arrayBuffer).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
useEffect(() => {
if (zip) {
const generateCurrentFileHashes = async () => {
const fileHashes: { [key: string]: string | null } = {} const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files) const fileNames = Object.values(zip.files).map(
.filter((entry) => entry.name.startsWith('files/') && !entry.dir) (entry) => entry.name
.map((entry) => entry.name) )
// generate hashes for all entries in files folder of zipArchive // generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files // these hashes can be used to verify the originality of files
@ -100,11 +146,30 @@ export const VerifyPage = () => {
} }
setCurrentFileHashes(fileHashes) setCurrentFileHashes(fileHashes)
setSigners(createSignatureContent.signers)
setViewers(createSignatureContent.viewers)
setCreatorFileHashes(createSignatureContent.fileHashes)
setSubmittedBy(createSignatureEvent.pubkey)
setMeta(metaInNavState)
setIsLoading(false)
}
})
.catch((err) => {
console.error(`error occurred in getting file from ${zipUrl}`, err)
toast.error(
err.message || `error occurred in getting file from ${zipUrl}`
)
})
.finally(() => {
setIsLoading(false)
})
} }
generateCurrentFileHashes() processSigit()
} }
}, [zip]) }, [uploadedZip, metaInNavState])
useEffect(() => { useEffect(() => {
if (submittedBy) { if (submittedBy) {
@ -159,7 +224,34 @@ export const VerifyPage = () => {
}) })
if (!zip) return if (!zip) return
setZip(zip)
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
.map((entry) => entry.name)
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
if (arrayBuffer) {
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName.replace(/^files\//, '')] = hash
}
} else {
fileHashes[fileName.replace(/^files\//, '')] = null
}
}
console.log('fileHashes :>> ', fileHashes)
setCurrentFileHashes(fileHashes)
setLoadingSpinnerDesc('Parsing meta.json') setLoadingSpinnerDesc('Parsing meta.json')

View File

@ -17,3 +17,6 @@ export const SET_RELAY_INFO = 'SET_RELAY_INFO'
export const SET_RELAY_MAP_UPDATED = 'SET_RELAY_MAP_UPDATED' export const SET_RELAY_MAP_UPDATED = 'SET_RELAY_MAP_UPDATED'
export const SET_MOST_POPULAR_RELAYS = 'SET_MOST_POPULAR_RELAYS' export const SET_MOST_POPULAR_RELAYS = 'SET_MOST_POPULAR_RELAYS'
export const SET_RELAY_CONNECTION_STATUS = 'SET_RELAY_CONNECTION_STATUS' export const SET_RELAY_CONNECTION_STATUS = 'SET_RELAY_CONNECTION_STATUS'
export const UPDATE_USER_APP_DATA = 'UPDATE_USER_APP_DATA'
export const UPDATE_PROCESSED_GIFT_WRAPS = 'UPDATE_PROCESSED_GIFT_WRAPS'

View File

@ -4,6 +4,7 @@ import { State } from './rootReducer'
export * from './auth/action' export * from './auth/action'
export * from './metadata/action' export * from './metadata/action'
export * from './relays/action' export * from './relays/action'
export * from './userAppData/action'
export const restoreState = (payload: State) => { export const restoreState = (payload: State) => {
return { return {

View File

@ -1,25 +1,29 @@
import { Event } from 'nostr-tools' import { Event } from 'nostr-tools'
import { combineReducers } from 'redux' import { combineReducers } from 'redux'
import { UserAppData } from '../types'
import * as ActionTypes from './actionTypes'
import authReducer from './auth/reducer' import authReducer from './auth/reducer'
import { AuthState } from './auth/types' import { AuthState } from './auth/types'
import metadataReducer from './metadata/reducer' import metadataReducer from './metadata/reducer'
import userRobotImageReducer from './userRobotImage/reducer'
import { RelaysState } from './relays/types'
import relaysReducer from './relays/reducer' import relaysReducer from './relays/reducer'
import * as ActionTypes from './actionTypes' import { RelaysState } from './relays/types'
import UserAppDataReducer from './userAppData/reducer'
import userRobotImageReducer from './userRobotImage/reducer'
export interface State { export interface State {
auth: AuthState auth: AuthState
metadata?: Event metadata?: Event
userRobotImage?: string userRobotImage?: string
relays: RelaysState relays: RelaysState
userAppData?: UserAppData
} }
export const appReducer = combineReducers({ export const appReducer = combineReducers({
auth: authReducer, auth: authReducer,
metadata: metadataReducer, metadata: metadataReducer,
userRobotImage: userRobotImageReducer, userRobotImage: userRobotImageReducer,
relays: relaysReducer relays: relaysReducer,
userAppData: UserAppDataReducer
}) })
// FIXME: define types // FIXME: define types

View File

@ -0,0 +1,15 @@
import { UserAppData } from '../../types'
import * as ActionTypes from '../actionTypes'
import { UpdateProcessedGiftWraps, UpdateUserAppData } from './types'
export const updateUserAppData = (payload: UserAppData): UpdateUserAppData => ({
type: ActionTypes.UPDATE_USER_APP_DATA,
payload
})
export const updateProcessedGiftWraps = (
payload: string[]
): UpdateProcessedGiftWraps => ({
type: ActionTypes.UPDATE_PROCESSED_GIFT_WRAPS,
payload
})

View File

@ -0,0 +1,35 @@
import { UserAppData } from '../../types'
import * as ActionTypes from '../actionTypes'
import { UserAppDataDispatchTypes } from './types'
const initialState: UserAppData = {
sigits: {},
processedGiftWraps: [],
blossomUrls: []
}
const reducer = (
state = initialState,
action: UserAppDataDispatchTypes
): UserAppData | null => {
switch (action.type) {
case ActionTypes.UPDATE_USER_APP_DATA:
return {
...action.payload
}
case ActionTypes.UPDATE_PROCESSED_GIFT_WRAPS:
return {
...state,
processedGiftWraps: action.payload
}
case ActionTypes.RESTORE_STATE:
return action.payload.userAppData || null
default:
return state
}
}
export default reducer

View File

@ -0,0 +1,18 @@
import { UserAppData } from '../../types'
import * as ActionTypes from '../actionTypes'
import { RestoreState } from '../actions'
export interface UpdateUserAppData {
type: typeof ActionTypes.UPDATE_USER_APP_DATA
payload: UserAppData
}
export interface UpdateProcessedGiftWraps {
type: typeof ActionTypes.UPDATE_PROCESSED_GIFT_WRAPS
payload: string[]
}
export type UserAppDataDispatchTypes =
| UpdateUserAppData
| UpdateProcessedGiftWraps
| RestoreState

View File

@ -1,3 +1,5 @@
import { Keys } from '../store/auth/types'
export enum UserRole { export enum UserRole {
signer = 'Signer', signer = 'Signer',
viewer = 'Viewer' viewer = 'Viewer'
@ -9,19 +11,19 @@ export interface User {
} }
export interface Meta { export interface Meta {
uuid: string
title: string
modifiedAt: number modifiedAt: number
createSignature: string createSignature: string
docSignatures: { [key: `npub1${string}`]: string } docSignatures: { [key: `npub1${string}`]: string }
exportSignature?: string exportSignature?: string
keys?: { sender: string; keys: { [user: `npub1${string}`]: string } }
} }
export interface CreateSignatureEventContent { export interface CreateSignatureEventContent {
signers: `npub1${string}`[] signers: `npub1${string}`[]
viewers: `npub1${string}`[] viewers: `npub1${string}`[]
fileHashes: { [key: string]: string } fileHashes: { [key: string]: string }
keys: { sender: string; keys: { [user: `npub1${string}`]: string } } title: string
zipUrl: string
} }
export interface SignedEventContent { export interface SignedEventContent {
@ -32,3 +34,10 @@ export interface Sigit {
fileUrl: string fileUrl: string
meta: Meta meta: Meta
} }
export interface UserAppData {
sigits: { [key: string]: Meta } // key will be id of create signature
processedGiftWraps: string[] // an array of ids of processed gift wrapped events
keyPair?: Keys // this key pair is used for blossom requests authentication
blossomUrls: string[] // array for storing Urls for the files that stores all the sigits and processedGiftWraps on blossom
}

View File

@ -10,9 +10,9 @@ import {
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { MetadataController, NostrController } from '../controllers' import { MetadataController, NostrController } from '../controllers'
import { appPrivateRoutes } from '../routes' import { appPrivateRoutes } from '../routes'
import { hexToNpub } from './nostr' import { hexToNpub, now } from './nostr'
import { parseJson } from './string' import { parseJson } from './string'
import { CreateSignatureEventContent } from '../types' import { CreateSignatureEventContent, Meta } from '../types'
import store from '../store/store' import store from '../store/store'
import { AuthState } from '../store/auth/types' import { AuthState } from '../store/auth/types'
@ -26,9 +26,6 @@ export const uploadToFileStorage = async (
file: File, file: File,
nostrController: NostrController nostrController: NostrController
) => { ) => {
// Get the current timestamp in seconds
const unixNow = Math.floor(Date.now() / 1000)
// Define event metadata for authorization // Define event metadata for authorization
const event: EventTemplate = { const event: EventTemplate = {
kind: 24242, kind: 24242,
@ -36,7 +33,7 @@ export const uploadToFileStorage = async (
created_at: Math.floor(Date.now() / 1000), created_at: Math.floor(Date.now() / 1000),
tags: [ tags: [
['t', 'upload'], ['t', 'upload'],
['expiration', String(unixNow + 60 * 5)], // Set expiration time to 5 minutes from now ['expiration', String(now() + 60 * 5)], // Set expiration time to 5 minutes from now
['name', file.name], ['name', file.name],
['size', String(file.size)] ['size', String(file.size)]
] ]
@ -301,16 +298,16 @@ export const generateKeys = async (
return { sender: getPublicKey(privateKey), keys } return { sender: getPublicKey(privateKey), keys }
} }
export const extractEncryptionKey = async (createSignature: string) => { export const extractZipUrlAndEncryptionKey = async (meta: Meta) => {
const createSignatureEvent = await parseJson<Event>(createSignature).catch( const createSignatureEvent = await parseJson<Event>(
(err) => { meta.createSignature
).catch((err) => {
console.log('err in parsing the createSignature event:>> ', err) console.log('err in parsing the createSignature event:>> ', err)
toast.error( toast.error(
err.message || 'error occurred in parsing the create signature event' err.message || 'error occurred in parsing the create signature event'
) )
return null return null
} })
)
if (!createSignatureEvent) return null if (!createSignatureEvent) return null
@ -332,15 +329,32 @@ export const extractEncryptionKey = async (createSignature: string) => {
if (!createSignatureContent) return null if (!createSignatureContent) return null
const zipUrl = createSignatureContent.zipUrl
const usersPubkey = (store.getState().auth as AuthState).usersPubkey! const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const usersNpub = hexToNpub(usersPubkey) const usersNpub = hexToNpub(usersPubkey)
const { sender, keys } = createSignatureContent.keys if (!meta.keys) return null
const { sender, keys } = meta.keys
if (usersNpub in keys) { if (usersNpub in keys) {
const nostrController = NostrController.getInstance()
const decrypted = await nostrController
.nip04Decrypt(sender, keys[usersNpub])
.catch((err) => {
console.log('An error occurred in decrypting encryption key', err)
toast.error('An error occurred in decrypting encryption key')
return null
})
if (!decrypted) return null
return { return {
sender, createSignatureEvent,
encryptedKey: keys[usersNpub] createSignatureContent,
zipUrl,
encryptionKey: decrypted
} }
} }

View File

@ -1,4 +1,6 @@
import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
import axios from 'axios' import axios from 'axios'
import _ from 'lodash'
import { import {
Event, Event,
EventTemplate, EventTemplate,
@ -17,12 +19,16 @@ import {
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { NIP05_REGEX } from '../constants' import { NIP05_REGEX } from '../constants'
import { MetadataController, NostrController } from '../controllers' import { MetadataController, NostrController } from '../controllers'
import { AuthState } from '../store/auth/types' import {
updateProcessedGiftWraps,
updateUserAppData as updateUserAppDataAction
} from '../store/actions'
import { AuthState, Keys } from '../store/auth/types'
import { RelaysState } from '../store/relays/types' import { RelaysState } from '../store/relays/types'
import store from '../store/store' import store from '../store/store'
import { Meta, Rumor, Sigit, SignedEvent } from '../types' import { Meta, SignedEvent, UserAppData } from '../types'
import { getHash } from './hash' import { getHash } from './hash'
import { parseJson } from './string' import { parseJson, removeLeadingSlash } from './string'
/** /**
* @param hexKey hex private or public key * @param hexKey hex private or public key
@ -203,7 +209,7 @@ export const getRoboHashPicture = (
return `https://robohash.org/${npub}.png?set=set${set}` return `https://robohash.org/${npub}.png?set=set${set}`
} }
const TWO_DAYS = 2 * 24 * 60 * 60 export const TWO_DAYS = 2 * 24 * 60 * 60
export const now = () => Math.round(Date.now() / 1000) export const now = () => Math.round(Date.now() / 1000)
export const randomNow = () => Math.round(now() - Math.random() * TWO_DAYS) export const randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)
@ -220,7 +226,7 @@ export const nip44ConversationKey = (
) => nip44.v2.utils.getConversationKey(privateKey, publicKey) ) => nip44.v2.utils.getConversationKey(privateKey, publicKey)
export const nip44Encrypt = ( export const nip44Encrypt = (
data: EventTemplate, data: UnsignedEvent,
privateKey: Uint8Array, privateKey: Uint8Array,
publicKey: string publicKey: string
) => ) =>
@ -262,31 +268,28 @@ export const countLeadingZeroes = (hex: string) => {
* @returns * @returns
*/ */
// //
export const createWrap = ( export const createWrap = (unsignedEvent: UnsignedEvent, receiver: string) => {
event: Event,
receiver: string,
difficulty: number = 10
) => {
// Generate a random secret key and its corresponding public key // Generate a random secret key and its corresponding public key
const randomKey = generateSecretKey() const randomKey = generateSecretKey()
const pubkey = getPublicKey(randomKey) const pubkey = getPublicKey(randomKey)
// Encrypt the event content using nip44 encryption // Encrypt the event content using nip44 encryption
const content = nip44Encrypt(event, randomKey, receiver) const content = nip44Encrypt(unsignedEvent, randomKey, receiver)
// Initialize nonce and leadingZeroes for PoW calculation // Initialize nonce and leadingZeroes for PoW calculation
let nonce = 0 let nonce = 0
let leadingZeroes = 0 let leadingZeroes = 0
const difficulty = Math.floor(Math.random() * 10) + 5 // random number between 5 & 10
// Loop until a valid PoW hash is found // Loop until a valid PoW hash is found
// eslint-disable-next-line no-constant-condition // eslint-disable-next-line no-constant-condition
while (true) { while (true) {
// Create an unsigned event with the necessary fields // Create an unsigned event with the necessary fields
const unsignedEvent: UnsignedEvent = { const event: UnsignedEvent = {
kind: 1059, // Event kind kind: 1059, // Event kind
content, // Encrypted content content, // Encrypted content
pubkey, // Public key of the creator pubkey, // Public key of the creator
created_at: randomNow(), // Current timestamp created_at: now(), // Current timestamp
tags: [ tags: [
// Tags including receiver and nonce // Tags including receiver and nonce
['p', receiver], ['p', receiver],
@ -295,7 +298,7 @@ export const createWrap = (
} }
// Calculate the SHA-256 hash of the unsigned event // Calculate the SHA-256 hash of the unsigned event
const hash = getEventHash(unsignedEvent) const hash = getEventHash(event)
// Count the number of leading zero bits in the hash // Count the number of leading zero bits in the hash
leadingZeroes = countLeadingZeroes(hash) leadingZeroes = countLeadingZeroes(hash)
@ -303,7 +306,7 @@ export const createWrap = (
// Check if the leading zero bits meet the required difficulty // Check if the leading zero bits meet the required difficulty
if (leadingZeroes >= difficulty) { if (leadingZeroes >= difficulty) {
// Finalize the event (sign it) and return the result // Finalize the event (sign it) and return the result
return finalizeEvent(unsignedEvent, randomKey) return finalizeEvent(event, randomKey)
} }
// Increment the nonce for the next iteration // Increment the nonce for the next iteration
@ -311,7 +314,7 @@ export const createWrap = (
} }
} }
export const getUsersAppData = async () => { export const getUsersAppData = async (): Promise<UserAppData | null> => {
const relays: string[] = [] const relays: string[] = []
const usersPubkey = (store.getState().auth as AuthState).usersPubkey! const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
@ -321,8 +324,6 @@ export const getUsersAppData = async () => {
// check if relaysMap in redux store is undefined // check if relaysMap in redux store is undefined
if (!relayMap) { if (!relayMap) {
// todo: use metadata controller
const metadataController = new MetadataController() const metadataController = new MetadataController()
const relaySet = await metadataController const relaySet = await metadataController
.findRelayListMetadata(usersPubkey) .findRelayListMetadata(usersPubkey)
@ -335,10 +336,10 @@ export const getUsersAppData = async () => {
}) })
// Return if metadata retrieval failed // Return if metadata retrieval failed
if (!relaySet) return if (!relaySet) return null
// Ensure relay list is not empty // Ensure relay list is not empty
if (relaySet.write.length === 0) return if (relaySet.write.length === 0) return null
relays.push(...relaySet.write) relays.push(...relaySet.write)
} else { } else {
@ -351,7 +352,7 @@ export const getUsersAppData = async () => {
} }
// generate an identifier for user's nip78 // generate an identifier for user's nip78
const hash = await getHash('sigit' + usersPubkey) const hash = await getHash('938' + usersPubkey)
if (!hash) return null if (!hash) return null
const filter: Filter = { const filter: Filter = {
@ -379,7 +380,18 @@ export const getUsersAppData = async () => {
if (!encryptedContent) return null if (!encryptedContent) return null
if (encryptedContent === '{}') { if (encryptedContent === '{}') {
return {} const secret = generateSecretKey()
const pubKey = getPublicKey(secret)
return {
sigits: {},
processedGiftWraps: [],
blossomUrls: [],
keyPair: {
private: bytesToHex(secret),
public: pubKey
}
}
} }
const decrypted = await nostrController const decrypted = await nostrController
@ -393,7 +405,8 @@ export const getUsersAppData = async () => {
if (!decrypted) return null if (!decrypted) return null
const parsedContent = await parseJson<{ const parsedContent = await parseJson<{
[uuid: string]: Sigit blossomUrls: string[]
keyPair: Keys
}>(decrypted).catch((err) => { }>(decrypted).catch((err) => {
console.log( console.log(
'An error occurred in parsing the content of kind 30078 event', 'An error occurred in parsing the content of kind 30078 event',
@ -405,39 +418,108 @@ export const getUsersAppData = async () => {
if (!parsedContent) return null if (!parsedContent) return null
return parsedContent const { blossomUrls, keyPair } = parsedContent
if (blossomUrls.length === 0) return null
const dataFromBlossom = await getUserAppDataFromBlossom(
blossomUrls[0],
keyPair.private
)
if (!dataFromBlossom) return null
const { sigits, processedGiftWraps } = dataFromBlossom
return {
blossomUrls,
keyPair,
sigits,
processedGiftWraps
}
} }
export const updateUsersAppData = async (fileUrl: string, meta: Meta) => { export const updateUsersAppData = async (meta: Meta) => {
const appData = await getUsersAppData() const appData = store.getState().userAppData
if (!appData) return null if (!appData || !appData.keyPair) return null
if (meta.uuid in appData) { const sigits = _.cloneDeep(appData.sigits)
// update meta only if income meta is more recent than already existing one
const existingMeta = appData[meta.uuid].meta const createSignatureEvent = await parseJson<Event>(
meta.createSignature
).catch((err) => {
console.log('err in parsing the createSignature event:>> ', err)
toast.error(
err.message || 'error occurred in parsing the create signature event'
)
return null
})
if (!createSignatureEvent) return null
const id = createSignatureEvent.id
let isUpdated = false
// check if sigit already exists
if (id in sigits) {
// update meta only if incoming meta is more recent
// than already existing one
const existingMeta = sigits[id]
if (existingMeta.modifiedAt < meta.modifiedAt) { if (existingMeta.modifiedAt < meta.modifiedAt) {
appData[meta.uuid] = { sigits[id] = meta
fileUrl, isUpdated = true
meta
}
} }
} else { } else {
appData[meta.uuid] = { sigits[id] = meta
fileUrl, isUpdated = true
meta
}
} }
appData[meta.uuid] = { if (!isUpdated) return null
fileUrl,
meta const blossomUrls = [...appData.blossomUrls]
const newBlossomUrl = await uploadUserAppDataToBlossom(
sigits,
appData.processedGiftWraps,
appData.keyPair.private
).catch((err) => {
console.log(
'An error occurred in uploading user app data file to blossom server',
err
)
toast.error(
'An error occurred in uploading user app data file to blossom server'
)
return null
})
if (!newBlossomUrl) return null
blossomUrls.unshift(newBlossomUrl)
if (blossomUrls.length > 10) {
const filesToDelete = blossomUrls.splice(10)
filesToDelete.forEach((url) => {
deleteBlossomFile(url, appData.keyPair!.private).catch((err) => {
console.log(
'An error occurred in removing old file of user app data from blossom server',
err
)
})
})
} }
const usersPubkey = (store.getState().auth as AuthState).usersPubkey! const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const nostrController = NostrController.getInstance() const nostrController = NostrController.getInstance()
const encryptedContent = await nostrController const encryptedContent = await nostrController
.nip04Encrypt(usersPubkey, JSON.stringify(appData)) .nip04Encrypt(
usersPubkey,
JSON.stringify({
blossomUrls,
keyPair: appData.keyPair
})
)
.catch((err) => { .catch((err) => {
console.log( console.log(
'An error occurred in encryption of content for app data', 'An error occurred in encryption of content for app data',
@ -452,7 +534,7 @@ export const updateUsersAppData = async (fileUrl: string, meta: Meta) => {
if (!encryptedContent) return null if (!encryptedContent) return null
// generate the identifier for user's appData event // generate the identifier for user's appData event
const hash = await getHash('sigit' + usersPubkey) const hash = await getHash('938' + usersPubkey)
if (!hash) return null if (!hash) return null
const updatedEvent: UnsignedEvent = { const updatedEvent: UnsignedEvent = {
@ -493,9 +575,143 @@ export const updateUsersAppData = async (fileUrl: string, meta: Meta) => {
if (!publishResult) return null if (!publishResult) return null
// update redux store
store.dispatch(
updateUserAppDataAction({
sigits,
blossomUrls,
processedGiftWraps: [...appData.processedGiftWraps],
keyPair: {
...appData.keyPair
}
})
)
return signedEvent return signedEvent
} }
const deleteBlossomFile = async (url: string, privateKey: string) => {
const pathname = new URL(url).pathname
const hash = removeLeadingSlash(pathname)
// Define event metadata for authorization
const event: EventTemplate = {
kind: 24242,
content: 'Authorize Upload',
created_at: now(),
tags: [
['t', 'delete'],
['expiration', String(now() + 60 * 5)], // Set expiration time to 5 minutes from now
['x', hash]
]
}
const authEvent = finalizeEvent(event, hexToBytes(privateKey))
// delete the file stored on file storage service using Axios
const response = await axios.delete(url, {
headers: {
Authorization: 'Nostr ' + btoa(JSON.stringify(authEvent)) // Set authorization header
}
})
console.log('response.data :>> ', response.data)
}
const uploadUserAppDataToBlossom = async (
sigits: { [key: string]: Meta },
processedGiftWraps: string[],
privateKey: string
) => {
const obj = {
sigits,
processedGiftWraps
}
const stringified = JSON.stringify(obj)
const secretKey = hexToBytes(privateKey)
const encrypted = nip44.v2.encrypt(
stringified,
nip44ConversationKey(secretKey, getPublicKey(secretKey))
)
const blob = new Blob([encrypted], { type: 'application/octet-stream' })
const file = new File([blob], 'encrypted.txt', {
type: 'application/octet-stream'
})
// Define event metadata for authorization
const event: EventTemplate = {
kind: 24242,
content: 'Authorize Upload',
created_at: now(),
tags: [
['t', 'upload'],
['expiration', String(now() + 60 * 5)], // Set expiration time to 5 minutes from now
['name', file.name],
['size', String(file.size)]
]
}
const authEvent = finalizeEvent(event, hexToBytes(privateKey))
const FILE_STORAGE_URL = 'https://blossom.sigit.io'
// Upload the file to the file storage service using Axios
const response = await axios.put(`${FILE_STORAGE_URL}/upload`, file, {
headers: {
Authorization: 'Nostr ' + btoa(JSON.stringify(authEvent)) // Set authorization header
}
})
// Return the URL of the uploaded file
return response.data.url as string
}
const getUserAppDataFromBlossom = async (url: string, privateKey: string) => {
const encrypted = await axios
.get(url, {
responseType: 'blob'
})
.then(async (res) => {
const file = new File([res.data], 'encrypted.txt')
const text = await file.text()
return text
})
.catch((err) => {
console.error(`error occurred in getting file from ${url}`, err)
toast.error(err.message || `error occurred in getting file from ${url}`)
return null
})
if (!encrypted) return null
const secret = hexToBytes(privateKey)
const pubkey = getPublicKey(secret)
const decrypted = nip44.v2.decrypt(
encrypted,
nip44ConversationKey(secret, pubkey)
)
const parsedContent = await parseJson<{
sigits: { [key: string]: Meta }
processedGiftWraps: string[]
}>(decrypted).catch((err) => {
console.log(
'An error occurred in parsing the user app data content from blossom server',
err
)
toast.error(
'An error occurred in parsing the user app data content from blossom server'
)
return null
})
return parsedContent
}
export const subscribeForSigits = async (pubkey: string) => { export const subscribeForSigits = async (pubkey: string) => {
// Get relay list metadata // Get relay list metadata
const metadataController = new MetadataController() const metadataController = new MetadataController()
@ -521,70 +737,71 @@ export const subscribeForSigits = async (pubkey: string) => {
} }
const pool = new SimplePool() const pool = new SimplePool()
pool.subscribeMany(relaySet.read, [filter], { return pool.subscribeMany(relaySet.read, [filter], {
onevent: (event) => { onevent: (event) => {
processReceivedEvent(event) processReceivedEvent(event)
} }
}) })
} }
const processReceivedEvent = async (event: Event, difficulty: number = 10) => { const processReceivedEvent = async (event: Event, difficulty: number = 5) => {
const processedEvents = (store.getState().userAppData as UserAppData)
.processedGiftWraps
if (processedEvents.includes(event.id)) return
store.dispatch(updateProcessedGiftWraps([...processedEvents, event.id]))
// validate PoW // validate PoW
// Count the number of leading zero bits in the hash // Count the number of leading zero bits in the hash
const leadingZeroes = countLeadingZeroes(event.id) const leadingZeroes = countLeadingZeroes(event.id)
if (leadingZeroes < difficulty) return if (leadingZeroes < difficulty) return
// decrypt the content of gift wrap event
const nostrController = NostrController.getInstance() const nostrController = NostrController.getInstance()
const stringifiedSealEvent = await nostrController.nip44Decrypt( const decrypted = await nostrController.nip44Decrypt(
event.pubkey, event.pubkey,
event.content event.content
) )
const sealEvent = await parseJson<Event>(stringifiedSealEvent)
const stringifiedRumor = await nostrController.nip44Decrypt( const internalUnsignedEvent = await parseJson<UnsignedEvent>(decrypted).catch(
sealEvent.pubkey, (err) => {
sealEvent.content console.log(
'An error occurred in parsing the internal unsigned event',
err
) )
const rumor = await parseJson<Rumor>(stringifiedRumor) return null
if (rumor.content === 'sigit-notification') {
const uTag = rumor.tags.find((tag) => tag[0] === 'u')
if (!uTag) return
const fileUrl = uTag[1]
const mTag = rumor.tags.find((tag) => tag[0] === 'm')
if (!mTag) return
const metaString = mTag[1]
const meta = await parseJson<Meta>(metaString)
updateUsersAppData(fileUrl, meta)
} }
)
if (!internalUnsignedEvent || internalUnsignedEvent.kind !== 938) return
const meta = await parseJson<Meta>(internalUnsignedEvent.content).catch(
(err) => {
console.log(
'An error occurred in parsing the internal unsigned event',
err
)
return null
}
)
if (!meta) return
updateUsersAppData(meta)
} }
export const sendNotification = async ( export const sendNotification = async (receiver: string, meta: Meta) => {
receiver: string,
meta: Meta,
fileUrl: string
) => {
const usersPubkey = (store.getState().auth as AuthState).usersPubkey! const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const unsignedEvent: UnsignedEvent = { const unsignedEvent: UnsignedEvent = {
kind: kinds.ShortTextNote, kind: 938,
pubkey: usersPubkey, pubkey: usersPubkey,
content: 'sigit-notification', content: JSON.stringify(meta),
tags: [ tags: [],
['u', fileUrl],
['m', JSON.stringify(meta)]
],
created_at: now() created_at: now()
} }
const rumor: Rumor = { const wrappedEvent = createWrap(unsignedEvent, receiver)
...unsignedEvent,
id: getEventHash(unsignedEvent)
}
const nostrController = NostrController.getInstance()
const seal = await nostrController.createSeal(rumor, receiver)
const wrappedEvent = createWrap(seal, receiver)
// Get relay list metadata // Get relay list metadata
const metadataController = new MetadataController() const metadataController = new MetadataController()
@ -605,6 +822,7 @@ export const sendNotification = async (
if (relaySet.read.length === 0) return if (relaySet.read.length === 0) return
// Publish the notification event to the recipient's read relays // Publish the notification event to the recipient's read relays
const nostrController = NostrController.getInstance()
await nostrController await nostrController
.publishEvent(wrappedEvent, relaySet.read) .publishEvent(wrappedEvent, relaySet.read)
.catch((errResults) => { .catch((errResults) => {
@ -612,6 +830,6 @@ export const sendNotification = async (
`An error occurred while publishing notification event for ${hexToNpub(receiver)}`, `An error occurred while publishing notification event for ${hexToNpub(receiver)}`,
errResults errResults
) )
return null throw errResults
}) })
} }

View File

@ -111,3 +111,19 @@ export const formatTimestamp = (timestamp: number) => {
// Combine parts into the desired format // Combine parts into the desired format
return `${day} ${month} ${year} ${formattedHours}:${minutes} ${ampm}` return `${day} ${month} ${year} ${formattedHours}:${minutes} ${ampm}`
} }
/**
* Removes the leading slash from a given string if it exists.
*
* @param str - The string from which to remove the leading slash.
* @returns The string without the leading slash.
*/
export const removeLeadingSlash = (str: string): string => {
// Check if the string starts with a leading slash
if (str.startsWith('/')) {
// If it does, return the string without the leading slash
return str.slice(1)
}
// If it doesn't, return the original string
return str
}