issue-38 #62

Closed
y wants to merge 48 commits from issue-38 into main
6 changed files with 104 additions and 100 deletions
Showing only changes of commit 25cbaea985 - Show all commits

View File

@ -29,13 +29,13 @@ import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers' import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes' import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer' import { State } from '../../store/rootReducer'
import { ProfileMetadata, User, UserRole } from '../../types' import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import { import {
encryptArrayBuffer, encryptArrayBuffer,
generateEncryptionKey, generateEncryptionKey,
getHash, getHash,
hexToNpub, hexToNpub,
pubToHex, npubToHex,
queryNip05, queryNip05,
sendDM, sendDM,
shorten, shorten,
@ -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)
} }
} }

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 = () => {
@ -47,8 +47,8 @@ export const Login = () => {
* Call login function when enter is pressed * Call login function when enter is pressed
*/ */
const handleInputKeyDown = (event: any) => { const handleInputKeyDown = (event: any) => {
if (event.code === "Enter" || event.code === "NumpadEnter") { if (event.code === 'Enter' || event.code === 'NumpadEnter') {
event.preventDefault(); event.preventDefault()
login() login()
} }
} }
@ -63,6 +63,7 @@ export const Login = () => {
dispatch(updateLoginMethod(LoginMethods.extension)) dispatch(updateLoginMethod(LoginMethods.extension))
setLoadingSpinnerDesc('Authenticating and finding metadata') setLoadingSpinnerDesc('Authenticating and finding metadata')
const redirectPath = const redirectPath =
await authController.authAndGetMetadataAndRelaysMap(pubkey) await authController.authAndGetMetadataAndRelaysMap(pubkey)
@ -223,7 +224,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

@ -37,6 +37,7 @@ import {
getRoboHashPicture, getRoboHashPicture,
hexToNpub, hexToNpub,
parseJson, parseJson,
npubToHex,
readContentOfZipEntry, readContentOfZipEntry,
sendDM, sendDM,
shorten, shorten,
@ -89,9 +90,11 @@ 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) 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 {
@ -288,7 +291,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)
@ -321,13 +324,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])
@ -347,13 +347,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)
@ -371,27 +372,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
@ -399,6 +392,12 @@ export const SignPage = () => {
} }
setIsLoading(false) setIsLoading(false)
// update search params with updated file url and encryption key
setSearchParams({
file: fileUrl,
key: key
})
} }
/** /**
@ -408,10 +407,11 @@ export const SignPage = () => {
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
@ -568,13 +568,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
} }
] ]
@ -582,13 +583,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
} }
] ]
@ -599,42 +601,27 @@ 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
)
}) })
} }
}) })
@ -669,15 +656,21 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
<Typography variant="h6" sx={{ color: textColor }}> <Typography variant="h6" sx={{ color: textColor }}>
Submitted By Submitted By
</Typography> </Typography>
{(function () {
const pubkey = npubToHex(meta.submittedBy)
const profile = metadata[pubkey!]
return (
<UserComponent <UserComponent
pubkey={meta.submittedBy} pubkey={pubkey!}
name={ name={
metadata[meta.submittedBy]?.display_name || profile?.display_name ||
metadata[meta.submittedBy]?.name || profile?.name ||
shorten(hexToNpub(meta.submittedBy)) shorten(meta.submittedBy)
} }
image={metadata[meta.submittedBy]?.picture} image={metadata[meta.submittedBy]?.picture}
/> />
)
})()}
</ListItem> </ListItem>
<ListItem <ListItem
sx={{ sx={{
@ -714,7 +707,8 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
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

View File

@ -18,6 +18,7 @@ import { MetadataController } from '../../controllers'
import { Meta, ProfileMetadata } from '../../types' import { Meta, ProfileMetadata } from '../../types'
import { import {
hexToNpub, hexToNpub,
npubToHex,
parseJson, parseJson,
readContentOfZipEntry, readContentOfZipEntry,
shorten shorten
@ -48,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) => {
@ -117,7 +120,8 @@ export const VerifyPage = () => {
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)
@ -142,8 +146,15 @@ export const VerifyPage = () => {
/> />
{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>
)} )}
</> </>
@ -227,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
@ -264,7 +275,7 @@ export const VerifyPage = () => {
gap: '15px' gap: '15px'
}} }}
> >
{displayUser(signer, true)} {displayUser(npubToHex(signer)!, true)}
</li> </li>
))} ))}
</ul> </ul>
@ -285,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,7 +140,6 @@ 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
*/ */