Compare commits

...

6 Commits

Author SHA1 Message Date
b
5b1cd8ccbd Merge pull request 'issue-40' (#52) from issue-40 into main
All checks were successful
Release / build_and_release (push) Successful in 1m6s
Reviewed-on: https://git.sigit.io/sig/it/pulls/52
Reviewed-by: Y <yury@4gl.io>
2024-05-17 09:23:50 +00:00
SwiftHawk
752fca3701 chore: install prettier locally as dev dep 2024-05-17 14:12:18 +05:00
SwiftHawk
4f11b1c4a8 chore: add comments 2024-05-17 13:59:03 +05:00
SwiftHawk
52bf4fd934 Merge branch 'main' into issue-40 2024-05-17 13:43:17 +05:00
SwiftHawk
ee2f0cbc97 feat: convert hexkeys to npub in meta.json 2024-05-17 13:34:56 +05:00
SwiftHawk
41f821159a chore create a component for user 2024-05-16 16:22:05 +05:00
11 changed files with 230 additions and 229 deletions

16
package-lock.json generated
View File

@ -44,6 +44,7 @@
"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"
@ -4300,6 +4301,21 @@
"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": "npx prettier --check \"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": "npx prettier --write \"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" "preview": "vite preview"
}, },
"dependencies": { "dependencies": {
@ -50,6 +50,7 @@
"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,12 +43,14 @@ export const AppBar = () => {
useEffect(() => { useEffect(() => {
if (metadataState) { if (metadataState) {
if (metadataState.content) { if (metadataState.content) {
const { picture, display_name, name } = JSON.parse(metadataState.content) const { picture, display_name, name } = JSON.parse(
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('')
@ -84,9 +86,7 @@ export const AppBar = () => {
}) })
) )
dispatch( dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent()))
setMetadataEvent(metadataController.getEmptyMetadataEvent())
)
// clear authToken saved in local storage // clear authToken saved in local storage
clearAuthToken() clearAuthToken()

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 { 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
@ -44,3 +47,47 @@ 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,7 +5,12 @@ 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 { clearAuthToken, clearState, loadState, saveNsecBunkerDelegatedKey } from '../utils' import {
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'
@ -29,9 +34,7 @@ export const MainLayout = () => {
}) })
) )
dispatch( dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent()))
setMetadataEvent(metadataController.getEmptyMetadataEvent())
)
// clear authToken saved in local storage // clear authToken saved in local storage
clearAuthToken() clearAuthToken()

View File

