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
19 changed files with 1473 additions and 520 deletions
Showing only changes of commit 5850ef7dce - Show all commits

30
package-lock.json generated
View File

@ -25,7 +25,7 @@
"jszip": "3.10.1",
"lodash": "4.17.21",
"mui-file-input": "4.0.4",
"nostr-tools": "2.3.1",
"nostr-tools": "2.7.0",
"react": "^18.2.0",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
@ -34,7 +34,8 @@
"react-router-dom": "6.22.1",
"react-toastify": "10.0.4",
"redux": "5.0.1",
"tseep": "1.2.1"
"tseep": "1.2.1",
"uuid": "10.0.0"
},
"devDependencies": {
"@types/crypto-js": "^4.2.2",
@ -42,6 +43,7 @@
"@types/lodash": "4.14.202",
"@types/react": "^18.2.56",
"@types/react-dom": "^18.2.19",
"@types/uuid": "9.0.8",
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
"@vitejs/plugin-react": "^4.2.1",
@ -2138,6 +2140,12 @@
"resolved": "https://registry.npmjs.org/@types/use-sync-external-store/-/use-sync-external-store-0.0.3.tgz",
"integrity": "sha512-EwmlvuaxPNej9+T4v5AuBPJa2x2UOJVdjCtDHgcDqitUeOtjnJKJ+apYjVcAoBEMjKW1VVFGZLUb5+qqa09XFA=="
},
"node_modules/@types/uuid": {
"version": "9.0.8",
"resolved": "https://registry.npmjs.org/@types/uuid/-/uuid-9.0.8.tgz",
"integrity": "sha512-jg+97EGIcY9AGHJJRaaPVgetKDsrTgbRjQ5Msgjh/DQKEFl0DtyRr/VCOyD1T2R1MNeWPK/u7JoGhlDZnKBAfA==",
"dev": true
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "7.1.0",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-7.1.0.tgz",
@ -4137,9 +4145,9 @@
}
},
"node_modules/nostr-tools": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.3.1.tgz",
"integrity": "sha512-qjKx2C3EzwiQOe2LPSPyCnp07pGz1pWaWjDXcm+L2y2c8iTECbvlzujDANm3nJUjWL5+LVRUVDovTZ1a/DC4Bg==",
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.7.0.tgz",
"integrity": "sha512-jJoL2J1CBiKDxaXZww27nY/Wsuxzx7AULxmGKFce4sskDu1tohNyfnzYQ8BvDyvkstU8kNZUAXPL32tre33uig==",
"dependencies": {
"@noble/ciphers": "^0.5.1",
"@noble/curves": "1.2.0",
@ -5211,6 +5219,18 @@
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="
},
"node_modules/uuid": {
"version": "10.0.0",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-10.0.0.tgz",
"integrity": "sha512-8XkAphELsDnEGrDxUOHB3RGvXz6TeuYSGEZBOjtTtPm2lwhGBjLgOzLHB63IUWfBpNucQjND6d3AOudO+H3RWQ==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"bin": {
"uuid": "dist/bin/uuid"
}
},
"node_modules/v8-compile-cache-lib": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz",

View File

