issue-38 #62

Closed
y wants to merge 48 commits from issue-38 into main
46 changed files with 2314 additions and 1044 deletions

View File

@ -1 +1 @@
VITE_MOST_POPULAR_RELAYS=wss://relay.damus.io wss://eden.nostr.land wss://nos.lol wss://relay.snort.social wss://relay.current.fyi wss://brb.io wss://nostr.orangepill.dev wss://nostr-pub.wellorder.net wss://nostr.bitcoiner.social wss://nostr.wine wss://nostr.oxtr.dev wss://relay.nostr.bg wss://nostr.mom wss://nostr.fmt.wiz.biz wss://relay.nostr.band wss://nostr-pub.semisol.dev wss://nostr.milou.lol wss://puravida.nostr.land wss://nostr.onsats.org wss://relay.nostr.info wss://offchain.pub wss://relay.orangepill.dev wss://no.str.cr wss://atlas.nostr.land wss://nostr.zebedee.cloud wss://nostr-relay.wlvs.space wss://relay.nostrati.com wss://relay.nostr.com.au wss://nostr.inosta.cc wss://nostr.rocks
VITE_MOST_POPULAR_RELAYS=wss://relay.damus.io wss://eden.nostr.land wss://nos.lol wss://relay.snort.social wss://relay.current.fyi wss://brb.io wss://nostr.orangepill.dev wss://nostr-pub.wellorder.net wss://nostr.wine wss://nostr.oxtr.dev wss://relay.nostr.bg wss://nostr.mom wss://nostr.fmt.wiz.biz wss://relay.nostr.band wss://nostr-pub.semisol.dev wss://nostr.milou.lol wss://puravida.nostr.land wss://nostr.onsats.org wss://relay.nostr.info wss://offchain.pub wss://relay.orangepill.dev wss://no.str.cr wss://atlas.nostr.land wss://nostr.zebedee.cloud wss://nostr-relay.wlvs.space wss://relay.nostrati.com wss://relay.nostr.com.au wss://nostr.inosta.cc wss://nostr.rocks

158
package-lock.json generated
View File

@ -13,17 +13,21 @@
"@mui/icons-material": "5.15.11",
"@mui/lab": "5.0.0-alpha.166",
"@mui/material": "5.15.11",
"@noble/hashes": "^1.4.0",
"@nostr-dev-kit/ndk": "2.5.0",
"@reduxjs/toolkit": "2.2.1",
"axios": "1.6.7",
"crypto-hash": "3.0.0",
"crypto-js": "^4.2.0",
"dnd-core": "16.0.1",
"file-saver": "2.0.5",
"jszip": "3.10.1",
"lodash": "4.17.21",
"mui-file-input": "4.0.4",
"nostr-tools": "2.3.1",
"react": "^18.2.0",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
"react-dom": "^18.2.0",
"react-redux": "9.1.0",
"react-router-dom": "6.22.1",
@ -43,6 +47,7 @@
"eslint": "^8.56.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"prettier": "3.2.5",
"ts-css-modules-vite-plugin": "1.0.20",
"typescript": "^5.2.2",
"vite": "^5.1.4"
@ -1505,9 +1510,9 @@
}
},
"node_modules/@noble/hashes": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz",
"integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==",
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.4.0.tgz",
"integrity": "sha512-V1JJ1WTRUqHHrOSh597hURcMqVKVGL/ea3kv0gSnEdsEZ0/+VyPghM1lMNGc00z7CIQorSvbKpuJkxvuHbvdbg==",
"engines": {
"node": ">= 16"
},
@ -1598,6 +1603,17 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nostr-dev-kit/ndk/node_modules/@noble/hashes": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz",
"integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==",
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@nostr-dev-kit/ndk/node_modules/nostr-tools": {
"version": "1.17.0",
"resolved": "https://registry.npmjs.org/nostr-tools/-/nostr-tools-1.17.0.tgz",
@ -1628,6 +1644,21 @@
"url": "https://opencollective.com/popperjs"
}
},
"node_modules/@react-dnd/asap": {
"version": "5.0.2",
"resolved": "https://registry.npmjs.org/@react-dnd/asap/-/asap-5.0.2.tgz",
"integrity": "sha512-WLyfoHvxhs0V9U+GTsGilGgf2QsPl6ZZ44fnv0/b8T3nQyvzxidxsg/ZltbWssbsRDlYW8UKSQMTGotuTotZ6A=="
},
"node_modules/@react-dnd/invariant": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@react-dnd/invariant/-/invariant-4.0.2.tgz",
"integrity": "sha512-xKCTqAK/FFauOM9Ta2pswIyT3D8AQlfrYdOi/toTPEhqCuAs1v5tcJ3Y08Izh1cJ5Jchwy9SeAXmMg6zrKs2iw=="
},
"node_modules/@react-dnd/shallowequal": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@react-dnd/shallowequal/-/shallowequal-4.0.2.tgz",
"integrity": "sha512-/RVXdLvJxLg4QKvMoM5WlwNR9ViO9z8B/qPcc+C0Sa/teJY7QG7kJ441DwzOjMYEY7GmU4dj5EcGHIkKZiQZCA=="
},
"node_modules/@reduxjs/toolkit": {
"version": "2.2.1",
"resolved": "https://registry.npmjs.org/@reduxjs/toolkit/-/toolkit-2.2.1.tgz",
@ -1863,6 +1894,28 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/bip32/node_modules/@noble/curves/node_modules/@noble/hashes": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz",
"integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==",
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/bip32/node_modules/@noble/hashes": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.3.tgz",
"integrity": "sha512-V7/fPHgl+jsVPXqqeOzT8egNj2iBIVt+ECeMMG8TdcnTikP3oaBtUVqpT/gYCR68aEBJSF+XbYUxStjbFMqIIA==",
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/bip39": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/@scure/bip39/-/bip39-1.2.1.tgz",
@ -1875,6 +1928,17 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@scure/bip39/node_modules/@noble/hashes": {
"version": "1.3.3",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.3.tgz",
"integrity": "sha512-V7/fPHgl+jsVPXqqeOzT8egNj2iBIVt+ECeMMG8TdcnTikP3oaBtUVqpT/gYCR68aEBJSF+XbYUxStjbFMqIIA==",
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@tsconfig/node10": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz",
@ -1974,7 +2038,7 @@
"version": "20.11.20",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.11.20.tgz",
"integrity": "sha512-7/rR21OS+fq8IyHTgtLkDK949uzsa6n8BkziAKtPVpugIkO6D+/ooXMvzXxDnZrmtXVfjb1bKQafYpb8s89LOg==",
"dev": true,
"devOptional": true,
"peer": true,
"dependencies": {
"undici-types": "~5.26.4"
@ -2716,6 +2780,24 @@
"node": ">=8"
}
},
"node_modules/dnd-core": {
"version": "16.0.1",
"resolved": "https://registry.npmjs.org/dnd-core/-/dnd-core-16.0.1.tgz",
"integrity": "sha512-HK294sl7tbw6F6IeuK16YSBUoorvHpY8RHO+9yFfaJyCDVb6n7PRcezrOEOa2SBCqiYpemh5Jx20ZcjKdFAVng==",
"dependencies": {
"@react-dnd/asap": "^5.0.1",
"@react-dnd/invariant": "^4.0.1",
"redux": "^4.2.0"
}
},
"node_modules/dnd-core/node_modules/redux": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-4.2.1.tgz",
"integrity": "sha512-LAUYz4lc+Do8/g7aeRa8JkyDErK6ekstQaqWQrNRW//MY1TvCEpMtpTWvlQ+FPbWCx+Xixu/6SHt5N0HR+SB4w==",
"dependencies": {
"@babel/runtime": "^7.9.2"
}
},
"node_modules/doctrine": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/doctrine/-/doctrine-3.0.0.tgz",
@ -3166,8 +3248,7 @@
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",
"dev": true
"integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="
},
"node_modules/fast-glob": {
"version": "3.3.2",
@ -4027,6 +4108,17 @@
}
}
},
"node_modules/nostr-tools/node_modules/@noble/hashes": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.1.tgz",
"integrity": "sha512-EbqwksQwz9xDRGfDST86whPBgM65E0OH/pCgqW0GBVzO22bNE+NuIbeTb714+IfSjU3aRk47EUvXIb5bTsenKA==",
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/nostr-wasm": {
"version": "0.1.0",
"resolved": "https://registry.npmjs.org/nostr-wasm/-/nostr-wasm-0.1.0.tgz",
@ -4244,6 +4336,21 @@
"node": ">= 0.8.0"
}
},
"node_modules/prettier": {
"version": "3.2.5",
"resolved": "https://registry.npmjs.org/prettier/-/prettier-3.2.5.tgz",
"integrity": "sha512-3/GWa9aOC0YeD7LUfvOG2NiDyhOWRvt1k+rcKhOuYnMY24iiCphgneUfJDyFXd6rZCAnuLBv6UeAULtrhT/F4A==",
"dev": true,
"bin": {
"prettier": "bin/prettier.cjs"
},
"engines": {
"node": ">=14"
},
"funding": {
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
"node_modules/pretty-bytes": {
"version": "6.1.1",
"resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-6.1.1.tgz",
@ -4320,6 +4427,43 @@
"node": ">=0.10.0"
}
},
"node_modules/react-dnd": {
"version": "16.0.1",
"resolved": "https://registry.npmjs.org/react-dnd/-/react-dnd-16.0.1.tgz",
"integrity": "sha512-QeoM/i73HHu2XF9aKksIUuamHPDvRglEwdHL4jsp784BgUuWcg6mzfxT0QDdQz8Wj0qyRKx2eMg8iZtWvU4E2Q==",
"dependencies": {
"@react-dnd/invariant": "^4.0.1",
"@react-dnd/shallowequal": "^4.0.1",
"dnd-core": "^16.0.1",
"fast-deep-equal": "^3.1.3",
"hoist-non-react-statics": "^3.3.2"
},
"peerDependencies": {
"@types/hoist-non-react-statics": ">= 3.3.1",
"@types/node": ">= 12",
"@types/react": ">= 16",
"react": ">= 16.14"
},
"peerDependenciesMeta": {
"@types/hoist-non-react-statics": {
"optional": true
},
"@types/node": {
"optional": true
},
"@types/react": {
"optional": true
}
}
},
"node_modules/react-dnd-html5-backend": {
"version": "16.0.1",
"resolved": "https://registry.npmjs.org/react-dnd-html5-backend/-/react-dnd-html5-backend-16.0.1.tgz",
"integrity": "sha512-Wu3dw5aDJmOGw8WjH1I1/yTH+vlXEL4vmjk5p+MHxP8HuHJS1lAGeIdG/hze1AvNeXWo/JgULV87LyQOr+r5jw==",
"dependencies": {
"dnd-core": "^16.0.1"
}
},
"node_modules/react-dom": {
"version": "18.2.0",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.2.0.tgz",
@ -4917,7 +5061,7 @@
"version": "5.26.5",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz",
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
"dev": true,
"devOptional": true,
"peer": true
},
"node_modules/update-browserslist-db": {

View File

@ -9,8 +9,8 @@
"build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"lint:fix": "eslint . --fix --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"formatter:check": "npx prettier --check \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"formatter:fix": "npx prettier --write \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"formatter:check": "prettier --check \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"formatter:fix": "prettier --write \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"preview": "vite preview"
},
"dependencies": {
@ -19,17 +19,21 @@
"@mui/icons-material": "5.15.11",
"@mui/lab": "5.0.0-alpha.166",
"@mui/material": "5.15.11",
"@noble/hashes": "^1.4.0",
"@nostr-dev-kit/ndk": "2.5.0",
"@reduxjs/toolkit": "2.2.1",
"axios": "1.6.7",
"crypto-hash": "3.0.0",
"crypto-js": "^4.2.0",
"dnd-core": "16.0.1",
"file-saver": "2.0.5",
"jszip": "3.10.1",
"lodash": "4.17.21",
"mui-file-input": "4.0.4",
"nostr-tools": "2.3.1",
"react": "^18.2.0",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
"react-dom": "^18.2.0",
"react-redux": "9.1.0",
"react-router-dom": "6.22.1",
@ -49,6 +53,7 @@
"eslint": "^8.56.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"prettier": "3.2.5",
"ts-css-modules-vite-plugin": "1.0.20",
"typescript": "^5.2.2",
"vite": "^5.1.4"

View File

@ -33,6 +33,14 @@ const App = () => {
}
}
const handleRootRedirect = () => {
if (authState.loggedIn) return appPrivateRoutes.homePage
const callbackPathEncoded = btoa(
window.location.href.split(`${window.location.origin}/#`)[1]
)
return `${appPublicRoutes.login}?callbackPath=${callbackPathEncoded}`
}
return (
<Routes>
<Route element={<MainLayout />}>
@ -66,18 +74,7 @@ const App = () => {
}
})}
<Route
path="*"
element={
<Navigate
to={
authState.loggedIn
? appPrivateRoutes.homePage
: appPublicRoutes.login
}
/>
}
/>
<Route path="*" element={<Navigate to={handleRootRedirect()} />} />
</Route>
</Routes>
)

View File