@ -18,20 +18,24 @@ 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 { Link, useNavigate } from 'react-router-dom' import { useSelector } from 'react-redux'
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, getProfileRoute } from '../../routes' import { appPrivateRoutes } from '../../routes'
import { ProfileMetadata, User, UserRole } from '../../types' import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import { import {
encryptArrayBuffer, encryptArrayBuffer,
generateEncryptionKey, generateEncryptionKey,
getHash, getHash,
getRoboHashPicture,
hexToNpub, hexToNpub,
pubToHex, npubToHex,
queryNip05, queryNip05,
sendDM, sendDM,
shorten, shorten,
@ -39,10 +43,6 @@ 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 = await pubToHex(userInput) const pubkey = npubToHex(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 = { const meta: Meta = {
signers: signers.map((signer) => signer.pubkey), signers: signers.map((signer) => hexToNpub(signer.pubkey)),
viewers: viewers.map((viewer) => viewer.pubkey), viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
fileHashes, fileHashes,
submittedBy: usersPubkey, submittedBy: hexToNpub(usersPubkey!),
signedEvents: { signedEvents: {
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2) [hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2)
} }
} }
@ -489,15 +489,6 @@ 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>
@ -511,31 +502,18 @@ 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}>
<Box className={styles.user}> <UserComponent
<img pubkey={user.pubkey}
onError={(event) => {imageLoadError(event, user.pubkey)}} name={
src={userMeta?.picture || roboUrl} userMeta?.display_name ||
alt="Profile Image" userMeta?.name ||
className="profile-image" shorten(hexToNpub(user.pubkey))
style={{ }
borderWidth: '3px', image={userMeta?.picture}
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 { pubToHex, queryNip05 } from '../../utils' import { npubToHex, 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 = await pubToHex(key) const pubkey = npubToHex(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 { Link, useNavigate, useSearchParams } from 'react-router-dom' import { 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, getProfileRoute } from '../../routes' import { appPrivateRoutes } 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,6 +36,7 @@ import {
getHash, getHash,
hexToNpub, hexToNpub,
parseJson, parseJson,
npubToHex,
readContentOfZipEntry, readContentOfZipEntry,
sendDM, sendDM,
shorten, shorten,
@ -88,9 +89,13 @@ 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)) {
setNextSinger(signer) // signers in meta.json are in npub1 format
// so, convert it to hex before setting to nextSigner
setNextSinger(npubToHex(signer)!)
if (signer === usersPubkey) { const usersNpub = hexToNpub(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 {
@ -287,7 +292,7 @@ export const SignPage = () => {
metaCopy.signedEvents = { metaCopy.signedEvents = {
...metaCopy.signedEvents, ...metaCopy.signedEvents,
[signedEvent.pubkey]: JSON.stringify(signedEvent, null, 2) [hexToNpub(signedEvent.pubkey)]: JSON.stringify(signedEvent, null, 2)
} }
const stringifiedMeta = JSON.stringify(metaCopy, null, 2) const stringifiedMeta = JSON.stringify(metaCopy, null, 2)
@ -320,13 +325,10 @@ export const SignPage = () => {
if (!arrayBuffer) return if (!arrayBuffer) return
const encryptionKey = await generateEncryptionKey() const key = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file') setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer( const encryptedArrayBuffer = await encryptArrayBuffer(arrayBuffer, key)
arrayBuffer,
encryptionKey
)
const blob = new Blob([encryptedArrayBuffer]) const blob = new Blob([encryptedArrayBuffer])
@ -346,13 +348,14 @@ 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(usersPubkey!) const signerIndex = meta.signers.indexOf(usersNpub)
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<string>() const userSet = new Set<`npub1${string}`>()
userSet.add(meta.submittedBy) userSet.add(meta.submittedBy)
@ -370,27 +373,19 @@ export const SignPage = () => {
// todo: execute in parallel // todo: execute in parallel
await sendDM( await sendDM(
fileUrl, fileUrl,
encryptionKey, key,
user, npubToHex(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,
encryptionKey, key,
nextSigner, npubToHex(nextSigner)!,
nostrController, nostrController,
false, false,
setAuthUrl setAuthUrl
@ -398,15 +393,22 @@ 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(usersPubkey) && !meta.signers.includes(usersNpub) &&
!meta.viewers.includes(usersPubkey) && !meta.viewers.includes(usersNpub) &&
meta.submittedBy !== usersPubkey meta.submittedBy !== usersNpub
) )
return return
@ -563,13 +565,14 @@ 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 === signer) !== -1) return prev if (prev.findIndex((user) => user.pubkey === hexKey) !== -1) return prev
return [ return [
...prev, ...prev,
{ {
pubkey: signer, pubkey: hexKey!,
role: UserRole.signer role: UserRole.signer
} }
] ]
@ -577,13 +580,14 @@ 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 === viewer) !== -1) return prev if (prev.findIndex((user) => user.pubkey === hexKey) !== -1) return prev
return [ return [
...prev, ...prev,
{ {
pubkey: viewer, pubkey: hexKey!,
role: UserRole.viewer role: UserRole.viewer
} }
] ]
@ -594,56 +598,32 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
useEffect(() => { useEffect(() => {
const metadataController = new MetadataController() const metadataController = new MetadataController()
metadataController const hexKeys: string[] = [
.findMetadata(meta.submittedBy) npubToHex(meta.submittedBy)!,
.then((metadataEvent) => { ...users.map((user) => user.pubkey)
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) => { hexKeys.forEach((key) => {
if (!(user.pubkey in metadata)) { if (!(key in metadata)) {
metadataController metadataController
.findMetadata(user.pubkey) .findMetadata(key)
.then((metadataEvent) => { .then((metadataEvent) => {
const metadataContent = const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent) metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent) if (metadataContent)
setMetadata((prev) => ({ setMetadata((prev) => ({
...prev, ...prev,
[user.pubkey]: metadataContent [key]: metadataContent
})) }))
}) })
.catch((err) => { .catch((err) => {
console.error( console.error(`error occurred in finding metadata for: ${key}`, err)
`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={{
@ -673,29 +653,21 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
<Typography variant="h6" sx={{ color: textColor }}> <Typography variant="h6" sx={{ color: textColor }}>
Submitted By Submitted By
</Typography> </Typography>
<Box className={styles.user}> {(function () {
<img const pubkey = npubToHex(meta.submittedBy)
onError={imageLoadError} const profile = metadata[pubkey!]
src={ return (
metadata[meta.submittedBy]?.picture || <UserComponent
getRoboImageUrl(meta.submittedBy) pubkey={pubkey!}
} name={
alt="Profile Image" profile?.display_name ||
className="profile-image" profile?.name ||
style={{ shorten(meta.submittedBy)
borderWidth: '3px', }
borderStyle: 'solid', image={metadata[meta.submittedBy]?.picture}
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={{
@ -727,14 +699,13 @@ 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
if (user.pubkey in meta.signedEvents) { const usersNpub = hexToNpub(user.pubkey)
if (usersNpub in meta.signedEvents) {
signedStatus = 'Signed' signedStatus = 'Signed'
} }
// check if user is the next signer // check if user is the next signer
@ -746,26 +717,15 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
return ( return (
<TableRow key={index}> <TableRow key={index}>
<TableCell className={styles.tableCell}> <TableCell className={styles.tableCell}>
<Box className={styles.user}> <UserComponent
<img pubkey={user.pubkey}
onError={imageLoadError} name={
src={userMeta?.picture || roboUrl} userMeta?.display_name ||
alt="Profile Image" userMeta?.name ||
className="profile-image" shorten(hexToNpub(user.pubkey))
style={{ }
borderWidth: '3px', image={userMeta?.picture}
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,22 +9,21 @@ 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()
@ -50,16 +49,18 @@ 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) => {
if (!(user in metadata)) { const pubkey = npubToHex(user)!
if (!(pubkey in metadata)) {
metadataController metadataController
.findMetadata(user) .findMetadata(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,
[user]: metadataContent [pubkey]: metadataContent
})) }))
}) })
.catch((err) => { .catch((err) => {
@ -113,22 +114,14 @@ 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 signedEventString = meta ? meta.signedEvents[pubkey] : null const npub = hexToNpub(pubkey)
const signedEventString = meta ? meta.signedEvents[npub] : null
if (signedEventString) { if (signedEventString) {
try { try {
const signedEvent = JSON.parse(signedEventString) const signedEvent = JSON.parse(signedEventString)
@ -143,31 +136,28 @@ export const VerifyPage = () => {
} }
return ( return (
<Box className={styles.user}> <>
<img <UserComponent
onError={(event) => {imageLoadError(event, pubkey)}} pubkey={pubkey}
src={profile?.picture || getRoboImageUrl(pubkey)} name={
alt="Profile Image" profile?.display_name || profile?.name || shorten(hexToNpub(pubkey))
className="profile-image" }
style={{ image={profile?.picture}
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 component="label"> <Typography
({isValidSignature ? 'Valid' : 'Not Valid'} Signature) component="label"
sx={{
color: isValidSignature
? theme.palette.text.primary
: theme.palette.error.main
}}
>
({isValidSignature ? 'Valid' : 'Invalid'} Signature)
</Typography> </Typography>
)} )}
</Box> </>
) )
} }
@ -248,7 +238,7 @@ export const VerifyPage = () => {
<Typography variant="h6" sx={{ color: textColor }}> <Typography variant="h6" sx={{ color: textColor }}>
Submitted By Submitted By
</Typography> </Typography>
{displayUser(meta.submittedBy)} {displayUser(npubToHex(meta.submittedBy)!)}
</ListItem> </ListItem>
<ListItem <ListItem
@ -276,8 +266,16 @@ export const VerifyPage = () => {
</Typography> </Typography>
<ul className={styles.usersList}> <ul className={styles.usersList}>
{meta.signers.map((signer) => ( {meta.signers.map((signer) => (
<li key={signer} style={{ color: textColor }}> <li
{displayUser(signer, true)} key={signer}
style={{
color: textColor,
display: 'flex',
alignItems: 'center',
gap: '15px'
}}
>
{displayUser(npubToHex(signer)!, true)}
</li> </li>
))} ))}
</ul> </ul>
@ -298,7 +296,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(viewer)} {displayUser(npubToHex(viewer)!)}
</li> </li>
))} ))}
</ul> </ul>

View File

@ -9,10 +9,10 @@ export interface User {
} }
export interface Meta { export interface Meta {
signers: string[] signers: `npub1${string}`[]
viewers: string[] viewers: `npub1${string}`[]
fileHashes: { [key: string]: string } fileHashes: { [key: string]: string }
submittedBy: string submittedBy: `npub1${string}`
signedEvents: { [key: string]: string } signedEvents: { [key: `npub1${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 pubToHex = async (pubKey: string): Promise<string | null> => { export const npubToHex = (pubKey: string): string | null => {
// If key is NPUB // If key is NPUB
if (pubKey.startsWith('npub')) { if (pubKey.startsWith('npub1')) {
try { try {
return nip19.decode(pubKey).data as string return nip19.decode(pubKey).data as string
} catch (error) { } catch (error) {
return Promise.resolve(null) return null
} }
} }
// valid hex key // valid hex key
if (validateHex(pubKey)) return Promise.resolve(pubKey) if (validateHex(pubKey)) return pubKey
// Not a valid hex key // Not a valid hex key
return Promise.resolve(null) return null
} }
/** /**
@ -56,9 +56,8 @@ export const nsecToHex = (nsec: string): string | null => {
return null return null
} }
export const hexToNpub = (hexPubkey: string | undefined): string => { export const hexToNpub = (hexPubkey: string): `npub1${string}` => {
if (!hexPubkey) return 'n/a' if (hexPubkey.startsWith('npub1')) return hexPubkey as `npub1${string}`
if (hexPubkey.includes('npub')) return hexPubkey
return nip19.npubEncode(hexPubkey) return nip19.npubEncode(hexPubkey)
} }
@ -141,8 +140,7 @@ 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 => {