@ -31,7 +31,7 @@
"jszip": "3.10.1",
"lodash": "4.17.21",
"mui-file-input": "4.0.4",
"nostr-tools": "2.3.1",
"nostr-tools": "2.7.0",
"react": "^18.2.0",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
@ -40,7 +40,8 @@
"react-router-dom": "6.22.1",
"react-toastify": "10.0.4",
"redux": "5.0.1",
"tseep": "1.2.1"
"tseep": "1.2.1",
"uuid": "10.0.0"
},
"devDependencies": {
"@types/crypto-js": "^4.2.2",
@ -48,6 +49,7 @@
"@types/lodash": "4.14.202",
"@types/react": "^18.2.56",
"@types/react-dom": "^18.2.19",
"@types/uuid": "9.0.8",
"@typescript-eslint/eslint-plugin": "^7.0.2",
"@typescript-eslint/parser": "^7.0.2",
"@vitejs/plugin-react": "^4.2.1",

View File

@ -1,9 +1,9 @@
import { Typography, IconButton, Box, useTheme } from '@mui/material'
import { Box, IconButton, Typography, useTheme } from '@mui/material'
import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { getProfileRoute } from '../routes'
import { State } from '../store/rootReducer'
import { hexToNpub } from '../utils'
import { Link } from 'react-router-dom'
import { getProfileRoute } from '../routes'
type Props = {
username: string
@ -60,6 +60,7 @@ type UserProps = {
*/
export const UserComponent = ({ pubkey, name, image }: UserProps) => {
const theme = useTheme()
const navigate = useNavigate()
const npub = hexToNpub(pubkey)
const roboImage = `https://robohash.org/${npub}.png?set=set3`
@ -67,6 +68,10 @@ export const UserComponent = ({ pubkey, name, image }: UserProps) => {
return (
<Box
sx={{ display: 'flex', alignItems: 'center', gap: '10px', flexGrow: 1 }}
onClick={(e) => {
e.stopPropagation()
navigate(getProfileRoute(pubkey))
}}
>
<img
src={image || roboImage}
@ -78,18 +83,16 @@ export const UserComponent = ({ pubkey, name, image }: UserProps) => {
borderColor: `#${pubkey.substring(0, 6)}`
}}
/>
<Link to={getProfileRoute(pubkey)}>
<Typography
component="label"
sx={{
textAlign: 'center',
cursor: 'pointer',
color: theme.palette.text.primary
}}
>
{name}
</Typography>
</Link>
<Typography
component="label"
sx={{
textAlign: 'center',
cursor: 'pointer',
color: theme.palette.text.primary
}}
>
{name}
</Typography>
</Box>
)
}

View File

@ -46,6 +46,7 @@ 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)
@ -68,6 +69,7 @@ export class MetadataController extends EventEmitter {
}
}
// todo use nostr controller to find event from connected relays
// If no valid metadata event is found from the special relay, get the most popular relays
const mostPopularRelays = await this.nostrController.getMostPopularRelays()
@ -141,6 +143,22 @@ export class MetadataController extends EventEmitter {
}
public findRelayListMetadata = async (hexKey: string) => {
let relayEvent: Event | null = null
// Attempt to retrieve the metadata event from the local cache
const cachedRelayListMetadataEvent =
await localCache.getUserRelayListMetadata(hexKey)
if (cachedRelayListMetadataEvent) {
const oneWeekInMS = 7 * 24 * 60 * 60 * 1000 // Number of milliseconds in one week
// Check if the cached event is not older than one week
if (Date.now() - cachedRelayListMetadataEvent.cachedAt < oneWeekInMS) {
relayEvent = cachedRelayListMetadataEvent.event
}
}
// define filter for relay list
const eventFilter: Filter = {
kinds: [kinds.RelayList],
authors: [hexKey]
@ -148,19 +166,38 @@ export class MetadataController extends EventEmitter {
const pool = new SimplePool()
let relayEvent = await pool
.get([this.specialMetadataRelay], eventFilter)
.catch((err) => {
console.error(err)
return null
})
// Try to get the relayList event from a special relay (wss://purplepag.es)
if (!relayEvent) {
relayEvent = await pool
.get([this.specialMetadataRelay], eventFilter)
.then((event) => {
if (event) {
// update the event in local cache
localCache.addUserRelayListMetadata(event)
}
return event
})
.catch((err) => {
console.error(err)
return null
})
}
if (!relayEvent) {
// If no valid relayList event is found from the special relay, get the most popular relays
const mostPopularRelays =
await this.nostrController.getMostPopularRelays()
// Query the most popular relays for relayList event
relayEvent = await pool
.get(mostPopularRelays, eventFilter)
.then((event) => {
if (event) {
// update the event in local cache
localCache.addUserRelayListMetadata(event)
}
return event
})
.catch((err) => {
console.error(err)
return null

View File

@ -2,46 +2,50 @@ import NDK, {
NDKEvent,
NDKNip46Signer,
NDKPrivateKeySigner,
NDKSubscription,
NDKUser,
NostrEvent,
NDKSubscription
NostrEvent
} from '@nostr-dev-kit/ndk'
import axios from 'axios'
import {
Event,
EventTemplate,
SimplePool,
UnsignedEvent,
Filter,
Relay,
SimplePool,
UnsignedEvent,
finalizeEvent,
kinds,
nip04,
nip19,
kinds
nip44
} from 'nostr-tools'
import { toast } from 'react-toastify'
import { EventEmitter } from 'tseep'
import {
updateNsecbunkerPubkey,
setMostPopularRelaysAction,
setRelayConnectionStatusAction,
setRelayInfoAction,
setRelayConnectionStatusAction
updateNsecbunkerPubkey
} from '../store/actions'
import { AuthState, LoginMethods } from '../store/auth/types'
import store from '../store/store'
import {
SignedEvent,
RelayMap,
RelayStats,
RelayReadStats,
RelayInfoObject,
RelayConnectionState,
RelayConnectionStatus,
RelayConnectionState
RelayInfoObject,
RelayMap,
RelayReadStats,
RelayStats,
Rumor,
SignedEvent
} from '../types'
import {
compareObjects,
getNsecBunkerDelegatedKey,
randomNow,
verifySignedEvent
} from '../utils'
import axios from 'axios'
export class NostrController extends EventEmitter {
private static instance: NostrController
@ -56,7 +60,8 @@ export class NostrController extends EventEmitter {
}
private getNostrObject = () => {
if (window.nostr) return window.nostr
// fix: this is not picking up type declaration from src/system/index.d.ts
if (window.nostr) return window.nostr as any
throw new Error(
`window.nostr object not present. Make sure you have an nostr extension installed/working properly.`
@ -260,6 +265,157 @@ export class NostrController extends EventEmitter {
return publishedRelays
}
/**
* Asynchronously retrieves an event from a set of relays based on a provided filter.
* If no relays are specified, it defaults to using connected relays.
*
* @param {Filter} filter - The filter criteria to find the event.
* @param {string[]} [relays] - An optional array of relay URLs to search for the event.
* @returns {Promise<Event | null>} - Returns a promise that resolves to the found event or null if not found.
*/
getEvent = async (
filter: Filter,
relays?: string[]
): Promise<Event | null> => {
// If no relays are provided or the provided array is empty, use connected relays if available.
if (!relays || relays.length === 0) {
relays = this.connectedRelays
? this.connectedRelays.map((relay) => relay.url)
: []
}
// If still no relays are available, reject the promise with an error message.
if (relays.length === 0) {
return Promise.reject('Provide some relays to find the event')
}
// Create a new instance of SimplePool to handle the relay connections and event retrieval.
const pool = new SimplePool()
// Attempt to retrieve the event from the specified relays using the filter criteria.
const event = await pool.get(relays, filter).catch((err) => {
// Log any errors that occur during the event retrieval process.
console.log('An error occurred in finding the event', err)
// Show an error toast notification to the user.
toast.error('An error occurred in finding the event')
// Return null if an error occurs, indicating that no event was found.
return null
})
// Return the found event, or null if an error occurred.
return event
}
createSeal = async (rumor: Rumor, receiver: string) => {
const encryptedContent = await this.nip44Encrypt(
receiver,
JSON.stringify(rumor)
)
const unsignedEvent: UnsignedEvent = {
kind: 13,
content: encryptedContent,
created_at: randomNow(),
tags: [],
pubkey: (store.getState().auth as AuthState).usersPubkey!
}
const signedEvent = await this.signEvent(unsignedEvent)
return signedEvent
}
nip44Encrypt = async (receiver: string, content: string) => {
const loginMethod = (store.getState().auth as AuthState).loginMethod
if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
if (!nostr.nip44) {
throw new Error(
`Your nostr extension does not support nip44 encryption & decryption`
)
}
const encrypted = await nostr.nip44.encrypt(receiver, content)
return encrypted as string
}
if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const nip44ConversationKey = nip44.v2.utils.getConversationKey(
privateKey,
receiver
)
const encrypted = nip44.v2.encrypt(content, nip44ConversationKey)
return encrypted
}
if (loginMethod === LoginMethods.nsecBunker) {
throw new Error(
`nip44 encryption is not yet supported for login method '${LoginMethods.nsecBunker}'`
)
}
throw new Error('Login method is undefined')
}
nip44Decrypt = async (sender: string, content: string) => {
const loginMethod = (store.getState().auth as AuthState).loginMethod
if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
if (!nostr.nip44) {
throw new Error(
`Your nostr extension does not support nip44 encryption & decryption`
)
}
const decrypted = await nostr.nip44.decrypt(sender, content)
return decrypted as string
}
if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const nip44ConversationKey = nip44.v2.utils.getConversationKey(
privateKey,
sender
)
const decrypted = nip44.v2.decrypt(content, nip44ConversationKey)
return decrypted
}
if (loginMethod === LoginMethods.nsecBunker) {
throw new Error(
`nip44 decryption is not yet supported for login method '${LoginMethods.nsecBunker}'`
)
}
throw new Error('Login method is undefined')
}
/**
* Signs an event with private key (if it is present in local storage) or
* with browser extension (if it is present) or
@ -330,7 +486,7 @@ export class NostrController extends EventEmitter {
}
}
nip04Encrypt = async (receiver: string, content: string) => {
nip04Encrypt = async (receiver: string, content: string): Promise<string> => {
const loginMethod = (store.getState().auth as AuthState).loginMethod
if (loginMethod === LoginMethods.extension) {
@ -385,7 +541,7 @@ export class NostrController extends EventEmitter {
* @param content - The encrypted content to decrypt.
* @returns A promise that resolves to the decrypted content.
*/
nip04Decrypt = async (sender: string, content: string) => {
nip04Decrypt = async (sender: string, content: string): Promise<string> => {
const loginMethod = (store.getState().auth as AuthState).loginMethod
if (loginMethod === LoginMethods.extension) {

View File

@ -10,7 +10,8 @@ import {
clearState,
getRoboHashPicture,
loadState,
saveNsecBunkerDelegatedKey
saveNsecBunkerDelegatedKey,
subscribeForSigits
} from '../utils'
import { LoadingSpinner } from '../components/LoadingSpinner'
import { Dispatch } from '../store/store'
@ -100,6 +101,8 @@ export const MainLayout = () => {
if (pubkey) {
dispatch(setUserRobotImage(getRoboHashPicture(pubkey)))
subscribeForSigits(pubkey)
}
}
}, [authState])

View File

@ -18,12 +18,18 @@ import {
Tooltip,
Typography
} from '@mui/material'
import type { Identifier, XYCoord } from 'dnd-core'
import saveAs from 'file-saver'
import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input'
import { useEffect, useRef, useState } from 'react'
import { Event, kinds } from 'nostr-tools'
import { useEffect, useMemo, 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'
@ -33,24 +39,21 @@ import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import {
encryptArrayBuffer,
generateEncryptionKey,
generateKeys,
generateKeysFile,
getHash,
hexToNpub,
isOnline,
now,
npubToHex,
queryNip05,
sendDM,
sendNotification,
shorten,
signEventForMetaFile,
updateUsersAppData,
uploadToFileStorage
} from '../../utils'
import styles from './style.module.scss'
import { DndProvider } from 'react-dnd'
import { HTML5Backend } from 'react-dnd-html5-backend'
import type { Identifier, XYCoord } from 'dnd-core'
import { useDrag, useDrop } from 'react-dnd'
import saveAs from 'file-saver'
import { Event, kinds } from 'nostr-tools'
export const CreatePage = () => {
const navigate = useNavigate()
@ -75,6 +78,15 @@ export const CreatePage = () => {
const nostrController = NostrController.getInstance()
// Set up event listener for authentication event
nostrController.on('nsecbunker-auth', (url) => {
setAuthUrl(url)
})
const uuid = useMemo(() => {
return uuidV4()
}, [])
useEffect(() => {
if (uploadedFile) {
setSelectedFiles([uploadedFile])
@ -283,16 +295,28 @@ export const CreatePage = () => {
return fileHashes
}
// Create a zip file with the selected files and sign the event
const createZipFile = async (fileHashes: {
[key: string]: string
}): Promise<{ zip: JSZip; createSignature: string } | null> => {
// 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)
@ -302,7 +326,8 @@ export const CreatePage = () => {
JSON.stringify({
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
fileHashes
fileHashes,
keys
}),
nostrController,
setIsLoading
@ -320,38 +345,6 @@ export const CreatePage = () => {
}
}
// Add metadata and file hashes to the zip file
const addMetaToZip = async (
zip: JSZip,
createSignature: string
): Promise<string | null> => {
// create content for meta file
const meta: Meta = {
title,
createSignature,
docSignatures: {}
}
try {
const stringifiedMeta = JSON.stringify(meta, null, 2)
zip.file('meta.json', stringifiedMeta)
const metaHash = await getHash(stringifiedMeta)
if (!metaHash) return null
const metaHashJson = {
[usersPubkey!]: metaHash
}
zip.file('hashes.json', JSON.stringify(metaHashJson, null, 2))
return metaHash
} catch (err) {
console.error(err)
toast.error('An error occurred in converting meta json to string')
return null
}
}
// Handle errors during zip file generation
const handleZipError = (err: any) => {
console.log('Error in zip:>> ', err)
@ -390,7 +383,7 @@ export const CreatePage = () => {
encryptionKey: string
): Promise<File | null> => {
// Get the current timestamp in seconds
const unixNow = Math.floor(Date.now() / 1000)
const unixNow = now()
const blob = new Blob([encryptedArrayBuffer])
// Create a File object with the Blob data
const file = new File([blob], `compressed.sigit`, {
@ -432,9 +425,9 @@ export const CreatePage = () => {
const handleOnlineFlow = async (
encryptedArrayBuffer: ArrayBuffer,
encryptionKey: string
meta: Meta
) => {
const unixNow = Math.floor(Date.now() / 1000)
const unixNow = now()
const blob = new Blob([encryptedArrayBuffer])
// Create a File object with the Blob data
const file = new File([blob], `compressed-${unixNow}.sigit`, {
@ -444,7 +437,12 @@ export const CreatePage = () => {
const fileUrl = await uploadFile(file)
if (!fileUrl) return
await sendDMs(fileUrl, encryptionKey)
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
@ -471,33 +469,21 @@ export const CreatePage = () => {
}
// Send DMs to signers and viewers with the file URL
const sendDMs = async (fileUrl: string, encryptionKey: string) => {
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)
if (signers.length > 0) {
await sendDM(
fileUrl,
encryptionKey,
signers[0].pubkey,
nostrController,
true,
setAuthUrl
)
} else {
for (const viewer of viewers) {
await sendDM(
fileUrl,
encryptionKey,
viewer.pubkey,
nostrController,
false,
setAuthUrl
)
}
}
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
@ -524,21 +510,30 @@ export const CreatePage = () => {
const fileHashes = await generateFileHashes()
if (!fileHashes) return
const createZipResponse = await createZipFile(fileHashes)
const encryptionKey = await generateEncryptionKey()
const createZipResponse = await initZipFileAndCreatorSignature(
encryptionKey,
fileHashes
)
if (!createZipResponse) return
const { zip, createSignature } = createZipResponse
const metaHash = await addMetaToZip(zip, createSignature)
if (!metaHash) return
// create content for meta file
const meta: Meta = {
uuid,
title,
modifiedAt: now(),
createSignature,
docSignatures: {}
}
setLoadingSpinnerDesc('Generating zip file')
const arrayBuffer = await generateZipFile(zip)
if (!arrayBuffer) return
const encryptionKey = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptZipFile(
arrayBuffer,
@ -546,12 +541,11 @@ export const CreatePage = () => {
)
if (await isOnline()) {
await handleOnlineFlow(encryptedArrayBuffer, encryptionKey)
await handleOnlineFlow(encryptedArrayBuffer, meta)
} else {
// todo: fix offline flow
await handleOfflineFlow(encryptedArrayBuffer, encryptionKey)
}
navigate(appPrivateRoutes.sign, { state: { arrayBuffer } })
}
if (authUrl) {

View File

@ -1,21 +1,59 @@
import {
Add,
CalendarMonth,
Description,
PersonOutline,
Upload
} from '@mui/icons-material'
import { Add, CalendarMonth, Description, Upload } from '@mui/icons-material'
import { Box, Button, Tooltip, Typography } from '@mui/material'
import JSZip from 'jszip'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import { appPrivateRoutes, appPublicRoutes } from '../../routes'
import styles from './style.module.scss'
import { useRef } from 'react'
import JSZip from 'jszip'
import { toast } from 'react-toastify'
import { MetadataController, NostrController } from '../../controllers'
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'
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 [profiles, setProfiles] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
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))
}
})
.finally(() => {
setIsLoading(false)
})
}, [])
const handleUploadClick = () => {
if (fileInputRef.current) {
@ -63,81 +101,193 @@ export const HomePage = () => {
}
}
if (authUrl) {
return (
<iframe
title="Nsecbunker auth"
src={authUrl}
width="100%"
height="500px"
/>
)
}
return (
<Box className={styles.container}>
<Box className={styles.header}>
<Typography variant="h3" className={styles.title}>
Sigits
</Typography>
{/* This is for desktop view */}
<Box
className={styles.actionButtons}
sx={{
display: {
xs: 'none',
md: 'flex'
}
}}
>
<input
type="file"
ref={fileInputRef}
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<Button
variant="outlined"
startIcon={<Upload />}
onClick={handleUploadClick}
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}>
<Box className={styles.header}>
<Typography variant="h3" className={styles.title}>
Sigits
</Typography>
{/* This is for desktop view */}
<Box
className={styles.actionButtons}
sx={{
display: {
xs: 'none',
md: 'flex'
}
}}
>
Upload
</Button>
<Button
variant="contained"
startIcon={<Add />}
onClick={() => navigate(appPrivateRoutes.create)}
>
Create
</Button>
</Box>
{/* This is for mobile view */}
<Box
className={styles.actionButtons}
sx={{
display: {
xs: 'flex',
md: 'none'
}
}}
>
<Tooltip title="Upload" arrow>
<input
type="file"
ref={fileInputRef}
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<Button
variant="outlined"
onClick={() => navigate(appPrivateRoutes.sign)}
startIcon={<Upload />}
onClick={handleUploadClick}
>
<Upload />
Upload
</Button>
</Tooltip>
<Tooltip title="Create" arrow>
<Button
variant="contained"
startIcon={<Add />}
onClick={() => navigate(appPrivateRoutes.create)}
>
<Add />
Create
</Button>
</Tooltip>
</Box>
{/* This is for mobile view */}
<Box
className={styles.actionButtons}
sx={{
display: {
xs: 'flex',
md: 'none'
}
}}
>
<Tooltip title="Upload" arrow>
<Button
variant="outlined"
onClick={() => navigate(appPrivateRoutes.sign)}
>
<Upload />
</Button>
</Tooltip>
<Tooltip title="Create" arrow>
<Button
variant="contained"
onClick={() => navigate(appPrivateRoutes.create)}
>
<Add />
</Button>
</Tooltip>
</Box>
</Box>
<Box className={styles.submissions}>
{sigits.map((sigit) => (
<DisplaySigit
key={sigit.meta.uuid}
sigit={sigit}
profiles={profiles}
setProfiles={setProfiles}
/>
))}
</Box>
</Box>
<Box className={styles.submissions}>
<PlaceHolder />
<PlaceHolder />
<PlaceHolder />
</Box>
</Box>
</>
)
}
const PlaceHolder = () => {
type SigitProps = {
sigit: Sigit
profiles: { [key: string]: ProfileMetadata }
setProfiles: Dispatch<SetStateAction<{ [key: string]: ProfileMetadata }>>
}
const DisplaySigit = ({ sigit, profiles, setProfiles }: SigitProps) => {
const navigate = useNavigate()
const [createdAt, setCreatedAt] = useState('')
const [submittedBy, setSubmittedBy] = useState<string>()
const [signers, setSigners] = useState<`npub1${string}`[]>([])
useEffect(() => {
const extractInfo = async () => {
const createSignatureEvent = await parseJson<Event>(
sigit.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
// created_at in nostr events are stored in seconds
// convert it to ms before formatting
setCreatedAt(formatTimestamp(createSignatureEvent.created_at * 1000))
const createSignatureContent =
await parseJson<CreateSignatureEventContent>(
createSignatureEvent.content
).catch((err) => {
console.log(
`err in parsing the createSignature event's content :>> `,
err
)
return null
})
if (!createSignatureContent) return
setSubmittedBy(createSignatureEvent.pubkey)
setSigners(createSignatureContent.signers)
}
extractInfo()
}, [sigit])
useEffect(() => {
const hexKeys: string[] = []
if (submittedBy) {
hexKeys.push(npubToHex(submittedBy)!)
}
hexKeys.push(...signers.map((signer) => npubToHex(signer)!))
const metadataController = new MetadataController()
hexKeys.forEach((key) => {
if (!(key in profiles)) {
const handleMetadataEvent = (event: Event) => {
const metadataContent =
metadataController.extractProfileMetadataContent(event)
if (metadataContent)
setProfiles((prev) => ({
...prev,
[key]: metadataContent
}))
}
metadataController.on(key, (kind: number, event: Event) => {
if (kind === kinds.Metadata) {
handleMetadataEvent(event)
}
})
metadataController
.findMetadata(key)
.then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(metadataEvent)
})
.catch((err) => {
console.error(`error occurred in finding metadata for: ${key}`, err)
})
}
})
}, [submittedBy, signers])
const handleNavigation = () => {
navigate(appPrivateRoutes.sign, { state: { sigit } })
}
return (
<Box
className={styles.item}
@ -147,14 +297,11 @@ const PlaceHolder = () => {
md: 'row'
}
}}
onClick={handleNavigation}
>
<Box
className={styles.titleBox}
sx={{
flexDirection: {
xs: 'row',
md: 'column'
},
borderBottomLeftRadius: {
xs: 'initial',
md: 'inherit'
@ -165,33 +312,101 @@ const PlaceHolder = () => {
}
}}
>
<Typography variant="body1" className={styles.titleBoxItem}>
<Typography variant="body1" className={styles.title}>
<Description />
Title
{sigit.meta.title}
</Typography>
<Typography variant="body2" className={styles.titleBoxItem}>
<PersonOutline />
Sigit
</Typography>
<Typography variant="body2" className={styles.titleBoxItem}>
{submittedBy &&
(function () {
const profile = profiles[submittedBy]
return (
<UserComponent
pubkey={submittedBy}
name={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(submittedBy))
}
image={profile?.picture}
/>
)
})()}
<Typography variant="body2" className={styles.date}>
<CalendarMonth />
07 Jun 10:23 AM
{createdAt}
</Typography>
</Box>
<Box className={styles.signers}>
<Box className={styles.signerItem}>
<Typography variant="button" className={styles.status}>
Sent
</Typography>
<Typography variant="body1">placeholder@sigit.io</Typography>
</Box>
<Box className={styles.signerItem}>
<Typography variant="button" className={styles.status}>
Awaiting
</Typography>
<Typography variant="body1">placeholder@sigit.io</Typography>
</Box>
{signers.map((signer) => {
const pubkey = npubToHex(signer)!
const profile = profiles[pubkey]
return (
<DisplaySigner
key={signer}
meta={sigit.meta}
profile={profile}
pubkey={pubkey}
/>
)
})}
</Box>
</Box>
)
}
enum SignStatus {
Signed = 'Signed',
Pending = 'Pending',
Invalid = 'Invalid Sign'
}
type DisplaySignerProps = {
meta: Meta
profile: ProfileMetadata
pubkey: string
}
const DisplaySigner = ({ meta, profile, pubkey }: DisplaySignerProps) => {
const [signStatus, setSignedStatus] = useState<SignStatus>()
useEffect(() => {
const updateSignStatus = async () => {
const npub = hexToNpub(pubkey)
if (npub in meta.docSignatures) {
parseJson<Event>(meta.docSignatures[npub])
.then((event) => {
const isValidSignature = verifyEvent(event)
if (isValidSignature) {
setSignedStatus(SignStatus.Signed)
} else {
setSignedStatus(SignStatus.Invalid)
}
})
.catch((err) => {
console.log(`err in parsing the docSignatures for ${npub}:>> `, err)
setSignedStatus(SignStatus.Invalid)
})
} else {
setSignedStatus(SignStatus.Pending)
}
}
updateSignStatus()
}, [meta, pubkey])
return (
<Box className={styles.signerItem}>
<Typography variant="button" className={styles.status}>
{signStatus}
</Typography>
<UserComponent
pubkey={pubkey}
name={
profile?.display_name || profile?.name || shorten(hexToNpub(pubkey))
}
image={profile?.picture}
/>
</Box>
)
}

View File

@ -28,23 +28,38 @@
.item {
display: flex;
gap: 10px;
background-color: #efeae6;
border-radius: 1rem;
cursor: pointer;
.titleBox {
display: flex;
align-items: flex-start;
justify-content: space-between;
flex-direction: column;
align-items: center;
gap: 10px;
padding: 10px;
background-color: #cdc8c499;
border-top-left-radius: inherit;
border-bottom-left-radius: inherit;
.titleBoxItem {
.title {
display: flex;
justify-content: center;
align-items: center;
color: var(--mui-palette-primary-light);
font-size: 1.5rem;
svg {
font-size: 1.5rem;
}
}
.date {
display: flex;
justify-content: center;
align-items: center;
color: var(--mui-palette-primary-light);
font-size: 1rem;
svg {
font-size: 1rem;
@ -58,7 +73,7 @@
flex: 1;
justify-content: center;
gap: 10px;
padding: 10px 0;
padding: 10px;
color: var(--mui-palette-primary-light);
.signerItem {

View File

@ -7,27 +7,34 @@ import { MuiFileInput } from 'mui-file-input'
import { Event, verifyEvent } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { useLocation, useNavigate, useSearchParams } from 'react-router-dom'
import { useLocation, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { NostrController } from '../../controllers'
import { appPublicRoutes } from '../../routes'
import { State } from '../../store/rootReducer'
import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types'
import {
CreateSignatureEventContent,
Meta,
Sigit,
SignedEvent
} from '../../types'
import {
decryptArrayBuffer,
encryptArrayBuffer,
extractEncryptionKey,
generateEncryptionKey,
generateKeysFile,
getHash,
hexToNpub,
isOnline,
now,
npubToHex,
parseJson,
readContentOfZipEntry,
sendDM,
sendNotification,
signEventForMetaFile,
uploadToFileStorage
updateUsersAppData
} from '../../utils'
import { DisplayMeta } from './internal/displayMeta'
import styles from './style.module.scss'
@ -40,10 +47,11 @@ enum SignedStatus {
export const SignPage = () => {
const navigate = useNavigate()
const location = useLocation()
const { arrayBuffer: decryptedArrayBuffer, uploadedZip } =
location.state || {}
const [searchParams, setSearchParams] = useSearchParams()
const {
sigit,
arrayBuffer: decryptedArrayBuffer,
uploadedZip
} = location.state || {}
const [displayInput, setDisplayInput] = useState(false)
@ -54,6 +62,7 @@ export const SignPage = () => {
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>()
@ -160,43 +169,127 @@ export const SignPage = () => {
}, [signers, signedBy, usersPubkey, submittedBy])
useEffect(() => {
const fileUrl = searchParams.get('file')
const key = searchParams.get('key')
const handleUpdatedMeta = 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'
)
setIsLoading(false)
return null
})
if (fileUrl && key) {
setIsLoading(true)
setLoadingSpinnerDesc('Fetching file from file server')
if (!createSignatureEvent) return
axios
.get(fileUrl, {
responseType: 'arraybuffer'
})
.then(async (res) => {
const fileName = fileUrl.split('/').pop()
const file = new File([res.data], fileName!)
const isValidCreateSignature = verifyEvent(createSignatureEvent)
const encryptedArrayBuffer = await file.arrayBuffer()
if (!isValidCreateSignature) {
toast.error('Create signature is invalid')
setIsLoading(false)
return
}
const arrayBuffer = await decryptArrayBuffer(
encryptedArrayBuffer,
key
).catch((err) => {
console.log('err in decryption:>> ', err)
toast.error(err.message || 'An error occurred in decrypting file.')
return null
})
if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer)
})
.catch((err) => {
console.error(`error occurred in getting file from ${fileUrl}`, err)
toast.error(
err.message || `error occurred in getting file from ${fileUrl}`
const createSignatureContent =
await parseJson<CreateSignatureEventContent>(
createSignatureEvent.content
).catch((err) => {
console.log(
`err in parsing the createSignature event's content :>> `,
err
)
toast.error(
err.message ||
`error occurred in parsing the create signature event's content`
)
})
.finally(() => {
setIsLoading(false)
return null
})
if (!createSignatureContent) return
setSigners(createSignatureContent.signers)
setViewers(createSignatureContent.viewers)
setCreatorFileHashes(createSignatureContent.fileHashes)
setSubmittedBy(createSignatureEvent.pubkey)
setSignedBy(Object.keys(meta.docSignatures) as `npub1${string}`[])
}
if (meta) {
handleUpdatedMeta(meta)
}
}, [meta])
useEffect(() => {
if (sigit) {
const processSigit = async () => {
setIsLoading(true)
setLoadingSpinnerDesc(
'Extracting encryption key from creator signature'
)
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) {
setIsLoading(false)
return
}
setLoadingSpinnerDesc('Fetching file from file server')
setFileUrl(fileUrl)
axios
.get(fileUrl, {
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)
})
.catch((err) => {
console.error(`error occurred in getting file from ${fileUrl}`, err)
toast.error(
err.message || `error occurred in getting file from ${fileUrl}`
)
})
.finally(() => {
setIsLoading(false)
})
}
processSigit()
} else if (decryptedArrayBuffer) {
handleDecryptedArrayBuffer(decryptedArrayBuffer).finally(() =>
setIsLoading(false)
@ -217,7 +310,7 @@ export const SignPage = () => {
setIsLoading(false)
setDisplayInput(true)
}
}, [searchParams, decryptedArrayBuffer, uploadedZip])
}, [decryptedArrayBuffer, uploadedZip])
const parseKeysJson = async (zip: JSZip) => {
const keysFileContent = await readContentOfZipEntry(
@ -312,7 +405,10 @@ export const SignPage = () => {
return null
}
const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => {
const handleDecryptedArrayBuffer = async (
arrayBuffer: ArrayBuffer,
meta?: Meta
) => {
const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip')
setLoadingSpinnerDesc('Parsing zip file')
@ -328,77 +424,34 @@ export const SignPage = () => {
setZip(zip)
setDisplayInput(false)
setLoadingSpinnerDesc('Parsing meta.json')
let parsedMetaJson: Meta | null = null
const metaFileContent = await readContentOfZipEntry(
zip,
'meta.json',
'string'
)
if (meta) {
parsedMetaJson = meta
} else {
setLoadingSpinnerDesc('Parsing meta.json')
if (!metaFileContent) {
setIsLoading(false)
return
}
const metaFileContent = await readContentOfZipEntry(
zip,
'meta.json',
'string'
)
const parsedMetaJson = await parseJson<Meta>(metaFileContent).catch(
(err) => {
if (!metaFileContent) {
setIsLoading(false)
return
}
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
}
)
if (!parsedMetaJson) return
const createSignatureEvent = await parseJson<Event>(
parsedMetaJson.createSignature
).catch((err) => {
console.log('err in parsing the createSignature event:>> ', err)
toast.error(
err.message || 'error occurred in parsing the create signature event'
)
setIsLoading(false)
return null
})
if (!createSignatureEvent) return
const isValidCreateSignature = verifyEvent(createSignatureEvent)
if (!isValidCreateSignature) {
toast.error('Create signature is invalid')
setIsLoading(false)
return
})
}
const createSignatureContent = await parseJson<CreateSignatureEventContent>(
createSignatureEvent.content
).catch((err) => {
console.log(
`err in parsing the createSignature event's content :>> `,
err
)
toast.error(
err.message ||
`error occurred in parsing the create signature event's content`
)
setIsLoading(false)
return null
})
if (!createSignatureContent) return
setSigners(createSignatureContent.signers)
setViewers(createSignatureContent.viewers)
setCreatorFileHashes(createSignatureContent.fileHashes)
setSubmittedBy(createSignatureEvent.pubkey)
setSignedBy(Object.keys(parsedMetaJson.docSignatures) as `npub1${string}`[])
setMeta(parsedMetaJson)
}
@ -417,20 +470,6 @@ export const SignPage = () => {
if (!zip || !meta) return
setIsLoading(true)
setLoadingSpinnerDesc('parsing hashes.json file')
const hashesFileContent = await readHashesFile()
if (!hashesFileContent) return
if (!hashesFileContent) {
setIsLoading(false)
return
}
const hashes = await parseHashes(hashesFileContent)
if (!hashes) return
setLoadingSpinnerDesc('Generating hashes for files')
setLoadingSpinnerDesc('Signing nostr event')
@ -441,56 +480,16 @@ export const SignPage = () => {
if (!signedEvent) return
const updatedMeta = updateMetaSignatures(meta, signedEvent)
const stringifiedMeta = JSON.stringify(updatedMeta, null, 2)
zip.file('meta.json', stringifiedMeta)
const metaHash = await getHash(stringifiedMeta)
if (!metaHash) return
const updatedHashes = updateHashes(hashes, metaHash)
zip.file('hashes.json', JSON.stringify(updatedHashes, null, 2))
const arrayBuffer = await generateZipArrayBuffer(zip)
if (!arrayBuffer) return
const key = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer(arrayBuffer, key)
setMeta(updatedMeta)
if (await isOnline()) {
await handleOnlineFlow(encryptedArrayBuffer, key)
if (fileUrl) await handleOnlineFlow(fileUrl, updatedMeta)
} else {
handleDecryptedArrayBuffer(arrayBuffer).finally(() => setIsLoading(false))
// todo: fix offline flow
// handleDecryptedArrayBuffer(arrayBuffer).finally(() => setIsLoading(false))
}
}
// Read the content of the hashes.json file
const readHashesFile = async (): Promise<string | null> => {
return await readContentOfZipEntry(zip!, 'hashes.json', 'string').catch(
(err) => {
console.log('Error reading hashes.json file:', err)
setIsLoading(false)
return null
}
)
}
// Parse the JSON content of the hashes file
const parseHashes = async (
hashesFileContent: string
): Promise<Record<string, string> | null> => {
return await parseJson<Record<string, string>>(hashesFileContent).catch(
(err) => {
console.log('Error parsing hashes.json content:', err)
toast.error(err.message || 'Error parsing hashes.json content')
setIsLoading(false)
return null
}
)
}
// Sign the event for the meta file
const signEventForMeta = async (prevSig: string) => {
return await signEventForMetaFile(
@ -507,40 +506,10 @@ export const SignPage = () => {
...metaCopy.docSignatures,
[hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2)
}
metaCopy.modifiedAt = now()
return metaCopy
}
// Update the hashes with the new meta hash
const updateHashes = (
hashes: Record<string, string>,
metaHash: string
): Record<string, string> => {
return {
...hashes,
[usersPubkey!]: metaHash
}
}
// Generate the zip array buffer
const generateZipArrayBuffer = async (
zip: JSZip
): Promise<ArrayBuffer | null> => {
return await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: {
level: 6
}
})
.catch((err) => {
console.log('Error generating zip file:', err)
setIsLoading(false)
toast.error(err.message || 'Error generating zip file')
return null
})
}
// create final zip file
const createFinalZipFile = async (
encryptedArrayBuffer: ArrayBuffer,
@ -617,58 +586,49 @@ export const SignPage = () => {
}
// Handle the online flow: upload file and send DMs
const handleOnlineFlow = async (
encryptedArrayBuffer: ArrayBuffer,
encryptionKey: string
) => {
const unixNow = Math.floor(Date.now() / 1000)
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 isLastSigner = checkIsLastSigner(signers)
if (isLastSigner) {
await sendDMToAllUsers(fileUrl, encryptionKey)
} else {
await sendDMToNextSigner(fileUrl, encryptionKey)
const handleOnlineFlow = async (fileUrl: string, meta: Meta) => {
setLoadingSpinnerDesc('Updating users app data')
const updatedEvent = await updateUsersAppData(fileUrl, meta)
if (!updatedEvent) {
setIsLoading(false)
return
}
// update search params with updated file url and encryption key
setSearchParams({
file: fileUrl,
key: encryptionKey
})
const userSet = new Set<`npub1${string}`>()
if (submittedBy) {
userSet.add(hexToNpub(submittedBy))
}
setIsLoading(false)
}
// Handle errors during file upload
const handleUploadError = (err: any) => {
console.log('Error in upload:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in uploading file')
return null
}
// Upload the file to file storage
const uploadFile = async (file: File): Promise<string | null> => {
setIsLoading(true)
setLoadingSpinnerDesc('Uploading sigit file to file storage.')
const fileUrl = await uploadToFileStorage(file, nostrController)
.then((url) => {
toast.success('Sigit uploaded to file storage')
return url
const isLastSigner = checkIsLastSigner(signers)
if (isLastSigner) {
signers.forEach((signer) => {
userSet.add(signer)
})
.catch(handleUploadError)
return fileUrl
viewers.forEach((viewer) => {
userSet.add(viewer)
})
} else {
const usersNpub = hexToNpub(usersPubkey!)
const currentSignerIndex = signers.indexOf(usersNpub)
const prevSigners = signers.slice(0, currentSignerIndex)
prevSigners.forEach((signer) => {
userSet.add(signer)
})
const nextSigner = signers[currentSignerIndex + 1]
userSet.add(nextSigner)
}
setLoadingSpinnerDesc('Sending notifications')
const users = Array.from(userSet)
const promises = users.map((user) =>
sendNotification(npubToHex(user)!, meta, fileUrl)
)
await Promise.allSettled(promises)
setIsLoading(false)
}
// Check if the current user is the last signer
@ -679,51 +639,6 @@ export const SignPage = () => {
return signerIndex === lastSignerIndex
}
// Send DM to all users (signers and viewers)
const sendDMToAllUsers = async (fileUrl: string, encryptionKey: string) => {
const userSet = new Set<`npub1${string}`>()
if (submittedBy) {
userSet.add(hexToNpub(submittedBy))
}
signers.forEach((signer) => {
userSet.add(signer)
})
viewers.forEach((viewer) => {
userSet.add(viewer)
})
const users = Array.from(userSet)
for (const user of users) {
await sendDM(
fileUrl,
encryptionKey,
npubToHex(user)!,
nostrController,
false,
setAuthUrl
)
}
}
// Send DM to the next signer
const sendDMToNextSigner = async (fileUrl: string, encryptionKey: string) => {
const usersNpub = hexToNpub(usersPubkey!)
const signerIndex = signers.indexOf(usersNpub)
const nextSigner = signers[signerIndex + 1]
await sendDM(
fileUrl,
encryptionKey,
npubToHex(nextSigner)!,
nostrController,
true,
setAuthUrl
)
}
const handleExport = async () => {
if (!meta || !zip || !usersPubkey) return

View File

@ -1,21 +1,31 @@
import { IDBPDatabase, openDB } from 'idb'
import { Event } from 'nostr-tools'
import { CachedMetadataEvent } from '../../types'
import { SchemaV1 } from './schema'
import { CachedEvent } from '../../types'
import { SchemaV2 } from './schema'
class LocalCache {
// Static property to hold the single instance of LocalCache
private static instance: LocalCache | null = null
private db!: IDBPDatabase<SchemaV1>
private db!: IDBPDatabase<SchemaV2>
// Private constructor to prevent direct instantiation
private constructor() {}
// Method to initialize the database
private async init() {
this.db = await openDB<SchemaV1>('sigit-cache', 1, {
upgrade(db) {
db.createObjectStore('userMetadata', { keyPath: 'event.pubkey' })
this.db = await openDB<SchemaV2>('sigit-cache', 2, {
upgrade(db, oldVersion) {
if (oldVersion < 1) {
db.createObjectStore('userMetadata', { keyPath: 'event.pubkey' })
}
if (oldVersion < 2) {
const v6 = db as unknown as IDBPDatabase<SchemaV2>
v6.createObjectStore('userRelayListMetadata', {
keyPath: 'event.pubkey'
})
}
}
})
}
@ -37,9 +47,7 @@ class LocalCache {
}
// Method to get user metadata by key
public async getUserMetadata(
key: string
): Promise<CachedMetadataEvent | null> {
public async getUserMetadata(key: string): Promise<CachedEvent | null> {
const data = await this.db.get('userMetadata', key)
return data || null
}
@ -49,6 +57,21 @@ class LocalCache {
await this.db.delete('userMetadata', key)
}
public async addUserRelayListMetadata(event: Event) {
await this.db.put('userRelayListMetadata', { event, cachedAt: Date.now() })
}
public async getUserRelayListMetadata(
key: string
): Promise<CachedEvent | null> {
const data = await this.db.get('userRelayListMetadata', key)
return data || null
}
public async deleteUserRelayListMetadata(key: string) {
await this.db.delete('userRelayListMetadata', key)
}
// Method to clear cache data
public async clearCacheData() {
// Clear the 'userMetadata' store in the IndexedDB database

View File

@ -1,9 +1,16 @@
import { DBSchema } from 'idb'
import { CachedMetadataEvent } from '../../types'
import { CachedEvent } from '../../types'
export interface SchemaV1 extends DBSchema {
userMetadata: {
key: string
value: CachedMetadataEvent
value: CachedEvent
}
}
export interface SchemaV2 extends SchemaV1 {
userRelayListMetadata: {
key: string
value: CachedEvent
}
}

View File

@ -1,6 +1,6 @@
import { Event } from 'nostr-tools'
export interface CachedMetadataEvent {
export interface CachedEvent {
event: Event
cachedAt: number
}

View File

@ -9,7 +9,9 @@ export interface User {
}
export interface Meta {
uuid: string
title: string
modifiedAt: number
createSignature: string
docSignatures: { [key: `npub1${string}`]: string }
exportSignature?: string
@ -19,8 +21,14 @@ export interface CreateSignatureEventContent {
signers: `npub1${string}`[]
viewers: `npub1${string}`[]
fileHashes: { [key: string]: string }
keys: { sender: string; keys: { [user: `npub1${string}`]: string } }
}
export interface SignedEventContent {
prevSig: string
}
export interface Sigit {
fileUrl: string
meta: Meta
}

View File

@ -1,3 +1,5 @@
import { UnsignedEvent } from 'nostr-tools'
export interface SignedEvent {
kind: number
tags: string[][]
@ -12,3 +14,5 @@ export interface NostrJoiningBlock {
block: number
encodedEventPointer: string
}
export type Rumor = UnsignedEvent & { id: string }

7
src/types/system/index.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
import type { WindowNostr } from 'nostr-tools/nip07'
declare global {
interface Window {
nostr?: WindowNostr
}
}

View File

@ -1,13 +1,20 @@
import axios from 'axios'
import {
Event,
EventTemplate,
generateSecretKey,
getPublicKey,
nip04
nip04,
verifyEvent
} from 'nostr-tools'
import { MetadataController, NostrController } from '../controllers'
import { toast } from 'react-toastify'
import { MetadataController, NostrController } from '../controllers'
import { appPrivateRoutes } from '../routes'
import { hexToNpub } from './nostr'
import { parseJson } from './string'
import { CreateSignatureEventContent } from '../types'
import store from '../store/store'
import { AuthState } from '../store/auth/types'
/**
* Uploads a file to a file storage service.
@ -254,3 +261,88 @@ export const generateKeysFile = async (
return null
}
}
/**
* Encrypt decryption key for each users pubkey.
*
* @param pubkeys - An array of public keys.
* @param key - The key that will be encrypted for each user.
* @returns A promise that resolves to a JSON object containing a random pubkey as sender and encrypted keys for each user, or null if an error occurs.
*/
export const generateKeys = async (
pubkeys: string[],
key: string
): Promise<{
sender: string
keys: { [user: `npub1${string}`]: string }
} | null> => {
// Generate a random private key to act as the sender
const privateKey = generateSecretKey()
const keys: { [user: `npub1${string}`]: string } = {}
// Encrypt the key for each user's public key
for (const pubkey of pubkeys) {
const npub = hexToNpub(pubkey)
const encryptedKey = await nip04
.encrypt(privateKey, pubkey, key)
.catch((err) => {
console.log(`An error occurred in encrypting key for ${npub}`, err)
toast.error('An error occurred in key encryption')
return null
})
if (!encryptedKey) return null
keys[npub] = encryptedKey
}
return { sender: getPublicKey(privateKey), keys }
}
export const extractEncryptionKey = async (createSignature: string) => {
const createSignatureEvent = await parseJson<Event>(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 isValidCreateSignature = verifyEvent(createSignatureEvent)
if (!isValidCreateSignature) {
toast.error('Create signature is invalid')
return null
}
const createSignatureContent = await parseJson<CreateSignatureEventContent>(
createSignatureEvent.content
).catch((err) => {
console.log(`err in parsing the createSignature event's content :>> `, err)
toast.error(
`error occurred in parsing the create signature event's content`
)
return null
})
if (!createSignatureContent) return null
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const usersNpub = hexToNpub(usersPubkey)
const { sender, keys } = createSignatureContent.keys
if (usersNpub in keys) {
return {
sender,
encryptedKey: keys[usersNpub]
}
}
return null
}

View File

@ -1,7 +1,28 @@
import { nip19, verifyEvent } from 'nostr-tools'
import { SignedEvent } from '../types'
import axios from 'axios'
import {
Event,
EventTemplate,
Filter,
SimplePool,
UnsignedEvent,
finalizeEvent,
generateSecretKey,
getEventHash,
getPublicKey,
kinds,
nip19,
nip44,
verifyEvent
} from 'nostr-tools'
import { toast } from 'react-toastify'
import { NIP05_REGEX } from '../constants'
import { MetadataController, NostrController } from '../controllers'
import { AuthState } from '../store/auth/types'
import { RelaysState } from '../store/relays/types'
import store from '../store/store'
import { Meta, Rumor, Sigit, SignedEvent } from '../types'
import { getHash } from './hash'
import { parseJson } from './string'
/**
* @param hexKey hex private or public key
@ -181,3 +202,416 @@ export const getRoboHashPicture = (
const npub = hexToNpub(pubkey)
return `https://robohash.org/${npub}.png?set=set${set}`
}
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)
/**
* Generate nip44 conversation key
* @param privateKey
* @param publicKey
* @returns
*/
export const nip44ConversationKey = (
privateKey: Uint8Array,
publicKey: string
) => nip44.v2.utils.getConversationKey(privateKey, publicKey)
export const nip44Encrypt = (
data: EventTemplate,
privateKey: Uint8Array,
publicKey: string
) =>
nip44.v2.encrypt(
JSON.stringify(data),
nip44ConversationKey(privateKey, publicKey)
)
export const nip44Decrypt = (data: Event, privateKey: Uint8Array) =>
JSON.parse(
nip44.v2.decrypt(
data.content,
nip44ConversationKey(privateKey, data.pubkey)
)
)
// Function to count leading zero bits
export const countLeadingZeroes = (hex: string) => {
let count = 0
for (let i = 0; i < hex.length; i++) {
const nibble = parseInt(hex[i], 16)
if (nibble === 0) {
count += 4
} else {
count += Math.clz32(nibble) - 28
break
}
}
return count
}
/**
* Function to create a wrapped event with PoW
* @param event Original event to be wrapped
* @param receiver Public key of the receiver
* @param difficulty PoW difficulty level (default is 20)
* @returns
*/
//
export const createWrap = (
event: Event,
receiver: string,
difficulty: number = 10
) => {
// 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)
// Initialize nonce and leadingZeroes for PoW calculation
let nonce = 0
let leadingZeroes = 0
// 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 = {
kind: 1059, // Event kind
content, // Encrypted content
pubkey, // Public key of the creator
created_at: randomNow(), // Current timestamp
tags: [
// Tags including receiver and nonce
['p', receiver],
['nonce', nonce.toString(), difficulty.toString()]
]
}
// Calculate the SHA-256 hash of the unsigned event
const hash = getEventHash(unsignedEvent)
// Count the number of leading zero bits in the hash
leadingZeroes = countLeadingZeroes(hash)
// 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)
}
// Increment the nonce for the next iteration
nonce++
}
}
export const getUsersAppData = async () => {
const relays: string[] = []
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const relayMap = store.getState().relays?.map
const nostrController = NostrController.getInstance()
// check if relaysMap in redux store is undefined
if (!relayMap) {
// todo: use metadata controller
const metadataController = new MetadataController()
const relaySet = await metadataController
.findRelayListMetadata(usersPubkey)
.catch((err) => {
console.log(
`An error occurred while finding relay list metadata for ${hexToNpub(usersPubkey)}`,
err
)
return null
})
// Return if metadata retrieval failed
if (!relaySet) return
// Ensure relay list is not empty
if (relaySet.write.length === 0) return
relays.push(...relaySet.write)
} else {
// filter write relays from user's relayMap stored in redux store
const writeRelays = Object.keys(relayMap).filter(
(key) => relayMap[key].write
)
relays.push(...writeRelays)
}
// generate an identifier for user's nip78
const hash = await getHash('sigit' + usersPubkey)
if (!hash) return null
const filter: Filter = {
kinds: [kinds.Application],
'#d': [hash]
}
const encryptedContent = await nostrController
.getEvent(filter, relays)
.then((event) => {
if (event) return event.content
// if person is using sigit for first time its possible that event is null
// so we'll return empty stringified object
return '{}'
})
.catch((err) => {
console.log(`An error occurred in finding kind 30078 event`, err)
toast.error(
'An error occurred in finding kind 30078 event for data storage'
)
return null
})
if (!encryptedContent) return null
if (encryptedContent === '{}') {
return {}
}
const decrypted = await nostrController
.nip04Decrypt(usersPubkey, encryptedContent)
.catch((err) => {
console.log('An error occurred while decrypting app data', err)
toast.error('An error occurred while decrypting app data')
return null
})
if (!decrypted) return null
const parsedContent = await parseJson<{
[uuid: string]: Sigit
}>(decrypted).catch((err) => {
console.log(
'An error occurred in parsing the content of kind 30078 event',
err
)
toast.error('An error occurred in parsing the content of kind 30078 event')
return null
})
if (!parsedContent) return null
return parsedContent
}
export const updateUsersAppData = async (fileUrl: string, meta: Meta) => {
const appData = await getUsersAppData()
if (!appData) 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
if (existingMeta.modifiedAt < meta.modifiedAt) {
appData[meta.uuid] = {
fileUrl,
meta
}
}
} else {
appData[meta.uuid] = {
fileUrl,
meta
}
}
appData[meta.uuid] = {
fileUrl,
meta
}
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const nostrController = NostrController.getInstance()
const encryptedContent = await nostrController
.nip04Encrypt(usersPubkey, JSON.stringify(appData))
.catch((err) => {
console.log(
'An error occurred in encryption of content for app data',
err
)
toast.error(
err.message || 'An error occurred in encryption of content for app data'
)
return null
})
if (!encryptedContent) return null
// generate the identifier for user's appData event
const hash = await getHash('sigit' + usersPubkey)
if (!hash) return null
const updatedEvent: UnsignedEvent = {
kind: kinds.Application,
pubkey: usersPubkey!,
created_at: now(),
tags: [['d', hash]],
content: encryptedContent
}
const signedEvent = await nostrController
.signEvent(updatedEvent)
.catch((err) => {
console.log('An error occurred in signing event', err)
toast.error(err.message || 'An error occurred in signing event')
return null
})
if (!signedEvent) return null
const relayMap = (store.getState().relays as RelaysState).map!
const writeRelays = Object.keys(relayMap).filter((key) => relayMap[key].write)
const publishResult = await nostrController
.publishEvent(signedEvent, writeRelays)
.catch((errResults) => {
console.log('err :>> ', errResults)
toast.error('An error occurred while publishing App data')
errResults.forEach((errResult: any) => {
toast.error(
`Publishing to ${errResult.relay} caused the following error: ${errResult.error}`
)
})
return null
})
if (!publishResult) return null
return signedEvent
}
export const subscribeForSigits = async (pubkey: string) => {
// Get relay list metadata
const metadataController = new MetadataController()
const relaySet = await metadataController
.findRelayListMetadata(pubkey)
.catch((err) => {
console.log(
`An error occurred while finding relay list metadata for ${hexToNpub(receiver)}`,
err
)
return null
})
// Return if metadata retrieval failed
if (!relaySet) return
// Ensure relay list is not empty
if (relaySet.read.length === 0) return
const filter: Filter = {
kinds: [1059],
'#p': [pubkey]
}
const pool = new SimplePool()
pool.subscribeMany(relaySet.read, [filter], {
onevent: (event) => {
processReceivedEvent(event)
}
})
}
const processReceivedEvent = async (event: Event, difficulty: number = 10) => {
// validate PoW
// Count the number of leading zero bits in the hash
const leadingZeroes = countLeadingZeroes(event.id)
if (leadingZeroes < difficulty) return
const nostrController = NostrController.getInstance()
const stringifiedSealEvent = await nostrController.nip44Decrypt(
event.pubkey,
event.content
)
const sealEvent = await parseJson<Event>(stringifiedSealEvent)
const stringifiedRumor = await nostrController.nip44Decrypt(
sealEvent.pubkey,
sealEvent.content
)
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)
}
}
export const sendNotification = async (
receiver: string,
meta: Meta,
fileUrl: string
) => {
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const unsignedEvent: UnsignedEvent = {
kind: kinds.ShortTextNote,
pubkey: usersPubkey,
content: 'sigit-notification',
tags: [
['u', fileUrl],
['m', JSON.stringify(meta)]
],
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)
// Get relay list metadata
const metadataController = new MetadataController()
const relaySet = await metadataController
.findRelayListMetadata(receiver)
.catch((err) => {
console.log(
`An error occurred while finding relay list metadata for ${hexToNpub(receiver)}`,
err
)
return null
})
// Return if metadata retrieval failed
if (!relaySet) return
// Ensure relay list is not empty
if (relaySet.read.length === 0) return
// Publish the notification event to the recipient's read relays
await nostrController
.publishEvent(wrappedEvent, relaySet.read)
.catch((errResults) => {
console.log(
`An error occurred while publishing notification event for ${hexToNpub(receiver)}`,
errResults
)
return null
})
}

View File

@ -93,3 +93,21 @@ export const parseJson = <T>(content: string): Promise<T> => {
*/
export const capitalizeFirstLetter = (str: string) =>
str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
export const formatTimestamp = (timestamp: number) => {
const date = new Date(timestamp)
// Extract date parts
const day = date.getDate().toString().padStart(2, '0')
const month = date.toLocaleString('default', { month: 'short' })
const year = date.getFullYear()
// Format time parts
const hours = date.getHours()
const minutes = date.getMinutes().toString().padStart(2, '0')
const ampm = hours >= 12 ? 'PM' : 'AM'
const formattedHours = (hours % 12 || 12).toString().padStart(2, '0')
// Combine parts into the desired format
return `${day} ${month} ${year} ${formattedHours}:${minutes} ${ampm}`
}