Compare commits

..

No commits in common. "5b1cd8ccbdb2da5a0480a386dd36ae282cafa438" and "706025a7a4895f7f37b6f8bf6a3f3e7c8f0f2c04" have entirely different histories.

11 changed files with 229 additions and 230 deletions

16
package-lock.json generated
View File

@ -44,7 +44,6 @@
"eslint": "^8.56.0", "eslint": "^8.56.0",
"eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5", "eslint-plugin-react-refresh": "^0.4.5",
"prettier": "3.2.5",
"ts-css-modules-vite-plugin": "1.0.20", "ts-css-modules-vite-plugin": "1.0.20",
"typescript": "^5.2.2", "typescript": "^5.2.2",
"vite": "^5.1.4" "vite": "^5.1.4"
@ -4301,21 +4300,6 @@
"node": ">= 0.8.0" "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": { "node_modules/pretty-bytes": {
"version": "6.1.1", "version": "6.1.1",
"resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-6.1.1.tgz", "resolved": "https://registry.npmjs.org/pretty-bytes/-/pretty-bytes-6.1.1.tgz",

View File

@ -9,8 +9,8 @@
"build": "tsc && vite build", "build": "tsc && vite build",
"lint": "eslint . --ext ts,tsx --report-unused-disable-directives --max-warnings 0", "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", "lint:fix": "eslint . --fix --ext ts,tsx --report-unused-disable-directives --max-warnings 0",
"formatter:check": "prettier --check \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"", "formatter:check": "npx 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}\"", "formatter:fix": "npx prettier --write \"src/**/*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}\"",
"preview": "vite preview" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
@ -50,7 +50,6 @@
"eslint": "^8.56.0", "eslint": "^8.56.0",
"eslint-plugin-react-hooks": "^4.6.0", "eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5", "eslint-plugin-react-refresh": "^0.4.5",
"prettier": "3.2.5",
"ts-css-modules-vite-plugin": "1.0.20", "ts-css-modules-vite-plugin": "1.0.20",
"typescript": "^5.2.2", "typescript": "^5.2.2",
"vite": "^5.1.4" "vite": "^5.1.4"

View File

@ -43,14 +43,12 @@ export const AppBar = () => {
useEffect(() => { useEffect(() => {
if (metadataState) { if (metadataState) {
if (metadataState.content) { if (metadataState.content) {
const { picture, display_name, name } = JSON.parse( const { picture, display_name, name } = JSON.parse(metadataState.content)
metadataState.content
)
if (picture) { if (picture) {
setUserAvatar(picture) setUserAvatar(picture)
} }
setUsername(shorten(display_name || name || '', 7)) setUsername(shorten(display_name || name || '', 7))
} else { } else {
setUserAvatar('') setUserAvatar('')
@ -86,7 +84,9 @@ export const AppBar = () => {
}) })
) )
dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent())) dispatch(
setMetadataEvent(metadataController.getEmptyMetadataEvent())
)
// clear authToken saved in local storage // clear authToken saved in local storage
clearAuthToken() clearAuthToken()

View File

@ -1,9 +1,6 @@
import { Typography, IconButton, Box, useTheme } from '@mui/material' import { Typography, IconButton } from '@mui/material'
import { useSelector } from 'react-redux' import { useSelector } from 'react-redux'
import { State } from '../store/rootReducer' import { State } from '../store/rootReducer'
import { hexToNpub } from '../utils'
import { Link } from 'react-router-dom'
import { getProfileRoute } from '../routes'
type Props = { type Props = {
username: string username: string
@ -47,47 +44,3 @@ const Username = ({ username, avatarContent, handleClick }: Props) => {
} }
export default Username 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

@ -5,12 +5,7 @@ import { useDispatch } from 'react-redux'
import { Outlet } from 'react-router-dom' import { Outlet } from 'react-router-dom'
import { AppBar } from '../components/AppBar/AppBar' import { AppBar } from '../components/AppBar/AppBar'
import { restoreState, setAuthState, setMetadataEvent } from '../store/actions' import { restoreState, setAuthState, setMetadataEvent } from '../store/actions'
import { import { clearAuthToken, clearState, loadState, saveNsecBunkerDelegatedKey } from '../utils'
clearAuthToken,
clearState,
loadState,
saveNsecBunkerDelegatedKey
} from '../utils'
import { LoadingSpinner } from '../components/LoadingSpinner' import { LoadingSpinner } from '../components/LoadingSpinner'
import { Dispatch } from '../store/store' import { Dispatch } from '../store/store'
import { MetadataController, NostrController } from '../controllers' import { MetadataController, NostrController } from '../controllers'
@ -34,7 +29,9 @@ export const MainLayout = () => {
}) })
) )
dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent())) dispatch(
setMetadataEvent(metadataController.getEmptyMetadataEvent())
)
// clear authToken saved in local storage // clear authToken saved in local storage
clearAuthToken() clearAuthToken()

