issue-40 #52

Merged
b merged 5 commits from issue-40 into main 2024-05-17 09:23:50 +00: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-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"
@ -4300,6 +4301,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",

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": {
@ -50,6 +50,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

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

@ -5,7 +5,12 @@ import { useDispatch } from 'react-redux'
import { Outlet } from 'react-router-dom'
import { AppBar } from '../components/AppBar/AppBar'
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 { Dispatch } from '../store/store'
import { MetadataController, NostrController } from '../controllers'
@ -29,9 +34,7 @@ export const MainLayout = () => {
})
)
dispatch(
setMetadataEvent(metadataController.getEmptyMetadataEvent())
)
dispatch(setMetadataEvent(metadataController.getEmptyMetadataEvent()))
// clear authToken saved in local storage
clearAuthToken()

View File

@ -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 { 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,
getRoboHashPicture,
hexToNpub,
pubToHex,
npubToHex,
queryNip05,
sendDM,
shorten,
@ -39,10 +43,6 @@ 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'
export const CreatePage = () => {
const navigate = useNavigate()
@ -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)
}
}
@ -489,15 +489,6 @@ const DisplayUser = ({
})
}, [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 (
<TableContainer component={Paper} elevation={3} sx={{ marginTop: '20px' }}>
<Table>
@ -511,31 +502,18 @@ const DisplayUser = ({
<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={(event) => {imageLoadError(event, user.pubkey)}}
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>
<UserComponent
pubkey={user.pubkey}
name={
userMeta?.display_name ||
userMeta?.name ||
shorten(hexToNpub(user.pubkey))
}
image={userMeta?.picture}
/>
</TableCell>
<TableCell className={styles.tableCell}>
<Select

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 = () => {
@ -213,7 +213,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

@ -21,12 +21,12 @@ import { MuiFileInput } from 'mui-file-input'
import { EventTemplate } from 'nostr-tools'
import { useEffect, useState } from 'react'
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 placeholderAvatar from '../../assets/images/nostr-logo.jpg'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserComponent } from '../../components/username'
import { MetadataController, NostrController } from '../../controllers'
import { appPrivateRoutes, getProfileRoute } from '../../routes'
import { appPrivateRoutes } from '../../routes'
import { State } from '../../store/rootReducer'
import { Meta, ProfileMetadata, User, UserRole } from '../../types'
import {
@ -36,6 +36,7 @@ import {
getHash,
hexToNpub,
parseJson,
npubToHex,
readContentOfZipEntry,
sendDM,
shorten,
@ -88,9 +89,13 @@ export const SignPage = () => {
} else {
for (const signer of meta.signers) {
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
setSignedStatus(SignedStatus.User_Is_Next_Signer)
} else {
@ -287,7 +292,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)
@ -320,13 +325,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])
@ -346,13 +348,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)
@ -370,27 +373,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
@ -398,15 +393,22 @@ export const SignPage = () => {
}
setIsLoading(false)
// update search params with updated file url and encryption key
setSearchParams({
file: fileUrl,
key: key
})
}
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
@ -563,13 +565,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
}
]
@ -577,13 +580,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
}
]
@ -594,56 +598,32 @@ 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)
})
}
})
}, [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={{
@ -673,29 +653,21 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
<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>
{(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={{
@ -727,14 +699,13 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
<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) {
const usersNpub = hexToNpub(user.pubkey)
if (usersNpub in meta.signedEvents) {
signedStatus = 'Signed'
}
// check if user is the next signer
@ -746,26 +717,15 @@ const DisplayMeta = ({ meta, nextSigner }: DisplayMetaProps) => {
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>
<UserComponent
pubkey={user.pubkey}
name={
userMeta?.display_name ||
userMeta?.name ||
shorten(hexToNpub(user.pubkey))
}
image={userMeta?.picture}
/>
</TableCell>
<TableCell className={styles.tableCell}>
{user.role}

View File

@ -9,22 +9,21 @@ import {
} from '@mui/material'
import JSZip from 'jszip'
import { MuiFileInput } from 'mui-file-input'
import { Event, verifyEvent } from 'nostr-tools'
import { useEffect, useState } from 'react'
import { Link } from 'react-router-dom'
import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserComponent } from '../../components/username'
import { MetadataController } from '../../controllers'
import { getProfileRoute } from '../../routes'
import { Meta, ProfileMetadata } from '../../types'
import {
getRoboHashPicture,
hexToNpub,
npubToHex,
parseJson,
readContentOfZipEntry,
shorten
} from '../../utils'
import styles from './style.module.scss'
import { Event, verifyEvent } from 'nostr-tools'
export const VerifyPage = () => {
const theme = useTheme()
@ -50,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) => {
@ -113,22 +114,14 @@ export const VerifyPage = () => {
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 profile = metadata[pubkey]
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)
@ -143,31 +136,28 @@ export const VerifyPage = () => {
}
return (
<Box className={styles.user}>
<img
onError={(event) => {imageLoadError(event, pubkey)}}
src={profile?.picture || getRoboImageUrl(pubkey)}
alt="Profile Image"
className="profile-image"
style={{
borderWidth: '3px',
borderStyle: 'solid',
borderColor: `#${pubkey.substring(0, 6)}`
}}
<>
<UserComponent
pubkey={pubkey}
name={
profile?.display_name || profile?.name || shorten(hexToNpub(pubkey))
}
image={profile?.picture}
/>
<Link to={getProfileRoute(pubkey)}>
<Typography component="label" className={styles.name}>
{profile?.display_name ||
profile?.name ||
shorten(hexToNpub(pubkey))}
</Typography>
</Link>
{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>
)}
</Box>
</>
)
}
@ -248,7 +238,7 @@ export const VerifyPage = () => {
<Typography variant="h6" sx={{ color: textColor }}>
Submitted By
</Typography>
{displayUser(meta.submittedBy)}
{displayUser(npubToHex(meta.submittedBy)!)}
</ListItem>
<ListItem
@ -276,8 +266,16 @@ export const VerifyPage = () => {
</Typography>
<ul className={styles.usersList}>
{meta.signers.map((signer) => (
<li key={signer} style={{ color: textColor }}>
{displayUser(signer, true)}
<li
key={signer}
style={{
color: textColor,
display: 'flex',
alignItems: 'center',
gap: '15px'
}}
>
{displayUser(npubToHex(signer)!, true)}
</li>
))}
</ul>
@ -298,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,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
*/
export const getRoboHashPicture = (pubkey: string): string => {