store-sigits and update working flow #116
@ -46,7 +46,6 @@ export class MetadataController extends EventEmitter {
|
||||
|
||||
const pool = new SimplePool()
|
||||
|
||||
// todo: use nostrController to get event
|
||||
// Try to get the metadata event from a special relay (wss://purplepag.es)
|
||||
const metadataEvent = await pool
|
||||
.get([this.specialMetadataRelay], eventFilter)
|
||||
@ -62,14 +61,17 @@ export class MetadataController extends EventEmitter {
|
||||
verifyEvent(metadataEvent) // Verify the event's authenticity
|
||||
) {
|
||||
// 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
|
||||
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
|
||||
const mostPopularRelays = await this.nostrController.getMostPopularRelays()
|
||||
|
||||
@ -125,11 +127,11 @@ export class MetadataController extends EventEmitter {
|
||||
|
||||
// If cached metadata is found, check its validity
|
||||
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
|
||||
if (Date.now() - cachedMetadataEvent.cachedAt > oneDayInMS) {
|
||||
// If older than one day, find the metadata from relays in background
|
||||
// Check if the cached metadata is older than one week
|
||||
if (Date.now() - cachedMetadataEvent.cachedAt > oneWeekInMS) {
|
||||
// If older than one week, find the metadata from relays in background
|
||||
|
||||
this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event)
|
||||
}
|
||||
|
@ -1,30 +1,40 @@
|
||||
import { Box } from '@mui/material'
|
||||
import Container from '@mui/material/Container'
|
||||
import { Event, kinds } from 'nostr-tools'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useDispatch, useSelector } from 'react-redux'
|
||||
import { Outlet } from 'react-router-dom'
|
||||
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 {
|
||||
clearAuthToken,
|
||||
clearState,
|
||||
getRoboHashPicture,
|
||||
getUsersAppData,
|
||||
loadState,
|
||||
saveNsecBunkerDelegatedKey,
|
||||
subscribeForSigits
|
||||
} from '../utils'
|
||||
import { LoadingSpinner } from '../components/LoadingSpinner'
|
||||
import { Dispatch } from '../store/store'
|
||||
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'
|
||||
import { useAppSelector } from '../hooks'
|
||||
import { SubCloser } from 'nostr-tools/abstract-pool'
|
||||
|
||||
export const MainLayout = () => {
|
||||
const dispatch: Dispatch = useDispatch()
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState(`Loading App`)
|
||||
const authState = useSelector((state: State) => state.auth)
|
||||
const usersAppData = useAppSelector((state) => state.userAppData)
|
||||
|
||||
useEffect(() => {
|
||||
const metadataController = new MetadataController()
|
||||
@ -84,11 +94,47 @@ export const MainLayout = () => {
|
||||
metadataController.findMetadata(usersPubkey).then((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)
|
||||
}, [dispatch])
|
||||
return () => {
|
||||
if (subCloser) {
|
||||
subCloser.close()
|
||||
}
|
||||
}
|
||||
}, [authState, usersAppData])
|
||||
|
||||
/**
|
||||
* When authState change user logged in / or app reloaded
|
||||
@ -101,13 +147,11 @@ export const MainLayout = () => {
|
||||
|
||||
if (pubkey) {
|
||||
dispatch(setUserRobotImage(getRoboHashPicture(pubkey)))
|
||||
|
||||
subscribeForSigits(pubkey)
|
||||
}
|
||||
}
|
||||
}, [authState])
|
||||
|
||||
if (isLoading) return <LoadingSpinner desc="Loading App" />
|
||||
if (isLoading) return <LoadingSpinner desc={loadingSpinnerDesc} />
|
||||
|
||||
return (
|
||||
<>
|
||||
|
@ -23,19 +23,23 @@ import saveAs from 'file-saver'
|
||||
import JSZip from 'jszip'
|
||||
import { MuiFileInput } from 'mui-file-input'
|
||||
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 { HTML5Backend } from 'react-dnd-html5-backend'
|
||||
import { useSelector } from 'react-redux'
|
||||
import { useLocation, useNavigate } from 'react-router-dom'
|
||||
import { toast } from 'react-toastify'
|
||||
import { v4 as uuidV4 } from 'uuid'
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner'
|
||||
import { UserComponent } from '../../components/username'
|
||||
import { MetadataController, NostrController } from '../../controllers'
|
||||
import { appPrivateRoutes } from '../../routes'
|
||||
import { State } from '../../store/rootReducer'
|
||||
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
|
||||
import {
|
||||
CreateSignatureEventContent,
|
||||
Meta,
|
||||
ProfileMetadata,
|
||||
User,
|
||||
UserRole
|
||||
} from '../../types'
|
||||
import {
|
||||
encryptArrayBuffer,
|
||||
generateEncryptionKey,
|
||||
@ -54,6 +58,7 @@ import {
|
||||
uploadToFileStorage
|
||||
} from '../../utils'
|
||||
import styles from './style.module.scss'
|
||||
import { appPrivateRoutes } from '../../routes'
|
||||
|
||||
export const CreatePage = () => {
|
||||
const navigate = useNavigate()
|
||||
@ -83,10 +88,6 @@ export const CreatePage = () => {
|
||||
setAuthUrl(url)
|
||||
})
|
||||
|
||||
const uuid = useMemo(() => {
|
||||
return uuidV4()
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (uploadedFile) {
|
||||
setSelectedFiles([uploadedFile])
|
||||
@ -295,56 +296,6 @@ export const CreatePage = () => {
|
||||
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
|
||||
const handleZipError = (err: any) => {
|
||||
console.log('Error in zip:>> ', err)
|
||||
@ -377,7 +328,7 @@ export const CreatePage = () => {
|
||||
return encryptArrayBuffer(arraybuffer, encryptionKey)
|
||||
}
|
||||
|
||||
// create final zip file
|
||||
// create final zip file for offline mode
|
||||
const createFinalZipFile = async (
|
||||
encryptedArrayBuffer: ArrayBuffer,
|
||||
encryptionKey: string
|
||||
@ -423,28 +374,6 @@ export const CreatePage = () => {
|
||||
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
|
||||
const handleUploadError = (err: any) => {
|
||||
console.log('Error in upload:>> ', err)
|
||||
@ -454,13 +383,19 @@ export const CreatePage = () => {
|
||||
}
|
||||
|
||||
// Upload the file to the storage
|
||||
const uploadFile = async (file: File): Promise<string | null> => {
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Uploading sigit to file storage.')
|
||||
const uploadFile = async (
|
||||
arrayBuffer: ArrayBuffer
|
||||
): 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)
|
||||
.then((url) => {
|
||||
toast.success('Sigit uploaded to file storage')
|
||||
toast.success('files.zip uploaded to file storage')
|
||||
return url
|
||||
})
|
||||
.catch(handleUploadError)
|
||||
@ -468,24 +403,6 @@ export const CreatePage = () => {
|
||||
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
|
||||
const handleOfflineFlow = async (
|
||||
encryptedArrayBuffer: ArrayBuffer,
|
||||
@ -501,35 +418,185 @@ export const CreatePage = () => {
|
||||
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 () => {
|
||||
if (!validateInputs()) return
|
||||
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Generating hashes for files')
|
||||
|
||||
setLoadingSpinnerDesc('Generating file hashes')
|
||||
const fileHashes = await generateFileHashes()
|
||||
if (!fileHashes) return
|
||||
if (!fileHashes) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
setLoadingSpinnerDesc('Generating encryption key')
|
||||
const encryptionKey = await generateEncryptionKey()
|
||||
|
||||
const createZipResponse = await initZipFileAndCreatorSignature(
|
||||
encryptionKey,
|
||||
fileHashes
|
||||
if (await isOnline()) {
|
||||
setLoadingSpinnerDesc('generating files.zip')
|
||||
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 = {
|
||||
uuid,
|
||||
title,
|
||||
modifiedAt: now(),
|
||||
createSignature,
|
||||
keys,
|
||||
modifiedAt: now(),
|
||||
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)
|
||||
if (!arrayBuffer) return
|
||||
@ -540,10 +607,6 @@ export const CreatePage = () => {
|
||||
encryptionKey
|
||||
)
|
||||
|
||||
if (await isOnline()) {
|
||||
await handleOnlineFlow(encryptedArrayBuffer, meta)
|
||||
} else {
|
||||
// todo: fix offline flow
|
||||
await handleOfflineFlow(encryptedArrayBuffer, encryptionKey)
|
||||
}
|
||||
}
|
||||
|
@ -1,59 +1,38 @@
|
||||
import { Add, CalendarMonth, Description, Upload } from '@mui/icons-material'
|
||||
import { Box, Button, Tooltip, Typography } from '@mui/material'
|
||||
import JSZip from 'jszip'
|
||||
import { Event, kinds, verifyEvent } from 'nostr-tools'
|
||||
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
|
||||
import { useNavigate } from 'react-router-dom'
|
||||
import { toast } from 'react-toastify'
|
||||
import { UserComponent } from '../../components/username'
|
||||
import { MetadataController } from '../../controllers'
|
||||
import { useAppSelector } from '../../hooks'
|
||||
import { appPrivateRoutes, appPublicRoutes } from '../../routes'
|
||||
import styles from './style.module.scss'
|
||||
import { MetadataController, NostrController } from '../../controllers'
|
||||
import { CreateSignatureEventContent, Meta, ProfileMetadata } from '../../types'
|
||||
import {
|
||||
formatTimestamp,
|
||||
getUsersAppData,
|
||||
hexToNpub,
|
||||
npubToHex,
|
||||
parseJson,
|
||||
shorten
|
||||
} from '../../utils'
|
||||
import { LoadingSpinner } from '../../components/LoadingSpinner'
|
||||
import {
|
||||
CreateSignatureEventContent,
|
||||
Meta,
|
||||
ProfileMetadata,
|
||||
Sigit
|
||||
} from '../../types'
|
||||
import { Event, kinds, verifyEvent } from 'nostr-tools'
|
||||
import { UserComponent } from '../../components/username'
|
||||
import styles from './style.module.scss'
|
||||
|
||||
export const HomePage = () => {
|
||||
const navigate = useNavigate()
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
const [isLoading, setIsLoading] = useState(true)
|
||||
const [loadingSpinnerDesc] = useState(`Finding user's app data`)
|
||||
const [authUrl, setAuthUrl] = useState<string>()
|
||||
const [sigits, setSigits] = useState<Sigit[]>([])
|
||||
|
||||
const [sigits, setSigits] = useState<Meta[]>([])
|
||||
const [profiles, setProfiles] = useState<{ [key: string]: ProfileMetadata }>(
|
||||
{}
|
||||
)
|
||||
const usersAppData = useAppSelector((state) => state.userAppData)
|
||||
|
||||
useEffect(() => {
|
||||
const nostrController = NostrController.getInstance()
|
||||
// Set up event listener for authentication event
|
||||
nostrController.on('nsecbunker-auth', (url) => {
|
||||
setAuthUrl(url)
|
||||
})
|
||||
|
||||
getUsersAppData()
|
||||
.then((res) => {
|
||||
if (res) {
|
||||
setSigits(Object.values(res))
|
||||
if (usersAppData) {
|
||||
setSigits(Object.values(usersAppData.sigits))
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
setIsLoading(false)
|
||||
})
|
||||
}, [])
|
||||
}, [usersAppData])
|
||||
|
||||
const handleUploadClick = () => {
|
||||
if (fileInputRef.current) {
|
||||
@ -101,20 +80,8 @@ export const HomePage = () => {
|
||||
}
|
||||
}
|
||||
|
||||
if (authUrl) {
|
||||
return (
|
||||
<iframe
|
||||
title="Nsecbunker auth"
|
||||
src={authUrl}
|
||||
width="100%"
|
||||
height="500px"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
|
||||
<Box className={styles.container}>
|
||||
<Box className={styles.header}>
|
||||
<Typography variant="h3" className={styles.title}>
|
||||
@ -180,10 +147,10 @@ export const HomePage = () => {
|
||||
</Box>
|
||||
</Box>
|
||||
<Box className={styles.submissions}>
|
||||
{sigits.map((sigit) => (
|
||||
{sigits.map((sigit, index) => (
|
||||
<DisplaySigit
|
||||
key={sigit.meta.uuid}
|
||||
sigit={sigit}
|
||||
key={`sigit-${index}`}
|
||||
meta={sigit}
|
||||
profiles={profiles}
|
||||
setProfiles={setProfiles}
|
||||
/>
|
||||
@ -195,22 +162,31 @@ export const HomePage = () => {
|
||||
}
|
||||
|
||||
type SigitProps = {
|
||||
sigit: Sigit
|
||||
meta: Meta
|
||||
profiles: { [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 [title, setTitle] = useState<string>()
|
||||
const [createdAt, setCreatedAt] = useState('')
|
||||
const [submittedBy, setSubmittedBy] = useState<string>()
|
||||
const [signers, setSigners] = useState<`npub1${string}`[]>([])
|
||||
const [signedStatus, setSignedStatus] = useState<SignedStatus>(
|
||||
SignedStatus.Partial
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
const extractInfo = async () => {
|
||||
const createSignatureEvent = await parseJson<Event>(
|
||||
sigit.meta.createSignature
|
||||
meta.createSignature
|
||||
).catch((err) => {
|
||||
console.log('err in parsing the createSignature event:>> ', err)
|
||||
toast.error(
|
||||
@ -238,11 +214,20 @@ const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
|
||||
|
||||
if (!createSignatureContent) return
|
||||
|
||||
setTitle(createSignatureContent.title)
|
||||
setSubmittedBy(createSignatureEvent.pubkey)
|
||||
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()
|
||||
}, [sigit])
|
||||
}, [meta])
|
||||
|
||||
useEffect(() => {
|
||||
const hexKeys: string[] = []
|
||||
@ -285,7 +270,11 @@ const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
|
||||
}, [submittedBy, signers])
|
||||
|
||||
const handleNavigation = () => {
|
||||
navigate(appPrivateRoutes.sign, { state: { sigit } })
|
||||
if (signedStatus === SignedStatus.Complete) {
|
||||
navigate(appPublicRoutes.verify, { state: { meta } })
|
||||
} else {
|
||||
navigate(appPrivateRoutes.sign, { state: { meta } })
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
@ -314,7 +303,7 @@ const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
|
||||
>
|
||||
<Typography variant="body1" className={styles.title}>
|
||||
<Description />
|
||||
{sigit.meta.title}
|
||||
{title}
|
||||
</Typography>
|
||||
{submittedBy &&
|
||||
(function () {
|
||||
@ -344,7 +333,7 @@ const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
|
||||
return (
|
||||
<DisplaySigner
|
||||
key={signer}
|
||||
meta={sigit.meta}
|
||||
meta={meta}
|
||||
profile={profile}
|
||||
pubkey={pubkey}
|
||||
/>
|
||||
|
@ -13,16 +13,11 @@ import { LoadingSpinner } from '../../components/LoadingSpinner'
|
||||
import { NostrController } from '../../controllers'
|
||||
import { appPublicRoutes } from '../../routes'
|
||||
import { State } from '../../store/rootReducer'
|
||||
import {
|
||||
CreateSignatureEventContent,
|
||||
Meta,
|
||||
Sigit,
|
||||
SignedEvent
|
||||
} from '../../types'
|
||||
import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types'
|
||||
import {
|
||||
decryptArrayBuffer,
|
||||
encryptArrayBuffer,
|
||||
extractEncryptionKey,
|
||||
extractZipUrlAndEncryptionKey,
|
||||
generateEncryptionKey,
|
||||
generateKeysFile,
|
||||
getHash,
|
||||
@ -48,7 +43,7 @@ export const SignPage = () => {
|
||||
const navigate = useNavigate()
|
||||
const location = useLocation()
|
||||
const {
|
||||
sigit,
|
||||
meta: metaInNavState,
|
||||
arrayBuffer: decryptedArrayBuffer,
|
||||
uploadedZip
|
||||
} = location.state || {}
|
||||
@ -57,12 +52,11 @@ export const SignPage = () => {
|
||||
|
||||
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 [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
|
||||
|
||||
const [fileUrl, setFileUrl] = useState<string>()
|
||||
const [meta, setMeta] = useState<Meta | null>(null)
|
||||
const [signedStatus, setSignedStatus] = useState<SignedStatus>()
|
||||
|
||||
@ -89,41 +83,6 @@ export const SignPage = () => {
|
||||
const [authUrl, setAuthUrl] = useState<string>()
|
||||
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(() => {
|
||||
if (signers.length > 0) {
|
||||
// check if all signers have signed then its fully signed
|
||||
@ -223,65 +182,32 @@ export const SignPage = () => {
|
||||
}, [meta])
|
||||
|
||||
useEffect(() => {
|
||||
if (sigit) {
|
||||
if (metaInNavState) {
|
||||
const processSigit = async () => {
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc(
|
||||
'Extracting encryption key from creator signature'
|
||||
)
|
||||
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
|
||||
|
||||
const { fileUrl, meta } = sigit as Sigit
|
||||
|
||||
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) {
|
||||
const res = await extractZipUrlAndEncryptionKey(metaInNavState)
|
||||
if (!res) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
const { zipUrl, encryptionKey } = res
|
||||
|
||||
setLoadingSpinnerDesc('Fetching file from file server')
|
||||
setFileUrl(fileUrl)
|
||||
axios
|
||||
.get(fileUrl, {
|
||||
.get(zipUrl, {
|
||||
responseType: 'arraybuffer'
|
||||
})
|
||||
.then(async (res) => {
|
||||
const fileName = fileUrl.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) handleDecryptedArrayBuffer(arrayBuffer, meta)
|
||||
.then((res) => {
|
||||
handleArrayBufferFromBlossom(res.data, encryptionKey)
|
||||
setMeta(metaInNavState)
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(`error occurred in getting file from ${fileUrl}`, err)
|
||||
console.error(`error occurred in getting file from ${zipUrl}`, err)
|
||||
toast.error(
|
||||
err.message || `error occurred in getting file from ${fileUrl}`
|
||||
err.message || `error occurred in getting file from ${zipUrl}`
|
||||
)
|
||||
})
|
||||
.finally(() => {
|
||||
@ -310,7 +236,63 @@ export const SignPage = () => {
|
||||
setIsLoading(false)
|
||||
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 keysFileContent = await readContentOfZipEntry(
|
||||
@ -405,10 +387,7 @@ export const SignPage = () => {
|
||||
return null
|
||||
}
|
||||
|
||||
const handleDecryptedArrayBuffer = async (
|
||||
arrayBuffer: ArrayBuffer,
|
||||
meta?: Meta
|
||||
) => {
|
||||
const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => {
|
||||
const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip')
|
||||
|
||||
setLoadingSpinnerDesc('Parsing zip file')
|
||||
@ -421,14 +400,39 @@ export const SignPage = () => {
|
||||
|
||||
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)
|
||||
|
||||
let parsedMetaJson: Meta | null = null
|
||||
|
||||
if (meta) {
|
||||
parsedMetaJson = meta
|
||||
} else {
|
||||
setLoadingSpinnerDesc('Parsing meta.json')
|
||||
|
||||
const metaFileContent = await readContentOfZipEntry(
|
||||
@ -442,15 +446,16 @@ export const SignPage = () => {
|
||||
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)
|
||||
toast.error(
|
||||
err.message || 'error occurred in parsing the content of meta.json'
|
||||
)
|
||||
setIsLoading(false)
|
||||
return null
|
||||
})
|
||||
}
|
||||
)
|
||||
|
||||
setMeta(parsedMetaJson)
|
||||
}
|
||||
@ -467,7 +472,7 @@ export const SignPage = () => {
|
||||
}
|
||||
|
||||
const handleSign = async () => {
|
||||
if (!zip || !meta) return
|
||||
if (Object.entries(files).length === 0 || !meta) return
|
||||
|
||||
setIsLoading(true)
|
||||
|
||||
@ -480,13 +485,12 @@ export const SignPage = () => {
|
||||
if (!signedEvent) return
|
||||
|
||||
const updatedMeta = updateMetaSignatures(meta, signedEvent)
|
||||
setMeta(updatedMeta)
|
||||
|
||||
if (await isOnline()) {
|
||||
if (fileUrl) await handleOnlineFlow(fileUrl, updatedMeta)
|
||||
await handleOnlineFlow(updatedMeta)
|
||||
} else {
|
||||
// todo: fix offline flow
|
||||
// handleDecryptedArrayBuffer(arrayBuffer).finally(() => setIsLoading(false))
|
||||
setMeta(updatedMeta)
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
@ -585,31 +589,33 @@ export const SignPage = () => {
|
||||
return null
|
||||
}
|
||||
|
||||
// Handle the online flow: upload file and send DMs
|
||||
const handleOnlineFlow = async (fileUrl: string, meta: Meta) => {
|
||||
// Handle the online flow: update users app data and send notifications
|
||||
const handleOnlineFlow = async (meta: Meta) => {
|
||||
setLoadingSpinnerDesc('Updating users app data')
|
||||
const updatedEvent = await updateUsersAppData(fileUrl, meta)
|
||||
const updatedEvent = await updateUsersAppData(meta)
|
||||
if (!updatedEvent) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
const userSet = new Set<`npub1${string}`>()
|
||||
if (submittedBy) {
|
||||
if (submittedBy && submittedBy !== usersPubkey) {
|
||||
userSet.add(hexToNpub(submittedBy))
|
||||
}
|
||||
|
||||
const usersNpub = hexToNpub(usersPubkey!)
|
||||
const isLastSigner = checkIsLastSigner(signers)
|
||||
if (isLastSigner) {
|
||||
signers.forEach((signer) => {
|
||||
if (signer !== usersNpub) {
|
||||
userSet.add(signer)
|
||||
}
|
||||
})
|
||||
|
||||
viewers.forEach((viewer) => {
|
||||
userSet.add(viewer)
|
||||
})
|
||||
} else {
|
||||
const usersNpub = hexToNpub(usersPubkey!)
|
||||
const currentSignerIndex = signers.indexOf(usersNpub)
|
||||
const prevSigners = signers.slice(0, currentSignerIndex)
|
||||
|
||||
@ -624,9 +630,16 @@ export const SignPage = () => {
|
||||
setLoadingSpinnerDesc('Sending notifications')
|
||||
const users = Array.from(userSet)
|
||||
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)
|
||||
}
|
||||
@ -640,7 +653,7 @@ export const SignPage = () => {
|
||||
}
|
||||
|
||||
const handleExport = async () => {
|
||||
if (!meta || !zip || !usersPubkey) return
|
||||
if (Object.entries(files).length === 0 || !meta || !usersPubkey) return
|
||||
|
||||
const usersNpub = hexToNpub(usersPubkey)
|
||||
if (
|
||||
@ -653,7 +666,7 @@ export const SignPage = () => {
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Signing nostr event')
|
||||
|
||||
const prevSig = await getLastSignersSig()
|
||||
const prevSig = getLastSignersSig()
|
||||
if (!prevSig) return
|
||||
|
||||
const signedEvent = await signEventForMetaFile(
|
||||
@ -676,8 +689,15 @@ export const SignPage = () => {
|
||||
null,
|
||||
2
|
||||
)
|
||||
|
||||
const zip = new JSZip()
|
||||
|
||||
zip.file('meta.json', stringifiedMeta)
|
||||
|
||||
Object.entries(files).forEach(([fileName, arrayBuffer]) => {
|
||||
zip.file(`files/${fileName}`, arrayBuffer)
|
||||
})
|
||||
|
||||
const arrayBuffer = await zip
|
||||
.generateAsync({
|
||||
type: 'arraybuffer',
|
||||
@ -705,7 +725,17 @@ export const SignPage = () => {
|
||||
}
|
||||
|
||||
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
|
||||
.generateAsync({
|
||||
@ -840,11 +870,11 @@ export const SignPage = () => {
|
||||
</>
|
||||
)}
|
||||
|
||||
{submittedBy && zip && meta && (
|
||||
{submittedBy && Object.entries(files).length > 0 && meta && (
|
||||
<>
|
||||
<DisplayMeta
|
||||
meta={meta}
|
||||
zip={zip}
|
||||
files={files}
|
||||
submittedBy={submittedBy}
|
||||
signers={signers}
|
||||
viewers={viewers}
|
||||
@ -871,7 +901,6 @@ export const SignPage = () => {
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{/* todo: In offline mode export sigit is not visible after last signer has signed*/}
|
||||
{isSignerOrCreator && (
|
||||
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
|
||||
<Button onClick={handleExportSigit} variant="contained">
|
||||
|
@ -1,4 +1,3 @@
|
||||
import JSZip from 'jszip'
|
||||
import {
|
||||
Meta,
|
||||
ProfileMetadata,
|
||||
@ -33,18 +32,12 @@ import { useState, useEffect } from 'react'
|
||||
import { toast } from 'react-toastify'
|
||||
import { UserComponent } from '../../../components/username'
|
||||
import { MetadataController } from '../../../controllers'
|
||||
import {
|
||||
npubToHex,
|
||||
readContentOfZipEntry,
|
||||
shorten,
|
||||
hexToNpub,
|
||||
parseJson
|
||||
} from '../../../utils'
|
||||
import { npubToHex, shorten, hexToNpub, parseJson } from '../../../utils'
|
||||
import styles from '../style.module.scss'
|
||||
|
||||
type DisplayMetaProps = {
|
||||
meta: Meta
|
||||
zip: JSZip
|
||||
files: { [filename: string]: ArrayBuffer }
|
||||
submittedBy: string
|
||||
signers: `npub1${string}`[]
|
||||
viewers: `npub1${string}`[]
|
||||
@ -57,7 +50,7 @@ type DisplayMetaProps = {
|
||||
|
||||
export const DisplayMeta = ({
|
||||
meta,
|
||||
zip,
|
||||
files,
|
||||
submittedBy,
|
||||
signers,
|
||||
viewers,
|
||||
@ -150,11 +143,7 @@ export const DisplayMeta = ({
|
||||
}, [users, submittedBy])
|
||||
|
||||
const downloadFile = async (filename: string) => {
|
||||
const arrayBuffer = await readContentOfZipEntry(
|
||||
zip,
|
||||
`files/${filename}`,
|
||||
'arraybuffer'
|
||||
)
|
||||
const arrayBuffer = files[filename]
|
||||
if (!arrayBuffer) return
|
||||
|
||||
const blob = new Blob([arrayBuffer])
|
||||
|
@ -23,6 +23,8 @@ import {
|
||||
SignedEventContent
|
||||
} from '../../types'
|
||||
import {
|
||||
decryptArrayBuffer,
|
||||
extractZipUrlAndEncryptionKey,
|
||||
getHash,
|
||||
hexToNpub,
|
||||
npubToHex,
|
||||
@ -33,6 +35,7 @@ import {
|
||||
import styles from './style.module.scss'
|
||||
import { Cancel, CheckCircle } from '@mui/icons-material'
|
||||
import { useLocation } from 'react-router-dom'
|
||||
import axios from 'axios'
|
||||
|
||||
export const VerifyPage = () => {
|
||||
const theme = useTheme()
|
||||
@ -41,13 +44,12 @@ export const VerifyPage = () => {
|
||||
)
|
||||
|
||||
const location = useLocation()
|
||||
const { uploadedZip } = location.state || {}
|
||||
const { uploadedZip, meta: metaInNavState } = location.state || {}
|
||||
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null)
|
||||
const [zip, setZip] = useState<JSZip>()
|
||||
const [meta, setMeta] = useState<Meta | null>(null)
|
||||
|
||||
const [submittedBy, setSubmittedBy] = useState<string>()
|
||||
@ -68,16 +70,60 @@ export const VerifyPage = () => {
|
||||
useEffect(() => {
|
||||
if (uploadedZip) {
|
||||
setSelectedFile(uploadedZip)
|
||||
}
|
||||
}, [uploadedZip])
|
||||
} else if (metaInNavState) {
|
||||
const processSigit = async () => {
|
||||
setIsLoading(true)
|
||||
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
|
||||
|
||||
const res = await extractZipUrlAndEncryptionKey(metaInNavState)
|
||||
if (!res) {
|
||||
setIsLoading(false)
|
||||
return
|
||||
}
|
||||
|
||||
const {
|
||||
zipUrl,
|
||||
encryptionKey,
|
||||
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 fileNames = Object.values(zip.files)
|
||||
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
|
||||
.map((entry) => entry.name)
|
||||
const fileNames = Object.values(zip.files).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
|
||||
@ -100,11 +146,30 @@ export const VerifyPage = () => {
|
||||
}
|
||||
|
||||
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(() => {
|
||||
if (submittedBy) {
|
||||
@ -159,7 +224,34 @@ export const VerifyPage = () => {
|
||||
})
|
||||
|
||||
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')
|
||||
|
||||
|
@ -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_MOST_POPULAR_RELAYS = 'SET_MOST_POPULAR_RELAYS'
|
||||
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'
|
||||
|
@ -4,6 +4,7 @@ import { State } from './rootReducer'
|
||||
export * from './auth/action'
|
||||
export * from './metadata/action'
|
||||
export * from './relays/action'
|
||||
export * from './userAppData/action'
|
||||
|
||||
export const restoreState = (payload: State) => {
|
||||
return {
|
||||
|
@ -1,25 +1,29 @@
|
||||
import { Event } from 'nostr-tools'
|
||||
import { combineReducers } from 'redux'
|
||||
import { UserAppData } from '../types'
|
||||
import * as ActionTypes from './actionTypes'
|
||||
import authReducer from './auth/reducer'
|
||||
import { AuthState } from './auth/types'
|
||||
import metadataReducer from './metadata/reducer'
|
||||
import userRobotImageReducer from './userRobotImage/reducer'
|
||||
import { RelaysState } from './relays/types'
|
||||
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 {
|
||||
auth: AuthState
|
||||
metadata?: Event
|
||||
userRobotImage?: string
|
||||
relays: RelaysState
|
||||
userAppData?: UserAppData
|
||||
}
|
||||
|
||||
export const appReducer = combineReducers({
|
||||
auth: authReducer,
|
||||
metadata: metadataReducer,
|
||||
userRobotImage: userRobotImageReducer,
|
||||
relays: relaysReducer
|
||||
relays: relaysReducer,
|
||||
userAppData: UserAppDataReducer
|
||||
})
|
||||
|
||||
// FIXME: define types
|
||||
|
15
src/store/userAppData/action.ts
Normal file
15
src/store/userAppData/action.ts
Normal 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
|
||||
})
|
35
src/store/userAppData/reducer.ts
Normal file
35
src/store/userAppData/reducer.ts
Normal 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
|
18
src/store/userAppData/types.ts
Normal file
18
src/store/userAppData/types.ts
Normal 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
|
@ -1,3 +1,5 @@
|
||||
import { Keys } from '../store/auth/types'
|
||||
|
||||
export enum UserRole {
|
||||
signer = 'Signer',
|
||||
viewer = 'Viewer'
|
||||
@ -9,19 +11,19 @@ export interface User {
|
||||
}
|
||||
|
||||
export interface Meta {
|
||||
uuid: string
|
||||
title: string
|
||||
modifiedAt: number
|
||||
createSignature: string
|
||||
docSignatures: { [key: `npub1${string}`]: string }
|
||||
exportSignature?: string
|
||||
keys?: { sender: string; keys: { [user: `npub1${string}`]: string } }
|
||||
}
|
||||
|
||||
export interface CreateSignatureEventContent {
|
||||
signers: `npub1${string}`[]
|
||||
viewers: `npub1${string}`[]
|
||||
fileHashes: { [key: string]: string }
|
||||
keys: { sender: string; keys: { [user: `npub1${string}`]: string } }
|
||||
title: string
|
||||
zipUrl: string
|
||||
}
|
||||
|
||||
export interface SignedEventContent {
|
||||
@ -32,3 +34,10 @@ export interface Sigit {
|
||||
fileUrl: string
|
||||
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
|
||||
}
|
||||
|
@ -10,9 +10,9 @@ import {
|
||||
import { toast } from 'react-toastify'
|
||||
import { MetadataController, NostrController } from '../controllers'
|
||||
import { appPrivateRoutes } from '../routes'
|
||||
import { hexToNpub } from './nostr'
|
||||
import { hexToNpub, now } from './nostr'
|
||||
import { parseJson } from './string'
|
||||
import { CreateSignatureEventContent } from '../types'
|
||||
import { CreateSignatureEventContent, Meta } from '../types'
|
||||
import store from '../store/store'
|
||||
import { AuthState } from '../store/auth/types'
|
||||
|
||||
@ -26,9 +26,6 @@ export const uploadToFileStorage = async (
|
||||
file: File,
|
||||
nostrController: NostrController
|
||||
) => {
|
||||
// Get the current timestamp in seconds
|
||||
const unixNow = Math.floor(Date.now() / 1000)
|
||||
|
||||
// Define event metadata for authorization
|
||||
const event: EventTemplate = {
|
||||
kind: 24242,
|
||||
@ -36,7 +33,7 @@ export const uploadToFileStorage = async (
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [
|
||||
['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],
|
||||
['size', String(file.size)]
|
||||
]
|
||||
@ -301,16 +298,16 @@ export const generateKeys = async (
|
||||
return { sender: getPublicKey(privateKey), keys }
|
||||
}
|
||||
|
||||
export const extractEncryptionKey = async (createSignature: string) => {
|
||||
const createSignatureEvent = await parseJson<Event>(createSignature).catch(
|
||||
(err) => {
|
||||
export const extractZipUrlAndEncryptionKey = async (meta: 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
|
||||
|
||||
@ -332,15 +329,32 @@ export const extractEncryptionKey = async (createSignature: string) => {
|
||||
|
||||
if (!createSignatureContent) return null
|
||||
|
||||
const zipUrl = createSignatureContent.zipUrl
|
||||
|
||||
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
|
||||
const usersNpub = hexToNpub(usersPubkey)
|
||||
|
||||
const { sender, keys } = createSignatureContent.keys
|
||||
if (!meta.keys) return null
|
||||
|
||||
const { sender, keys } = meta.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 {
|
||||
sender,
|
||||
encryptedKey: keys[usersNpub]
|
||||
createSignatureEvent,
|
||||
createSignatureContent,
|
||||
zipUrl,
|
||||
encryptionKey: decrypted
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,4 +1,6 @@
|
||||
import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
|
||||
import axios from 'axios'
|
||||
import _ from 'lodash'
|
||||
import {
|
||||
Event,
|
||||
EventTemplate,
|
||||
@ -17,12 +19,16 @@ import {
|
||||
import { toast } from 'react-toastify'
|
||||
import { NIP05_REGEX } from '../constants'
|
||||
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 store from '../store/store'
|
||||
import { Meta, Rumor, Sigit, SignedEvent } from '../types'
|
||||
import { Meta, SignedEvent, UserAppData } from '../types'
|
||||
import { getHash } from './hash'
|
||||
import { parseJson } from './string'
|
||||
import { parseJson, removeLeadingSlash } from './string'
|
||||
|
||||
/**
|
||||
* @param hexKey hex private or public key
|
||||
@ -203,7 +209,7 @@ export const getRoboHashPicture = (
|
||||
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 randomNow = () => Math.round(now() - Math.random() * TWO_DAYS)
|
||||
@ -220,7 +226,7 @@ export const nip44ConversationKey = (
|
||||
) => nip44.v2.utils.getConversationKey(privateKey, publicKey)
|
||||
|
||||
export const nip44Encrypt = (
|
||||
data: EventTemplate,
|
||||
data: UnsignedEvent,
|
||||
privateKey: Uint8Array,
|
||||
publicKey: string
|
||||
) =>
|
||||
@ -262,31 +268,28 @@ export const countLeadingZeroes = (hex: string) => {
|
||||
* @returns
|
||||
*/
|
||||
//
|
||||
export const createWrap = (
|
||||
event: Event,
|
||||
receiver: string,
|
||||
difficulty: number = 10
|
||||
) => {
|
||||
export const createWrap = (unsignedEvent: UnsignedEvent, receiver: string) => {
|
||||
// Generate a random secret key and its corresponding public key
|
||||
const randomKey = generateSecretKey()
|
||||
const pubkey = getPublicKey(randomKey)
|
||||
|
||||
// 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
|
||||
let nonce = 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
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
// Create an unsigned event with the necessary fields
|
||||
const unsignedEvent: UnsignedEvent = {
|
||||
const event: UnsignedEvent = {
|
||||
kind: 1059, // Event kind
|
||||
content, // Encrypted content
|
||||
pubkey, // Public key of the creator
|
||||
created_at: randomNow(), // Current timestamp
|
||||
created_at: now(), // Current timestamp
|
||||
tags: [
|
||||
// Tags including receiver and nonce
|
||||
['p', receiver],
|
||||
@ -295,7 +298,7 @@ export const createWrap = (
|
||||
}
|
||||
|
||||
// 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
|
||||
leadingZeroes = countLeadingZeroes(hash)
|
||||
@ -303,7 +306,7 @@ export const createWrap = (
|
||||
// Check if the leading zero bits meet the required difficulty
|
||||
if (leadingZeroes >= difficulty) {
|
||||
// Finalize the event (sign it) and return the result
|
||||
return finalizeEvent(unsignedEvent, randomKey)
|
||||
return finalizeEvent(event, randomKey)
|
||||
}
|
||||
|
||||
// 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 usersPubkey = (store.getState().auth as AuthState).usersPubkey!
|
||||
@ -321,8 +324,6 @@ export const getUsersAppData = async () => {
|
||||
|
||||
// check if relaysMap in redux store is undefined
|
||||
if (!relayMap) {
|
||||
// todo: use metadata controller
|
||||
|
||||
const metadataController = new MetadataController()
|
||||
const relaySet = await metadataController
|
||||
.findRelayListMetadata(usersPubkey)
|
||||
@ -335,10 +336,10 @@ export const getUsersAppData = async () => {
|
||||
})
|
||||
|
||||
// Return if metadata retrieval failed
|
||||
if (!relaySet) return
|
||||
if (!relaySet) return null
|
||||
|
||||
// Ensure relay list is not empty
|
||||
if (relaySet.write.length === 0) return
|
||||
if (relaySet.write.length === 0) return null
|
||||
|
||||
relays.push(...relaySet.write)
|
||||
} else {
|
||||
@ -351,7 +352,7 @@ export const getUsersAppData = async () => {
|
||||
}
|
||||
|
||||
// generate an identifier for user's nip78
|
||||
const hash = await getHash('sigit' + usersPubkey)
|
||||
const hash = await getHash('938' + usersPubkey)
|
||||
if (!hash) return null
|
||||
|
||||
const filter: Filter = {
|
||||
@ -379,7 +380,18 @@ export const getUsersAppData = async () => {
|
||||
if (!encryptedContent) return null
|
||||
|
||||
if (encryptedContent === '{}') {
|
||||
return {}
|
||||
const secret = generateSecretKey()
|
||||
const pubKey = getPublicKey(secret)
|
||||
|
||||
return {
|
||||
sigits: {},
|
||||
processedGiftWraps: [],
|
||||
blossomUrls: [],
|
||||
keyPair: {
|
||||
private: bytesToHex(secret),
|
||||
public: pubKey
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const decrypted = await nostrController
|
||||
@ -393,7 +405,8 @@ export const getUsersAppData = async () => {
|
||||
if (!decrypted) return null
|
||||
|
||||
const parsedContent = await parseJson<{
|
||||
[uuid: string]: Sigit
|
||||
blossomUrls: string[]
|
||||
keyPair: Keys
|
||||
}>(decrypted).catch((err) => {
|
||||
console.log(
|
||||
'An error occurred in parsing the content of kind 30078 event',
|
||||
@ -405,39 +418,108 @@ export const getUsersAppData = async () => {
|
||||
|
||||
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) => {
|
||||
const appData = await getUsersAppData()
|
||||
if (!appData) return null
|
||||
export const updateUsersAppData = async (meta: Meta) => {
|
||||
const appData = store.getState().userAppData
|
||||
if (!appData || !appData.keyPair) return null
|
||||
|
||||
if (meta.uuid in appData) {
|
||||
// update meta only if income meta is more recent than already existing one
|
||||
const existingMeta = appData[meta.uuid].meta
|
||||
const sigits = _.cloneDeep(appData.sigits)
|
||||
|
||||
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) {
|
||||
appData[meta.uuid] = {
|
||||
fileUrl,
|
||||
meta
|
||||
}
|
||||
sigits[id] = meta
|
||||
isUpdated = true
|
||||
}
|
||||
} else {
|
||||
appData[meta.uuid] = {
|
||||
fileUrl,
|
||||
meta
|
||||
}
|
||||
sigits[id] = meta
|
||||
isUpdated = true
|
||||
}
|
||||
|
||||
appData[meta.uuid] = {
|
||||
fileUrl,
|
||||
meta
|
||||
if (!isUpdated) return null
|
||||
|
||||
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 nostrController = NostrController.getInstance()
|
||||
const encryptedContent = await nostrController
|
||||
.nip04Encrypt(usersPubkey, JSON.stringify(appData))
|
||||
.nip04Encrypt(
|
||||
usersPubkey,
|
||||
JSON.stringify({
|
||||
blossomUrls,
|
||||
keyPair: appData.keyPair
|
||||
})
|
||||
)
|
||||
.catch((err) => {
|
||||
console.log(
|
||||
'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
|
||||
|
||||
// generate the identifier for user's appData event
|
||||
const hash = await getHash('sigit' + usersPubkey)
|
||||
const hash = await getHash('938' + usersPubkey)
|
||||
if (!hash) return null
|
||||
|
||||
const updatedEvent: UnsignedEvent = {
|
||||
@ -493,9 +575,143 @@ export const updateUsersAppData = async (fileUrl: string, meta: Meta) => {
|
||||
|
||||
if (!publishResult) return null
|
||||
|
||||
// update redux store
|
||||
store.dispatch(
|
||||
updateUserAppDataAction({
|
||||
sigits,
|
||||
blossomUrls,
|
||||
processedGiftWraps: [...appData.processedGiftWraps],
|
||||
keyPair: {
|
||||
...appData.keyPair
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
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) => {
|
||||
// Get relay list metadata
|
||||
const metadataController = new MetadataController()
|
||||
@ -521,70 +737,71 @@ export const subscribeForSigits = async (pubkey: string) => {
|
||||
}
|
||||
const pool = new SimplePool()
|
||||
|
||||
pool.subscribeMany(relaySet.read, [filter], {
|
||||
return pool.subscribeMany(relaySet.read, [filter], {
|
||||
onevent: (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
|
||||
// Count the number of leading zero bits in the hash
|
||||
const leadingZeroes = countLeadingZeroes(event.id)
|
||||
if (leadingZeroes < difficulty) return
|
||||
|
||||
// decrypt the content of gift wrap event
|
||||
const nostrController = NostrController.getInstance()
|
||||
const stringifiedSealEvent = await nostrController.nip44Decrypt(
|
||||
const decrypted = await nostrController.nip44Decrypt(
|
||||
event.pubkey,
|
||||
event.content
|
||||
)
|
||||
const sealEvent = await parseJson<Event>(stringifiedSealEvent)
|
||||
const stringifiedRumor = await nostrController.nip44Decrypt(
|
||||
sealEvent.pubkey,
|
||||
sealEvent.content
|
||||
|
||||
const internalUnsignedEvent = await parseJson<UnsignedEvent>(decrypted).catch(
|
||||
(err) => {
|
||||
console.log(
|
||||
'An error occurred in parsing the internal unsigned event',
|
||||
err
|
||||
)
|
||||
const rumor = await parseJson<Rumor>(stringifiedRumor)
|
||||
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)
|
||||
return null
|
||||
}
|
||||
)
|
||||
|
||||
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 (
|
||||
receiver: string,
|
||||
meta: Meta,
|
||||
fileUrl: string
|
||||
) => {
|
||||
export const sendNotification = async (receiver: string, meta: Meta) => {
|
||||
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
|
||||
|
||||
const unsignedEvent: UnsignedEvent = {
|
||||
kind: kinds.ShortTextNote,
|
||||
kind: 938,
|
||||
pubkey: usersPubkey,
|
||||
content: 'sigit-notification',
|
||||
tags: [
|
||||
['u', fileUrl],
|
||||
['m', JSON.stringify(meta)]
|
||||
],
|
||||
content: JSON.stringify(meta),
|
||||
tags: [],
|
||||
created_at: now()
|
||||
}
|
||||
|
||||
const rumor: Rumor = {
|
||||
...unsignedEvent,
|
||||
id: getEventHash(unsignedEvent)
|
||||
}
|
||||
|
||||
const nostrController = NostrController.getInstance()
|
||||
const seal = await nostrController.createSeal(rumor, receiver)
|
||||
const wrappedEvent = createWrap(seal, receiver)
|
||||
const wrappedEvent = createWrap(unsignedEvent, receiver)
|
||||
|
||||
// Get relay list metadata
|
||||
const metadataController = new MetadataController()
|
||||
@ -605,6 +822,7 @@ export const sendNotification = async (
|
||||
if (relaySet.read.length === 0) return
|
||||
|
||||
// Publish the notification event to the recipient's read relays
|
||||
const nostrController = NostrController.getInstance()
|
||||
await nostrController
|
||||
.publishEvent(wrappedEvent, relaySet.read)
|
||||
.catch((errResults) => {
|
||||
@ -612,6 +830,6 @@ export const sendNotification = async (
|
||||
`An error occurred while publishing notification event for ${hexToNpub(receiver)}`,
|
||||
errResults
|
||||
)
|
||||
return null
|
||||
throw errResults
|
||||
})
|
||||
}
|
||||
|
@ -111,3 +111,19 @@ export const formatTimestamp = (timestamp: number) => {
|
||||
// Combine parts into the desired format
|
||||
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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user