View File

@ -18,24 +18,20 @@ import {
Tooltip, Tooltip,
Typography Typography
} from '@mui/material' } from '@mui/material'
import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input' import { MuiFileInput } from 'mui-file-input'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux' import { Link, useNavigate } from 'react-router-dom'
import { useNavigate } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers' import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes' import { appPrivateRoutes, getProfileRoute } from '../../routes'
import { State } from '../../store/rootReducer' import { ProfileMetadata, User, UserRole } from '../../types'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import { import {
encryptArrayBuffer, encryptArrayBuffer,
generateEncryptionKey, generateEncryptionKey,
getHash, getHash,
getRoboHashPicture,
hexToNpub, hexToNpub,
npubToHex, pubToHex,
queryNip05, queryNip05,
sendDM, sendDM,
shorten, shorten,
@ -43,6 +39,10 @@ import {
uploadToFileStorage uploadToFileStorage
} from '../../utils' } from '../../utils'
import styles from './style.module.scss' 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'
export const CreatePage = () => { export const CreatePage = () => {
const navigate = useNavigate() const navigate = useNavigate()
@ -109,7 +109,7 @@ export const CreatePage = () => {
} }
if (userInput.startsWith('npub')) { if (userInput.startsWith('npub')) {
const pubkey = npubToHex(userInput) const pubkey = await pubToHex(userInput)
if (pubkey) { if (pubkey) {
addUser(pubkey) addUser(pubkey)
setUserInput('') setUserInput('')
@ -246,13 +246,13 @@ export const CreatePage = () => {
if (!signedEvent) return if (!signedEvent) return
// create content for meta file // create content for meta file
const meta: Meta = { const meta = {
signers: signers.map((signer) => hexToNpub(signer.pubkey)), signers: signers.map((signer) => signer.pubkey),
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)), viewers: viewers.map((viewer) => viewer.pubkey),
fileHashes, fileHashes,
submittedBy: hexToNpub(usersPubkey!), submittedBy: usersPubkey,
signedEvents: { signedEvents: {
[hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2) [signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
} }
} }
@ -489,6 +489,15 @@ const DisplayUser = ({
}) })
}, [users]) }, [users])
/**
* Use robohash if any of the users images fail to load
* @param event img tag onError event
* @param pubkey of the user
*/
const imageLoadError = (event: any, pubkey: string) => {
event.target.src = getRoboHashPicture(pubkey)
}
return ( return (
<TableContainer component={Paper} elevation={3} sx={{ marginTop: '20px' }}> <TableContainer component={Paper} elevation={3} sx={{ marginTop: '20px' }}>
<Table> <Table>
@ -502,18 +511,31 @@ const DisplayUser = ({
<TableBody> <TableBody>
{users.map((user, index) => { {users.map((user, index) => {
const userMeta = metadata[user.pubkey] const userMeta = metadata[user.pubkey]
const npub = hexToNpub(user.pubkey)
const roboUrl = `https://robohash.org/${npub}.png?set=set3`
return ( return (
<TableRow key={index}> <TableRow key={index}>
<TableCell className={styles.tableCell}> <TableCell className={styles.tableCell}>
<UserComponent <Box className={styles.user}>
pubkey={user.pubkey} <img
name={ onError={(event) => {imageLoadError(event, user.pubkey)}}
userMeta?.display_name || src={userMeta?.picture || roboUrl}
userMeta?.name || alt="Profile Image"
shorten(hexToNpub(user.pubkey)) className="profile-image"
} style={{
image={userMeta?.picture} 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>
<TableCell className={styles.tableCell}> <TableCell className={styles.tableCell}>
<Select <Select

View File

@ -18,7 +18,7 @@ import {
} from '../../store/actions' } from '../../store/actions'
import { LoginMethods } from '../../store/auth/types' import { LoginMethods } from '../../store/auth/types'
import { Dispatch } from '../../store/store' import { Dispatch } from '../../store/store'
import { npubToHex, queryNip05 } from '../../utils' import { pubToHex, queryNip05 } from '../../utils'
import styles from './style.module.scss' import styles from './style.module.scss'
export const Login = () => { export const Login = () => {
@ -213,7 +213,7 @@ export const Login = () => {
const keyEndIndex = inputValue.indexOf('?relay=') const keyEndIndex = inputValue.indexOf('?relay=')
const key = inputValue.substring(keyStartIndex, keyEndIndex) const key = inputValue.substring(keyStartIndex, keyEndIndex)
const pubkey = npubToHex(key) const pubkey = await pubToHex(key)
if (!pubkey) { if (!pubkey) {
toast.error('Invalid pubkey in bunker connection string.') toast.error('Invalid pubkey in bunker connection string.')

View File

@ -21,12 +21,12 @@ import { MuiFileInput } from 'mui-file-input'
import { EventTemplate } from 'nostr-tools' import { EventTemplate } from 'nostr-tools'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { useSelector } from 'react-redux' import { useSelector } from 'react-redux'
import { useNavigate, useSearchParams } from 'react-router-dom' import { Link, useNavigate, useSearchParams } from 'react-router-dom'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import placeholderAvatar from '../../assets/images/nostr-logo.jpg'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers' import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes' import { appPrivateRoutes, getProfileRoute } from '../../routes'
import { State } from '../../store/rootReducer' import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types' import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import { import {
@ -36,7 +36,6 @@ import {
getHash, getHash,
hexToNpub, hexToNpub,
parseJson, parseJson,
npubToHex,
readContentOfZipEntry, readContentOfZipEntry,
sendDM, sendDM,
shorten, shorten,
@ -89,13 +88,9 @@ export const SignPage = () => {
} else { } else {
for (const signer of meta.signers) { for (const signer of meta.signers) {
if (!signedBy.includes(signer)) { if (!signedBy.includes(signer)) {
// signers in meta.json are in npub1 format setNextSinger(signer)
// so, convert it to hex before setting to nextSigner
setNextSinger(npubToHex(signer)!)
const usersNpub = hexToNpub(usersPubkey!) if (signer === usersPubkey) {
if (signer === usersNpub) {
// logged in user is the next signer // logged in user is the next signer
setSignedStatus(SignedStatus.User_Is_Next_Signer) setSignedStatus(SignedStatus.User_Is_Next_Signer)
} else { } else {
@ -292,7 +287,7 @@ export const SignPage = () => {
metaCopy.signedEvents = { metaCopy.signedEvents = {
...metaCopy.signedEvents, ...metaCopy.signedEvents,
[hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2) [signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2)
} }
const stringifiedMeta = JSON.stringify(metaCopy, null, 2) const stringifiedMeta = JSON.stringify(metaCopy, null, 2)
@ -325,10 +320,13 @@ export const SignPage = () => {
if (!arrayBuffer) return if (!arrayBuffer) return
const key = await generateEncryptionKey() const encryptionKey = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file') setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer(arrayBuffer, key) const encryptedArrayBuffer = await encryptArrayBuffer(
arrayBuffer,
encryptionKey
)
const blob = new Blob([encryptedArrayBuffer]) const blob = new Blob([encryptedArrayBuffer])
@ -348,14 +346,13 @@ export const SignPage = () => {
if (!fileUrl) return if (!fileUrl) return
// check if the current user is the last signer // check if the current user is the last signer
const usersNpub = hexToNpub(usersPubkey!)
const lastSignerIndex = meta.signers.length - 1 const lastSignerIndex = meta.signers.length - 1
const signerIndex = meta.signers.indexOf(usersNpub) const signerIndex = meta.signers.indexOf(usersPubkey!)
const isLastSigner = signerIndex === lastSignerIndex const isLastSigner = signerIndex === lastSignerIndex
// if current user is the last signer, then send DMs to all signers and viewers // if current user is the last signer, then send DMs to all signers and viewers
if (isLastSigner) { if (isLastSigner) {
const userSet = new Set<`npub1${string}`>() const userSet = new Set<string>()
userSet.add(meta.submittedBy) userSet.add(meta.submittedBy)
@ -373,19 +370,27 @@ export const SignPage = () => {
// todo: execute in parallel // todo: execute in parallel
await sendDM( await sendDM(
fileUrl, fileUrl,
key, encryptionKey,
npubToHex(user)!, user,
nostrController, nostrController,
false, false,
setAuthUrl setAuthUrl
) )
} }
// when user is the last signer and has sent
// the final document to all the signers and viewers
// update search params with updated file url and encryption key
setSearchParams({
file: fileUrl,
key: encryptionKey
})
} else { } else {
const nextSigner = meta.signers[signerIndex + 1] const nextSigner = meta.signers[signerIndex + 1]
await sendDM( await sendDM(
fileUrl, fileUrl,
key, encryptionKey,
npubToHex(nextSigner)!, nextSigner,
nostrController, nostrController,
false, false,
setAuthUrl setAuthUrl
@ -393,22 +398,15 @@ export const SignPage = () => {
} }
setIsLoading(false) setIsLoading(false)
// update search params with updated file url and encryption key
setSearchParams({
file: fileUrl,
key: key
})
} }
const handleExport = async () => { const handleExport = async () => {
if (!meta || !zip || !usersPubkey) return if (!meta || !zip || !usersPubkey) return
const usersNpub = hexToNpub(usersPubkey)
if ( if (
!meta.signers.includes(usersNpub) && !meta.signers.includes(usersPubkey) &&
!meta.viewers.includes(usersNpub) && !meta.viewers.includes(usersPubkey) &&
meta.submittedBy !== usersNpub meta.submittedBy !== usersPubkey
) )
return return
@ -565,14 +563,13 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
useEffect(() => { useEffect(() => {
meta.signers.forEach((signer) => { meta.signers.forEach((signer) => {
const hexKey = npubToHex(signer)
setUsers((prev) => { setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === hexKey) !== -1) return prev if (prev.findIndex((user) => user.pubkey === signer) !== -1) return prev
return [ return [
...prev, ...prev,
{ {
pubkey: hexKey!, pubkey: signer,
role: UserRole.signer role: UserRole.signer
} }
] ]
@ -580,14 +577,13 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
}) })
meta.viewers.forEach((viewer) => { meta.viewers.forEach((viewer) => {
const hexKey = npubToHex(viewer)
setUsers((prev) => { setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === hexKey) !== -1) return prev if (prev.findIndex((user) => user.pubkey === viewer) !== -1) return prev
return [ return [
...prev, ...prev,
{ {
pubkey: hexKey!, pubkey: viewer,
role: UserRole.viewer role: UserRole.viewer
} }
] ]
@ -598,32 +594,56 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
useEffect(() => { useEffect(() => {
const metadataController = new MetadataController() const metadataController = new MetadataController()
const hexKeys: string[] = [ metadataController
npubToHex(meta.submittedBy)!, .findMetadata(meta.submittedBy)
...users.map((user) => user.pubkey) .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
)
})
hexKeys.forEach((key) => { users.forEach((user) => {
if (!(key in metadata)) { if (!(user.pubkey in metadata)) {
metadataController metadataController
.findMetadata(key) .findMetadata(user.pubkey)
.then((metadataEvent) => { .then((metadataEvent) => {
const metadataContent = const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent) metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent) if (metadataContent)
setMetadata((prev) => ({ setMetadata((prev) => ({
...prev, ...prev,
[key]: metadataContent [user.pubkey]: metadataContent
})) }))
}) })
.catch((err) => { .catch((err) => {
console.error(`error occurred in finding metadata for: ${key}`, err) console.error(
`error occurred in finding metadata for: ${user.pubkey}`,
err
)
}) })
} }
}) })
}, [users, meta.submittedBy]) }, [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 ( return (
<List <List
sx={{ sx={{
@ -653,21 +673,29 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
<Typography variant="h6" sx={{ color: textColor }}> <Typography variant="h6" sx={{ color: textColor }}>
Submitted By Submitted By
</Typography> </Typography>
{(function () { <Box className={styles.user}>
const pubkey = npubToHex(meta.submittedBy) <img
const profile = metadata[pubkey!] onError={imageLoadError}
return ( src={
<UserComponent metadata[meta.submittedBy]?.picture ||
pubkey={pubkey!} getRoboImageUrl(meta.submittedBy)
name={ }
profile?.display_name || alt="Profile Image"
profile?.name || className="profile-image"
shorten(meta.submittedBy) style={{
} borderWidth: '3px',
image={metadata[meta.submittedBy]?.picture} 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>
<ListItem <ListItem
sx={{ sx={{
@ -699,13 +727,14 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
<TableBody> <TableBody>
{users.map((user, index) => { {users.map((user, index) => {
const userMeta = metadata[user.pubkey] const userMeta = metadata[user.pubkey]
const npub = hexToNpub(user.pubkey)
const roboUrl = `https://robohash.org/${npub}.png?set=set3`
let signedStatus = '-' let signedStatus = '-'
if (user.role === UserRole.signer) { if (user.role === UserRole.signer) {
// check if user has signed the document // check if user has signed the document
const usersNpub = hexToNpub(user.pubkey) if (user.pubkey in meta.signedEvents) {
if (usersNpub in meta.signedEvents) {
signedStatus = 'Signed' signedStatus = 'Signed'
} }
// check if user is the next signer // check if user is the next signer
@ -717,15 +746,26 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
return ( return (
<TableRow key={index}> <TableRow key={index}>
<TableCell className={styles.tableCell}> <TableCell className={styles.tableCell}>
<UserComponent <Box className={styles.user}>
pubkey={user.pubkey} <img
name={ onError={imageLoadError}
userMeta?.display_name || src={userMeta?.picture || roboUrl}
userMeta?.name || alt="Profile Image"
shorten(hexToNpub(user.pubkey)) className="profile-image"
} style={{
image={userMeta?.picture} 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>
<TableCell className={styles.tableCell}> <TableCell className={styles.tableCell}>
{user.role} {user.role}

View File

@ -9,21 +9,22 @@ import {
} from '@mui/material' } from '@mui/material'
import JSZip from 'jszip' import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input' import { MuiFileInput } from 'mui-file-input'
import { Event, verifyEvent } from 'nostr-tools'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserComponent } from '../../components/username'
import { MetadataController } from '../../controllers' import { MetadataController } from '../../controllers'
import { getProfileRoute } from '../../routes'
import { Meta, ProfileMetadata } from '../../types' import { Meta, ProfileMetadata } from '../../types'
import { import {
getRoboHashPicture,
hexToNpub, hexToNpub,
npubToHex,
parseJson, parseJson,
readContentOfZipEntry, readContentOfZipEntry,
shorten shorten
} from '../../utils' } from '../../utils'
import styles from './style.module.scss' import styles from './style.module.scss'
import { Event, verifyEvent } from 'nostr-tools'
export const VerifyPage = () => { export const VerifyPage = () => {
const theme = useTheme() const theme = useTheme()
@ -49,18 +50,16 @@ export const VerifyPage = () => {
const users = [meta.submittedBy, ...meta.signers, ...meta.viewers] const users = [meta.submittedBy, ...meta.signers, ...meta.viewers]
users.forEach((user) => { users.forEach((user) => {
const pubkey = npubToHex(user)! if (!(user in metadata)) {
if (!(pubkey in metadata)) {
metadataController metadataController
.findMetadata(pubkey) .findMetadata(user)
.then((metadataEvent) => { .then((metadataEvent) => {
const metadataContent = const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent) metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent) if (metadataContent)
setMetadata((prev) => ({ setMetadata((prev) => ({
...prev, ...prev,
[pubkey]: metadataContent [user]: metadataContent
})) }))
}) })
.catch((err) => { .catch((err) => {
@ -114,14 +113,22 @@ export const VerifyPage = () => {
setIsLoading(false) setIsLoading(false)
} }
const imageLoadError = (event: any, pubkey: string) => {
const npub = hexToNpub(pubkey)
event.target.src = getRoboImageUrl(npub)
}
const getRoboImageUrl = (pubkey: string) => {
return getRoboHashPicture(pubkey)
}
const displayUser = (pubkey: string, verifySignature = false) => { const displayUser = (pubkey: string, verifySignature = false) => {
const profile = metadata[pubkey] const profile = metadata[pubkey]
let isValidSignature = false let isValidSignature = false
if (verifySignature) { if (verifySignature) {
const npub = hexToNpub(pubkey) const signedEventString = meta ? meta.signedEvents[pubkey] : null
const signedEventString = meta ? meta.signedEvents[npub] : null
if (signedEventString) { if (signedEventString) {
try { try {
const signedEvent = JSON.parse(signedEventString) const signedEvent = JSON.parse(signedEventString)
@ -136,28 +143,31 @@ export const VerifyPage = () => {
} }
return ( return (
<> <Box className={styles.user}>
<UserComponent <img
pubkey={pubkey} onError={(event) => {imageLoadError(event, pubkey)}}
name={ src={profile?.picture || getRoboImageUrl(pubkey)}
profile?.display_name || profile?.name || shorten(hexToNpub(pubkey)) alt="Profile Image"
} className="profile-image"
image={profile?.picture} style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${pubkey.substring(0, 6)}`
}}
/> />
<Link to={getProfileRoute(pubkey)}>
<Typography component="label" className={styles.name}>
{profile?.display_name ||
profile?.name ||
shorten(hexToNpub(pubkey))}
</Typography>
</Link>
{verifySignature && ( {verifySignature && (
<Typography <Typography component="label">
component="label" ({isValidSignature ? 'Valid' : 'Not Valid'} Signature)
sx={{
color: isValidSignature
? theme.palette.text.primary
: theme.palette.error.main
}}
>
({isValidSignature ? 'Valid' : 'Invalid'} Signature)
</Typography> </Typography>
)} )}
</> </Box>
) )
} }
@ -238,7 +248,7 @@ export const VerifyPage = () => {
<Typography variant="h6" sx={{ color: textColor }}> <Typography variant="h6" sx={{ color: textColor }}>
Submitted By Submitted By
</Typography> </Typography>
{displayUser(npubToHex(meta.submittedBy)!)} {displayUser(meta.submittedBy)}
</ListItem> </ListItem>
<ListItem <ListItem
@ -266,16 +276,8 @@ export const VerifyPage = () => {
</Typography> </Typography>
<ul className={styles.usersList}> <ul className={styles.usersList}>
{meta.signers.map((signer) => ( {meta.signers.map((signer) => (
<li <li key={signer} style={{ color: textColor }}>
key={signer} {displayUser(signer, true)}
style={{
color: textColor,
display: 'flex',
alignItems: 'center',
gap: '15px'
}}
>
{displayUser(npubToHex(signer)!, true)}
</li> </li>
))} ))}
</ul> </ul>
@ -296,7 +298,7 @@ export const VerifyPage = () => {
<ul className={styles.usersList}> <ul className={styles.usersList}>
{meta.viewers.map((viewer) => ( {meta.viewers.map((viewer) => (
<li key={viewer} style={{ color: textColor }}> <li key={viewer} style={{ color: textColor }}>
{displayUser(npubToHex(viewer)!)} {displayUser(viewer)}
</li> </li>
))} ))}
</ul> </ul>

View File

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

View File

@ -17,21 +17,21 @@ const validateHex = (hexKey: string) => {
* @param pubKey in NPUB, HEX format * @param pubKey in NPUB, HEX format
* @returns HEX format * @returns HEX format
*/ */
export const npubToHex = (pubKey: string): string | null => { export const pubToHex = async (pubKey: string): Promise<string | null> => {
// If key is NPUB // If key is NPUB
if (pubKey.startsWith('npub1')) { if (pubKey.startsWith('npub')) {
try { try {
return nip19.decode(pubKey).data as string return nip19.decode(pubKey).data as string
} catch (error) { } catch (error) {
return null return Promise.resolve(null)
} }
} }
// valid hex key // valid hex key
if (validateHex(pubKey)) return pubKey if (validateHex(pubKey)) return Promise.resolve(pubKey)
// Not a valid hex key // Not a valid hex key
return null return Promise.resolve(null)
} }
/** /**
@ -56,8 +56,9 @@ export const nsecToHex = (nsec: string): string | null => {
return null return null
} }
export const hexToNpub = (hexPubkey: string): `npub1${string}` => { export const hexToNpub = (hexPubkey: string | undefined): string => {
if (hexPubkey.startsWith('npub1')) return hexPubkey as `npub1${string}` if (!hexPubkey) return 'n/a'
if (hexPubkey.includes('npub')) return hexPubkey
return nip19.npubEncode(hexPubkey) return nip19.npubEncode(hexPubkey)
} }
@ -140,7 +141,8 @@ export const base64DecodeAuthToken = (authToken: string): SignedEvent => {
} }
/** /**
* @param pubkey in hex or npub format *
* @param pubkey in hex or npub format
* @returns robohash.org url for the avatar * @returns robohash.org url for the avatar
*/ */
export const getRoboHashPicture = (pubkey: string): string => { export const getRoboHashPicture = (pubkey: string): string => {