Compare commits

...

19 Commits

Author SHA1 Message Date
b
70262bd5d2 Merge pull request 'store-sigits and update working flow' (#116) from store-sigits into staging
All checks were successful
Release to Staging / build_and_release (push) Successful in 59s
Reviewed-on: #116
Reviewed-by: Stixx <m@noreply.git.nostrdev.com>
2024-07-11 11:42:18 +00:00
daniyal
d5c45902b8 chore: add nip70 tag to signed events in meta.json 2024-07-10 14:30:14 +05:00
SH
7df6ab8c84 fix: return immediately from publish event when published to at least one relay and keep publishing to other in background 2024-07-09 17:17:57 +05:00
SwiftHawk
0aaa20092e chore: add comments 2024-07-09 01:16:47 +05:00
SwiftHawk
8eaf9cb61c fix: use dedicated key from nip78 in auth event for uploading files.zip 2024-07-09 00:01:03 +05:00
SwiftHawk
6b135ac54d fix: add timeout in publishing updated app data and sending notifications 2024-07-08 16:50:38 +05:00
SwiftHawk
6553ed89e0 fix: styles fixed in homepage 2024-07-08 16:49:48 +05:00
SwiftHawk
8167c5d05f chore: fix upload btn behaior in mobile view 2024-07-08 14:27:41 +05:00
SwiftHawk
fa7a6e85f4 fix: fetch app data from after login 2024-07-08 14:27:09 +05:00
SwiftHawk
ef5376e2d1 fix: add default title for sigit 2024-07-08 14:26:36 +05:00
SwiftHawk
016ccea74f chore: quick fix 2024-07-05 14:19:33 +05:00
SwiftHawk
412da32293 chore remove unused code 2024-07-05 14:17:12 +05:00
SwiftHawk
f3b24dee65 chore: remove unused code from nostr controller 2024-07-05 14:09:47 +05:00
SwiftHawk
d5024745f1 fix: navigation to profile page from username component 2024-07-05 14:04:20 +05:00
SwiftHawk
08baf5dedd chore: remove unused npm package uuid 2024-07-05 13:44:02 +05:00
SwiftHawk
d4c50dabaf chore: update flow for storing sigits 2024-07-05 13:38:04 +05:00
SwiftHawk
88bdce33c9 chore: quick fix 2024-06-28 14:25:41 +05:00
SwiftHawk
5850ef7dce chore: push unfinished changes 2024-06-28 14:24:14 +05:00
SwiftHawk
b91abe1e68 chore: npm audit fix 2024-06-20 21:56:47 +05:00
27 changed files with 2361 additions and 862 deletions

22
package-lock.json generated
View File

@ -25,7 +25,7 @@
"jszip": "3.10.1", "jszip": "3.10.1",
"lodash": "4.17.21", "lodash": "4.17.21",
"mui-file-input": "4.0.4", "mui-file-input": "4.0.4",
"nostr-tools": "2.3.1", "nostr-tools": "2.7.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dnd": "16.0.1", "react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1", "react-dnd-html5-backend": "16.0.1",
@ -2507,12 +2507,12 @@
} }
}, },
"node_modules/braces": { "node_modules/braces": {
"version": "3.0.2", "version": "3.0.3",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
"integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"fill-range": "^7.0.1" "fill-range": "^7.1.1"
}, },
"engines": { "engines": {
"node": ">=8" "node": ">=8"
@ -3380,9 +3380,9 @@
"integrity": "sha512-P9bmyZ3h/PRG+Nzga+rbdI4OEpNDzAVyy74uVO9ATgzLK6VtAsYybF/+TOCvrc0MO793d6+42lLyZTw7/ArVzA==" "integrity": "sha512-P9bmyZ3h/PRG+Nzga+rbdI4OEpNDzAVyy74uVO9ATgzLK6VtAsYybF/+TOCvrc0MO793d6+42lLyZTw7/ArVzA=="
}, },
"node_modules/fill-range": { "node_modules/fill-range": {
"version": "7.0.1", "version": "7.1.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
"integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"to-regex-range": "^5.0.1" "to-regex-range": "^5.0.1"
@ -4137,9 +4137,9 @@
} }
}, },
"node_modules/nostr-tools": { "node_modules/nostr-tools": {
"version": "2.3.1", "version": "2.7.0",
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.3.1.tgz", "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.7.0.tgz",
"integrity": "sha512-qjKx2C3EzwiQOe2LPSPyCnp07pGz1pWaWjDXcm+L2y2c8iTECbvlzujDANm3nJUjWL5+LVRUVDovTZ1a/DC4Bg==", "integrity": "sha512-jJoL2J1CBiKDxaXZww27nY/Wsuxzx7AULxmGKFce4sskDu1tohNyfnzYQ8BvDyvkstU8kNZUAXPL32tre33uig==",
"dependencies": { "dependencies": {
"@noble/ciphers": "^0.5.1", "@noble/ciphers": "^0.5.1",
"@noble/curves": "1.2.0", "@noble/curves": "1.2.0",

View File

@ -31,7 +31,7 @@
"jszip": "3.10.1", "jszip": "3.10.1",
"lodash": "4.17.21", "lodash": "4.17.21",
"mui-file-input": "4.0.4", "mui-file-input": "4.0.4",
"nostr-tools": "2.3.1", "nostr-tools": "2.7.0",
"react": "^18.2.0", "react": "^18.2.0",
"react-dnd": "16.0.1", "react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1", "react-dnd-html5-backend": "16.0.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 { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { getProfileRoute } from '../routes'
import { State } from '../store/rootReducer' import { State } from '../store/rootReducer'
import { hexToNpub } from '../utils' import { hexToNpub } from '../utils'
import { Link } from 'react-router-dom'
import { getProfileRoute } from '../routes'
type Props = { type Props = {
username: string username: string
@ -60,10 +60,17 @@ type UserProps = {
*/ */
export const UserComponent = ({ pubkey, name, image }: UserProps) => { export const UserComponent = ({ pubkey, name, image }: UserProps) => {
const theme = useTheme() const theme = useTheme()
const navigate = useNavigate()
const npub = hexToNpub(pubkey) const npub = hexToNpub(pubkey)
const roboImage = `https://robohash.org/${npub}.png?set=set3` const roboImage = `https://robohash.org/${npub}.png?set=set3`
const handleClick = (e: React.MouseEvent<HTMLElement, MouseEvent>) => {
e.stopPropagation()
// navigate to user's profile
navigate(getProfileRoute(pubkey))
}
return ( return (
<Box <Box
sx={{ display: 'flex', alignItems: 'center', gap: '10px', flexGrow: 1 }} sx={{ display: 'flex', alignItems: 'center', gap: '10px', flexGrow: 1 }}
@ -77,19 +84,19 @@ export const UserComponent = ({ pubkey, name, image }: UserProps) => {
borderStyle: 'solid', borderStyle: 'solid',
borderColor: `#${pubkey.substring(0, 6)}` borderColor: `#${pubkey.substring(0, 6)}`
}} }}
onClick={handleClick}
/> />
<Link to={getProfileRoute(pubkey)}> <Typography
<Typography component="label"
component="label" sx={{
sx={{ textAlign: 'center',
textAlign: 'center', cursor: 'pointer',
cursor: 'pointer', color: theme.palette.text.primary
color: theme.palette.text.primary }}
}} onClick={handleClick}
> >
{name} {name}
</Typography> </Typography>
</Link>
</Box> </Box>
) )
} }

View File

@ -61,11 +61,15 @@ export class MetadataController extends EventEmitter {
verifyEvent(metadataEvent) // Verify the event's authenticity verifyEvent(metadataEvent) // Verify the event's authenticity
) { ) {
// If there's no current event or the new metadata event is more recent // If there's no current event or the new metadata event is more recent
if (!currentEvent || metadataEvent.created_at > currentEvent.created_at) { if (
!currentEvent ||
metadataEvent.created_at >= currentEvent.created_at
) {
// Handle the new metadata event // Handle the new metadata event
this.handleNewMetadataEvent(metadataEvent) this.handleNewMetadataEvent(metadataEvent)
return metadataEvent
} }
return metadataEvent
} }
// If no valid metadata event is found from the special relay, get the most popular relays // If no valid metadata event is found from the special relay, get the most popular relays
@ -123,11 +127,11 @@ export class MetadataController extends EventEmitter {
// If cached metadata is found, check its validity // If cached metadata is found, check its validity
if (cachedMetadataEvent) { if (cachedMetadataEvent) {
const oneDayInMS = 24 * 60 * 60 * 1000 // Number of milliseconds in one day const oneWeekInMS = 7 * 24 * 60 * 60 * 1000 // Number of milliseconds in one week
// Check if the cached metadata is older than one day // Check if the cached metadata is older than one week
if (Date.now() - cachedMetadataEvent.cachedAt > oneDayInMS) { if (Date.now() - cachedMetadataEvent.cachedAt > oneWeekInMS) {
// If older than one day, find the metadata from relays in background // If older than one week, find the metadata from relays in background
this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event) this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event)
} }
@ -141,6 +145,22 @@ export class MetadataController extends EventEmitter {
} }
public findRelayListMetadata = async (hexKey: string) => { 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 = { const eventFilter: Filter = {
kinds: [kinds.RelayList], kinds: [kinds.RelayList],
authors: [hexKey] authors: [hexKey]
@ -148,19 +168,38 @@ export class MetadataController extends EventEmitter {
const pool = new SimplePool() const pool = new SimplePool()
let relayEvent = await pool // Try to get the relayList event from a special relay (wss://purplepag.es)
.get([this.specialMetadataRelay], eventFilter) if (!relayEvent) {
.catch((err) => { relayEvent = await pool
console.error(err) .get([this.specialMetadataRelay], eventFilter)
return null .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 (!relayEvent) {
// If no valid relayList event is found from the special relay, get the most popular relays
const mostPopularRelays = const mostPopularRelays =
await this.nostrController.getMostPopularRelays() await this.nostrController.getMostPopularRelays()
// Query the most popular relays for relayList event
relayEvent = await pool relayEvent = await pool
.get(mostPopularRelays, eventFilter) .get(mostPopularRelays, eventFilter)
.then((event) => {
if (event) {
// update the event in local cache
localCache.addUserRelayListMetadata(event)
}
return event
})
.catch((err) => { .catch((err) => {
console.error(err) console.error(err)
return null return null

View File

@ -2,46 +2,48 @@ import NDK, {
NDKEvent, NDKEvent,
NDKNip46Signer, NDKNip46Signer,
NDKPrivateKeySigner, NDKPrivateKeySigner,
NDKSubscription,
NDKUser, NDKUser,
NostrEvent, NostrEvent
NDKSubscription
} from '@nostr-dev-kit/ndk' } from '@nostr-dev-kit/ndk'
import axios from 'axios'
import { import {
Event, Event,
EventTemplate, EventTemplate,
SimplePool,
UnsignedEvent,
Filter, Filter,
Relay, Relay,
SimplePool,
UnsignedEvent,
finalizeEvent, finalizeEvent,
kinds,
nip04, nip04,
nip19, nip19,
kinds nip44
} from 'nostr-tools' } from 'nostr-tools'
import { toast } from 'react-toastify'
import { EventEmitter } from 'tseep' import { EventEmitter } from 'tseep'
import { import {
updateNsecbunkerPubkey,
setMostPopularRelaysAction, setMostPopularRelaysAction,
setRelayConnectionStatusAction,
setRelayInfoAction, setRelayInfoAction,
setRelayConnectionStatusAction updateNsecbunkerPubkey
} from '../store/actions' } from '../store/actions'
import { AuthState, LoginMethods } from '../store/auth/types' import { AuthState, LoginMethods } from '../store/auth/types'
import store from '../store/store' import store from '../store/store'
import { import {
SignedEvent, RelayConnectionState,
RelayMap,
RelayStats,
RelayReadStats,
RelayInfoObject,
RelayConnectionStatus, RelayConnectionStatus,
RelayConnectionState RelayInfoObject,
RelayMap,
RelayReadStats,
RelayStats,
SignedEvent
} from '../types' } from '../types'
import { import {
compareObjects, compareObjects,
getNsecBunkerDelegatedKey, getNsecBunkerDelegatedKey,
verifySignedEvent verifySignedEvent
} from '../utils' } from '../utils'
import axios from 'axios'
export class NostrController extends EventEmitter { export class NostrController extends EventEmitter {
private static instance: NostrController private static instance: NostrController
@ -56,7 +58,8 @@ export class NostrController extends EventEmitter {
} }
private getNostrObject = () => { 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( throw new Error(
`window.nostr object not present. Make sure you have an nostr extension installed/working properly.` `window.nostr object not present. Make sure you have an nostr extension installed/working properly.`
@ -220,29 +223,31 @@ export class NostrController extends EventEmitter {
/** /**
* Function will publish provided event to the provided relays * Function will publish provided event to the provided relays
*
* @param event - The event to publish.
* @param relays - An array of relay URLs to publish the event to.
* @returns A promise that resolves to an array of relays where the event was successfully published.
*/ */
publishEvent = async (event: Event, relays: string[]) => { publishEvent = async (event: Event, relays: string[]) => {
const simplePool = new SimplePool() const simplePool = new SimplePool()
// Publish the event to all relays
const promises = simplePool.publish(relays, event) const promises = simplePool.publish(relays, event)
const results = await Promise.allSettled(promises) // Use Promise.race to wait for the first successful publish
const firstSuccessfulPublish = await Promise.race(
promises.map((promise, index) =>
promise.then(() => relays[index]).catch(() => null)
)
)
const publishedRelays: string[] = [] if (!firstSuccessfulPublish) {
// If no publish was successful, collect the reasons for failures
console.log('results of publish event :>> ', results)
results.forEach((result, index) => {
if (result.status === 'fulfilled') {
publishedRelays.push(relays[index])
}
})
if (publishedRelays.length === 0) {
const failedPublishes: any[] = [] const failedPublishes: any[] = []
const fallbackRejectionReason = const fallbackRejectionReason =
'Attempt to publish an event has been rejected with unknown reason.' 'Attempt to publish an event has been rejected with unknown reason.'
const results = await Promise.allSettled(promises)
results.forEach((res, index) => { results.forEach((res, index) => {
if (res.status === 'rejected') { if (res.status === 'rejected') {
failedPublishes.push({ failedPublishes.push({
@ -257,7 +262,187 @@ export class NostrController extends EventEmitter {
throw failedPublishes throw failedPublishes
} }
return publishedRelays // Continue publishing to other relays in the background
promises.forEach((promise, index) => {
promise.catch((err) => {
console.log(`Failed to publish to ${relays[index]}`, err)
})
})
return [firstSuccessfulPublish]
}
/**
* 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
}
/**
* Encrypts the given content for the specified receiver using NIP-44 encryption.
*
* @param receiver The public key of the receiver.
* @param content The content to be encrypted.
* @returns The encrypted content as a string.
* @throws Error if the nostr extension does not support NIP-44, if the private key pair is not found, or if the login method is unsupported.
*/
nip44Encrypt = async (receiver: string, content: string) => {
// Retrieve the current login method from the application's redux state.
const loginMethod = (store.getState().auth as AuthState).loginMethod
// Handle encryption when the login method is via an extension.
if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
// Check if the nostr object supports NIP-44 encryption.
if (!nostr.nip44) {
throw new Error(
`Your nostr extension does not support nip44 encryption & decryption`
)
}
// Encrypt the content using NIP-44 provided by the nostr extension.
const encrypted = await nostr.nip44.encrypt(receiver, content)
return encrypted as string
}
// Handle encryption when the login method is via a private key.
if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
// Check if the private and public key pair is available.
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
// Decode the private key.
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
// Generate the conversation key using NIP-44 utilities.
const nip44ConversationKey = nip44.v2.utils.getConversationKey(
privateKey,
receiver
)
// Encrypt the content using the generated conversation key.
const encrypted = nip44.v2.encrypt(content, nip44ConversationKey)
return encrypted
}
// Throw an error if the login method is nsecBunker (not supported).
if (loginMethod === LoginMethods.nsecBunker) {
throw new Error(
`nip44 encryption is not yet supported for login method '${LoginMethods.nsecBunker}'`
)
}
// Throw an error if the login method is undefined or unsupported.
throw new Error('Login method is undefined')
}
/**
* Decrypts the given content from the specified sender using NIP-44 decryption.
*
* @param sender The public key of the sender.
* @param content The encrypted content to be decrypted.
* @returns The decrypted content as a string.
* @throws Error if the nostr extension does not support NIP-44, if the private key pair is not found, or if the login method is unsupported.
*/
nip44Decrypt = async (sender: string, content: string) => {
// Retrieve the current login method from the application's redux state.
const loginMethod = (store.getState().auth as AuthState).loginMethod
// Handle decryption when the login method is via an extension.
if (loginMethod === LoginMethods.extension) {
const nostr = this.getNostrObject()
// Check if the nostr object supports NIP-44 decryption.
if (!nostr.nip44) {
throw new Error(
`Your nostr extension does not support nip44 encryption & decryption`
)
}
// Decrypt the content using NIP-44 provided by the nostr extension.
const decrypted = await nostr.nip44.decrypt(sender, content)
return decrypted as string
}
// Handle decryption when the login method is via a private key.
if (loginMethod === LoginMethods.privateKey) {
const keys = (store.getState().auth as AuthState).keyPair
// Check if the private and public key pair is available.
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
// Decode the private key.
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
// Generate the conversation key using NIP-44 utilities.
const nip44ConversationKey = nip44.v2.utils.getConversationKey(
privateKey,
sender
)
// Decrypt the content using the generated conversation key.
const decrypted = nip44.v2.decrypt(content, nip44ConversationKey)
return decrypted
}
// Throw an error if the login method is nsecBunker (not supported).
if (loginMethod === LoginMethods.nsecBunker) {
throw new Error(
`nip44 decryption is not yet supported for login method '${LoginMethods.nsecBunker}'`
)
}
// Throw an error if the login method is undefined or unsupported.
throw new Error('Login method is undefined')
} }
/** /**
@ -330,7 +515,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 const loginMethod = (store.getState().auth as AuthState).loginMethod
if (loginMethod === LoginMethods.extension) { if (loginMethod === LoginMethods.extension) {
@ -385,7 +570,7 @@ export class NostrController extends EventEmitter {
* @param content - The encrypted content to decrypt. * @param content - The encrypted content to decrypt.
* @returns A promise that resolves to the decrypted content. * @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 const loginMethod = (store.getState().auth as AuthState).loginMethod
if (loginMethod === LoginMethods.extension) { if (loginMethod === LoginMethods.extension) {

View File

@ -1,29 +1,40 @@
import { Box } from '@mui/material' import { Box } from '@mui/material'
import Container from '@mui/material/Container' import Container from '@mui/material/Container'
import { Event, kinds } from 'nostr-tools'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux' import { useDispatch, useSelector } from 'react-redux'
import { Outlet } from 'react-router-dom' import { Outlet } from 'react-router-dom'
import { AppBar } from '../components/AppBar/AppBar' import { AppBar } from '../components/AppBar/AppBar'
import { restoreState, setAuthState, setMetadataEvent } from '../store/actions' import { LoadingSpinner } from '../components/LoadingSpinner'
import { MetadataController, NostrController } from '../controllers'
import {
restoreState,
setAuthState,
setMetadataEvent,
updateUserAppData
} from '../store/actions'
import { LoginMethods } from '../store/auth/types'
import { State } from '../store/rootReducer'
import { Dispatch } from '../store/store'
import { setUserRobotImage } from '../store/userRobotImage/action'
import { import {
clearAuthToken, clearAuthToken,
clearState, clearState,
getRoboHashPicture, getRoboHashPicture,
getUsersAppData,
loadState, loadState,
saveNsecBunkerDelegatedKey saveNsecBunkerDelegatedKey,
subscribeForSigits
} from '../utils' } from '../utils'
import { LoadingSpinner } from '../components/LoadingSpinner' import { useAppSelector } from '../hooks'
import { Dispatch } from '../store/store' import { SubCloser } from 'nostr-tools/abstract-pool'
import { MetadataController, NostrController } from '../controllers'
import { LoginMethods } from '../store/auth/types'
import { setUserRobotImage } from '../store/userRobotImage/action'
import { State } from '../store/rootReducer'
import { Event, kinds } from 'nostr-tools'
export const MainLayout = () => { export const MainLayout = () => {
const dispatch: Dispatch = useDispatch() const dispatch: Dispatch = useDispatch()
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState(`Loading App`)
const authState = useSelector((state: State) => state.auth) const authState = useSelector((state: State) => state.auth)
const usersAppData = useAppSelector((state) => state.userAppData)
useEffect(() => { useEffect(() => {
const metadataController = new MetadataController() const metadataController = new MetadataController()
@ -83,11 +94,33 @@ export const MainLayout = () => {
metadataController.findMetadata(usersPubkey).then((metadataEvent) => { metadataController.findMetadata(usersPubkey).then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(metadataEvent) if (metadataEvent) handleMetadataEvent(metadataEvent)
}) })
} 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) {
subscribeForSigits(pubkey).then((res) => {
subCloser = res || null
})
} }
} }
setIsLoading(false) return () => {
}, [dispatch]) if (subCloser) {
subCloser.close()
}
}
}, [authState, usersAppData])
/** /**
* When authState change user logged in / or app reloaded * When authState change user logged in / or app reloaded
@ -101,10 +134,20 @@ export const MainLayout = () => {
if (pubkey) { if (pubkey) {
dispatch(setUserRobotImage(getRoboHashPicture(pubkey))) dispatch(setUserRobotImage(getRoboHashPicture(pubkey)))
} }
setIsLoading(true)
setLoadingSpinnerDesc(`Fetching user's app data`)
getUsersAppData()
.then((appData) => {
if (appData) {
dispatch(updateUserAppData(appData))
}
})
.finally(() => setIsLoading(false))
} }
}, [authState]) }, [authState])
if (isLoading) return <LoadingSpinner desc="Loading App" /> if (isLoading) return <LoadingSpinner desc={loadingSpinnerDesc} />
return ( return (
<> <>

View File

@ -18,9 +18,14 @@ import {
Tooltip, Tooltip,
Typography Typography
} from '@mui/material' } from '@mui/material'
import type { Identifier, XYCoord } from 'dnd-core'
import saveAs from 'file-saver'
import JSZip from 'jszip' import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input' import { MuiFileInput } from 'mui-file-input'
import { Event, kinds } from 'nostr-tools'
import { useEffect, 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 { useSelector } from 'react-redux'
import { useLocation, useNavigate } from 'react-router-dom' import { useLocation, useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
@ -29,28 +34,32 @@ import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers' import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes' import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer' import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types' import {
CreateSignatureEventContent,
Meta,
ProfileMetadata,
User,
UserRole
} from '../../types'
import { import {
encryptArrayBuffer, encryptArrayBuffer,
formatTimestamp,
generateEncryptionKey, generateEncryptionKey,
generateKeys,
generateKeysFile, generateKeysFile,
getHash, getHash,
hexToNpub, hexToNpub,
isOnline, isOnline,
now,
npubToHex, npubToHex,
queryNip05, queryNip05,
sendDM, sendNotification,
shorten, shorten,
signEventForMetaFile, signEventForMetaFile,
updateUsersAppData,
uploadToFileStorage uploadToFileStorage
} from '../../utils' } from '../../utils'
import styles from './style.module.scss' 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 = () => { export const CreatePage = () => {
const navigate = useNavigate() const navigate = useNavigate()
@ -62,7 +71,7 @@ export const CreatePage = () => {
const [authUrl, setAuthUrl] = useState<string>() const [authUrl, setAuthUrl] = useState<string>()
const [title, setTitle] = useState('') const [title, setTitle] = useState(`sigit_${formatTimestamp(Date.now())}`)
const [selectedFiles, setSelectedFiles] = useState<File[]>([]) const [selectedFiles, setSelectedFiles] = useState<File[]>([])
const [userInput, setUserInput] = useState('') const [userInput, setUserInput] = useState('')
@ -75,6 +84,11 @@ export const CreatePage = () => {
const nostrController = NostrController.getInstance() const nostrController = NostrController.getInstance()
// Set up event listener for authentication event
nostrController.on('nsecbunker-auth', (url) => {
setAuthUrl(url)
})
useEffect(() => { useEffect(() => {
if (uploadedFile) { if (uploadedFile) {
setSelectedFiles([uploadedFile]) setSelectedFiles([uploadedFile])
@ -283,75 +297,6 @@ export const CreatePage = () => {
return fileHashes 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> => {
const zip = new JSZip()
selectedFiles.forEach((file) => {
zip.file(`files/${file.name}`, file)
})
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
}),
nostrController,
setIsLoading
)
if (!createSignature) return null
try {
return {
zip,
createSignature: JSON.stringify(createSignature, null, 2)
}
} catch (error) {
return null
}
}
// 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 // Handle errors during zip file generation
const handleZipError = (err: any) => { const handleZipError = (err: any) => {
console.log('Error in zip:>> ', err) console.log('Error in zip:>> ', err)
@ -384,13 +329,13 @@ export const CreatePage = () => {
return encryptArrayBuffer(arraybuffer, encryptionKey) return encryptArrayBuffer(arraybuffer, encryptionKey)
} }
// create final zip file // create final zip file for offline mode
const createFinalZipFile = async ( const createFinalZipFile = async (
encryptedArrayBuffer: ArrayBuffer, encryptedArrayBuffer: ArrayBuffer,
encryptionKey: string encryptionKey: string
): Promise<File | null> => { ): Promise<File | null> => {
// Get the current timestamp in seconds // Get the current timestamp in seconds
const unixNow = Math.floor(Date.now() / 1000) const unixNow = now()
const blob = new Blob([encryptedArrayBuffer]) const blob = new Blob([encryptedArrayBuffer])
// Create a File object with the Blob data // Create a File object with the Blob data
const file = new File([blob], `compressed.sigit`, { const file = new File([blob], `compressed.sigit`, {
@ -430,23 +375,6 @@ export const CreatePage = () => {
return finalZipFile return finalZipFile
} }
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
await sendDMs(fileUrl, encryptionKey)
}
// Handle errors during file upload // Handle errors during file upload
const handleUploadError = (err: any) => { const handleUploadError = (err: any) => {
console.log('Error in upload:>> ', err) console.log('Error in upload:>> ', err)
@ -456,13 +384,19 @@ export const CreatePage = () => {
} }
// Upload the file to the storage // Upload the file to the storage
const uploadFile = async (file: File): Promise<string | null> => { const uploadFile = async (
setIsLoading(true) arrayBuffer: ArrayBuffer
setLoadingSpinnerDesc('Uploading sigit to file storage.') ): Promise<string | null> => {
const unixNow = now()
const blob = new Blob([arrayBuffer])
// Create a File object with the Blob data
const file = new File([blob], `compressed-${unixNow}.sigit`, {
type: 'application/sigit'
})
const fileUrl = await uploadToFileStorage(file, nostrController) const fileUrl = await uploadToFileStorage(file)
.then((url) => { .then((url) => {
toast.success('Sigit uploaded to file storage') toast.success('files.zip uploaded to file storage')
return url return url
}) })
.catch(handleUploadError) .catch(handleUploadError)
@ -470,36 +404,6 @@ export const CreatePage = () => {
return fileUrl return fileUrl
} }
// Send DMs to signers and viewers with the file URL
const sendDMs = async (fileUrl: string, encryptionKey: string) => {
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
)
}
}
}
// Manage offline scenarios for signing or viewing the file // Manage offline scenarios for signing or viewing the file
const handleOfflineFlow = async ( const handleOfflineFlow = async (
encryptedArrayBuffer: ArrayBuffer, encryptedArrayBuffer: ArrayBuffer,
@ -515,43 +419,200 @@ export const CreatePage = () => {
saveAs(finalZipFile, 'request.sigit.zip') saveAs(finalZipFile, 'request.sigit.zip')
} }
const generateFilesZip = async (): Promise<ArrayBuffer | null> => {
const zip = new JSZip()
selectedFiles.forEach((file) => {
zip.file(file.name, file)
})
const arraybuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
})
.catch(handleZipError)
return arraybuffer
}
const generateCreateSignature = async (
fileHashes: {
[key: string]: string
},
zipUrl: string
) => {
const signers = users.filter((user) => user.role === UserRole.signer)
const viewers = users.filter((user) => user.role === UserRole.viewer)
const content: CreateSignatureEventContent = {
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
fileHashes,
zipUrl,
title
}
setLoadingSpinnerDesc('Signing nostr event for create signature')
const createSignature = await signEventForMetaFile(
JSON.stringify(content),
nostrController,
setIsLoading
).catch(() => {
console.log('An error occurred in signing event for meta file', error)
toast.error('An error occurred in signing event for meta file')
return null
})
if (!createSignature) return null
return JSON.stringify(createSignature, null, 2)
}
// Send notifications to signers and viewers
const sendNotifications = (meta: Meta) => {
const signers = users.filter((user) => user.role === UserRole.signer)
const viewers = users.filter((user) => user.role === UserRole.viewer)
// no need to send notification to self so remove it from the list
const receivers = (
signers.length > 0
? [signers[0].pubkey]
: viewers.map((viewer) => viewer.pubkey)
).filter((receiver) => receiver !== usersPubkey)
const promises = receivers.map((receiver) =>
sendNotification(receiver, meta)
)
return promises
}
const handleCreate = async () => { const handleCreate = async () => {
if (!validateInputs()) return if (!validateInputs()) return
setIsLoading(true) setIsLoading(true)
setLoadingSpinnerDesc('Generating hashes for files') setLoadingSpinnerDesc('Generating file hashes')
const fileHashes = await generateFileHashes() const fileHashes = await generateFileHashes()
if (!fileHashes) return if (!fileHashes) {
setIsLoading(false)
const createZipResponse = await createZipFile(fileHashes) return
if (!createZipResponse) return
const { zip, createSignature } = createZipResponse
const metaHash = await addMetaToZip(zip, createSignature)
if (!metaHash) return
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,
encryptionKey
)
if (await isOnline()) {
await handleOnlineFlow(encryptedArrayBuffer, encryptionKey)
} else {
await handleOfflineFlow(encryptedArrayBuffer, encryptionKey)
} }
navigate(appPrivateRoutes.sign, { state: { arrayBuffer } }) setLoadingSpinnerDesc('Generating encryption key')
const encryptionKey = await generateEncryptionKey()
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
)
setLoadingSpinnerDesc('Uploading files.zip to file storage')
const fileUrl = await uploadFile(encryptedArrayBuffer)
if (!fileUrl) {
setIsLoading(false)
return
}
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 = {
createSignature,
keys,
modifiedAt: now(),
docSignatures: {}
}
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) {
setIsLoading(false)
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
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptZipFile(
arrayBuffer,
encryptionKey
)
await handleOfflineFlow(encryptedArrayBuffer, encryptionKey)
}
} }
if (authUrl) { if (authUrl) {

View File

@ -1,21 +1,38 @@
import { import { CalendarMonth, Description, Upload } from '@mui/icons-material'
Add,
CalendarMonth,
Description,
PersonOutline,
Upload
} from '@mui/icons-material'
import { Box, Button, Tooltip, Typography } from '@mui/material' import { Box, Button, Tooltip, Typography } from '@mui/material'
import { useNavigate } from 'react-router-dom'
import { appPrivateRoutes, appPublicRoutes } from '../../routes'
import styles from './style.module.scss'
import { useRef } from 'react'
import JSZip from 'jszip' 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 { toast } from 'react-toastify'
import { UserComponent } from '../../components/username'
import { MetadataController } from '../../controllers'
import { useAppSelector } from '../../hooks'
import { appPrivateRoutes, appPublicRoutes } from '../../routes'
import { CreateSignatureEventContent, Meta, ProfileMetadata } from '../../types'
import {
formatTimestamp,
hexToNpub,
npubToHex,
parseJson,
shorten
} from '../../utils'
import styles from './style.module.scss'
export const HomePage = () => { export const HomePage = () => {
const navigate = useNavigate() const navigate = useNavigate()
const fileInputRef = useRef<HTMLInputElement>(null) const fileInputRef = useRef<HTMLInputElement>(null)
const [sigits, setSigits] = useState<Meta[]>([])
const [profiles, setProfiles] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
const usersAppData = useAppSelector((state) => state.userAppData)
useEffect(() => {
if (usersAppData) {
setSigits(Object.values(usersAppData.sigits))
}
}, [usersAppData])
const handleUploadClick = () => { const handleUploadClick = () => {
if (fileInputRef.current) { if (fileInputRef.current) {
@ -64,80 +81,184 @@ export const HomePage = () => {
} }
return ( return (
<Box className={styles.container}> <>
<Box className={styles.header}> <Box className={styles.container}>
<Typography variant="h3" className={styles.title}> <Box className={styles.header}>
Sigits <Typography variant="h3" className={styles.title}>
</Typography> Sigits
{/* This is for desktop view */} </Typography>
<Box {/* This is for desktop view */}
className={styles.actionButtons} <Box
sx={{ className={styles.actionButtons}
display: { sx={{
xs: 'none', display: {
md: 'flex' xs: 'none',
} md: 'flex'
}} }
> }}
<input
type="file"
ref={fileInputRef}
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<Button
variant="outlined"
startIcon={<Upload />}
onClick={handleUploadClick}
> >
Upload <input
</Button> type="file"
<Button ref={fileInputRef}
variant="contained" style={{ display: 'none' }}
startIcon={<Add />} onChange={handleFileChange}
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>
<Button <Button
variant="outlined" variant="outlined"
onClick={() => navigate(appPrivateRoutes.sign)} startIcon={<Upload />}
onClick={handleUploadClick}
> >
<Upload /> Upload
</Button> </Button>
</Tooltip> </Box>
<Tooltip title="Create" arrow> {/* This is for mobile view */}
<Button <Box
variant="contained" className={styles.actionButtons}
onClick={() => navigate(appPrivateRoutes.create)} sx={{
> display: {
<Add /> xs: 'flex',
</Button> md: 'none'
</Tooltip> }
}}
>
<Tooltip title="Upload" arrow>
<Button variant="outlined" onClick={handleUploadClick}>
<Upload />
</Button>
</Tooltip>
</Box>
</Box>
<Box className={styles.submissions}>
{sigits.map((sigit, index) => (
<DisplaySigit
key={`sigit-${index}`}
meta={sigit}
profiles={profiles}
setProfiles={setProfiles}
/>
))}
</Box> </Box>
</Box> </Box>
<Box className={styles.submissions}> </>
<PlaceHolder />
<PlaceHolder />
<PlaceHolder />
</Box>
</Box>
) )
} }
const PlaceHolder = () => { type SigitProps = {
meta: Meta
profiles: { [key: string]: ProfileMetadata }
setProfiles: Dispatch<SetStateAction<{ [key: string]: ProfileMetadata }>>
}
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>(
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
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()
}, [meta])
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 = () => {
if (signedStatus === SignedStatus.Complete) {
navigate(appPublicRoutes.verify, { state: { meta } })
} else {
navigate(appPrivateRoutes.sign, { state: { meta } })
}
}
return ( return (
<Box <Box
className={styles.item} className={styles.item}
@ -147,14 +268,11 @@ const PlaceHolder = () => {
md: 'row' md: 'row'
} }
}} }}
onClick={handleNavigation}
> >
<Box <Box
className={styles.titleBox} className={styles.titleBox}
sx={{ sx={{
flexDirection: {
xs: 'row',
md: 'column'
},
borderBottomLeftRadius: { borderBottomLeftRadius: {
xs: 'initial', xs: 'initial',
md: 'inherit' md: 'inherit'
@ -165,33 +283,103 @@ const PlaceHolder = () => {
} }
}} }}
> >
<Typography variant="body1" className={styles.titleBoxItem}> <Typography variant="body1" className={styles.title}>
<Description /> <Description />
Title {title}
</Typography> </Typography>
<Typography variant="body2" className={styles.titleBoxItem}> {submittedBy &&
<PersonOutline /> (function () {
Sigit const profile = profiles[submittedBy]
</Typography> return (
<Typography variant="body2" className={styles.titleBoxItem}> <UserComponent
pubkey={submittedBy}
name={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(submittedBy))
}
image={profile?.picture}
/>
)
})()}
<Typography variant="body2" className={styles.date}>
<CalendarMonth /> <CalendarMonth />
07 Jun 10:23 AM {createdAt}
</Typography> </Typography>
</Box> </Box>
<Box className={styles.signers}> <Box className={styles.signers}>
<Box className={styles.signerItem}> {signers.map((signer) => {
<Typography variant="button" className={styles.status}> const pubkey = npubToHex(signer)!
Sent const profile = profiles[pubkey]
</Typography>
<Typography variant="body1">placeholder@sigit.io</Typography> return (
</Box> <DisplaySigner
<Box className={styles.signerItem}> key={signer}
<Typography variant="button" className={styles.status}> meta={meta}
Awaiting profile={profile}
</Typography> pubkey={pubkey}
<Typography variant="body1">placeholder@sigit.io</Typography> />
</Box> )
})}
</Box> </Box>
</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), 5)
}
image={profile?.picture}
/>
</Box>
)
}

View File

@ -28,23 +28,40 @@
.item { .item {
display: flex; display: flex;
gap: 10px;
background-color: #efeae6; background-color: #efeae6;
border-radius: 1rem; border-radius: 1rem;
cursor: pointer;
.titleBox { .titleBox {
display: flex; display: flex;
align-items: flex-start; flex: 4;
justify-content: space-between; flex-direction: column;
align-items: center;
overflow-wrap: anywhere;
gap: 10px;
padding: 10px; padding: 10px;
background-color: #cdc8c499; background-color: #cdc8c499;
border-top-left-radius: inherit; border-top-left-radius: inherit;
border-bottom-left-radius: inherit;
.titleBoxItem { .title {
display: flex; display: flex;
justify-content: center; justify-content: center;
align-items: center; align-items: center;
color: var(--mui-palette-primary-light); 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 { svg {
font-size: 1rem; font-size: 1rem;
@ -55,10 +72,10 @@
.signers { .signers {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
flex: 1; flex: 6;
justify-content: center; justify-content: center;
gap: 10px; gap: 10px;
padding: 10px 0; padding: 10px;
color: var(--mui-palette-primary-light); color: var(--mui-palette-primary-light);
.signerItem { .signerItem {

View File

@ -7,7 +7,7 @@ import { MuiFileInput } from 'mui-file-input'
import { Event, verifyEvent } from 'nostr-tools' import { Event, verifyEvent } from 'nostr-tools'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux' 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 { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import { NostrController } from '../../controllers' import { NostrController } from '../../controllers'
@ -17,17 +17,19 @@ import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types'
import { import {
decryptArrayBuffer, decryptArrayBuffer,
encryptArrayBuffer, encryptArrayBuffer,
extractZipUrlAndEncryptionKey,
generateEncryptionKey, generateEncryptionKey,
generateKeysFile, generateKeysFile,
getHash, getHash,
hexToNpub, hexToNpub,
isOnline, isOnline,
now,
npubToHex, npubToHex,
parseJson, parseJson,
readContentOfZipEntry, readContentOfZipEntry,
sendDM, sendNotification,
signEventForMetaFile, signEventForMetaFile,
uploadToFileStorage updateUsersAppData
} from '../../utils' } from '../../utils'
import { DisplayMeta } from './internal/displayMeta' import { DisplayMeta } from './internal/displayMeta'
import styles from './style.module.scss' import styles from './style.module.scss'
@ -40,16 +42,23 @@ enum SignedStatus {
export const SignPage = () => { export const SignPage = () => {
const navigate = useNavigate() const navigate = useNavigate()
const location = useLocation() const location = useLocation()
const { arrayBuffer: decryptedArrayBuffer, uploadedZip } =
location.state || {}
const [searchParams, setSearchParams] = useSearchParams() /**
* uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains keys.json
* arrayBuffer will be received in navigation from create page in offline mode
* meta will be received in navigation from create & home page in online mode
*/
const {
meta: metaInNavState,
arrayBuffer: decryptedArrayBuffer,
uploadedZip
} = location.state || {}
const [displayInput, setDisplayInput] = useState(false) const [displayInput, setDisplayInput] = useState(false)
const [selectedFile, setSelectedFile] = useState<File | null>(null) const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [zip, setZip] = useState<JSZip>() const [files, setFiles] = useState<{ [filename: string]: ArrayBuffer }>({})
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
@ -80,41 +89,6 @@ export const SignPage = () => {
const [authUrl, setAuthUrl] = useState<string>() const [authUrl, setAuthUrl] = useState<string>()
const nostrController = NostrController.getInstance() const nostrController = NostrController.getInstance()
useEffect(() => {
if (zip) {
const generateCurrentFileHashes = async () => {
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
.map((entry) => entry.name)
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
if (arrayBuffer) {
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName.replace(/^files\//, '')] = hash
}
} else {
fileHashes[fileName.replace(/^files\//, '')] = null
}
}
setCurrentFileHashes(fileHashes)
}
generateCurrentFileHashes()
}
}, [zip])
useEffect(() => { useEffect(() => {
if (signers.length > 0) { if (signers.length > 0) {
// check if all signers have signed then its fully signed // check if all signers have signed then its fully signed
@ -160,43 +134,94 @@ export const SignPage = () => {
}, [signers, signedBy, usersPubkey, submittedBy]) }, [signers, signedBy, usersPubkey, submittedBy])
useEffect(() => { useEffect(() => {
const fileUrl = searchParams.get('file') const handleUpdatedMeta = async (meta: Meta) => {
const key = searchParams.get('key') 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) { if (!createSignatureEvent) return
setIsLoading(true)
setLoadingSpinnerDesc('Fetching file from file server')
axios const isValidCreateSignature = verifyEvent(createSignatureEvent)
.get(fileUrl, {
responseType: 'arraybuffer'
})
.then(async (res) => {
const fileName = fileUrl.split('/').pop()
const file = new File([res.data], fileName!)
const encryptedArrayBuffer = await file.arrayBuffer() if (!isValidCreateSignature) {
toast.error('Create signature is invalid')
setIsLoading(false)
return
}
const arrayBuffer = await decryptArrayBuffer( const createSignatureContent =
encryptedArrayBuffer, await parseJson<CreateSignatureEventContent>(
key createSignatureEvent.content
).catch((err) => { ).catch((err) => {
console.log('err in decryption:>> ', err) console.log(
toast.error(err.message || 'An error occurred in decrypting file.') `err in parsing the createSignature event's content :>> `,
return null err
}) )
toast.error(
if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer) err.message ||
}) `error occurred in parsing the create signature event's content`
.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) 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 (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 } = res
setLoadingSpinnerDesc('Fetching file from file server')
axios
.get(zipUrl, {
responseType: 'arraybuffer'
})
.then((res) => {
handleArrayBufferFromBlossom(res.data, encryptionKey)
setMeta(metaInNavState)
})
.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)
})
}
processSigit()
} else if (decryptedArrayBuffer) { } else if (decryptedArrayBuffer) {
handleDecryptedArrayBuffer(decryptedArrayBuffer).finally(() => handleDecryptedArrayBuffer(decryptedArrayBuffer).finally(() =>
setIsLoading(false) setIsLoading(false)
@ -217,7 +242,63 @@ export const SignPage = () => {
setIsLoading(false) setIsLoading(false)
setDisplayInput(true) setDisplayInput(true)
} }
}, [searchParams, decryptedArrayBuffer, uploadedZip]) }, [decryptedArrayBuffer, uploadedZip, metaInNavState])
const handleArrayBufferFromBlossom = async (
arrayBuffer: ArrayBuffer,
encryptionKey: string
) => {
// array buffer returned from blossom is encrypted.
// So, first decrypt it
const decrypted = await decryptArrayBuffer(
arrayBuffer,
encryptionKey
).catch((err) => {
console.log('err in decryption:>> ', err)
toast.error(err.message || 'An error occurred in decrypting file.')
setIsLoading(false)
return null
})
if (!decrypted) return
const zip = await JSZip.loadAsync(decrypted).catch((err) => {
console.log('err in loading zip file :>> ', err)
toast.error(err.message || 'An error occurred in loading zip file.')
setIsLoading(false)
return null
})
if (!zip) return
const files: { [filename: string]: ArrayBuffer } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files).map((entry) => entry.name)
// generate hashes for all files in zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
if (arrayBuffer) {
files[fileName] = arrayBuffer
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName] = hash
}
} else {
fileHashes[fileName] = null
}
}
setFiles(files)
setCurrentFileHashes(fileHashes)
}
const parseKeysJson = async (zip: JSZip) => { const parseKeysJson = async (zip: JSZip) => {
const keysFileContent = await readContentOfZipEntry( const keysFileContent = await readContentOfZipEntry(
@ -325,7 +406,37 @@ export const SignPage = () => {
if (!zip) return if (!zip) return
setZip(zip) const files: { [filename: string]: ArrayBuffer } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
.map((entry) => entry.name)
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (let fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
fileName = fileName.replace(/^files\//, '')
if (arrayBuffer) {
files[fileName] = arrayBuffer
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName] = hash
}
} else {
fileHashes[fileName] = null
}
}
setFiles(files)
setCurrentFileHashes(fileHashes)
setDisplayInput(false) setDisplayInput(false)
setLoadingSpinnerDesc('Parsing meta.json') setLoadingSpinnerDesc('Parsing meta.json')
@ -352,53 +463,6 @@ export const SignPage = () => {
} }
) )
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) setMeta(parsedMetaJson)
} }
@ -414,23 +478,9 @@ export const SignPage = () => {
} }
const handleSign = async () => { const handleSign = async () => {
if (!zip || !meta) return if (Object.entries(files).length === 0 || !meta) return
setIsLoading(true) setIsLoading(true)
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') setLoadingSpinnerDesc('Signing nostr event')
@ -442,55 +492,14 @@ export const SignPage = () => {
const updatedMeta = updateMetaSignatures(meta, signedEvent) 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)
if (await isOnline()) { if (await isOnline()) {
await handleOnlineFlow(encryptedArrayBuffer, key) await handleOnlineFlow(updatedMeta)
} else { } else {
handleDecryptedArrayBuffer(arrayBuffer).finally(() => setIsLoading(false)) setMeta(updatedMeta)
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 // Sign the event for the meta file
const signEventForMeta = async (prevSig: string) => { const signEventForMeta = async (prevSig: string) => {
return await signEventForMetaFile( return await signEventForMetaFile(
@ -507,40 +516,10 @@ export const SignPage = () => {
...metaCopy.docSignatures, ...metaCopy.docSignatures,
[hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2) [hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2)
} }
metaCopy.modifiedAt = now()
return metaCopy 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 // create final zip file
const createFinalZipFile = async ( const createFinalZipFile = async (
encryptedArrayBuffer: ArrayBuffer, encryptedArrayBuffer: ArrayBuffer,
@ -616,59 +595,59 @@ export const SignPage = () => {
return null return null
} }
// Handle the online flow: upload file and send DMs // Handle the online flow: update users app data and send notifications
const handleOnlineFlow = async ( const handleOnlineFlow = async (meta: Meta) => {
encryptedArrayBuffer: ArrayBuffer, setLoadingSpinnerDesc('Updating users app data')
encryptionKey: string const updatedEvent = await updateUsersAppData(meta)
) => { if (!updatedEvent) {
const unixNow = Math.floor(Date.now() / 1000) setIsLoading(false)
const blob = new Blob([encryptedArrayBuffer]) return
// 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)
} }
// update search params with updated file url and encryption key const userSet = new Set<`npub1${string}`>()
setSearchParams({ if (submittedBy && submittedBy !== usersPubkey) {
file: fileUrl, userSet.add(hexToNpub(submittedBy))
key: encryptionKey }
})
setIsLoading(false) const usersNpub = hexToNpub(usersPubkey!)
} const isLastSigner = checkIsLastSigner(signers)
if (isLastSigner) {
// Handle errors during file upload signers.forEach((signer) => {
const handleUploadError = (err: any) => { if (signer !== usersNpub) {
console.log('Error in upload:>> ', err) userSet.add(signer)
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
}) })
.catch(handleUploadError)
return fileUrl viewers.forEach((viewer) => {
userSet.add(viewer)
})
} else {
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)
)
await Promise.all(promises)
.then(() => {
toast.success('Notifications sent successfully')
setMeta(meta)
})
.catch(() => {
toast.error('Failed to publish notifications')
})
setIsLoading(false)
} }
// Check if the current user is the last signer // Check if the current user is the last signer
@ -679,53 +658,8 @@ export const SignPage = () => {
return signerIndex === lastSignerIndex 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 () => { const handleExport = async () => {
if (!meta || !zip || !usersPubkey) return if (Object.entries(files).length === 0 || !meta || !usersPubkey) return
const usersNpub = hexToNpub(usersPubkey) const usersNpub = hexToNpub(usersPubkey)
if ( if (
@ -738,7 +672,7 @@ export const SignPage = () => {
setIsLoading(true) setIsLoading(true)
setLoadingSpinnerDesc('Signing nostr event') setLoadingSpinnerDesc('Signing nostr event')
const prevSig = await getLastSignersSig() const prevSig = getLastSignersSig()
if (!prevSig) return if (!prevSig) return
const signedEvent = await signEventForMetaFile( const signedEvent = await signEventForMetaFile(
@ -761,8 +695,15 @@ export const SignPage = () => {
null, null,
2 2
) )
const zip = new JSZip()
zip.file('meta.json', stringifiedMeta) zip.file('meta.json', stringifiedMeta)
Object.entries(files).forEach(([fileName, arrayBuffer]) => {
zip.file(`files/${fileName}`, arrayBuffer)
})
const arrayBuffer = await zip const arrayBuffer = await zip
.generateAsync({ .generateAsync({
type: 'arraybuffer', type: 'arraybuffer',
@ -790,7 +731,17 @@ export const SignPage = () => {
} }
const handleExportSigit = async () => { const handleExportSigit = async () => {
if (!zip) return if (Object.entries(files).length === 0 || !meta) return
const zip = new JSZip()
const stringifiedMeta = JSON.stringify(meta, null, 2)
zip.file('meta.json', stringifiedMeta)
Object.entries(files).forEach(([fileName, arrayBuffer]) => {
zip.file(`files/${fileName}`, arrayBuffer)
})
const arrayBuffer = await zip const arrayBuffer = await zip
.generateAsync({ .generateAsync({
@ -925,11 +876,11 @@ export const SignPage = () => {
</> </>
)} )}
{submittedBy && zip && meta && ( {submittedBy && Object.entries(files).length > 0 && meta && (
<> <>
<DisplayMeta <DisplayMeta
meta={meta} meta={meta}
zip={zip} files={files}
submittedBy={submittedBy} submittedBy={submittedBy}
signers={signers} signers={signers}
viewers={viewers} viewers={viewers}
@ -956,7 +907,6 @@ export const SignPage = () => {
</Box> </Box>
)} )}
{/* todo: In offline mode export sigit is not visible after last signer has signed*/}
{isSignerOrCreator && ( {isSignerOrCreator && (
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}> <Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExportSigit} variant="contained"> <Button onClick={handleExportSigit} variant="contained">

View File

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

View File

@ -23,6 +23,8 @@ import {
SignedEventContent SignedEventContent
} from '../../types' } from '../../types'
import { import {
decryptArrayBuffer,
extractZipUrlAndEncryptionKey,
getHash, getHash,
hexToNpub, hexToNpub,
npubToHex, npubToHex,
@ -33,6 +35,7 @@ import {
import styles from './style.module.scss' import styles from './style.module.scss'
import { Cancel, CheckCircle } from '@mui/icons-material' import { Cancel, CheckCircle } from '@mui/icons-material'
import { useLocation } from 'react-router-dom' import { useLocation } from 'react-router-dom'
import axios from 'axios'
export const VerifyPage = () => { export const VerifyPage = () => {
const theme = useTheme() const theme = useTheme()
@ -41,13 +44,16 @@ export const VerifyPage = () => {
) )
const location = useLocation() const location = useLocation()
const { uploadedZip } = location.state || {} /**
* uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains meta.json
* meta will be received in navigation from create & home page in online mode
*/
const { uploadedZip, meta: metaInNavState } = location.state || {}
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [selectedFile, setSelectedFile] = useState<File | null>(null) const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [zip, setZip] = useState<JSZip>()
const [meta, setMeta] = useState<Meta | null>(null) const [meta, setMeta] = useState<Meta | null>(null)
const [submittedBy, setSubmittedBy] = useState<string>() const [submittedBy, setSubmittedBy] = useState<string>()
@ -68,43 +74,106 @@ export const VerifyPage = () => {
useEffect(() => { useEffect(() => {
if (uploadedZip) { if (uploadedZip) {
setSelectedFile(uploadedZip) setSelectedFile(uploadedZip)
} } else if (metaInNavState) {
}, [uploadedZip]) const processSigit = async () => {
setIsLoading(true)
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
useEffect(() => { const res = await extractZipUrlAndEncryptionKey(metaInNavState)
if (zip) { if (!res) {
const generateCurrentFileHashes = async () => { setIsLoading(false)
const fileHashes: { [key: string]: string | null } = {} return
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) 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
const fileHashes: { [key: string]: string | null } = {}
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
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)
setSigners(createSignatureContent.signers)
setViewers(createSignatureContent.viewers)
setCreatorFileHashes(createSignatureContent.fileHashes)
setSubmittedBy(createSignatureEvent.pubkey)
setMeta(metaInNavState)
setIsLoading(false)
}
})
.catch((err) => {
console.error(`error occurred in getting file from ${zipUrl}`, err)
toast.error(
err.message || `error occurred in getting file from ${zipUrl}`
)
})
.finally(() => {
setIsLoading(false)
})
} }
generateCurrentFileHashes() processSigit()
} }
}, [zip]) }, [uploadedZip, metaInNavState])
useEffect(() => { useEffect(() => {
if (submittedBy) { if (submittedBy) {
@ -159,7 +228,34 @@ export const VerifyPage = () => {
}) })
if (!zip) return if (!zip) return
setZip(zip)
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
.map((entry) => entry.name)
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
if (arrayBuffer) {
const hash = await getHash(arrayBuffer)
if (hash) {
fileHashes[fileName.replace(/^files\//, '')] = hash
}
} else {
fileHashes[fileName.replace(/^files\//, '')] = null
}
}
console.log('fileHashes :>> ', fileHashes)
setCurrentFileHashes(fileHashes)
setLoadingSpinnerDesc('Parsing meta.json') setLoadingSpinnerDesc('Parsing meta.json')

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,3 +1,5 @@
import { Keys } from '../store/auth/types'
export enum UserRole { export enum UserRole {
signer = 'Signer', signer = 'Signer',
viewer = 'Viewer' viewer = 'Viewer'
@ -9,18 +11,33 @@ export interface User {
} }
export interface Meta { export interface Meta {
title: string modifiedAt: number
createSignature: string createSignature: string
docSignatures: { [key: `npub1${string}`]: string } docSignatures: { [key: `npub1${string}`]: string }
exportSignature?: string exportSignature?: string
keys?: { sender: string; keys: { [user: `npub1${string}`]: string } }
} }
export interface CreateSignatureEventContent { export interface CreateSignatureEventContent {
signers: `npub1${string}`[] signers: `npub1${string}`[]
viewers: `npub1${string}`[] viewers: `npub1${string}`[]
fileHashes: { [key: string]: string } fileHashes: { [key: string]: string }
title: string
zipUrl: string
} }
export interface SignedEventContent { export interface SignedEventContent {
prevSig: string prevSig: string
} }
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
}

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,21 @@
import axios from 'axios' import axios from 'axios'
import { import {
Event,
EventTemplate, EventTemplate,
finalizeEvent,
generateSecretKey, generateSecretKey,
getPublicKey, getPublicKey,
nip04 nip04,
verifyEvent
} from 'nostr-tools' } from 'nostr-tools'
import { MetadataController, NostrController } from '../controllers'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { appPrivateRoutes } from '../routes' import { NostrController } from '../controllers'
import { AuthState } from '../store/auth/types'
import store from '../store/store'
import { CreateSignatureEventContent, Meta } from '../types'
import { hexToNpub, now } from './nostr'
import { parseJson } from './string'
import { hexToBytes } from '@noble/hashes/utils'
/** /**
* Uploads a file to a file storage service. * Uploads a file to a file storage service.
@ -15,13 +23,7 @@ import { appPrivateRoutes } from '../routes'
* @param nostrController The NostrController instance for handling authentication. * @param nostrController The NostrController instance for handling authentication.
* @returns The URL of the uploaded file. * @returns The URL of the uploaded file.
*/ */
export const uploadToFileStorage = async ( export const uploadToFileStorage = async (file: File) => {
file: File,
nostrController: NostrController
) => {
// Get the current timestamp in seconds
const unixNow = Math.floor(Date.now() / 1000)
// Define event metadata for authorization // Define event metadata for authorization
const event: EventTemplate = { const event: EventTemplate = {
kind: 24242, kind: 24242,
@ -29,14 +31,21 @@ export const uploadToFileStorage = async (
created_at: Math.floor(Date.now() / 1000), created_at: Math.floor(Date.now() / 1000),
tags: [ tags: [
['t', 'upload'], ['t', 'upload'],
['expiration', String(unixNow + 60 * 5)], // Set expiration time to 5 minutes from now ['expiration', String(now() + 60 * 5)], // Set expiration time to 5 minutes from now
['name', file.name], ['name', file.name],
['size', String(file.size)] ['size', String(file.size)]
] ]
} }
// Sign the authorization event using the NostrController const key = store.getState().userAppData?.keyPair?.private
const authEvent = await nostrController.signEvent(event) if (!key) {
throw new Error(
'Key to interact with blossom server is not defined in user app data'
)
}
// Sign the authorization event using the dedicated key stored in user app data
const authEvent = finalizeEvent(event, hexToBytes(key))
// URL of the file storage service // URL of the file storage service
const FILE_STORAGE_URL = 'https://blossom.sigit.io' // REFACTOR: should be an env const FILE_STORAGE_URL = 'https://blossom.sigit.io' // REFACTOR: should be an env
@ -53,128 +62,6 @@ export const uploadToFileStorage = async (
return response.data.url as string return response.data.url as string
} }
/**
* Sends a Direct Message (DM) to a recipient, encrypting the content and handling authentication.
* @param fileUrl The URL of the encrypted zip file to be included in the DM.
* @param encryptionKey The encryption key used to decrypt the zip file to be included in the DM.
* @param pubkey The public key of the recipient.
* @param nostrController The NostrController instance for handling authentication and encryption.
* @param isSigner Boolean indicating whether the recipient is a signer or viewer.
* @param setAuthUrl Function to set the authentication URL in the component state.
*/
export const sendDM = async (
fileUrl: string,
encryptionKey: string,
pubkey: string,
nostrController: NostrController,
isSigner: boolean,
setAuthUrl: (value: React.SetStateAction<string | undefined>) => void
) => {
// Construct the content of the DM
const initialLine = isSigner
? 'Your signature is requested on the document below!'
: 'You have received a signed document.'
const decryptionUrl = `${window.location.origin}/#${
appPrivateRoutes.sign
}?file=${encodeURIComponent(fileUrl)}&key=${encodeURIComponent(
encryptionKey
)}`
const content = `${initialLine}\n\n${decryptionUrl}`
// Set up event listener for authentication event
nostrController.on('nsecbunker-auth', (url) => {
setAuthUrl(url)
})
// Set up timeout promise to handle encryption timeout
const timeoutPromise = new Promise<never>((_, reject) => {
setTimeout(() => {
reject(new Error('Timeout occurred'))
}, 60000) // Timeout duration = 60 seconds
})
// Encrypt the DM content, with timeout
const encrypted = await Promise.race([
nostrController.nip04Encrypt(pubkey, content),
timeoutPromise
])
.then((res) => {
return res
})
.catch((err) => {
console.log('err :>> ', err)
toast.error(
err.message || 'An error occurred while encrypting DM content'
)
return null
})
.finally(() => {
setAuthUrl(undefined) // Clear authentication URL
})
// Return if encryption failed
if (!encrypted) return
// Construct event metadata for the DM
const event: EventTemplate = {
kind: 4, // DM event type
content: encrypted, // Encrypted DM content
created_at: Math.floor(Date.now() / 1000), // Current timestamp
tags: [['p', pubkey]] // Tag with recipient's public key
}
// Sign the DM event
const signedEvent = await nostrController.signEvent(event).catch((err) => {
console.log('err :>> ', err)
toast.error(err.message || 'An error occurred while signing event for DM')
return null
})
// Return if event signing failed
if (!signedEvent) return
// Get relay list metadata
const metadataController = new MetadataController()
const relaySet = await metadataController
.findRelayListMetadata(pubkey)
.catch((err) => {
toast.error(
err.message || 'An error occurred while finding relay list metadata'
)
return null
})
// Return if metadata retrieval failed
if (!relaySet) return
// Ensure relay list is not empty
if (relaySet.read.length === 0) {
toast.error('No relay found for publishing encrypted DM')
return
}
// Publish the signed DM event to the recipient's read relays
await nostrController
.publishEvent(signedEvent, relaySet.read)
.then((relays) => {
toast.success(`Encrypted DM sent on: ${relays.join('\n')}`)
})
.catch((errResults) => {
console.log('err :>> ', errResults)
toast.error('An error occurred while publishing DM')
errResults.forEach((errResult: any) => {
toast.error(
`Publishing to ${errResult.relay} caused the following error: ${errResult.error}`
)
})
return null
})
}
/** /**
* Signs an event for a meta.json file. * Signs an event for a meta.json file.
* @param content contains content for event. * @param content contains content for event.
@ -192,7 +79,7 @@ export const signEventForMetaFile = async (
kind: 27235, // Event type for meta file kind: 27235, // Event type for meta file
content: content, // content for event content: content, // content for event
created_at: Math.floor(Date.now() / 1000), // Current timestamp created_at: Math.floor(Date.now() / 1000), // Current timestamp
tags: [] tags: [['-']] // For understanding why "-" tag is used here see: https://github.com/nostr-protocol/nips/blob/protected-events-tag/70.md
} }
// Sign the event // Sign the event
@ -254,3 +141,126 @@ export const generateKeysFile = async (
return null 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 }
}
/**
* Function to extract the ZIP URL and encryption key from the provided metadata.
* @param meta - The metadata object containing the create signature and encryption keys.
* @returns A promise that resolves to an object containing the create signature event,
* create signature content, ZIP URL, and decrypted encryption key.
*/
export const extractZipUrlAndEncryptionKey = async (meta: Meta) => {
// Parse the create signature event from the metadata
const createSignatureEvent = await parseJson<Event>(
meta.createSignature
).catch((err) => {
// Log and display an error message if parsing fails
console.log('err in parsing the createSignature event:>> ', err)
toast.error(
err.message || 'error occurred in parsing the create signature event'
)
return null
})
// Return null if the create signature event could not be parsed
if (!createSignatureEvent) return null
// Verify the validity of the create signature event
const isValidCreateSignature = verifyEvent(createSignatureEvent)
if (!isValidCreateSignature) {
toast.error('Create signature is invalid')
return null
}
// Parse the content of the create signature event
const createSignatureContent = await parseJson<CreateSignatureEventContent>(
createSignatureEvent.content
).catch((err) => {
// Log and display an error message if parsing fails
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
})
// Return null if the create signature content could not be parsed
if (!createSignatureContent) return null
// Extract the ZIP URL from the create signature content
const zipUrl = createSignatureContent.zipUrl
// Retrieve the user's public key from the state
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const usersNpub = hexToNpub(usersPubkey)
// Return null if the metadata does not contain keys
if (!meta.keys) return null
const { sender, keys } = meta.keys
// Check if the user's public key is in the keys object
if (usersNpub in keys) {
// Instantiate the NostrController to decrypt the encryption key
const nostrController = NostrController.getInstance()
const decrypted = await nostrController
.nip04Decrypt(sender, keys[usersNpub])
.catch((err) => {
// Log and display an error message if decryption fails
console.log('An error occurred in decrypting encryption key', err)
toast.error('An error occurred in decrypting encryption key')
return null
})
// Return null if the encryption key could not be decrypted
if (!decrypted) return null
// Return the parsed and decrypted data
return {
createSignatureEvent,
createSignatureContent,
zipUrl,
encryptionKey: decrypted
}
}
return null
}

View File

@ -1,7 +1,35 @@
import { nip19, verifyEvent } from 'nostr-tools' import { bytesToHex, hexToBytes } from '@noble/hashes/utils'
import { SignedEvent } from '../types'
import axios from 'axios' import axios from 'axios'
import _ from 'lodash'
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 { NIP05_REGEX } from '../constants'
import { MetadataController, NostrController } from '../controllers'
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, SignedEvent, UserAppData } from '../types'
import { getHash } from './hash'
import { parseJson, removeLeadingSlash } from './string'
import { timeout } from './utils'
/** /**
* @param hexKey hex private or public key * @param hexKey hex private or public key
@ -181,3 +209,710 @@ export const getRoboHashPicture = (
const npub = hexToNpub(pubkey) const npub = hexToNpub(pubkey)
return `https://robohash.org/${npub}.png?set=set${set}` return `https://robohash.org/${npub}.png?set=set${set}`
} }
export const now = () => Math.round(Date.now() / 1000)
/**
* 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: UnsignedEvent,
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 = (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(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 event: UnsignedEvent = {
kind: 1059, // Event kind
content, // Encrypted content
pubkey, // Public key of the creator
created_at: now(), // 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(event)
// 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(event, randomKey)
}
// Increment the nonce for the next iteration
nonce++
}
}
export const getUsersAppData = async (): Promise<UserAppData | null> => {
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) {
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 null
// Ensure relay list is not empty
if (relaySet.write.length === 0) return null
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('938' + 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 === '{}') {
const secret = generateSecretKey()
const pubKey = getPublicKey(secret)
return {
sigits: {},
processedGiftWraps: [],
blossomUrls: [],
keyPair: {
private: bytesToHex(secret),
public: pubKey
}
}
}
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<{
blossomUrls: string[]
keyPair: Keys
}>(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
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 (meta: Meta) => {
const appData = store.getState().userAppData
if (!appData || !appData.keyPair) return null
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) {
sigits[id] = meta
isUpdated = true
}
} else {
sigits[id] = meta
isUpdated = true
}
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
// insert new blossom url at the start of the array
blossomUrls.unshift(newBlossomUrl)
// only keep last 10 blossom urls, delete older ones
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!
// encrypt content for storing in kind 30078 event
const nostrController = NostrController.getInstance()
const encryptedContent = await nostrController
.nip04Encrypt(
usersPubkey,
JSON.stringify({
blossomUrls,
keyPair: appData.keyPair
})
)
.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('938' + 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)
console.log(`publishing event kind: ${kinds.Application}`)
const publishResult = await Promise.race([
nostrController.publishEvent(signedEvent, writeRelays),
timeout(1000 * 30)
]).catch((err) => {
console.log('err :>> ', err)
if (err.message === 'Timeout') {
toast.error('Timeout occurred in publishing updated app data')
} else if (Array.isArray(err)) {
err.forEach((errResult) => {
toast.error(
`Publishing to ${errResult.relay} caused the following error: ${errResult.error}`
)
})
} else {
toast.error(
'An unexpected error occurred in publishing updated app data '
)
}
return null
})
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)
}
/**
* Function to upload user application data to the Blossom server.
* @param sigits - An object containing metadata for the user application data.
* @param processedGiftWraps - An array of processed gift wrap IDs.
* @param privateKey - The private key used for encryption.
* @returns A promise that resolves to the URL of the uploaded file.
*/
const uploadUserAppDataToBlossom = async (
sigits: { [key: string]: Meta },
processedGiftWraps: string[],
privateKey: string
) => {
// Create an object containing the sigits and processed gift wraps
const obj = {
sigits,
processedGiftWraps
}
// Convert the object to a JSON string
const stringified = JSON.stringify(obj)
// Convert the private key from hex to bytes
const secretKey = hexToBytes(privateKey)
// Encrypt the JSON string using the secret key
const encrypted = nip44.v2.encrypt(
stringified,
nip44ConversationKey(secretKey, getPublicKey(secretKey))
)
// Create a blob from the encrypted data
const blob = new Blob([encrypted], { type: 'application/octet-stream' })
// Create a file from the blob
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)]
]
}
// Finalize the event with the private key
const authEvent = finalizeEvent(event, hexToBytes(privateKey))
// URL of the file storage service
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
}
/**
* Function to retrieve and decrypt user application data from Blossom server.
* @param url - The URL to fetch the encrypted data from.
* @param privateKey - The private key used for decryption.
* @returns A promise that resolves to the decrypted and parsed user application data.
*/
const getUserAppDataFromBlossom = async (url: string, privateKey: string) => {
// Initialize errorCode to track HTTP error codes
let errorCode = 0
// Fetch the encrypted data from the provided URL
const encrypted = await axios
.get(url, {
responseType: 'blob' // Expect a blob response
})
.then(async (res) => {
// Convert the blob response to a File object
const file = new File([res.data], 'encrypted.txt')
// Read the text content from the file
const text = await file.text()
return text
})
.catch((err) => {
// Log and display an error message if the request fails
console.error(`error occurred in getting file from ${url}`, err)
toast.error(err.message || `error occurred in getting file from ${url}`)
// Set errorCode to the HTTP status code if available
if (err.request) {
const { status } = err.request
errorCode = status
}
return null
})
// Return a default value if the requested resource is not found (404)
if (errorCode === 404) {
return {
sigits: {},
processedGiftWraps: []
}
}
// Return null if the encrypted data could not be retrieved
if (!encrypted) return null
// Convert the private key from hex to bytes
const secret = hexToBytes(privateKey)
// Get the public key corresponding to the private key
const pubkey = getPublicKey(secret)
// Decrypt the encrypted data using the secret and public key
const decrypted = nip44.v2.decrypt(
encrypted,
nip44ConversationKey(secret, pubkey)
)
// Parse the decrypted JSON content
const parsedContent = await parseJson<{
sigits: { [key: string]: Meta }
processedGiftWraps: string[]
}>(decrypted).catch((err) => {
// Log and display an error message if parsing fails
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 the parsed content
return parsedContent
}
/**
* Function to subscribe to sigits notifications for a specified public key.
* @param pubkey - The public key to subscribe to.
* @returns A promise that resolves when the subscription is successful.
*/
export const subscribeForSigits = async (pubkey: string) => {
// Instantiate the MetadataController to retrieve relay list metadata
const metadataController = new MetadataController()
const relaySet = await metadataController
.findRelayListMetadata(pubkey)
.catch((err) => {
// Log an error if retrieving relay list metadata fails
console.log(
`An error occurred while finding relay list metadata for ${hexToNpub(pubkey)}`,
err
)
return null
})
// Return if metadata retrieval failed
if (!relaySet) return
// Ensure relay list is not empty
if (relaySet.read.length === 0) return
// Define the filter for the subscription
const filter: Filter = {
kinds: [1059],
'#p': [pubkey]
}
// Instantiate a new SimplePool for the subscription
const pool = new SimplePool()
// Subscribe to the specified relays with the defined filter
return pool.subscribeMany(relaySet.read, [filter], {
// Define a callback function to handle received events
onevent: (event) => {
processReceivedEvent(event) // Process the received event
}
})
}
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 decrypted = await nostrController.nip44Decrypt(
event.pubkey,
event.content
)
const internalUnsignedEvent = await parseJson<UnsignedEvent>(decrypted).catch(
(err) => {
console.log(
'An error occurred in parsing the internal unsigned event',
err
)
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)
}
/**
* Function to send a notification to a specified receiver.
* @param receiver - The recipient's public key.
* @param meta - Metadata associated with the notification.
*/
export const sendNotification = async (receiver: string, meta: Meta) => {
// Retrieve the user's public key from the state
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
// Create an unsigned event object with the provided metadata
const unsignedEvent: UnsignedEvent = {
kind: 938,
pubkey: usersPubkey,
content: JSON.stringify(meta),
tags: [],
created_at: now()
}
// Wrap the unsigned event with the receiver's information
const wrappedEvent = createWrap(unsignedEvent, receiver)
// Instantiate the MetadataController to retrieve relay list metadata
const metadataController = new MetadataController()
const relaySet = await metadataController
.findRelayListMetadata(receiver)
.catch((err) => {
// Log an error if retrieving relay list metadata fails
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
console.log('Publishing notifications')
// Publish the notification event to the recipient's read relays
const nostrController = NostrController.getInstance()
// Attempt to publish the event to the relays, with a timeout of 2 minutes
await Promise.race([
nostrController.publishEvent(wrappedEvent, relaySet.read),
timeout(1000 * 30)
]).catch((err) => {
// Log an error if publishing the notification event fails
console.log(
`An error occurred while publishing notification event for ${hexToNpub(receiver)}`,
err
)
throw err
})
}

View File

@ -93,3 +93,37 @@ export const parseJson = <T>(content: string): Promise<T> => {
*/ */
export const capitalizeFirstLetter = (str: string) => export const capitalizeFirstLetter = (str: string) =>
str.charAt(0).toUpperCase() + str.slice(1).toLowerCase() 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}`
}
/**
* 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
}

View File

@ -49,3 +49,18 @@ export const isOnline = async () => {
return false // If an error occurs, return false return false // If an error occurs, return false
} }
} }
/**
* Creates a promise that rejects with a timeout error after a specified duration.
* @param ms The duration in milliseconds after which the promise should reject. Defaults to 60000 milliseconds (1 minute).
* @returns A promise that rejects with an Error('Timeout') after the specified duration.
*/
export const timeout = (ms: number = 60000) => {
return new Promise<never>((_, reject) => {
// Set a timeout using setTimeout
setTimeout(() => {
// Reject the promise with an Error indicating a timeout
reject(new Error('Timeout'))
}, ms) // Timeout duration in milliseconds
})
}