@ -10,21 +10,28 @@ import {
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { setAuthState } from '../../store/actions'
import { setAuthState, setMetadataEvent } from '../../store/actions'
import { State } from '../../store/rootReducer'
import { Dispatch } from '../../store/store'
import Username from '../username'
import { Link, useNavigate } from 'react-router-dom'
import nostrichAvatar from '../../assets/images/avatar.png'
import { NostrController } from '../../controllers'
import { appPublicRoutes, getProfileRoute } from '../../routes'
import {
appPrivateRoutes,
appPublicRoutes,
getProfileRoute
} from '../../routes'
import { MetadataController, NostrController } from '../../controllers'
import {
clearAuthToken,
clearState,
saveNsecBunkerDelegatedKey,
shorten
} from '../../utils'
import styles from './style.module.scss'
import { setUserRobotImage } from '../../store/userRobotImage/action'
const metadataController = new MetadataController()
export const AppBar = () => {
const navigate = useNavigate()
@ -32,21 +39,31 @@ export const AppBar = () => {
const dispatch: Dispatch = useDispatch()
const [username, setUsername] = useState('')
const [userAvatar, setUserAvatar] = useState(nostrichAvatar)
const [userAvatar, setUserAvatar] = useState('')
const [anchorElUser, setAnchorElUser] = useState<null | HTMLElement>(null)
const authState = useSelector((state: State) => state.auth)
const metadataState = useSelector((state: State) => state.metadata)
const userRobotImage = useSelector((state: State) => state.userRobotImage)
useEffect(() => {
if (metadataState && metadataState.content) {
const { picture, display_name, name } = JSON.parse(metadataState.content)
if (metadataState) {
if (metadataState.content) {
const { picture, display_name, name } = JSON.parse(
metadataState.content
)
if (picture) setUserAvatar(picture)
if (picture || userRobotImage) {
setUserAvatar(picture || userRobotImage)
}
setUsername(shorten(display_name || name || '', 7))
setUsername(shorten(display_name || name || '', 7))
} else {
setUserAvatar(userRobotImage || '')
setUsername('')
}
}
}, [metadataState])
}, [metadataState, userRobotImage])
const handleOpenUserMenu = (event: React.MouseEvent<HTMLElement>) => {
setAnchorElUser(event.currentTarget)
@ -67,15 +84,19 @@ export const AppBar = () => {
handleCloseUserMenu()
dispatch(
setAuthState({
keyPair: undefined,
loggedIn: false,
usersPubkey: undefined,
loginMethod: undefined,
nsecBunkerPubkey: undefined
})
)
dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent()))
dispatch(setUserRobotImage(null))
// clear authToken saved in local storage
clearAuthToken()
clearState()
// update nsecBunker delegated key after logout
const nostrController = NostrController.getInstance()
@ -143,6 +164,16 @@ export const AppBar = () => {
>
Profile
</MenuItem>
<MenuItem
onClick={() => {
navigate(appPrivateRoutes.relays)
}}
sx={{
justifyContent: 'center'
}}
>
Relays
</MenuItem>
<Link
to={appPublicRoutes.help}
target="_blank"

View File

@ -1,6 +1,9 @@
import { Typography, IconButton } from '@mui/material'
import { Typography, IconButton, Box, useTheme } from '@mui/material'
import { useSelector } from 'react-redux'
import { State } from '../store/rootReducer'
import { hexToNpub } from '../utils'
import { Link } from 'react-router-dom'
import { getProfileRoute } from '../routes'
type Props = {
username: string
@ -44,3 +47,47 @@ const Username = ({ username, avatarContent, handleClick }: Props) => {
}
export default Username
type UserProps = {
pubkey: string
name: string
image?: string
}
/**
* This component will be used for the displaying username and profile picture.
* If image is not available, robohash image will be displayed
*/
export const UserComponent = ({ pubkey, name, image }: UserProps) => {
const theme = useTheme()
const npub = hexToNpub(pubkey)
const roboImage = `https://robohash.org/${npub}.png?set=set3`
return (
<Box sx={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
<img
src={image || roboImage}
alt="User Image"
className="profile-image"
style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${pubkey.substring(0, 6)}`
}}
/>
<Link to={getProfileRoute(pubkey)}>
<Typography
component="label"
sx={{
textAlign: 'center',
cursor: 'pointer',
color: theme.palette.text.primary
}}
>
{name}
</Typography>
</Link>
</Box>
)
}

View File

@ -1,13 +1,18 @@
import { EventTemplate } from 'nostr-tools'
import { MetadataController, NostrController } from '.'
import { setAuthState, setMetadataEvent } from '../store/actions'
import {
setAuthState,
setMetadataEvent,
setRelayMapAction
} from '../store/actions'
import store from '../store/store'
import {
base64DecodeAuthToken,
base64EncodeSignedEvent,
getAuthToken,
getVisitedLink,
saveAuthToken
saveAuthToken,
compareObjects
} from '../utils'
import { appPrivateRoutes } from '../routes'
import { SignedEvent } from '../types'
@ -30,14 +35,22 @@ export class AuthController {
* @returns url to redirect if authentication successfull
* or error if otherwise
*/
async authenticateAndFindMetadata(pubkey: string) {
async authAndGetMetadataAndRelaysMap(pubkey: string) {
const emptyMetadata = this.metadataController.getEmptyMetadataEvent()
this.metadataController
.findMetadata(pubkey)
.then((event) => {
store.dispatch(setMetadataEvent(event))
if (event) {
store.dispatch(setMetadataEvent(event))
} else {
store.dispatch(setMetadataEvent(emptyMetadata))
}
})
.catch((err) => {
console.error('Error occurred while finding metadata', err)
console.warn('Error occurred while finding metadata', err)
store.dispatch(setMetadataEvent(emptyMetadata))
})
// Nostr uses unix timestamps
@ -61,6 +74,27 @@ export class AuthController {
})
)
const relaysState = store.getState().relays
if (relaysState) {
// Relays state is defined and there is no need to await for the latest relay map
this.nostrController.getRelayMap(pubkey).then((relayMap) => {
if (!compareObjects(relaysState?.map, relayMap)) {
store.dispatch(setRelayMapAction(relayMap.map))
}
})
} else {
// Relays state is not defined, await for the latest relay map
const relayMap = await this.nostrController.getRelayMap(pubkey)
if (Object.keys(relayMap).length < 1) {
// Navigate user to relays page
return Promise.resolve(appPrivateRoutes.relays)
}
store.dispatch(setRelayMapAction(relayMap.map))
}
const visitedLink = getVisitedLink()
if (visitedLink) {

View File

@ -23,6 +23,18 @@ export class MetadataController {
this.nostrController = NostrController.getInstance()
}
public getEmptyMetadataEvent = (): Event => {
return {
content: '',
created_at: new Date().valueOf(),
id: '',
kind: 0,
pubkey: '',
sig: '',
tags: []
}
}
public findMetadata = async (hexKey: string) => {
const eventFilter: Filter = {
kinds: [kinds.Metadata],
@ -130,6 +142,7 @@ export class MetadataController {
public extractProfileMetadataContent = (event: VerifiedEvent) => {
try {
if (!event.content) return {}
return JSON.parse(event.content) as ProfileMetadata
} catch (error) {
console.log('error in parsing metadata event content :>> ', error)

View File

@ -9,20 +9,23 @@ import {
Event,
EventTemplate,
SimplePool,
Filter,
UnsignedEvent,
finalizeEvent,
nip04,
nip19
nip19,
kinds
} from 'nostr-tools'
import { EventEmitter } from 'tseep'
import { updateNsecbunkerPubkey } from '../store/actions'
import { AuthState, LoginMethods } from '../store/auth/types'
import store from '../store/store'
import { SignedEvent } from '../types'
import { SignedEvent, RelayMap } from '../types'
import { getNsecBunkerDelegatedKey, verifySignedEvent } from '../utils'
export class NostrController extends EventEmitter {
private static instance: NostrController
private specialMetadataRelay = 'wss://purplepag.es'
private bunkerNDK: NDK | undefined
private remoteSigner: NDKNip46Signer | undefined
@ -216,12 +219,16 @@ export class NostrController extends EventEmitter {
if (publishedRelays.length === 0) {
const failedPublishes: any[] = []
const fallbackRejectionReason =
'Attempt to publish an event has been rejected with unknown reason.'
results.forEach((res, index) => {
if (res.status === 'rejected') {
failedPublishes.push({
relay: relays[index],
error: res.reason.message
error: res.reason
? res.reason.message || fallbackRejectionReason
: fallbackRejectionReason
})
}
})
@ -319,15 +326,18 @@ export class NostrController extends EventEmitter {
}
if (loginMethod === LoginMethods.privateKey) {
const keyPair = (store.getState().auth as AuthState).keyPair
const keys = (store.getState().auth as AuthState).keyPair
if (!keyPair) {
if (!keys) {
throw new Error(
`Login method is ${LoginMethods.privateKey} but private & public key pair is not found.`
)
}
const encrypted = await nip04.encrypt(keyPair.private, receiver, content)
const { private: nsec } = keys
const privateKey = nip19.decode(nsec).data as Uint8Array
const encrypted = await nip04.encrypt(privateKey, receiver, content)
return encrypted
}
@ -364,6 +374,110 @@ export class NostrController extends EventEmitter {
return Promise.resolve(pubKey)
}
/**
* Provides relay map.
* @param npub - user's npub
* @returns - promise that resolves into relay map and a timestamp when it has been updated.
*/
getRelayMap = async (
npub: string
): Promise<{ map: RelayMap; mapUpdated: number }> => {
const mostPopularRelays = import.meta.env.VITE_MOST_POPULAR_RELAYS
const hardcodedPopularRelays = (mostPopularRelays || '').split(' ')
const popularRelayURIs = [
this.specialMetadataRelay,
...hardcodedPopularRelays
]
const pool = new SimplePool()
// More info about this kind of event available https://github.com/nostr-protocol/nips/blob/master/65.md
const eventFilter: Filter = {
kinds: [kinds.RelayList],
authors: [npub]
}
const event = await pool.get(popularRelayURIs, eventFilter).catch((err) => {
return Promise.reject(err)
})
if (event) {
// Handle founded 10002 event
const relaysMap: RelayMap = {}
// 'r' stands for 'relay'
const relayTags = event.tags.filter((tag) => tag[0] === 'r')
relayTags.forEach((tag) => {
const uri = tag[1]
const relayType = tag[2]
// if 3rd element of relay tag is undefined, relay is WRITE and READ
relaysMap[uri] = {
write: relayType ? relayType === 'write' : true,
read: relayType ? relayType === 'read' : true
}
})
return Promise.resolve({ map: relaysMap, mapUpdated: event.created_at })
} else {
return Promise.reject('User relays were not found.')
}
}
/**
* Publishes relay map.
* @param relayMap - relay map.
* @param npub - user's npub.
* @returns - promise that resolves into a string representing publishing result.
*/
publishRelayMap = async (
relayMap: RelayMap,
npub: string
): Promise<string> => {
const timestamp = Math.floor(Date.now() / 1000)
const relayURIs = Object.keys(relayMap)
// More info about this kind of event available https://github.com/nostr-protocol/nips/blob/master/65.md
const tags: string[][] = relayURIs.map((relayURI) =>
[
'r',
relayURI,
relayMap[relayURI].read && relayMap[relayURI].write
? ''
: relayMap[relayURI].write
? 'write'
: 'read'
].filter((value) => value !== '')
)
const newRelayMapEvent: UnsignedEvent = {
kind: kinds.RelayList,
tags,
content: '',
pubkey: npub,
created_at: timestamp
}
const signedEvent = await this.signEvent(newRelayMapEvent)
let relaysToPublish = relayURIs
// If relay map is empty, use most popular relay URIs
if (!relaysToPublish.length) {
const mostPopularRelays = import.meta.env.VITE_MOST_POPULAR_RELAYS
const hardcodedPopularRelays = (mostPopularRelays || '').split(' ')
relaysToPublish = [this.specialMetadataRelay, ...hardcodedPopularRelays]
}
await this.publishEvent(signedEvent, relaysToPublish)
return Promise.resolve(
`Relay Map published on: ${relaysToPublish.join('\n')}`
)
}
/**
* Generates NDK Private Signer
* @returns nSecBunker delegated key

1
src/hooks/index.ts Normal file
View File

@ -0,0 +1 @@
export * from './store'

6
src/hooks/store.ts Normal file
View File

@ -0,0 +1,6 @@
import { useDispatch, useSelector } from 'react-redux'
import type { Dispatch, RootState } from '../store/store'
// Use instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = useDispatch.withTypes<Dispatch>()
export const useAppSelector = useSelector.withTypes<RootState>()

View File

@ -1,24 +1,36 @@
import { Box } from '@mui/material'
import Container from '@mui/material/Container'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useDispatch, useSelector } from 'react-redux'
import { Outlet } from 'react-router-dom'
import { AppBar } from '../components/AppBar/AppBar'
import { restoreState, setAuthState } from '../store/actions'
import { clearAuthToken, loadState, saveNsecBunkerDelegatedKey } from '../utils'
import { restoreState, setAuthState, setMetadataEvent } from '../store/actions'
import {
clearAuthToken,
clearState,
getRoboHashPicture,
loadState,
saveNsecBunkerDelegatedKey
} from '../utils'
import { LoadingSpinner } from '../components/LoadingSpinner'
import { Dispatch } from '../store/store'
import { NostrController } from '../controllers'
import { MetadataController, NostrController } from '../controllers'
import { LoginMethods } from '../store/auth/types'
import { setUserRobotImage } from '../store/userRobotImage/action'
import { State } from '../store/rootReducer'
const metadataController = new MetadataController()
export const MainLayout = () => {
const dispatch: Dispatch = useDispatch()
const [isLoading, setIsLoading] = useState(true)
const authState = useSelector((state: State) => state.auth)
useEffect(() => {
const logout = () => {
dispatch(
setAuthState({
keyPair: undefined,
loggedIn: false,
usersPubkey: undefined,
loginMethod: undefined,
@ -26,8 +38,11 @@ export const MainLayout = () => {
})
)
dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent()))
// clear authToken saved in local storage
clearAuthToken()
clearState()
// update nsecBunker delegated key
const newDelegatedKey =
@ -59,6 +74,21 @@ export const MainLayout = () => {
setIsLoading(false)
}, [dispatch])
/**
* When authState change user logged in / or app reloaded
* we set robohash avatar in the global state based on user npub
* so that avatar will be consistent across the app when kind 0 is empty
*/
useEffect(() => {
if (authState && authState.loggedIn) {
const pubkey = authState.usersPubkey || authState.keyPair?.public
if (pubkey) {
dispatch(setUserRobotImage(getRoboHashPicture(pubkey)))
}
}
}, [authState])
if (isLoading) return <LoadingSpinner desc="Loading App" />
return (

View File

@ -14,7 +14,9 @@ store.subscribe(
_.throttle(() => {
saveState({
auth: store.getState().auth,
metadata: store.getState().metadata
metadata: store.getState().metadata,
userRobotImage: store.getState().userRobotImage,
relays: store.getState().relays
})
}, 1000)
)

View File

@ -1,4 +1,4 @@
import { Clear } from '@mui/icons-material'
import { Clear, DragHandle } from '@mui/icons-material'
import {
Box,
Button,
@ -18,20 +18,24 @@ import {
Tooltip,
Typography
} from '@mui/material'
import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input'
import { useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
import placeholderAvatar from '../../assets/images/nostr-logo.jpg'
import { useEffect, useRef, useState } from 'react'
import { useSelector } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes, getProfileRoute } from '../../routes'
import { ProfileMetadata, User, UserRole } from '../../types'
import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import {
encryptArrayBuffer,
generateEncryptionKey,
getHash,
hexToNpub,
pubToHex,
npubToHex,
queryNip05,
sendDM,
shorten,
@ -39,10 +43,10 @@ import {
uploadToFileStorage
} from '../../utils'
import styles from './style.module.scss'
import { toast } from 'react-toastify'
import JSZip from 'jszip'
import { useSelector } from 'react-redux'
import { State } from '../../store/rootReducer'
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'
export const CreatePage = () => {
const navigate = useNavigate()
@ -85,13 +89,21 @@ export const CreatePage = () => {
const addUser = (pubkey: string) => {
setUsers((prev) => {
const signers = prev.filter((user) => user.role === UserRole.signer)
const viewers = prev.filter((user) => user.role === UserRole.viewer)
const existingUserIndex = prev.findIndex(
(user) => user.pubkey === pubkey
)
// add new
if (existingUserIndex === -1)
return [...prev, { pubkey, role: userRole }]
if (existingUserIndex === -1) {
if (userRole === UserRole.signer) {
return [...signers, { pubkey, role: userRole }, ...viewers]
} else {
return [...signers, ...viewers, { pubkey, role: userRole }]
}
}
const existingUser = prev[existingUserIndex]
@ -104,12 +116,16 @@ export const CreatePage = () => {
updatedUser.role = userRole
updatedUsers[existingUserIndex] = updatedUser
return updatedUsers
// signers should be placed at the start of the array
return [
...updatedUsers.filter((user) => user.role === UserRole.signer),
...updatedUsers.filter((user) => user.role === UserRole.viewer)
]
})
}
if (userInput.startsWith('npub')) {
const pubkey = await pubToHex(userInput)
const pubkey = npubToHex(userInput)
if (pubkey) {
addUser(pubkey)
setUserInput('')
@ -132,7 +148,7 @@ export const CreatePage = () => {
setLoadingSpinnerDesc('')
})
if (nip05Profile) {
if (nip05Profile && nip05Profile.pubkey) {
const pubkey = nip05Profile.pubkey
addUser(pubkey)
setUserInput('')
@ -145,25 +161,40 @@ export const CreatePage = () => {
setError('Invalid input! Make sure to provide correct npub or nip05.')
}
const handleUserRoleChange = (role: UserRole, index: number) => {
setUsers((prevUsers) => {
// Create a shallow copy of the previous state
const updatedUsers = [...prevUsers]
// Create a shallow copy of the user object at the specified index
const updatedUser = { ...updatedUsers[index] }
// Update the role property of the copied user object
updatedUser.role = role
// Update the user object at the specified index in the copied array
updatedUsers[index] = updatedUser
// Return the updated array
return updatedUsers
})
const handleUserRoleChange = (role: UserRole, pubkey: string) => {
setUsers((prevUsers) =>
prevUsers.map((user) => {
if (user.pubkey === pubkey) {
return {
...user,
role
}
}
return user
})
)
}
const handleRemoveUser = (pubkey: string) => {
setUsers((prev) => prev.filter((user) => user.pubkey !== pubkey))
}
/**
* changes the position of signer in the signers list
*
* @param dragIndex represents the current position of user
* @param hoverIndex represents the target position of user
*/
const moveSigner = (dragIndex: number, hoverIndex: number) => {
setUsers((prevUsers) => {
const updatedUsers = [...prevUsers]
const [draggedUser] = updatedUsers.splice(dragIndex, 1)
updatedUsers.splice(hoverIndex, 0, draggedUser)
return updatedUsers
})
}
const handleSelectFiles = (files: File[]) => {
setDisplayUserInput(true)
setSelectedFiles((prev) => {
@ -246,13 +277,13 @@ export const CreatePage = () => {
if (!signedEvent) return
// create content for meta file
const meta = {
signers: signers.map((signer) => signer.pubkey),
viewers: viewers.map((viewer) => viewer.pubkey),
const meta: Meta = {
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
fileHashes,
submittedBy: usersPubkey,
submittedBy: hexToNpub(usersPubkey!),
signedEvents: {
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
[hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2)
}
}
@ -351,7 +382,7 @@ export const CreatePage = () => {
setIsLoading(false)
navigate(
`${appPrivateRoutes.verify}?file=${encodeURIComponent(
`${appPrivateRoutes.sign}?file=${encodeURIComponent(
fileUrl
)}&key=${encodeURIComponent(encryptionKey)}`
)
@ -397,7 +428,7 @@ export const CreatePage = () => {
{displayUserInput && (
<>
<Typography component="label" variant="h6">
Select signers and viewers
Add Counterparties
</Typography>
<Box className={styles.inputBlock}>
<TextField
@ -435,6 +466,7 @@ export const CreatePage = () => {
users={users}
handleUserRoleChange={handleUserRoleChange}
handleRemoveUser={handleRemoveUser}
moveSigner={moveSigner}
/>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleCreate} variant="contained">
@ -450,14 +482,16 @@ export const CreatePage = () => {
type DisplayUsersProps = {
users: User[]
handleUserRoleChange: (role: UserRole, index: number) => void
handleUserRoleChange: (role: UserRole, pubkey: string) => void
handleRemoveUser: (pubkey: string) => void
moveSigner: (dragIndex: number, hoverIndex: number) => void
}
const DisplayUser = ({
users,
handleUserRoleChange,
handleRemoveUser
handleRemoveUser,
moveSigner
}: DisplayUsersProps) => {
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
@ -489,77 +523,223 @@ const DisplayUser = ({
})
}, [users])
const imageLoadError = (event: any) => {
event.target.src = placeholderAvatar
}
return (
<TableContainer component={Paper} elevation={3} sx={{ marginTop: '20px' }}>
<Table>
<TableHead>
<TableRow>
<TableCell className={styles.tableCell}>User</TableCell>
<TableCell className={styles.tableCell}>Role</TableCell>
<TableCell className={styles.tableHeaderCell}>User</TableCell>
<TableCell className={styles.tableHeaderCell}>Role</TableCell>
<TableCell>Action</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map((user, index) => {
const userMeta = metadata[user.pubkey]
const npub = hexToNpub(user.pubkey)
const roboUrl = `https://robohash.org/${npub}.png?set=set3`
return (
<TableRow key={index}>
<TableCell className={styles.tableCell}>
<Box className={styles.user}>
<img
onError={imageLoadError}
src={userMeta?.picture || roboUrl}
alt="Profile Image"
className="profile-image"
style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${user.pubkey.substring(0, 6)}`
}}
<DndProvider backend={HTML5Backend}>
{users
.filter((user) => user.role === UserRole.signer)
.map((user, index) => (
<SignerRow
key={`signer-${index}`}
userMeta={metadata[user.pubkey]}
user={user}
index={index}
moveSigner={moveSigner}
handleUserRoleChange={handleUserRoleChange}
handleRemoveUser={handleRemoveUser}
/>
))}
</DndProvider>
{users
.filter((user) => user.role === UserRole.viewer)
.map((user, index) => {
const userMeta = metadata[user.pubkey]
return (
<TableRow key={index}>
<TableCell className={styles.tableCell}>
<UserComponent
pubkey={user.pubkey}
name={
userMeta?.display_name ||
userMeta?.name ||
shorten(hexToNpub(user.pubkey))
}
image={userMeta?.picture}
/>
<Link to={getProfileRoute(user.pubkey)}>
<Typography component="label" className={styles.name}>
{userMeta?.display_name ||
userMeta?.name ||
shorten(npub)}
</Typography>
</Link>
</Box>
</TableCell>
<TableCell className={styles.tableCell}>
<Select
fullWidth
value={user.role}
onChange={(e) =>
handleUserRoleChange(e.target.value as UserRole, index)
}
>
<MenuItem value={UserRole.signer}>
{UserRole.signer}
</MenuItem>
<MenuItem value={UserRole.viewer}>
{UserRole.viewer}
</MenuItem>
</Select>
</TableCell>
<TableCell>
<Tooltip title="Remove User" arrow>
<IconButton onClick={() => handleRemoveUser(user.pubkey)}>
<Clear style={{ color: 'red' }} />
</IconButton>
</Tooltip>
</TableCell>
</TableRow>
)
})}
</TableCell>
<TableCell className={styles.tableCell}>
<Select
fullWidth
value={user.role}
onChange={(e) =>
handleUserRoleChange(
e.target.value as UserRole,
user.pubkey
)
}
>
<MenuItem value={UserRole.signer}>
{UserRole.signer}
</MenuItem>
<MenuItem value={UserRole.viewer}>
{UserRole.viewer}
</MenuItem>
</Select>
</TableCell>
<TableCell>
<Tooltip title="Remove User" arrow>
<IconButton onClick={() => handleRemoveUser(user.pubkey)}>
<Clear style={{ color: 'red' }} />
</IconButton>
</Tooltip>
</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</TableContainer>
)
}
interface DragItem {
index: number
id: string
type: string
}
type SignerRowProps = {
userMeta: ProfileMetadata
user: User
index: number
moveSigner: (dragIndex: number, hoverIndex: number) => void
handleUserRoleChange: (role: UserRole, pubkey: string) => void
handleRemoveUser: (pubkey: string) => void
}
const SignerRow = ({
userMeta,
user,
index,
moveSigner,
handleUserRoleChange,
handleRemoveUser
}: SignerRowProps) => {
const ref = useRef<HTMLTableRowElement>(null)
const [{ handlerId }, drop] = useDrop<
DragItem,
void,
{ handlerId: Identifier | null }
>({
accept: 'row',
collect(monitor) {
return {
handlerId: monitor.getHandlerId()
}
},
hover(item: DragItem, monitor) {
if (!ref.current) {
return
}
const dragIndex = item.index
const hoverIndex = index
// Don't replace items with themselves
if (dragIndex === hoverIndex) {
return
}
// Determine rectangle on screen
const hoverBoundingRect = ref.current?.getBoundingClientRect()
// Get vertical middle
const hoverMiddleY =
(hoverBoundingRect.bottom - hoverBoundingRect.top) / 2
// Determine mouse position
const clientOffset = monitor.getClientOffset()
// Get pixels to the top
const hoverClientY = (clientOffset as XYCoord).y - hoverBoundingRect.top
// Only perform the move when the mouse has crossed half of the items height
// When dragging downwards, only move when the cursor is below 50%
// When dragging upwards, only move when the cursor is above 50%
// Dragging downwards
if (dragIndex < hoverIndex && hoverClientY < hoverMiddleY) {
return
}
// Dragging upwards
if (dragIndex > hoverIndex && hoverClientY > hoverMiddleY) {
return
}
// Time to actually perform the action
moveSigner(dragIndex, hoverIndex)
// Note: we're mutating the monitor item here!
// Generally it's better to avoid mutations,
// but it's good here for the sake of performance
// to avoid expensive index searches.
item.index = hoverIndex
}
})
const [{ isDragging }, drag] = useDrag({
type: 'row',
item: () => {
return { id: user.pubkey, index }
},
collect: (monitor: any) => ({
isDragging: monitor.isDragging()
})
})
const opacity = isDragging ? 0 : 1
drag(drop(ref))
return (
<TableRow
sx={{ cursor: 'move', opacity }}
data-handler-id={handlerId}
ref={ref}
>
<TableCell
className={styles.tableCell}
sx={{ display: 'flex', alignItems: 'center', gap: '10px' }}
>
<DragHandle />
<UserComponent
pubkey={user.pubkey}
name={
userMeta?.display_name ||
userMeta?.name ||
shorten(hexToNpub(user.pubkey))
}
image={userMeta?.picture}
/>
</TableCell>
<TableCell className={styles.tableCell}>
<Select
fullWidth
value={user.role}
onChange={(e) =>
handleUserRoleChange(e.target.value as UserRole, user.pubkey)
}
>
<MenuItem value={UserRole.signer}>{UserRole.signer}</MenuItem>
<MenuItem value={UserRole.viewer}>{UserRole.viewer}</MenuItem>
</Select>
</TableCell>
<TableCell>
<Tooltip title="Remove User" arrow>
<IconButton onClick={() => handleRemoveUser(user.pubkey)}>
<Clear style={{ color: 'red' }} />
</IconButton>
</Tooltip>
</TableCell>
</TableRow>
)
}

View File

@ -17,8 +17,13 @@
border-bottom: 0.5px solid;
}
.tableHeaderCell {
border-right: 1px solid rgba(224, 224, 224, 1);
}
.tableCell {
border-right: 1px solid rgba(224, 224, 224, 1);
height: 56px;
.user {
display: flex;

View File

@ -1,141 +0,0 @@
import { Box, Button, TextField, Typography } from '@mui/material'
import saveAs from 'file-saver'
import { MuiFileInput } from 'mui-file-input'
import { useEffect, useState } from 'react'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { decryptArrayBuffer } from '../../utils'
import styles from './style.module.scss'
import { toast } from 'react-toastify'
import { useSearchParams } from 'react-router-dom'
import axios from 'axios'
import { DecryptionError } from '../../types/errors/DecryptionError'
export const DecryptZip = () => {
const [searchParams] = useSearchParams()
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [encryptionKey, setEncryptionKey] = useState('')
const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [isDraggingOver, setIsDraggingOver] = useState(false)
useEffect(() => {
const fileUrl = searchParams.get('file')
if (fileUrl) {
setIsLoading(true)
setLoadingSpinnerDesc('Fetching zip file')
axios
.get(fileUrl, {
responseType: 'arraybuffer'
})
.then((res) => {
const fileName = fileUrl.split('/').pop()
const file = new File([res.data], fileName!)
setSelectedFile(file)
})
.catch((err) => {
console.error(
`error occurred in getting zip file from ${fileUrl}`,
err
)
})
.finally(() => {
setIsLoading(false)
})
}
const key = searchParams.get('key')
if (key) setEncryptionKey(key)
}, [searchParams])
const handleDecrypt = async () => {
if (!selectedFile || !encryptionKey) return
setIsLoading(true)
setLoadingSpinnerDesc('Decrypting zip file')
const encryptedArrayBuffer = await selectedFile.arrayBuffer()
const arrayBuffer = await decryptArrayBuffer(
encryptedArrayBuffer,
encryptionKey
).catch((err: DecryptionError) => {
console.log('err in decryption:>> ', err)
toast.error(err.message)
setIsLoading(false)
return null
})
if (!arrayBuffer) return
const blob = new Blob([arrayBuffer])
saveAs(blob, 'decrypted.zip')
setIsLoading(false)
}
const handleDrop = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault()
setIsDraggingOver(false)
const file = event.dataTransfer.files[0]
if (file.type === 'application/zip') setSelectedFile(file)
}
const handleDragOver = (event: React.DragEvent<HTMLDivElement>) => {
event.preventDefault()
setIsDraggingOver(true)
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}>
<Typography component="label" variant="h6">
Select encrypted zip file
</Typography>
<Box
className={styles.inputBlock}
onDrop={handleDrop}
onDragOver={handleDragOver}
>
{isDraggingOver && (
<Box className={styles.fileDragOver}>
<Typography variant="body1">Drop file here</Typography>
</Box>
)}
<MuiFileInput
placeholder="Drop file here, or click to select"
value={selectedFile}
onChange={(value) => setSelectedFile(value)}
InputProps={{
inputProps: {
accept: '.zip'
}
}}
/>
<TextField
label="Encryption Key"
variant="outlined"
value={encryptionKey}
onChange={(e) => setEncryptionKey(e.target.value)}
/>
</Box>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button
onClick={handleDecrypt}
variant="contained"
disabled={!selectedFile || !encryptionKey}
>
Decrypt
</Button>
</Box>
</Box>
</>
)
}

View File

@ -1,27 +0,0 @@
@import '../../colors.scss';
.container {
display: flex;
flex-direction: column;
color: $text-color;
.inputBlock {
position: relative;
display: flex;
flex-direction: column;
gap: 25px;
}
.fileDragOver {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(255, 255, 255, 0.8);
z-index: 1;
display: flex;
justify-content: center;
align-items: center;
}
}

View File

@ -14,6 +14,12 @@ export const HomePage = () => {
>
Create
</Button>
<Button
onClick={() => navigate(appPrivateRoutes.sign)}
variant="contained"
>
Sign
</Button>
<Button
onClick={() => navigate(appPrivateRoutes.verify)}
variant="contained"

View File

@ -59,7 +59,7 @@ export const LandingPage = () => {
}}
variant="h4"
>
What is Nostr?
Secure Document Signing
</Typography>
<Typography
sx={{
@ -69,24 +69,31 @@ export const LandingPage = () => {
}}
variant="body1"
>
Nostr is a decentralised messaging protocol where YOU own your
identity. To get started, you must have an existing{' '}
SIGit is an open-source and self-hostable solution for secure
document signing and verification. Code is MIT licenced and
available at{' '}
<a
className="bold-link"
target="_blank"
href="https://nostr.com/"
href="https://git.sigit.io/sig/it"
>
Nostr account
https://git.sigit.io/sig/it
</a>
.
<br />
<br />
No email required - all notifications are made using the nQuiz
relay.
SIGit lets you Create, Sign and Verify signature packs from any
device with a browser.
<br />
<br />
If you no longer wish to hear from us, simply remove
relay.nquiz.io from your list of relays.
Unlike other solutions, SIGit is totally private - files are
encrypted locally, and valid packs can only be exported by named
recipients.
<br />
<br />
IMPORTANT - please note that SIGit is currently ALPHA software and
should only be used for testing purposes until we have finalised
the signature / verification process.
</Typography>
</Box>
</Box>

View File

@ -2,7 +2,7 @@ import { Box, Button, TextField, Typography } from '@mui/material'
import { getPublicKey, nip19 } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useDispatch } from 'react-redux'
import { useNavigate } from 'react-router-dom'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import {
@ -18,10 +18,12 @@ import {
} from '../../store/actions'
import { LoginMethods } from '../../store/auth/types'
import { Dispatch } from '../../store/store'
import { pubToHex, queryNip05 } from '../../utils'
import { npubToHex, queryNip05 } from '../../utils'
import styles from './style.module.scss'
export const Login = () => {
const [searchParams] = useSearchParams()
const dispatch: Dispatch = useDispatch()
const navigate = useNavigate()
@ -43,6 +45,29 @@ export const Login = () => {
}, 500)
}, [])
/**
* Call login function when enter is pressed
*/
const handleInputKeyDown = (event: any) => {
if (event.code === 'Enter' || event.code === 'NumpadEnter') {
event.preventDefault()
login()
}
}
const navigateAfterLogin = (path: string) => {
const callbackPath = searchParams.get('callbackPath')
if (callbackPath) {
// base64 decoded path
const path = atob(callbackPath)
navigate(path)
return
}
navigate(path)
}
const loginWithExtension = async () => {
setIsLoading(true)
setLoadingSpinnerDesc('Capturing pubkey from nostr extension')
@ -54,9 +79,9 @@ export const Login = () => {
setLoadingSpinnerDesc('Authenticating and finding metadata')
const redirectPath =
await authController.authenticateAndFindMetadata(pubkey)
await authController.authAndGetMetadataAndRelaysMap(pubkey)
navigate(redirectPath)
navigateAfterLogin(redirectPath)
})
.catch((err) => {
toast.error('Error capturing public key from nostr extension: ' + err)
@ -93,13 +118,13 @@ export const Login = () => {
setLoadingSpinnerDesc('Authenticating and finding metadata')
const redirectPath = await authController
.authenticateAndFindMetadata(publickey)
.authAndGetMetadataAndRelaysMap(publickey)
.catch((err) => {
toast.error('Error occurred in authentication: ' + err)
return null
})
if (redirectPath) navigate(redirectPath)
if (redirectPath) navigateAfterLogin(redirectPath)
setIsLoading(false)
setLoadingSpinnerDesc('')
@ -188,13 +213,13 @@ export const Login = () => {
setLoadingSpinnerDesc('Authenticating and finding metadata')
const redirectPath = await authController
.authenticateAndFindMetadata(pubkey!)
.authAndGetMetadataAndRelaysMap(pubkey!)
.catch((err) => {
toast.error('Error occurred in authentication: ' + err)
return null
})
if (redirectPath) navigate(redirectPath)
if (redirectPath) navigateAfterLogin(redirectPath)
})
.catch((err) => {
toast.error(
@ -213,7 +238,7 @@ export const Login = () => {
const keyEndIndex = inputValue.indexOf('?relay=')
const key = inputValue.substring(keyStartIndex, keyEndIndex)
const pubkey = await pubToHex(key)
const pubkey = npubToHex(key)
if (!pubkey) {
toast.error('Invalid pubkey in bunker connection string.')
@ -248,13 +273,13 @@ export const Login = () => {
setLoadingSpinnerDesc('Authenticating and finding metadata')
const redirectPath = await authController
.authenticateAndFindMetadata(pubkey!)
.authAndGetMetadataAndRelaysMap(pubkey!)
.catch((err) => {
toast.error('Error occurred in authentication: ' + err)
return null
})
if (redirectPath) navigate(redirectPath)
if (redirectPath) navigateAfterLogin(redirectPath)
})
.catch((err) => {
toast.error(
@ -303,7 +328,8 @@ export const Login = () => {
<div className={styles.loginPage}>
<Typography variant="h4">Welcome to Sigit</Typography>
<TextField
label="nip05 / npub / nsec / bunker connx string"
onKeyDown={handleInputKeyDown}
label="nip05 login / nip46 bunker string / nsec"
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
sx={{ width: '100%', mt: 2 }}

View File

@ -1,6 +1,5 @@
import ContentCopyIcon from '@mui/icons-material/ContentCopy'
import {
CircularProgress,
IconButton,
InputProps,
List,
@ -12,10 +11,9 @@ import {
useTheme
} from '@mui/material'
import { UnsignedEvent, nip19, kinds, VerifiedEvent } from 'nostr-tools'
import { useEffect, useMemo, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { Link, useParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import placeholderAvatar from '../../assets/images/nostr-logo.jpg'
import { MetadataController, NostrController } from '../../controllers'
import { NostrJoiningBlock, ProfileMetadata } from '../../types'
import styles from './style.module.scss'
@ -27,6 +25,7 @@ import { setMetadataEvent } from '../../store/actions'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { LoginMethods } from '../../store/auth/types'
import { SmartToy } from '@mui/icons-material'
import { getRoboHashPicture } from '../../utils'
export const ProfilePage = () => {
const theme = useTheme()
@ -43,16 +42,18 @@ export const ProfilePage = () => {
useState<NostrJoiningBlock | null>(null)
const [profileMetadata, setProfileMetadata] = useState<ProfileMetadata>()
const [savingProfileMetadata, setSavingProfileMetadata] = useState(false)
const [avatarLoading, setAvatarLoading] = useState(false)
const metadataState = useSelector((state: State) => state.metadata)
const keys = useSelector((state: State) => state.auth?.keyPair)
const { usersPubkey, loginMethod } = useSelector((state: State) => state.auth)
const userRobotImage = useSelector((state: State) => state.userRobotImage)
const [isUsersOwnProfile, setIsUsersOwnProfile] = useState(false)
const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc] = useState('Fetching metadata')
const robotSet = useRef(1)
useEffect(() => {
if (npub) {
try {
@ -211,22 +212,21 @@ export const ProfilePage = () => {
setSavingProfileMetadata(false)
}
/**
* Called by clicking on the robot icon inside Picture URL input
* On every click, next robohash set will be generated.
* There are 5 sets at the moment, after 5th set function will start over from set 1.
*/
const generateRobotAvatar = () => {
setAvatarLoading(true)
robotSet.current++
if (robotSet.current > 5) robotSet.current = 1
const robotAvatarLink = `https://robohash.org/${npub}.png?set=set3`
const robotAvatarLink = getRoboHashPicture(npub!, robotSet.current)
setProfileMetadata((prev) => ({
...prev,
picture: ''
picture: robotAvatarLink
}))
setTimeout(() => {
setProfileMetadata((prev) => ({
...prev,
picture: robotAvatarLink
}))
})
}
/**
@ -234,21 +234,31 @@ export const ProfilePage = () => {
* @returns robohash generate button, loading spinner or no button
*/
const robohashButton = () => {
if (profileMetadata?.picture?.includes('robohash')) return null
return (
<Tooltip title="Generate a robohash avatar">
{avatarLoading ? (
<CircularProgress style={{ padding: 8 }} size={22} />
) : (
<IconButton onClick={generateRobotAvatar}>
<SmartToy />
</IconButton>
)}
<IconButton onClick={generateRobotAvatar}>
<SmartToy />
</IconButton>
</Tooltip>
)
}
/**
* Handles the logic for Image URL.
* If no picture in kind 0 found - use robohash avatar
*
* @returns robohash image url
*/
const getProfileImage = (metadata: ProfileMetadata) => {
if (!isUsersOwnProfile) {
return metadata.picture || getRoboHashPicture(npub!)
}
// userRobotImage is used only when visiting own profile
// while kind 0 picture is not set
return metadata.picture || userRobotImage || getRoboHashPicture(npub!)
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
@ -282,13 +292,10 @@ export const ProfilePage = () => {
>
<img
onError={(event: any) => {
event.target.src = placeholderAvatar
}}
onLoad={() => {
setAvatarLoading(false)
event.target.src = getRoboHashPicture(npub!)
}}
className={styles.img}
src={profileMetadata.picture || placeholderAvatar}
src={getProfileImage(profileMetadata)}
alt="Profile Image"
/>
@ -309,7 +316,7 @@ export const ProfilePage = () => {
</ListItem>
{editItem('picture', 'Picture URL', undefined, undefined, {
endAdornment: robohashButton()
endAdornment: isUsersOwnProfile ? robohashButton() : undefined
})}
{editItem('name', 'Username')}

234
src/pages/relays/index.tsx Normal file
View File

@ -0,0 +1,234 @@
import { useEffect, useState } from 'react'
import { Box, List, ListItem, TextField } from '@mui/material'
import RouterIcon from '@mui/icons-material/Router'
import styles from './style.module.scss'
import Switch from '@mui/material/Switch'
import ListItemText from '@mui/material/ListItemText'
import Divider from '@mui/material/Divider'
import { NostrController } from '../../controllers'
import { RelayMap } from '../../types'
import LogoutIcon from '@mui/icons-material/Logout'
import { useAppSelector, useAppDispatch } from '../../hooks'
import { compareObjects } from '../../utils'
import { setRelayMapAction } from '../../store/actions'
import { toast } from 'react-toastify'
export const RelaysPage = () => {
const nostrController = NostrController.getInstance()
const relaysState = useAppSelector((state) => state.relays)
const usersPubkey = useAppSelector((state) => state.auth?.usersPubkey)
const dispatch = useAppDispatch()
const [newRelayURI, setNewRelayURI] = useState<string>()
const [newRelayURIerror, setNewRelayURIerror] = useState<string>()
const [relayMap, setRelayMap] = useState<RelayMap | undefined>(
relaysState?.map
)
useEffect(() => {
let isMounted = false
const fetchData = async () => {
if (usersPubkey) {
isMounted = true
// call async func to fetch relay map
const newRelayMap = await nostrController.getRelayMap(usersPubkey)
// handle fetched relay map
if (isMounted) {
if (
!relaysState?.mapUpdated ||
newRelayMap.mapUpdated > relaysState?.mapUpdated
)
if (
!relaysState?.map ||
!compareObjects(relaysState.map, newRelayMap)
) {
setRelayMap(newRelayMap.map)
dispatch(setRelayMapAction(newRelayMap.map))
}
}
}
}
// Publishing relay map can take some time.
// This is why data fetch should happen only if relay map was received more than 5 minutes ago.
if (
usersPubkey &&
(!relaysState?.mapUpdated ||
Date.now() - relaysState?.mapUpdated > 5 * 60 * 1000) // 5 minutes
) {
fetchData()
}
// cleanup func
return () => {
isMounted = false
}
}, [dispatch, usersPubkey, relaysState, nostrController])
const relayRequirementWarning = () =>
toast.warning('At least one write relay is needed for SIGit to work.')
const handleLeaveRelay = async (relay: string) => {
if (relayMap) {
if (Object.keys(relayMap).length === 1) {
relayRequirementWarning()
} else {
const relayMapCopy = JSON.parse(JSON.stringify(relayMap))
// Remove relay from relay map
delete relayMapCopy[relay]
setRelayMap(relayMapCopy)
dispatch(setRelayMapAction(relayMapCopy))
if (usersPubkey) {
// Publish updated relay map.
const relayMapPublishingRes = await nostrController
.publishRelayMap(relayMapCopy, usersPubkey)
.catch((err) => handlePublishRelayMapError(err))
if (relayMapPublishingRes) toast.success(relayMapPublishingRes)
}
}
}
}
const handlePublishRelayMapError = (err: any) => {
const errorPrefix = 'Error while publishing Relay Map'
if (Array.isArray(err)) {
err.forEach((errorObj: { relay: string; error: string }) => {
toast.error(
`${errorPrefix} to ${errorObj.relay}. Error: ${errorObj.error || 'Unknown'}`
)
})
} else {
toast.error(`${errorPrefix}. Error: ${err.message || 'Unknown'}`)
}
}
const handleRelayWriteChange = async (
relay: string,
event: React.ChangeEvent<HTMLInputElement>
) => {
if (relayMap && relayMap[relay]) {
if (
!event.target.checked &&
Object.keys(relayMap).filter((relay) => relayMap[relay].write)
.length === 1
) {
relayRequirementWarning()
} else {
const relayMapCopy = JSON.parse(JSON.stringify(relayMap))
relayMapCopy[relay].write = event.target.checked
setRelayMap(relayMapCopy)
dispatch(setRelayMapAction(relayMapCopy))
if (usersPubkey) {
// Publish updated relay map
const relayMapPublishingRes = await nostrController
.publishRelayMap(relayMapCopy, usersPubkey)
.catch((err) => handlePublishRelayMapError(err))
if (relayMapPublishingRes) toast.success(relayMapPublishingRes)
}
}
}
}
const handleTextFieldChange = async () => {
// Check if new relay URI is a valid string
if (
newRelayURI &&
!/^wss:\/\/[-a-zA-Z0-9@:%._\\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}/.test(
newRelayURI
)
) {
setNewRelayURIerror(
'New relay URI is not valid. Example of valid relay URI: wss://sigit.relay.io'
)
} else if (newRelayURI) {
const relayMapCopy = JSON.parse(JSON.stringify(relayMap))
relayMapCopy[newRelayURI.trim()] = { write: true, read: true }
setRelayMap(relayMapCopy)
setNewRelayURI('')
dispatch(setRelayMapAction(relayMapCopy))
if (usersPubkey) {
// Publish updated relay map
const relayMapPublishingRes = await nostrController
.publishRelayMap(relayMapCopy, usersPubkey)
.catch((err) => handlePublishRelayMapError(err))
if (relayMapPublishingRes) toast.success(relayMapPublishingRes)
}
}
}
useEffect(() => {
// Display notification if an empty relay map has been received
if (relayMap && Object.keys(relayMap).length === 0) {
relayRequirementWarning()
}
}, [relayMap])
return (
<Box className={styles.container}>
<Box>
<TextField
label="Add new relay"
value={newRelayURI}
onBlur={() => handleTextFieldChange()}
onChange={(e) => setNewRelayURI(e.target.value)}
helperText={newRelayURIerror}
error={!!newRelayURIerror}
placeholder="wss://"
className={styles.relayURItextfield}
/>
</Box>
<Box className={styles.sectionTitle}>
<RouterIcon className={styles.sectionIcon} />
<span>YOUR RELAYS</span>
</Box>
{relayMap && (
<Box className={styles.relaysContainer}>
{Object.keys(relayMap).map((relay, i) => (
<Box className={styles.relay} key={`relay_${i}`}>
<List>
<ListItem>
<ListItemText primary={relay} />
<Box
className={styles.leaveRelayContainer}
onClick={() => handleLeaveRelay(relay)}
>
<LogoutIcon />
<span>Leave</span>
</Box>
</ListItem>
<Divider className={styles.relayDivider} />
<ListItem>
<ListItemText primary="Publish to this relay?" />
<Switch
checked={relayMap[relay].write}
onChange={(event) => handleRelayWriteChange(relay, event)}
/>
</ListItem>
</List>
</Box>
))}
</Box>
)}
</Box>
)
}

View File

@ -0,0 +1,47 @@
@import '../../colors.scss';
.container {
margin-top: 25px;
.relayURItextfield {
width: 100%;
}
.sectionIcon {
font-size: 30px;
}
.sectionTitle {
margin-top: 35px;
margin-bottom: 10px;
display: flex;
flex-direction: row;
gap: 5px;
font-size: 1.5rem;
line-height: 2rem;
font-weight: 600;
}
.relaysContainer {
display: flex;
flex-direction: column;
gap: 15px;
}
.relay {
border: 1px solid rgba(0, 0, 0, 0.12);
border-radius: 4px;
.relayDivider {
margin-left: 10px;
margin-right: 10px;
}
.leaveRelayContainer {
display: flex;
flex-direction: row;
gap: 10px;
cursor: pointer;
}
}
}

747
src/pages/sign/index.tsx Normal file
View File

@ -0,0 +1,747 @@
import {
Box,
Button,
List,
ListItem,
ListSubheader,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
TextField,
Typography,
useTheme
} from '@mui/material'
import axios from 'axios'
import saveAs from 'file-saver'
import JSZip from 'jszip'
import _ from 'lodash'
import { MuiFileInput } from 'mui-file-input'
import { EventTemplate } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import {
decryptArrayBuffer,
encryptArrayBuffer,
generateEncryptionKey,
getHash,
getRoboHashPicture,
hexToNpub,
parseJson,
npubToHex,
readContentOfZipEntry,
sendDM,
shorten,
signEventForMetaFile,
uploadToFileStorage
} from '../../utils'
import styles from './style.module.scss'
enum SignedStatus {
Fully_Signed,
User_Is_Next_Signer,
User_Is_Not_Next_Signer
}
export const SignPage = () => {
const navigate = useNavigate()
const [searchParams, setSearchParams] = useSearchParams()
const [displayInput, setDisplayInput] = useState(false)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [encryptionKey, setEncryptionKey] = useState('')
const [zip, setZip] = useState<JSZip>()
const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [meta, setMeta] = useState<Meta | null>(null)
const [signedStatus, setSignedStatus] = useState<SignedStatus>()
const [nextSinger, setNextSinger] = useState<string>()
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const [authUrl, setAuthUrl] = useState<string>()
const nostrController = NostrController.getInstance()
useEffect(() => {
if (meta) {
setDisplayInput(false)
// get list of users who have signed
const signedBy = Object.keys(meta.signedEvents)
if (meta.signers.length > 0) {
// check if all signers have signed then its fully signed
if (meta.signers.every((signer) => signedBy.includes(signer))) {
setSignedStatus(SignedStatus.Fully_Signed)
} else {
for (const signer of meta.signers) {
if (!signedBy.includes(signer)) {
// signers in meta.json are in npub1 format
// so, convert it to hex before setting to nextSigner
setNextSinger(npubToHex(signer)!)
const usersNpub = hexToNpub(usersPubkey!)
if (signer === usersNpub) {
// logged in user is the next signer
setSignedStatus(SignedStatus.User_Is_Next_Signer)
} else {
setSignedStatus(SignedStatus.User_Is_Not_Next_Signer)
}
break
}
}
}
} else {
// there's no signer just viewers. So its fully signed
setSignedStatus(SignedStatus.Fully_Signed)
}
}
}, [meta, usersPubkey])
useEffect(() => {
const fileUrl = searchParams.get('file')
const key = searchParams.get('key')
if (fileUrl && key) {
setIsLoading(true)
setLoadingSpinnerDesc('Fetching file from file server')
axios
.get(fileUrl, {
responseType: 'arraybuffer'
})
.then((res) => {
const fileName = fileUrl.split('/').pop()
const file = new File([res.data], fileName!)
decrypt(file, decodeURIComponent(key)).then((arrayBuffer) => {
if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer)
})
})
.catch((err) => {
console.error(`error occurred in getting file from ${fileUrl}`, err)
toast.error(
err.message || `error occurred in getting file from ${fileUrl}`
)
})
.finally(() => {
setIsLoading(false)
})
} else {
setIsLoading(false)
setDisplayInput(true)
}
}, [searchParams])
const decrypt = async (file: File, key: string) => {
setLoadingSpinnerDesc('Decrypting file')
const encryptedArrayBuffer = await file.arrayBuffer()
const arrayBuffer = await decryptArrayBuffer(encryptedArrayBuffer, key)
.catch((err) => {
console.log('err in decryption:>> ', err)
toast.error(err.message || 'An error occurred in decrypting file.')
return null
})
.finally(() => {
setIsLoading(false)
})
return arrayBuffer
}
const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => {
const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip')
setLoadingSpinnerDesc('Parsing zip file')
const zip = await JSZip.loadAsync(decryptedZipFile).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
setZip(zip)
setLoadingSpinnerDesc('Parsing meta.json')
const metaFileContent = await readContentOfZipEntry(
zip,
'meta.json',
'string'
)
if (!metaFileContent) {
setIsLoading(false)
return
}
const parsedMetaJson = await parseJson<Meta>(metaFileContent).catch(
(err) => {
console.log('err in parsing the content of meta.json :>> ', err)
toast.error(
err.message || 'error occurred in parsing the content of meta.json'
)
setIsLoading(false)
return null
}
)
setMeta(parsedMetaJson)
}
const handleDecrypt = async () => {
if (!selectedFile || !encryptionKey) return
setIsLoading(true)
const arrayBuffer = await decrypt(
selectedFile,
decodeURIComponent(encryptionKey)
)
if (!arrayBuffer) return
handleDecryptedArrayBuffer(arrayBuffer)
}
const handleSign = async () => {
if (!zip || !meta) return
setIsLoading(true)
setLoadingSpinnerDesc('parsing hashes.json file')
const hashesFileContent = await readContentOfZipEntry(
zip,
'hashes.json',
'string'
)
if (!hashesFileContent) {
setIsLoading(false)
return
}
let hashes = await parseJson(hashesFileContent).catch((err) => {
console.log('err in parsing the content of hashes.json :>> ', err)
toast.error(
err.message || 'error occurred in parsing the content of hashes.json'
)
setIsLoading(false)
return null
})
if (!hashes) return
setLoadingSpinnerDesc('Generating hashes for files')
const fileHashes: { [key: string]: string } = {}
const fileNames = Object.keys(meta.fileHashes)
// 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 filePath = `files/${fileName}`
const arrayBuffer = await readContentOfZipEntry(
zip,
filePath,
'arraybuffer'
)
if (!arrayBuffer) {
setIsLoading(false)
return
}
const hash = await getHash(arrayBuffer)
if (!hash) {
setIsLoading(false)
return
}
fileHashes[fileName] = hash
}
setLoadingSpinnerDesc('Signing nostr event')
const signedEvent = await signEventForMetaFile(
fileHashes,
nostrController,
setIsLoading
)
if (!signedEvent) return
const metaCopy = _.cloneDeep(meta)
metaCopy.signedEvents = {
...metaCopy.signedEvents,
[hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2)
}
const stringifiedMeta = JSON.stringify(metaCopy, null, 2)
zip.file('meta.json', stringifiedMeta)
const metaHash = await getHash(stringifiedMeta)
if (!metaHash) return
hashes = {
...hashes,
[usersPubkey!]: metaHash
}
zip.file('hashes.json', JSON.stringify(hashes, null, 2))
const arrayBuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: {
level: 6
}
})
.catch((err) => {
console.log('err in zip:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in generating zip file')
return null
})
if (!arrayBuffer) return
const key = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer(arrayBuffer, key)
const blob = new Blob([encryptedArrayBuffer])
setLoadingSpinnerDesc('Uploading zip file to file storage.')
const fileUrl = await uploadToFileStorage(blob, nostrController)
.then((url) => {
toast.success('zip file uploaded to file storage')
return url
})
.catch((err) => {
console.log('err in upload:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in uploading zip file')
return null
})
if (!fileUrl) return
// check if the current user is the last signer
const usersNpub = hexToNpub(usersPubkey!)
const lastSignerIndex = meta.signers.length - 1
const signerIndex = meta.signers.indexOf(usersNpub)
const isLastSigner = signerIndex === lastSignerIndex
// if current user is the last signer, then send DMs to all signers and viewers
if (isLastSigner) {
const userSet = new Set<`npub1${string}`>()
userSet.add(meta.submittedBy)
meta.signers.forEach((signer) => {
userSet.add(signer)
})
meta.viewers.forEach((viewer) => {
userSet.add(viewer)
})
const users = Array.from(userSet)
for (const user of users) {
// todo: execute in parallel
await sendDM(
fileUrl,
key,
npubToHex(user)!,
nostrController,
false,
setAuthUrl
)
}
} else {
const nextSigner = meta.signers[signerIndex + 1]
await sendDM(
fileUrl,
key,
npubToHex(nextSigner)!,
nostrController,
false,
setAuthUrl
)
}
setIsLoading(false)
// update search params with updated file url and encryption key
setSearchParams({
file: fileUrl,
key: key
})
}
/**
*
* @returns exported.zip including signed files and meta info (about signers and viewers)
*/
const handleExport = async () => {
if (!meta || !zip || !usersPubkey) return
const usersNpub = hexToNpub(usersPubkey)
if (
!meta.signers.includes(usersNpub) &&
!meta.viewers.includes(usersNpub) &&
meta.submittedBy !== usersNpub
)
return
setIsLoading(true)
setLoadingSpinnerDesc('Signing nostr event')
const event: EventTemplate = {
kind: 1,
content: '',
created_at: Math.floor(Date.now() / 1000), // Current timestamp
tags: []
}
// Sign the event
const signedEvent = await nostrController.signEvent(event).catch((err) => {
console.error(err)
toast.error(err.message || 'Error occurred in signing nostr event')
setIsLoading(false) // Set loading state to false
return null
})
if (!signedEvent) return
const exportSignature = JSON.stringify(signedEvent, null, 2)
const stringifiedMeta = JSON.stringify(
{
...meta,
exportSignature
},
null,
2
)
zip.file('meta.json', stringifiedMeta)
const arrayBuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: {
level: 6
}
})
.catch((err) => {
console.log('err in zip:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in generating zip file')
return null
})
if (!arrayBuffer) return
const blob = new Blob([arrayBuffer])
saveAs(blob, 'exported.zip')
setIsLoading(false)
navigate(appPrivateRoutes.verify)
}
if (authUrl) {
return (
<iframe
title="Nsecbunker auth"
src={authUrl}
width="100%"
height="500px"
/>
)
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}>
{displayInput && (
<>
<Typography component="label" variant="h6">
Select sigit file
</Typography>
<Box className={styles.inputBlock}>
<MuiFileInput
placeholder="Select file"
value={selectedFile}
onChange={(value) => setSelectedFile(value)}
/>
{selectedFile && (
<TextField
label="Encryption Key"
variant="outlined"
value={encryptionKey}
onChange={(e) => setEncryptionKey(e.target.value)}
/>
)}
</Box>
{selectedFile && encryptionKey && (
<Box sx={{ mt: 2, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleDecrypt} variant="contained">
Decrypt
</Button>
</Box>
)}
</>
)}
{meta && signedStatus === SignedStatus.Fully_Signed && (
<>
<DisplayMeta meta={meta} nextSigner={nextSinger} />
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant="contained">
Export
</Button>
</Box>
</>
)}
{meta && signedStatus === SignedStatus.User_Is_Not_Next_Signer && (
<DisplayMeta meta={meta} nextSigner={nextSinger} />
)}
{meta && signedStatus === SignedStatus.User_Is_Next_Signer && (
<>
<DisplayMeta meta={meta} nextSigner={nextSinger} />
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleSign} variant="contained">
Sign
</Button>
</Box>
</>
)}
</Box>
</>
)
}
type DisplayMetaProps = {
meta: Meta
nextSigner?: string
}
const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
const theme = useTheme()
const textColor = theme.palette.getContrastText(
theme.palette.background.paper
)
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
const [users, setUsers] = useState<User[]>([])
useEffect(() => {
meta.signers.forEach((signer) => {
const hexKey = npubToHex(signer)
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === hexKey) !== -1) return prev
return [
...prev,
{
pubkey: hexKey!,
role: UserRole.signer
}
]
})
})
meta.viewers.forEach((viewer) => {
const hexKey = npubToHex(viewer)
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === hexKey) !== -1) return prev
return [
...prev,
{
pubkey: hexKey!,
role: UserRole.viewer
}
]
})
})
}, [meta])
useEffect(() => {
const metadataController = new MetadataController()
const hexKeys: string[] = [
npubToHex(meta.submittedBy)!,
...users.map((user) => user.pubkey)
]
hexKeys.forEach((key) => {
if (!(key in metadata)) {
metadataController
.findMetadata(key)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[key]: metadataContent
}))
})
.catch((err) => {
console.error(`error occurred in finding metadata for: ${key}`, err)
})
}
})
}, [users, meta.submittedBy])
return (
<List
sx={{
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader
sx={{
borderBottom: '0.5px solid',
paddingBottom: 1,
paddingTop: 1,
fontSize: '1.5rem'
}}
className={styles.subHeader}
>
Meta Info
</ListSubheader>
}
>
<ListItem
sx={{
marginTop: 1,
gap: '15px'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Submitted By
</Typography>
{(function () {
const pubkey = npubToHex(meta.submittedBy)
const profile = metadata[pubkey!]
return (
<UserComponent
pubkey={pubkey!}
name={
profile?.display_name ||
profile?.name ||
shorten(meta.submittedBy)
}
image={metadata[meta.submittedBy]?.picture}
/>
)
})()}
</ListItem>
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Files
</Typography>
<ul>
{Object.keys(meta.fileHashes).map((file, index) => (
<li key={index} style={{ color: textColor }}>
{file}
</li>
))}
</ul>
</ListItem>
<ListItem sx={{ marginTop: 1 }}>
<Table>
<TableHead>
<TableRow>
<TableCell className={styles.tableCell}>User</TableCell>
<TableCell className={styles.tableCell}>Role</TableCell>
<TableCell>Signed Status</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map((user, index) => {
const userMeta = metadata[user.pubkey]
let signedStatus = '-'
if (user.role === UserRole.signer) {
// check if user has signed the document
const usersNpub = hexToNpub(user.pubkey)
if (usersNpub in meta.signedEvents) {
signedStatus = 'Signed'
}
// check if user is the next signer
else if (user.pubkey === nextSigner) {
signedStatus = 'Awaiting Signature'
}
}
return (
<TableRow key={index}>
<TableCell className={styles.tableCell}>
<UserComponent
pubkey={user.pubkey}
name={
userMeta?.display_name ||
userMeta?.name ||
shorten(hexToNpub(user.pubkey))
}
image={userMeta?.picture}
/>
</TableCell>
<TableCell className={styles.tableCell}>
{user.role}
</TableCell>
<TableCell>{signedStatus}</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</ListItem>
</List>
)
}

View File

@ -0,0 +1,31 @@
@import '../../colors.scss';
.container {
color: $text-color;
.inputBlock {
position: relative;
display: flex;
flex-direction: column;
gap: 25px;
}
.user {
display: flex;
align-items: center;
gap: 10px;
.name {
text-align: center;
cursor: pointer;
}
}
.tableCell {
border-right: 1px solid rgba(224, 224, 224, 1);
.user {
@extend .user;
}
}
}

View File

@ -4,168 +4,81 @@ import {
List,
ListItem,
ListSubheader,
Table,
TableBody,
TableCell,
TableHead,
TableRow,
TextField,
Typography,
useTheme
} from '@mui/material'
import axios from 'axios'
import saveAs from 'file-saver'
import JSZip from 'jszip'
import _ from 'lodash'
import { MuiFileInput } from 'mui-file-input'
import { EventTemplate } from 'nostr-tools'
import { Event, verifyEvent } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux'
import { Link, useSearchParams } from 'react-router-dom'
import { toast } from 'react-toastify'
import placeholderAvatar from '../../assets/images/nostr-logo.jpg'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { MetadataController, NostrController } from '../../controllers'
import { getProfileRoute } from '../../routes'
import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import { UserComponent } from '../../components/username'
import { MetadataController } from '../../controllers'
import { Meta, ProfileMetadata } from '../../types'
import {
decryptArrayBuffer,
encryptArrayBuffer,
generateEncryptionKey,
getHash,
hexToNpub,
npubToHex,
parseJson,
readContentOfZipEntry,
sendDM,
shorten,
signEventForMetaFile,
uploadToFileStorage
shorten
} from '../../utils'
import styles from './style.module.scss'
enum SignedStatus {
Fully_Signed,
User_Is_Next_Signer,
User_Is_Not_Next_Signer
}
export const VerifyPage = () => {
const [searchParams] = useSearchParams()
const theme = useTheme()
const [displayInput, setDisplayInput] = useState(false)
const textColor = theme.palette.getContrastText(
theme.palette.background.paper
)
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [encryptionKey, setEncryptionKey] = useState('')
const [zip, setZip] = useState<JSZip>()
const [isLoading, setIsLoading] = useState(true)
const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [meta, setMeta] = useState<Meta | null>(null)
const [signedStatus, setSignedStatus] = useState<SignedStatus>()
const [nextSinger, setNextSinger] = useState<string>()
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const [authUrl, setAuthUrl] = useState<string>()
const nostrController = NostrController.getInstance()
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
useEffect(() => {
if (meta) {
setDisplayInput(false)
const metadataController = new MetadataController()
// get list of users who have signed
const signedBy = Object.keys(meta.signedEvents)
const users = [meta.submittedBy, ...meta.signers, ...meta.viewers]
if (meta.signers.length > 0) {
// check if all signers have signed then its fully signed
if (meta.signers.every((signer) => signedBy.includes(signer))) {
setSignedStatus(SignedStatus.Fully_Signed)
} else {
for (const signer of meta.signers) {
if (!signedBy.includes(signer)) {
setNextSinger(signer)
users.forEach((user) => {
const pubkey = npubToHex(user)!
if (signer === usersPubkey) {
// logged in user is the next signer
setSignedStatus(SignedStatus.User_Is_Next_Signer)
} else {
setSignedStatus(SignedStatus.User_Is_Not_Next_Signer)
}
break
}
}
if (!(pubkey in metadata)) {
metadataController
.findMetadata(pubkey)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[pubkey]: metadataContent
}))
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user}`,
err
)
})
}
} else {
// there's no signer just viewers. So its fully signed
setSignedStatus(SignedStatus.Fully_Signed)
}
}
}, [meta, usersPubkey])
useEffect(() => {
const fileUrl = searchParams.get('file')
const key = searchParams.get('key')
if (fileUrl && key) {
setIsLoading(true)
setLoadingSpinnerDesc('Fetching file from file server')
axios
.get(fileUrl, {
responseType: 'arraybuffer'
})
.then((res) => {
const fileName = fileUrl.split('/').pop()
const file = new File([res.data], fileName!)
decrypt(file, key).then((arrayBuffer) => {
if (arrayBuffer) handleDecryptedArrayBuffer(arrayBuffer)
})
})
.catch((err) => {
console.error(`error occurred in getting file from ${fileUrl}`, err)
toast.error(
err.message || `error occurred in getting file from ${fileUrl}`
)
})
.finally(() => {
setIsLoading(false)
})
} else {
setIsLoading(false)
setDisplayInput(true)
}
}, [searchParams])
const decrypt = async (file: File, key: string) => {
setLoadingSpinnerDesc('Decrypting file')
const encryptedArrayBuffer = await file.arrayBuffer()
const arrayBuffer = await decryptArrayBuffer(encryptedArrayBuffer, key)
.catch((err) => {
console.log('err in decryption:>> ', err)
toast.error(err.message || 'An error occurred in decrypting file.')
return null
})
.finally(() => {
setIsLoading(false)
})
}
}, [meta])
return arrayBuffer
}
const handleVerify = async () => {
if (!selectedFile) return
setIsLoading(true)
const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => {
const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip')
setLoadingSpinnerDesc('Parsing zip file')
const zip = await JSZip.loadAsync(decryptedZipFile).catch((err) => {
const zip = await JSZip.loadAsync(selectedFile).catch((err) => {
console.log('err in loading zip file :>> ', err)
toast.error(err.message || 'An error occurred in loading zip file.')
return null
@ -173,8 +86,6 @@ export const VerifyPage = () => {
if (!zip) return
setZip(zip)
setLoadingSpinnerDesc('Parsing meta.json')
const metaFileContent = await readContentOfZipEntry(
@ -200,574 +111,220 @@ export const VerifyPage = () => {
)
setMeta(parsedMetaJson)
setIsLoading(false)
}
const handleDecrypt = async () => {
if (!selectedFile || !encryptionKey) return
const displayUser = (pubkey: string, verifySignature = false) => {
const profile = metadata[pubkey]
setIsLoading(true)
const arrayBuffer = await decrypt(selectedFile, encryptionKey)
let isValidSignature = false
if (!arrayBuffer) return
handleDecryptedArrayBuffer(arrayBuffer)
}
const handleSign = async () => {
if (!zip || !meta) return
setIsLoading(true)
setLoadingSpinnerDesc('parsing hashes.json file')
const hashesFileContent = await readContentOfZipEntry(
zip,
'hashes.json',
'string'
)
if (!hashesFileContent) {
setIsLoading(false)
return
}
let hashes = await parseJson(hashesFileContent).catch((err) => {
console.log('err in parsing the content of hashes.json :>> ', err)
toast.error(
err.message || 'error occurred in parsing the content of hashes.json'
)
setIsLoading(false)
return null
})
if (!hashes) return
setLoadingSpinnerDesc('Generating hashes for files')
const fileHashes: { [key: string]: string } = {}
const fileNames = Object.keys(meta.fileHashes)
// 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 filePath = `files/${fileName}`
const arrayBuffer = await readContentOfZipEntry(
zip,
filePath,
'arraybuffer'
)
if (!arrayBuffer) {
setIsLoading(false)
return
}
const hash = await getHash(arrayBuffer)
if (!hash) {
setIsLoading(false)
return
}
fileHashes[fileName] = hash
}
setLoadingSpinnerDesc('Signing nostr event')
const signedEvent = await signEventForMetaFile(
fileHashes,
nostrController,
setIsLoading
)
if (!signedEvent) return
const metaCopy = _.cloneDeep(meta)
metaCopy.signedEvents = {
...metaCopy.signedEvents,
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
}
const stringifiedMeta = JSON.stringify(metaCopy, null, 2)
zip.file('meta.json', stringifiedMeta)
const metaHash = await getHash(stringifiedMeta)
if (!metaHash) return
hashes = {
...hashes,
[usersPubkey!]: metaHash
}
zip.file('hashes.json', JSON.stringify(hashes, null, 2))
const arrayBuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: {
level: 6
if (verifySignature) {
const npub = hexToNpub(pubkey)
const signedEventString = meta ? meta.signedEvents[npub] : null
if (signedEventString) {
try {
const signedEvent = JSON.parse(signedEventString)
isValidSignature = verifyEvent(signedEvent)
} catch (error) {
console.error(
`An error occurred in parsing and verifying the signature event for ${pubkey}`,
error
)
}
})
.catch((err) => {
console.log('err in zip:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in generating zip file')
return null
})
}
}
if (!arrayBuffer) return
return (
<>
<UserComponent
pubkey={pubkey}
name={
profile?.display_name || profile?.name || shorten(hexToNpub(pubkey))
}
image={profile?.picture}
/>
const encryptionKey = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer(
arrayBuffer,
encryptionKey
{verifySignature && (
<Typography
component="label"
sx={{
color: isValidSignature
? theme.palette.text.primary
: theme.palette.error.main
}}
>
({isValidSignature ? 'Valid' : 'Invalid'} Signature)
</Typography>
)}
</>
)
}
const blob = new Blob([encryptedArrayBuffer])
const displayExportedBy = () => {
if (!meta || !meta.exportSignature) return null
setLoadingSpinnerDesc('Uploading zip file to file storage.')
const fileUrl = await uploadToFileStorage(blob, nostrController)
.then((url) => {
toast.success('zip file uploaded to file storage')
return url
})
.catch((err) => {
console.log('err in upload:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in uploading zip file')
return null
})
const exportSignatureString = meta.exportSignature
if (!fileUrl) return
try {
const exportSignatureEvent = JSON.parse(exportSignatureString) as Event
// check if the current user is the last signer
const lastSignerIndex = meta.signers.length - 1
const signerIndex = meta.signers.indexOf(usersPubkey!)
const isLastSigner = signerIndex === lastSignerIndex
// if current user is the last signer, then send DMs to all signers and viewers
if (isLastSigner) {
const userSet = new Set<string>()
userSet.add(meta.submittedBy)
meta.signers.forEach((signer) => {
userSet.add(signer)
})
meta.viewers.forEach((viewer) => {
userSet.add(viewer)
})
const users = Array.from(userSet)
for (const user of users) {
// todo: execute in parallel
await sendDM(
fileUrl,
encryptionKey,
user,
nostrController,
false,
setAuthUrl
if (verifyEvent(exportSignatureEvent)) {
return displayUser(exportSignatureEvent.pubkey)
} else {
toast.error(`Invalid export signature!`)
return (
<Typography component="label" sx={{ color: 'red' }}>
Invalid export signature
</Typography>
)
}
} else {
const nextSigner = meta.signers[signerIndex + 1]
await sendDM(
fileUrl,
encryptionKey,
nextSigner,
nostrController,
false,
setAuthUrl
)
}
setIsLoading(false)
}
const handleExport = async () => {
if (!meta || !zip || !usersPubkey) return
if (
!meta.signers.includes(usersPubkey) &&
!meta.viewers.includes(usersPubkey) &&
meta.submittedBy !== usersPubkey
)
return
setIsLoading(true)
setLoadingSpinnerDesc('Signing nostr event')
const event: EventTemplate = {
kind: 1,
content: '',
created_at: Math.floor(Date.now() / 1000), // Current timestamp
tags: []
}
// Sign the event
const signedEvent = await nostrController.signEvent(event).catch((err) => {
console.error(err)
toast.error(err.message || 'Error occurred in signing nostr event')
setIsLoading(false) // Set loading state to false
} catch (error) {
console.error(`An error occurred wile parsing exportSignature`, error)
return null
})
if (!signedEvent) return
const exportSignature = JSON.stringify(signedEvent, null, 2)
const stringifiedMeta = JSON.stringify(
{
...meta,
exportSignature
},
null,
2
)
zip.file('meta.json', stringifiedMeta)
const arrayBuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: {
level: 6
}
})
.catch((err) => {
console.log('err in zip:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in generating zip file')
return null
})
if (!arrayBuffer) return
const blob = new Blob([arrayBuffer])
saveAs(blob, 'exported.zip')
setIsLoading(false)
}
if (authUrl) {
return (
<iframe
title="Nsecbunker auth"
src={authUrl}
width="100%"
height="500px"
/>
)
}
}
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Box className={styles.container}>
{displayInput && (
{!meta && (
<>
<Typography component="label" variant="h6">
Select sigit file
Select exported zip file
</Typography>
<Box className={styles.inputBlock}>
<MuiFileInput
placeholder="Select file"
value={selectedFile}
onChange={(value) => setSelectedFile(value)}
InputProps={{
inputProps: {
accept: '.zip'
}
}}
/>
<MuiFileInput
placeholder="Select file"
value={selectedFile}
onChange={(value) => setSelectedFile(value)}
InputProps={{
inputProps: {
accept: '.zip'
}
}}
/>
{selectedFile && (
<TextField
label="Encryption Key"
variant="outlined"
value={encryptionKey}
onChange={(e) => setEncryptionKey(e.target.value)}
/>
)}
</Box>
{selectedFile && encryptionKey && (
{selectedFile && (
<Box sx={{ mt: 2, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleDecrypt} variant="contained">
Decrypt
<Button onClick={handleVerify} variant="contained">
Verify
</Button>
</Box>
)}
</>
)}
{meta && signedStatus === SignedStatus.Fully_Signed && (
{meta && (
<>
<DisplayMeta meta={meta} nextSigner={nextSinger} />
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant="contained">
Export
</Button>
</Box>
</>
)}
<List
sx={{
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader className={styles.subHeader}>
Meta Info
</ListSubheader>
}
>
<ListItem
sx={{
marginTop: 1,
gap: '15px'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Submitted By
</Typography>
{displayUser(npubToHex(meta.submittedBy)!)}
</ListItem>
{meta && signedStatus === SignedStatus.User_Is_Not_Next_Signer && (
<DisplayMeta meta={meta} nextSigner={nextSinger} />
)}
<ListItem
sx={{
marginTop: 1,
gap: '15px'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Exported By
</Typography>
{displayExportedBy()}
</ListItem>
{meta && signedStatus === SignedStatus.User_Is_Next_Signer && (
<>
<DisplayMeta meta={meta} nextSigner={nextSinger} />
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleSign} variant="contained">
Sign
</Button>
</Box>
{meta.signers.length > 0 && (
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Signers
</Typography>
<ul className={styles.usersList}>
{meta.signers.map((signer) => (
<li
key={signer}
style={{
color: textColor,
display: 'flex',
alignItems: 'center',
gap: '15px'
}}
>
{displayUser(npubToHex(signer)!, true)}
</li>
))}
</ul>
</ListItem>
)}
{meta.viewers.length > 0 && (
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Viewers
</Typography>
<ul className={styles.usersList}>
{meta.viewers.map((viewer) => (
<li key={viewer} style={{ color: textColor }}>
{displayUser(npubToHex(viewer)!)}
</li>
))}
</ul>
</ListItem>
)}
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Files
</Typography>
<ul>
{Object.keys(meta.fileHashes).map((file, index) => (
<li key={index} style={{ color: textColor }}>
{file}
</li>
))}
</ul>
</ListItem>
</List>
</>
)}
</Box>
</>
)
}
type DisplayMetaProps = {
meta: Meta
nextSigner?: string
}
const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
const theme = useTheme()
const textColor = theme.palette.getContrastText(
theme.palette.background.paper
)
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
const [users, setUsers] = useState<User[]>([])
useEffect(() => {
meta.signers.forEach((signer) => {
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === signer) !== -1) return prev
return [
...prev,
{
pubkey: signer,
role: UserRole.signer
}
]
})
})
meta.viewers.forEach((viewer) => {
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === viewer) !== -1) return prev
return [
...prev,
{
pubkey: viewer,
role: UserRole.viewer
}
]
})
})
}, [meta])
useEffect(() => {
const metadataController = new MetadataController()
metadataController
.findMetadata(meta.submittedBy)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[meta.submittedBy]: metadataContent
}))
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${meta.submittedBy}`,
err
)
})
users.forEach((user) => {
if (!(user.pubkey in metadata)) {
metadataController
.findMetadata(user.pubkey)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[user.pubkey]: metadataContent
}))
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user.pubkey}`,
err
)
})
}
})
}, [users, meta.submittedBy])
const imageLoadError = (event: any) => {
event.target.src = placeholderAvatar
}
const getRoboImageUrl = (pubkey: string) => {
const npub = hexToNpub(pubkey)
return `https://robohash.org/${npub}.png?set=set3`
}
return (
<List
sx={{
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader
sx={{
borderBottom: '0.5px solid',
paddingBottom: 1,
paddingTop: 1,
fontSize: '1.5rem'
}}
className={styles.subHeader}
>
Meta Info
</ListSubheader>
}
>
<ListItem
sx={{
marginTop: 1,
gap: '15px'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Submitted By
</Typography>
<Box className={styles.user}>
<img
onError={imageLoadError}
src={
metadata[meta.submittedBy]?.picture ||
getRoboImageUrl(meta.submittedBy)
}
alt="Profile Image"
className="profile-image"
style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${meta.submittedBy.substring(0, 6)}`
}}
/>
<Link to={getProfileRoute(meta.submittedBy)}>
<Typography component="label" className={styles.name}>
{metadata[meta.submittedBy]?.display_name ||
metadata[meta.submittedBy]?.name ||
shorten(hexToNpub(meta.submittedBy))}
</Typography>
</Link>
</Box>
</ListItem>
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Files
</Typography>
<ul>
{Object.keys(meta.fileHashes).map((file, index) => (
<li key={index} style={{ color: textColor }}>
{file}
</li>
))}
</ul>
</ListItem>
<ListItem sx={{ marginTop: 1 }}>
<Table>
<TableHead>
<TableRow>
<TableCell className={styles.tableCell}>User</TableCell>
<TableCell className={styles.tableCell}>Role</TableCell>
<TableCell>Signed Status</TableCell>
</TableRow>
</TableHead>
<TableBody>
{users.map((user, index) => {
const userMeta = metadata[user.pubkey]
const npub = hexToNpub(user.pubkey)
const roboUrl = `https://robohash.org/${npub}.png?set=set3`
let signedStatus = '-'
if (user.role === UserRole.signer) {
// check if user has signed the document
if (user.pubkey in meta.signedEvents) {
signedStatus = 'Signed'
}
// check if user is the next signer
else if (user.pubkey === nextSigner) {
signedStatus = 'Awaiting Signature'
}
}
return (
<TableRow key={index}>
<TableCell className={styles.tableCell}>
<Box className={styles.user}>
<img
onError={imageLoadError}
src={userMeta?.picture || roboUrl}
alt="Profile Image"
className="profile-image"
style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${user.pubkey.substring(0, 6)}`
}}
/>
<Link to={getProfileRoute(user.pubkey)}>
<Typography component="label" className={styles.name}>
{userMeta?.display_name ||
userMeta?.name ||
shorten(npub)}
</Typography>
</Link>
</Box>
</TableCell>
<TableCell className={styles.tableCell}>
{user.role}
</TableCell>
<TableCell>{signedStatus}</TableCell>
</TableRow>
)
})}
</TableBody>
</Table>
</ListItem>
</List>
)
}

View File

@ -2,12 +2,20 @@
.container {
color: $text-color;
display: flex;
flex-direction: column;
.inputBlock {
position: relative;
.subHeader {
border-bottom: 0.5px solid;
font-size: 1.5rem;
}
.usersList {
display: flex;
flex-direction: column;
gap: 25px;
gap: 10px;
list-style: none;
margin-top: 10px;
}
.user {

View File

@ -4,12 +4,16 @@ import { LandingPage } from '../pages/landing/LandingPage'
import { Login } from '../pages/login'
import { ProfilePage } from '../pages/profile'
import { hexToNpub } from '../utils'
import { RelaysPage } from '../pages/relays'
import { SignPage } from '../pages/sign'
import { VerifyPage } from '../pages/verify'
export const appPrivateRoutes = {
homePage: '/',
create: '/create',
verify: '/verify'
sign: '/sign',
verify: '/verify',
relays: '/relays'
}
export const appPublicRoutes = {
@ -48,8 +52,20 @@ export const privateRoutes = [
path: appPrivateRoutes.create,
element: <CreatePage />
},
{
path: appPrivateRoutes.relays,
element: <RelaysPage />
},
{
path: appPrivateRoutes.sign,
element: <SignPage />
},
{
path: appPrivateRoutes.verify,
element: <VerifyPage />
},
{
path: appPrivateRoutes.relays,
element: <RelaysPage />
}
]

View File

@ -7,3 +7,9 @@ export const UPDATE_NSECBUNKER_PUBKEY = 'UPDATE_NSECBUNKER_PUBKEY'
export const UPDATE_NSECBUNKER_RELAYS = 'UPDATE_NSECBUNKER_RELAYS'
export const SET_METADATA_EVENT = 'SET_METADATA_EVENT'
export const SET_RELAY_MAP = 'SET_RELAY_MAP'
export const SET_USER_ROBOT_IMAGE = 'SET_USER_ROBOT_IMAGE'
export const SET_RELAY_MAP = 'SET_RELAY_MAP'

View File

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

View File

@ -0,0 +1,8 @@
import * as ActionTypes from '../actionTypes'
import { SetRelayMapAction } from './types'
import { RelayMap } from '../../types'
export const setRelayMapAction = (payload: RelayMap): SetRelayMapAction => ({
type: ActionTypes.SET_RELAY_MAP,
payload
})

View File

@ -0,0 +1,22 @@
import * as ActionTypes from '../actionTypes'
import { RelaysDispatchTypes, RelaysState } from './types'
const initialState: RelaysState | null = null
const reducer = (
state = initialState,
action: RelaysDispatchTypes
): RelaysState | null => {
switch (action.type) {
case ActionTypes.SET_RELAY_MAP:
return { map: action.payload, mapUpdated: Date.now() }
case ActionTypes.RESTORE_STATE:
return action.payload.relays
default:
return state
}
}
export default reducer

12
src/store/relays/types.ts Normal file
View File

@ -0,0 +1,12 @@
import * as ActionTypes from '../actionTypes'
import { RestoreState } from '../actions'
import { RelayMap } from '../../types'
export type RelaysState = { map: RelayMap; mapUpdated: number }
export interface SetRelayMapAction {
type: typeof ActionTypes.SET_RELAY_MAP
payload: RelayMap
}
export type RelaysDispatchTypes = SetRelayMapAction | RestoreState

View File

@ -3,13 +3,20 @@ import { combineReducers } from 'redux'
import authReducer from './auth/reducer'
import { AuthState } from './auth/types'
import metadataReducer from './metadata/reducer'
import userRobotImageReducer from './userRobotImage/reducer'
import { RelaysState } from './relays/types'
import relaysReducer from './relays/reducer'
export interface State {
auth: AuthState
relays: RelaysState
metadata?: Event
userRobotImage?: string
}
export default combineReducers({
auth: authReducer,
metadata: metadataReducer
metadata: metadataReducer,
relays: relaysReducer,
userRobotImage: userRobotImageReducer
})

View File

@ -1,8 +1,11 @@
import { configureStore } from '@reduxjs/toolkit'
import rootReducer from './rootReducer'
const store = configureStore({ reducer: rootReducer })
const store = configureStore({
reducer: rootReducer
})
export default store
export type Dispatch = typeof store.dispatch
export type RootState = ReturnType<typeof store.getState>

View File

@ -0,0 +1,9 @@
import * as ActionTypes from '../actionTypes'
import { SetUserRobotImage } from './types'
export const setUserRobotImage = (
payload: string | null
): SetUserRobotImage => ({
type: ActionTypes.SET_USER_ROBOT_IMAGE,
payload
})

View File

@ -0,0 +1,22 @@
import * as ActionTypes from '../actionTypes'
import { MetadataDispatchTypes } from './types'
const initialState: string | null = null
const reducer = (
state = initialState,
action: MetadataDispatchTypes
): string | null | undefined => {
switch (action.type) {
case ActionTypes.SET_USER_ROBOT_IMAGE:
return action.payload
case ActionTypes.RESTORE_STATE:
return action.payload.userRobotImage
default:
return state
}
}
export default reducer

View File

@ -0,0 +1,9 @@
import * as ActionTypes from '../actionTypes'
import { RestoreState } from '../actions'
export interface SetUserRobotImage {
type: typeof ActionTypes.SET_USER_ROBOT_IMAGE
payload: string | null
}
export type MetadataDispatchTypes = SetUserRobotImage | RestoreState

View File

@ -9,9 +9,10 @@ export interface User {
}
export interface Meta {
signers: string[]
viewers: string[]
signers: `npub1${string}`[]
viewers: `npub1${string}`[]
fileHashes: { [key: string]: string }
submittedBy: string
signedEvents: { [key: string]: string }
submittedBy: `npub1${string}`
signedEvents: { [key: `npub1${string}`]: string }
exportSignature?: string
}

View File

@ -17,3 +17,10 @@ export interface NostrJoiningBlock {
block: number
encodedEventPointer: string
}
export type RelayMap = {
[key: string]: {
read: boolean
write: boolean
}
}

View File

@ -5,3 +5,4 @@ export * from './misc'
export * from './nostr'
export * from './string'
export * from './zip'
export * from './utils'

View File

@ -22,6 +22,10 @@ export const loadState = (): State | undefined => {
}
}
export const clearState = () => {
localStorage.removeItem('state')
}
export const saveNsecBunkerDelegatedKey = (privateKey: string) => {
localStorage.setItem('nsecbunker-delegated-key', privateKey)
}

View File

@ -76,12 +76,12 @@ export const sendDM = async (
: 'You have received a signed document.'
const decryptionUrl = `${window.location.origin}/#${
appPrivateRoutes.verify
appPrivateRoutes.sign
}?file=${encodeURIComponent(fileUrl)}&key=${encodeURIComponent(
encryptionKey
)}`
const content = `${initialLine}\n\n${decryptionUrl}\n\nDirect download${fileUrl}`
const content = `${initialLine}\n\n${decryptionUrl}`
// Set up event listener for authentication event
nostrController.on('nsecbunker-auth', (url) => {

View File

@ -17,21 +17,21 @@ const validateHex = (hexKey: string) => {
* @param pubKey in NPUB, HEX format
* @returns HEX format
*/
export const pubToHex = async (pubKey: string): Promise<string | null> => {
export const npubToHex = (pubKey: string): string | null => {
// If key is NPUB
if (pubKey.startsWith('npub')) {
if (pubKey.startsWith('npub1')) {
try {
return nip19.decode(pubKey).data as string
} catch (error) {
return Promise.resolve(null)
return null
}
}
// valid hex key
if (validateHex(pubKey)) return Promise.resolve(pubKey)
if (validateHex(pubKey)) return pubKey
// Not a valid hex key
return Promise.resolve(null)
return null
}
/**
@ -56,8 +56,8 @@ export const nsecToHex = (nsec: string): string | null => {
return null
}
export const hexToNpub = (hexPubkey: string | undefined): string => {
if (!hexPubkey) return 'n/a'
export const hexToNpub = (hexPubkey: string): `npub1${string}` => {
if (hexPubkey.startsWith('npub1')) return hexPubkey as `npub1${string}`
return nip19.npubEncode(hexPubkey)
}
@ -138,3 +138,16 @@ export const base64DecodeAuthToken = (authToken: string): SignedEvent => {
throw new Error('An error occurred in JSON.parse of the auth token')
}
}
/**
* @param pubkey in hex or npub format
* @returns robohash.org url for the avatar
*/
export const getRoboHashPicture = (
pubkey?: string,
set: number = 1
): string => {
if (!pubkey) return ''
const npub = hexToNpub(pubkey)
return `https://robohash.org/${npub}.png?set=set${set}`
}

13
src/utils/utils.ts Normal file
View File

@ -0,0 +1,13 @@
export const compareObjects = (
obj1: object | null | undefined,
obj2: object | null | undefined
): boolean => {
if (Array.isArray(obj1) && Array.isArray(obj2)) {
const obj1Copy = [...obj1].sort()
const obj2Copy = [...obj2].sort()
return JSON.stringify(obj1Copy) === JSON.stringify(obj2Copy)
}
return JSON.stringify(obj1) === JSON.stringify(obj2)
}

View File

@ -17,6 +17,11 @@ export const readContentOfZipEntry = async <T extends OutputType>(
// Get the zip entry corresponding to the specified file path
const zipEntry = zip.files[filePath]
if (!zipEntry) {
toast.error(`Couldn't find file in zip archive at ${filePath}`)
return null
}
// Read the content of the zip entry asynchronously
const fileContent = await zipEntry.async(outputType).catch((err) => {
// Handle any errors that occur during the read operation