Compare commits

..

No commits in common. "70262bd5d26d5bde5d82e21fa236b273f687d8c0" and "3f944bdf73103e6a0152c32bc788d363c323f42b" have entirely different histories.

27 changed files with 854 additions and 2353 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.7.0", "nostr-tools": "2.3.1",
"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.3", "version": "3.0.2",
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
"dev": true, "dev": true,
"dependencies": { "dependencies": {
"fill-range": "^7.1.1" "fill-range": "^7.0.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.1.1", "version": "7.0.1",
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
"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.7.0", "version": "2.3.1",
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.7.0.tgz", "resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-2.3.1.tgz",
"integrity": "sha512-jJoL2J1CBiKDxaXZww27nY/Wsuxzx7AULxmGKFce4sskDu1tohNyfnzYQ8BvDyvkstU8kNZUAXPL32tre33uig==", "integrity": "sha512-qjKx2C3EzwiQOe2LPSPyCnp07pGz1pWaWjDXcm+L2y2c8iTECbvlzujDANm3nJUjWL5+LVRUVDovTZ1a/DC4Bg==",
"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.7.0", "nostr-tools": "2.3.1",
"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 { Box, IconButton, Typography, useTheme } from '@mui/material' import { Typography, IconButton, Box, 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,17 +60,10 @@ 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 }}
@ -84,19 +77,19 @@ export const UserComponent = ({ pubkey, name, image }: UserProps) => {
borderStyle: 'solid', borderStyle: 'solid',
borderColor: `#${pubkey.substring(0, 6)}` borderColor: `#${pubkey.substring(0, 6)}`
}} }}
onClick={handleClick}
/> />
<Typography <Link to={getProfileRoute(pubkey)}>
component="label" <Typography
sx={{ component="label"
textAlign: 'center', sx={{
cursor: 'pointer', textAlign: 'center',
color: theme.palette.text.primary cursor: 'pointer',
}} color: theme.palette.text.primary
onClick={handleClick} }}
> >
{name} {name}
</Typography> </Typography>
</Link>
</Box> </Box>
) )
} }

View File

