feat: convert hexkeys to npub in meta.json

This commit is contained in:
SwiftHawk 2024-05-17 13:34:56 +05:00 committed by Yury
parent 2d06e21bf5
commit 25cbaea985
6 changed files with 104 additions and 100 deletions

View File

@ -29,13 +29,13 @@ import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer'
import { ProfileMetadata, User, UserRole } from '../../types'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import {
encryptArrayBuffer,
generateEncryptionKey,
getHash,
hexToNpub,
pubToHex,
npubToHex,
queryNip05,
sendDM,
shorten,
@ -109,7 +109,7 @@ export const CreatePage = () => {
}
if (userInput.startsWith('npub')) {
const pubkey = await pubToHex(userInput)
const pubkey = npubToHex(userInput)
if (pubkey) {
addUser(pubkey)
setUserInput('')
@ -246,13 +246,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)
}
}

View File

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

View File

@ -37,6 +37,7 @@ import {
getRoboHashPicture,
hexToNpub,
parseJson,
npubToHex,
readContentOfZipEntry,
sendDM,
shorten,
@ -89,9 +90,11 @@ export const SignPage = () => {
} else {
for (const signer of meta.signers) {
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
setSignedStatus(SignedStatus.User_Is_Next_Signer)
} else {
@ -288,7 +291,7 @@ export const SignPage = () => {
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)
@ -321,13 +324,10 @@ export const SignPage = () => {
if (!arrayBuffer) return
const encryptionKey = await generateEncryptionKey()
const key = await generateEncryptionKey()
setLoadingSpinnerDesc('Encrypting zip file')
const encryptedArrayBuffer = await encryptArrayBuffer(
arrayBuffer,
encryptionKey
)
const encryptedArrayBuffer = await encryptArrayBuffer(arrayBuffer, key)
const blob = new Blob([encryptedArrayBuffer])
@ -347,13 +347,14 @@ export const SignPage = () => {
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(usersPubkey!)
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<string>()
const userSet = new Set<`npub1${string}`>()
userSet.add(meta.submittedBy)
@ -371,27 +372,19 @@ export const SignPage = () => {
// todo: execute in parallel
await sendDM(
fileUrl,
encryptionKey,
user,
key,
npubToHex(user)!,
nostrController,
false,
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 {
const nextSigner = meta.signers[signerIndex + 1]
await sendDM(
fileUrl,
encryptionKey,
nextSigner,
key,
npubToHex(nextSigner)!,
nostrController,
false,
setAuthUrl
@ -399,6 +392,12 @@ export const SignPage = () => {
}
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 () => {
if (!meta || !zip || !usersPubkey) return
const usersNpub = hexToNpub(usersPubkey)
if (
!meta.signers.includes(usersPubkey) &&
!meta.viewers.includes(usersPubkey) &&
meta.submittedBy !== usersPubkey
!meta.signers.includes(usersNpub) &&
!meta.viewers.includes(usersNpub) &&
meta.submittedBy !== usersNpub
)
return
@ -568,13 +568,14 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
useEffect(() => {
meta.signers.forEach((signer) => {
const hexKey = npubToHex(signer)
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === signer) !== -1) return prev
if (prev.findIndex((user) => user.pubkey === hexKey) !== -1) return prev
return [
...prev,
{
pubkey: signer,
pubkey: hexKey!,
role: UserRole.signer
}
]
@ -582,13 +583,14 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
})
meta.viewers.forEach((viewer) => {
const hexKey = npubToHex(viewer)
setUsers((prev) => {
if (prev.findIndex((user) => user.pubkey === viewer) !== -1) return prev
if (prev.findIndex((user) => user.pubkey === hexKey) !== -1) return prev
return [
...prev,
{
pubkey: viewer,
pubkey: hexKey!,
role: UserRole.viewer
}
]
@ -599,42 +601,27 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
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
)
})
const hexKeys: string[] = [
npubToHex(meta.submittedBy)!,
...users.map((user) => user.pubkey)
]
users.forEach((user) => {
if (!(user.pubkey in metadata)) {
hexKeys.forEach((key) => {
if (!(key in metadata)) {
metadataController
.findMetadata(user.pubkey)
.findMetadata(key)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[user.pubkey]: metadataContent
[key]: metadataContent
}))
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user.pubkey}`,
err
)
console.error(`error occurred in finding metadata for: ${key}`, err)
})
}
})
@ -669,15 +656,21 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
<Typography variant="h6" sx={{ color: textColor }}>
Submitted By
</Typography>
{(function () {
const pubkey = npubToHex(meta.submittedBy)
const profile = metadata[pubkey!]
return (
<UserComponent
pubkey={meta.submittedBy}
pubkey={pubkey!}
name={
metadata[meta.submittedBy]?.display_name ||
metadata[meta.submittedBy]?.name ||
shorten(hexToNpub(meta.submittedBy))
profile?.display_name ||
profile?.name ||
shorten(meta.submittedBy)
}
image={metadata[meta.submittedBy]?.picture}
/>
)
})()}
</ListItem>
<ListItem
sx={{
@ -714,7 +707,8 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
if (user.role === UserRole.signer) {
// 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'
}
// check if user is the next signer

View File

@ -18,6 +18,7 @@ import { MetadataController } from '../../controllers'
import { Meta, ProfileMetadata } from '../../types'
import {
hexToNpub,
npubToHex,
parseJson,
readContentOfZipEntry,
shorten
@ -48,16 +49,18 @@ export const VerifyPage = () => {
const users = [meta.submittedBy, ...meta.signers, ...meta.viewers]
users.forEach((user) => {
if (!(user in metadata)) {
const pubkey = npubToHex(user)!
if (!(pubkey in metadata)) {
metadataController
.findMetadata(user)
.findMetadata(pubkey)
.then((metadataEvent) => {
const metadataContent =
metadataController.extractProfileMetadataContent(metadataEvent)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[user]: metadataContent
[pubkey]: metadataContent
}))
})
.catch((err) => {
@ -117,7 +120,8 @@ export const VerifyPage = () => {
let isValidSignature = false
if (verifySignature) {
const signedEventString = meta ? meta.signedEvents[pubkey] : null
const npub = hexToNpub(pubkey)
const signedEventString = meta ? meta.signedEvents[npub] : null
if (signedEventString) {
try {
const signedEvent = JSON.parse(signedEventString)
@ -142,8 +146,15 @@ export const VerifyPage = () => {
/>
{verifySignature && (
<Typography component="label">
({isValidSignature ? 'Valid' : 'Not Valid'} Signature)
<Typography
component="label"
sx={{
color: isValidSignature
? theme.palette.text.primary
: theme.palette.error.main
}}
>
({isValidSignature ? 'Valid' : 'Invalid'} Signature)
</Typography>
)}
</>
@ -227,7 +238,7 @@ export const VerifyPage = () => {
<Typography variant="h6" sx={{ color: textColor }}>
Submitted By
</Typography>
{displayUser(meta.submittedBy)}
{displayUser(npubToHex(meta.submittedBy)!)}
</ListItem>
<ListItem
@ -264,7 +275,7 @@ export const VerifyPage = () => {
gap: '15px'
}}
>
{displayUser(signer, true)}
{displayUser(npubToHex(signer)!, true)}
</li>
))}
</ul>
@ -285,7 +296,7 @@ export const VerifyPage = () => {
<ul className={styles.usersList}>
{meta.viewers.map((viewer) => (
<li key={viewer} style={{ color: textColor }}>
{displayUser(viewer)}
{displayUser(npubToHex(viewer)!)}
</li>
))}
</ul>

View File

@ -9,10 +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,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,9 +56,8 @@ export const nsecToHex = (nsec: string): string | null => {
return null
}
export const hexToNpub = (hexPubkey: string | undefined): string => {
if (!hexPubkey) return 'n/a'
if (hexPubkey.includes('npub')) return hexPubkey
export const hexToNpub = (hexPubkey: string): `npub1${string}` => {
if (hexPubkey.startsWith('npub1')) return hexPubkey as `npub1${string}`
return nip19.npubEncode(hexPubkey)
}
@ -141,7 +140,6 @@ export const base64DecodeAuthToken = (authToken: string): SignedEvent => {
}
/**
*
* @param pubkey in hex or npub format
* @returns robohash.org url for the avatar
*/