@ -61,15 +61,11 @@ 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 ( if (!currentEvent || metadataEvent.created_at > currentEvent.created_at) {
!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
@ -127,11 +123,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 oneWeekInMS = 7 * 24 * 60 * 60 * 1000 // Number of milliseconds in one week const oneDayInMS = 24 * 60 * 60 * 1000 // Number of milliseconds in one day
// Check if the cached metadata is older than one week // Check if the cached metadata is older than one day
if (Date.now() - cachedMetadataEvent.cachedAt > oneWeekInMS) { if (Date.now() - cachedMetadataEvent.cachedAt > oneDayInMS) {
// If older than one week, find the metadata from relays in background // If older than one day, find the metadata from relays in background
this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event) this.checkForMoreRecentMetadata(hexKey, cachedMetadataEvent.event)
} }
@ -145,22 +141,6 @@ 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]
@ -168,38 +148,19 @@ export class MetadataController extends EventEmitter {
const pool = new SimplePool() const pool = new SimplePool()
// Try to get the relayList event from a special relay (wss://purplepag.es) let relayEvent = await pool
if (!relayEvent) { .get([this.specialMetadataRelay], eventFilter)
relayEvent = await pool .catch((err) => {
.get([this.specialMetadataRelay], eventFilter) console.error(err)
.then((event) => { return null
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,48 +2,46 @@ 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,
Filter,
Relay,
SimplePool, SimplePool,
UnsignedEvent, UnsignedEvent,
Filter,
Relay,
finalizeEvent, finalizeEvent,
kinds,
nip04, nip04,
nip19, nip19,
nip44 kinds
} 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,
updateNsecbunkerPubkey setRelayConnectionStatusAction
} 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 {
RelayConnectionState, SignedEvent,
RelayConnectionStatus,
RelayInfoObject,
RelayMap, RelayMap,
RelayReadStats,
RelayStats, RelayStats,
SignedEvent RelayReadStats,
RelayInfoObject,
RelayConnectionStatus,
RelayConnectionState
} 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
@ -58,8 +56,7 @@ export class NostrController extends EventEmitter {
} }
private getNostrObject = () => { private getNostrObject = () => {
// fix: this is not picking up type declaration from src/system/index.d.ts if (window.nostr) return window.nostr
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.`
@ -223,31 +220,29 @@ 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)
// Use Promise.race to wait for the first successful publish const results = await Promise.allSettled(promises)
const firstSuccessfulPublish = await Promise.race(
promises.map((promise, index) =>
promise.then(() => relays[index]).catch(() => null)
)
)
if (!firstSuccessfulPublish) { const publishedRelays: string[] = []
// 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({
@ -262,187 +257,7 @@ export class NostrController extends EventEmitter {
throw failedPublishes throw failedPublishes
} }
// Continue publishing to other relays in the background return publishedRelays
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')
} }
/** /**
@ -515,7 +330,7 @@ export class NostrController extends EventEmitter {
} }
} }
nip04Encrypt = async (receiver: string, content: string): Promise<string> => { nip04Encrypt = async (receiver: string, content: 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) {
@ -570,7 +385,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): Promise<string> => { nip04Decrypt = async (sender: string, content: 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,40 +1,29 @@
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 { LoadingSpinner } from '../components/LoadingSpinner' import { restoreState, setAuthState, setMetadataEvent } from '../store/actions'
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 { useAppSelector } from '../hooks' import { LoadingSpinner } from '../components/LoadingSpinner'
import { SubCloser } from 'nostr-tools/abstract-pool' import { Dispatch } from '../store/store'
import { MetadataController, NostrController } from '../controllers'
import { LoginMethods } from '../store/auth/types'
import { setUserRobotImage } from '../store/userRobotImage/action'
import { State } from '../store/rootReducer'
import { Event, kinds } from 'nostr-tools'
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()
@ -94,34 +83,12 @@ 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)
} }
setIsLoading(false)
}, [dispatch]) }, [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
})
}
}
return () => {
if (subCloser) {
subCloser.close()
}
}
}, [authState, usersAppData])
/** /**
* When authState change user logged in / or app reloaded * When authState change user logged in / or app reloaded
* we set robohash avatar in the global state based on user npub * we set robohash avatar in the global state based on user npub
@ -134,20 +101,10 @@ 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={loadingSpinnerDesc} /> if (isLoading) return <LoadingSpinner desc="Loading App" />
return ( return (
<> <>

View File

@ -18,14 +18,9 @@ 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'
@ -34,32 +29,28 @@ 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 { import { Meta, ProfileMetadata, User, UserRole } from '../../types'
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,
sendNotification, sendDM,
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()
@ -71,7 +62,7 @@ export const CreatePage = () => {
const [authUrl, setAuthUrl] = useState<string>() const [authUrl, setAuthUrl] = useState<string>()
const [title, setTitle] = useState(`sigit_${formatTimestamp(Date.now())}`) const [title, setTitle] = useState('')
const [selectedFiles, setSelectedFiles] = useState<File[]>([]) const [selectedFiles, setSelectedFiles] = useState<File[]>([])
const [userInput, setUserInput] = useState('') const [userInput, setUserInput] = useState('')
@ -84,11 +75,6 @@ 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])
@ -297,6 +283,75 @@ 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)
@ -329,13 +384,13 @@ export const CreatePage = () => {
return encryptArrayBuffer(arraybuffer, encryptionKey) return encryptArrayBuffer(arraybuffer, encryptionKey)
} }
// create final zip file for offline mode // create final zip file
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 = now() const unixNow = Math.floor(Date.now() / 1000)
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`, {
@ -375,6 +430,23 @@ 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)
@ -384,19 +456,13 @@ export const CreatePage = () => {
} }
// Upload the file to the storage // Upload the file to the storage
const uploadFile = async ( const uploadFile = async (file: File): Promise<string | null> => {
arrayBuffer: ArrayBuffer setIsLoading(true)
): Promise<string | null> => { setLoadingSpinnerDesc('Uploading sigit to file storage.')
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) const fileUrl = await uploadToFileStorage(file, nostrController)
.then((url) => { .then((url) => {
toast.success('files.zip uploaded to file storage') toast.success('Sigit uploaded to file storage')
return url return url
}) })
.catch(handleUploadError) .catch(handleUploadError)
@ -404,6 +470,36 @@ 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,
@ -419,200 +515,43 @@ 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 file hashes') setLoadingSpinnerDesc('Generating hashes for files')
const fileHashes = await generateFileHashes()
if (!fileHashes) { const fileHashes = await generateFileHashes()
setIsLoading(false) if (!fileHashes) return
return
} const createZipResponse = await createZipFile(fileHashes)
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
setLoadingSpinnerDesc('Generating encryption key')
const encryptionKey = await generateEncryptionKey() const encryptionKey = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptZipFile(
arrayBuffer,
encryptionKey
)
if (await isOnline()) { if (await isOnline()) {
setLoadingSpinnerDesc('generating files.zip') await handleOnlineFlow(encryptedArrayBuffer, encryptionKey)
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 { } 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) await handleOfflineFlow(encryptedArrayBuffer, encryptionKey)
} }
navigate(appPrivateRoutes.sign, { state: { arrayBuffer } })
} }
if (authUrl) { if (authUrl) {

View File

@ -1,38 +1,21 @@
import { CalendarMonth, Description, Upload } from '@mui/icons-material'
import { Box, Button, Tooltip, Typography } from '@mui/material'
import JSZip from 'jszip'
import { Event, kinds, verifyEvent } from 'nostr-tools'
import { Dispatch, SetStateAction, useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import { UserComponent } from '../../components/username'
import { MetadataController } from '../../controllers'
import { useAppSelector } from '../../hooks'
import { appPrivateRoutes, appPublicRoutes } from '../../routes'
import { CreateSignatureEventContent, Meta, ProfileMetadata } from '../../types'
import { import {
formatTimestamp, Add,
hexToNpub, CalendarMonth,
npubToHex, Description,
parseJson, PersonOutline,
shorten Upload
} from '../../utils' } from '@mui/icons-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 styles from './style.module.scss'
import { useRef } from 'react'
import JSZip from 'jszip'
import { toast } from 'react-toastify'
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) {
@ -81,184 +64,80 @@ export const HomePage = () => {
} }
return ( return (
<> <Box className={styles.container}>
<Box className={styles.container}> <Box className={styles.header}>
<Box className={styles.header}> <Typography variant="h3" className={styles.title}>
<Typography variant="h3" className={styles.title}> Sigits
Sigits </Typography>
</Typography> {/* This is for desktop view */}
{/* This is for desktop view */} <Box
<Box className={styles.actionButtons}
className={styles.actionButtons} sx={{
sx={{ display: {
display: { xs: 'none',
xs: 'none', md: 'flex'
md: 'flex' }
} }}
}} >
<input
type="file"
ref={fileInputRef}
style={{ display: 'none' }}
onChange={handleFileChange}
/>
<Button
variant="outlined"
startIcon={<Upload />}
onClick={handleUploadClick}
> >
<input Upload
type="file" </Button>
ref={fileInputRef} <Button
style={{ display: 'none' }} variant="contained"
onChange={handleFileChange} startIcon={<Add />}
/> onClick={() => navigate(appPrivateRoutes.create)}
>
Create
</Button>
</Box>
{/* This is for mobile view */}
<Box
className={styles.actionButtons}
sx={{
display: {
xs: 'flex',
md: 'none'
}
}}
>
<Tooltip title="Upload" arrow>
<Button <Button
variant="outlined" variant="outlined"
startIcon={<Upload />} onClick={() => navigate(appPrivateRoutes.sign)}
onClick={handleUploadClick}
> >
Upload <Upload />
</Button> </Button>
</Box> </Tooltip>
{/* This is for mobile view */} <Tooltip title="Create" arrow>
<Box <Button
className={styles.actionButtons} variant="contained"
sx={{ onClick={() => navigate(appPrivateRoutes.create)}
display: { >
xs: 'flex', <Add />
md: 'none' </Button>
} </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>
) )
} }
type SigitProps = { const PlaceHolder = () => {
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}
@ -268,11 +147,14 @@ const DisplaySigit = ({ meta, profiles, setProfiles }: SigitProps) => {
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'
@ -283,103 +165,33 @@ const DisplaySigit = ({ meta, profiles, setProfiles }: SigitProps) => {
} }
}} }}
> >
<Typography variant="body1" className={styles.title}> <Typography variant="body1" className={styles.titleBoxItem}>
<Description /> <Description />
{title} Title
</Typography> </Typography>
{submittedBy && <Typography variant="body2" className={styles.titleBoxItem}>
(function () { <PersonOutline />
const profile = profiles[submittedBy] Sigit
return ( </Typography>
<UserComponent <Typography variant="body2" className={styles.titleBoxItem}>
pubkey={submittedBy}
name={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(submittedBy))
}
image={profile?.picture}
/>
)
})()}
<Typography variant="body2" className={styles.date}>
<CalendarMonth /> <CalendarMonth />
{createdAt} 07 Jun 10:23 AM
</Typography> </Typography>
</Box> </Box>
<Box className={styles.signers}> <Box className={styles.signers}>
{signers.map((signer) => { <Box className={styles.signerItem}>
const pubkey = npubToHex(signer)! <Typography variant="button" className={styles.status}>
const profile = profiles[pubkey] Sent
</Typography>
return ( <Typography variant="body1">placeholder@sigit.io</Typography>
<DisplaySigner </Box>
key={signer} <Box className={styles.signerItem}>
meta={meta} <Typography variant="button" className={styles.status}>
profile={profile} Awaiting
pubkey={pubkey} </Typography>
/> <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,40 +28,23 @@
.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;
flex: 4; align-items: flex-start;
flex-direction: column; justify-content: space-between;
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;
.title { .titleBoxItem {
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;
@ -72,10 +55,10 @@
.signers { .signers {
display: flex; display: flex;
flex-direction: column; flex-direction: column;
flex: 6; flex: 1;
justify-content: center; justify-content: center;
gap: 10px; gap: 10px;
padding: 10px; padding: 10px 0;
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 } from 'react-router-dom' import { useLocation, useNavigate, useSearchParams } 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,19 +17,17 @@ 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,
sendNotification, sendDM,
signEventForMetaFile, signEventForMetaFile,
updateUsersAppData uploadToFileStorage
} 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'
@ -42,23 +40,16 @@ 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 [files, setFiles] = useState<{ [filename: string]: ArrayBuffer }>({}) const [zip, setZip] = useState<JSZip>()
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
@ -89,6 +80,41 @@ 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
@ -134,94 +160,43 @@ export const SignPage = () => {
}, [signers, signedBy, usersPubkey, submittedBy]) }, [signers, signedBy, usersPubkey, submittedBy])
useEffect(() => { useEffect(() => {
const handleUpdatedMeta = async (meta: Meta) => { const fileUrl = searchParams.get('file')
const createSignatureEvent = await parseJson<Event>( const key = searchParams.get('key')
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 (!createSignatureEvent) return if (fileUrl && key) {
setIsLoading(true)
setLoadingSpinnerDesc('Fetching file from file server')
const isValidCreateSignature = verifyEvent(createSignatureEvent) axios
.get(fileUrl, {
if (!isValidCreateSignature) { responseType: 'arraybuffer'
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
}) })
.then(async (res) => {
const fileName = fileUrl.split('/').pop()
const file = new File([res.data], fileName!)
if (!createSignatureContent) return const encryptedArrayBuffer = await file.arrayBuffer()
setSigners(createSignatureContent.signers) const arrayBuffer = await decryptArrayBuffer(
setViewers(createSignatureContent.viewers) encryptedArrayBuffer,
setCreatorFileHashes(createSignatureContent.fileHashes) key
setSubmittedBy(createSignatureEvent.pubkey) ).catch((err) => {
console.log('err in decryption:>> ', err)
toast.error(err.message || 'An error occurred in decrypting file.')
return null
})
setSignedBy(Object.keys(meta.docSignatures) as `npub1${string}`[]) if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer)
} })
.catch((err) => {
if (meta) { console.error(`error occurred in getting file from ${fileUrl}`, err)
handleUpdatedMeta(meta) toast.error(
} err.message || `error occurred in getting file from ${fileUrl}`
}, [meta]) )
})
useEffect(() => { .finally(() => {
if (metaInNavState) {
const processSigit = async () => {
setIsLoading(true)
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
const res = await extractZipUrlAndEncryptionKey(metaInNavState)
if (!res) {
setIsLoading(false) 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)
@ -242,63 +217,7 @@ export const SignPage = () => {
setIsLoading(false) setIsLoading(false)
setDisplayInput(true) setDisplayInput(true)
} }
}, [decryptedArrayBuffer, uploadedZip, metaInNavState]) }, [searchParams, decryptedArrayBuffer, uploadedZip])
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(
@ -406,37 +325,7 @@ export const SignPage = () => {
if (!zip) return if (!zip) return
const files: { [filename: string]: ArrayBuffer } = {} 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 (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')
@ -463,6 +352,53 @@ 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)
} }
@ -478,9 +414,23 @@ export const SignPage = () => {
} }
const handleSign = async () => { const handleSign = async () => {
if (Object.entries(files).length === 0 || !meta) return if (!zip || !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')
@ -492,14 +442,55 @@ 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(updatedMeta) await handleOnlineFlow(encryptedArrayBuffer, key)
} else { } else {
setMeta(updatedMeta) handleDecryptedArrayBuffer(arrayBuffer).finally(() => setIsLoading(false))
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(
@ -516,10 +507,40 @@ 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,
@ -595,61 +616,61 @@ export const SignPage = () => {
return null return null
} }
// Handle the online flow: update users app data and send notifications // Handle the online flow: upload file and send DMs
const handleOnlineFlow = async (meta: Meta) => { const handleOnlineFlow = async (
setLoadingSpinnerDesc('Updating users app data') encryptedArrayBuffer: ArrayBuffer,
const updatedEvent = await updateUsersAppData(meta) encryptionKey: string
if (!updatedEvent) { ) => {
setIsLoading(false) const unixNow = Math.floor(Date.now() / 1000)
return 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 userSet = new Set<`npub1${string}`>() const fileUrl = await uploadFile(file)
if (submittedBy && submittedBy !== usersPubkey) { if (!fileUrl) return
userSet.add(hexToNpub(submittedBy))
}
const usersNpub = hexToNpub(usersPubkey!)
const isLastSigner = checkIsLastSigner(signers) const isLastSigner = checkIsLastSigner(signers)
if (isLastSigner) { if (isLastSigner) {
signers.forEach((signer) => { await sendDMToAllUsers(fileUrl, encryptionKey)
if (signer !== usersNpub) {
userSet.add(signer)
}
})
viewers.forEach((viewer) => {
userSet.add(viewer)
})
} else { } else {
const currentSignerIndex = signers.indexOf(usersNpub) await sendDMToNextSigner(fileUrl, encryptionKey)
const prevSigners = signers.slice(0, currentSignerIndex)
prevSigners.forEach((signer) => {
userSet.add(signer)
})
const nextSigner = signers[currentSignerIndex + 1]
userSet.add(nextSigner)
} }
setLoadingSpinnerDesc('Sending notifications') // update search params with updated file url and encryption key
const users = Array.from(userSet) setSearchParams({
const promises = users.map((user) => file: fileUrl,
sendNotification(npubToHex(user)!, meta) key: encryptionKey
) })
await Promise.all(promises)
.then(() => {
toast.success('Notifications sent successfully')
setMeta(meta)
})
.catch(() => {
toast.error('Failed to publish notifications')
})
setIsLoading(false) setIsLoading(false)
} }
// Handle errors during file upload
const handleUploadError = (err: any) => {
console.log('Error in upload:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in uploading file')
return null
}
// Upload the file to file storage
const uploadFile = async (file: File): Promise<string | null> => {
setIsLoading(true)
setLoadingSpinnerDesc('Uploading sigit file to file storage.')
const fileUrl = await uploadToFileStorage(file, nostrController)
.then((url) => {
toast.success('Sigit uploaded to file storage')
return url
})
.catch(handleUploadError)
return fileUrl
}
// Check if the current user is the last signer // Check if the current user is the last signer
const checkIsLastSigner = (signers: string[]): boolean => { const checkIsLastSigner = (signers: string[]): boolean => {
const usersNpub = hexToNpub(usersPubkey!) const usersNpub = hexToNpub(usersPubkey!)
@ -658,8 +679,53 @@ 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 (Object.entries(files).length === 0 || !meta || !usersPubkey) return if (!meta || !zip || !usersPubkey) return
const usersNpub = hexToNpub(usersPubkey) const usersNpub = hexToNpub(usersPubkey)
if ( if (
@ -672,7 +738,7 @@ export const SignPage = () => {
setIsLoading(true) setIsLoading(true)
setLoadingSpinnerDesc('Signing nostr event') setLoadingSpinnerDesc('Signing nostr event')
const prevSig = getLastSignersSig() const prevSig = await getLastSignersSig()
if (!prevSig) return if (!prevSig) return
const signedEvent = await signEventForMetaFile( const signedEvent = await signEventForMetaFile(
@ -695,15 +761,8 @@ 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',
@ -731,17 +790,7 @@ export const SignPage = () => {
} }
const handleExportSigit = async () => { const handleExportSigit = async () => {
if (Object.entries(files).length === 0 || !meta) return if (!zip) 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({
@ -876,11 +925,11 @@ export const SignPage = () => {
</> </>
)} )}
{submittedBy && Object.entries(files).length > 0 && meta && ( {submittedBy && zip && meta && (
<> <>
<DisplayMeta <DisplayMeta
meta={meta} meta={meta}
files={files} zip={zip}
submittedBy={submittedBy} submittedBy={submittedBy}
signers={signers} signers={signers}
viewers={viewers} viewers={viewers}
@ -907,6 +956,7 @@ 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,3 +1,4 @@
import JSZip from 'jszip'
import { import {
Meta, Meta,
ProfileMetadata, ProfileMetadata,
@ -32,12 +33,18 @@ 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 { npubToHex, shorten, hexToNpub, parseJson } from '../../../utils' import {
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
files: { [filename: string]: ArrayBuffer } zip: JSZip
submittedBy: string submittedBy: string
signers: `npub1${string}`[] signers: `npub1${string}`[]
viewers: `npub1${string}`[] viewers: `npub1${string}`[]
@ -50,7 +57,7 @@ type DisplayMetaProps = {
export const DisplayMeta = ({ export const DisplayMeta = ({
meta, meta,
files, zip,
submittedBy, submittedBy,
signers, signers,
viewers, viewers,
@ -143,7 +150,11 @@ export const DisplayMeta = ({
}, [users, submittedBy]) }, [users, submittedBy])
const downloadFile = async (filename: string) => { const downloadFile = async (filename: string) => {
const arrayBuffer = files[filename] const arrayBuffer = await readContentOfZipEntry(
zip,
`files/${filename}`,
'arraybuffer'
)
if (!arrayBuffer) return if (!arrayBuffer) return
const blob = new Blob([arrayBuffer]) const blob = new Blob([arrayBuffer])

View File

@ -23,8 +23,6 @@ import {
SignedEventContent SignedEventContent
} from '../../types' } from '../../types'
import { import {
decryptArrayBuffer,
extractZipUrlAndEncryptionKey,
getHash, getHash,
hexToNpub, hexToNpub,
npubToHex, npubToHex,
@ -35,7 +33,6 @@ 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()
@ -44,16 +41,13 @@ 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>()
@ -74,106 +68,43 @@ export const VerifyPage = () => {
useEffect(() => { useEffect(() => {
if (uploadedZip) { if (uploadedZip) {
setSelectedFile(uploadedZip) setSelectedFile(uploadedZip)
} else if (metaInNavState) { }
const processSigit = async () => { }, [uploadedZip])
setIsLoading(true)
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
const res = await extractZipUrlAndEncryptionKey(metaInNavState) useEffect(() => {
if (!res) { if (zip) {
setIsLoading(false) const generateCurrentFileHashes = async () => {
return 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
}
} }
const { setCurrentFileHashes(fileHashes)
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)
})
} }
processSigit() generateCurrentFileHashes()
} }
}, [uploadedZip, metaInNavState]) }, [zip])
useEffect(() => { useEffect(() => {
if (submittedBy) { if (submittedBy) {
@ -228,34 +159,7 @@ 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,31 +1,21 @@
import { IDBPDatabase, openDB } from 'idb' import { IDBPDatabase, openDB } from 'idb'
import { Event } from 'nostr-tools' import { Event } from 'nostr-tools'
import { CachedEvent } from '../../types' import { CachedMetadataEvent } from '../../types'
import { SchemaV2 } from './schema' import { SchemaV1 } 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<SchemaV2> private db!: IDBPDatabase<SchemaV1>
// 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<SchemaV2>('sigit-cache', 2, { this.db = await openDB<SchemaV1>('sigit-cache', 1, {
upgrade(db, oldVersion) { upgrade(db) {
if (oldVersion < 1) { db.createObjectStore('userMetadata', { keyPath: 'event.pubkey' })
db.createObjectStore('userMetadata', { keyPath: 'event.pubkey' })
}
if (oldVersion < 2) {
const v6 = db as unknown as IDBPDatabase<SchemaV2>
v6.createObjectStore('userRelayListMetadata', {
keyPath: 'event.pubkey'
})
}
} }
}) })
} }
@ -47,7 +37,9 @@ class LocalCache {
} }
// Method to get user metadata by key // Method to get user metadata by key
public async getUserMetadata(key: string): Promise<CachedEvent | null> { public async getUserMetadata(
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
} }
@ -57,21 +49,6 @@ 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,16 +1,9 @@
import { DBSchema } from 'idb' import { DBSchema } from 'idb'
import { CachedEvent } from '../../types' import { CachedMetadataEvent } from '../../types'
export interface SchemaV1 extends DBSchema { export interface SchemaV1 extends DBSchema {
userMetadata: { userMetadata: {
key: string key: string
value: CachedEvent value: CachedMetadataEvent
}
}
export interface SchemaV2 extends SchemaV1 {
userRelayListMetadata: {
key: string
value: CachedEvent
} }
} }

View File

@ -17,6 +17,3 @@ 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,7 +4,6 @@ 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,29 +1,25 @@
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 relaysReducer from './relays/reducer'
import { RelaysState } from './relays/types'
import UserAppDataReducer from './userAppData/reducer'
import userRobotImageReducer from './userRobotImage/reducer' import userRobotImageReducer from './userRobotImage/reducer'
import { RelaysState } from './relays/types'
import relaysReducer from './relays/reducer'
import * as ActionTypes from './actionTypes'
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

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

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

@ -1,18 +0,0 @@
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 CachedEvent { export interface CachedMetadataEvent {
event: Event event: Event
cachedAt: number cachedAt: number
} }

View File

@ -1,5 +1,3 @@
import { Keys } from '../store/auth/types'
export enum UserRole { export enum UserRole {
signer = 'Signer', signer = 'Signer',
viewer = 'Viewer' viewer = 'Viewer'
@ -11,33 +9,18 @@ export interface User {
} }
export interface Meta { export interface Meta {
modifiedAt: number title: string
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
}

View File

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

View File

@ -1,21 +1,13 @@
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 { NostrController } from '../controllers' import { appPrivateRoutes } from '../routes'
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.
@ -23,7 +15,13 @@ import { hexToBytes } from '@noble/hashes/utils'
* @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 (file: File) => { export const uploadToFileStorage = async (
file: File,
nostrController: NostrController
) => {
// Get the current timestamp in seconds
const unixNow = Math.floor(Date.now() / 1000)
// Define event metadata for authorization // Define event metadata for authorization
const event: EventTemplate = { const event: EventTemplate = {
kind: 24242, kind: 24242,
@ -31,21 +29,14 @@ export const uploadToFileStorage = async (file: File) => {
created_at: Math.floor(Date.now() / 1000), created_at: Math.floor(Date.now() / 1000),
tags: [ tags: [
['t', 'upload'], ['t', 'upload'],
['expiration', String(now() + 60 * 5)], // Set expiration time to 5 minutes from now ['expiration', String(unixNow + 60 * 5)], // Set expiration time to 5 minutes from now
['name', file.name], ['name', file.name],
['size', String(file.size)] ['size', String(file.size)]
] ]
} }
const key = store.getState().userAppData?.keyPair?.private // Sign the authorization event using the NostrController
if (!key) { const authEvent = await nostrController.signEvent(event)
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
@ -62,6 +53,128 @@ export const uploadToFileStorage = async (file: File) => {
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.
@ -79,7 +192,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: [['-']] // For understanding why "-" tag is used here see: https://github.com/nostr-protocol/nips/blob/protected-events-tag/70.md tags: []
} }
// Sign the event // Sign the event
@ -141,126 +254,3 @@ 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,35 +1,7 @@
import { bytesToHex, hexToBytes } from '@noble/hashes/utils' import { nip19, verifyEvent } from 'nostr-tools'
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
@ -209,710 +181,3 @@ 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,37 +93,3 @@ 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,18 +49,3 @@ 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
})
}