Signing Page - New Design #152

Merged
eugene merged 29 commits from sigit-info-signing-page into staging 2024-08-20 11:29:11 +00:00
13 changed files with 659 additions and 508 deletions
Showing only changes of commit 7d3daa8d13 - Show all commits

View File

@ -1,9 +1,6 @@
import { useEffect, useState } from 'react' import { Meta } from '../../types'
import { Meta, ProfileMetadata } from '../../types'
import { SigitCardDisplayInfo, SigitStatus } from '../../utils' import { SigitCardDisplayInfo, SigitStatus } from '../../utils'
import { Event, kinds } from 'nostr-tools'
import { Link } from 'react-router-dom' import { Link } from 'react-router-dom'
import { MetadataController } from '../../controllers'
import { formatTimestamp, hexToNpub, npubToHex, shorten } from '../../utils' import { formatTimestamp, hexToNpub, npubToHex, shorten } from '../../utils'
import { appPublicRoutes, appPrivateRoutes } from '../../routes' import { appPublicRoutes, appPrivateRoutes } from '../../routes'
import { Button, Divider, Tooltip } from '@mui/material' import { Button, Divider, Tooltip } from '@mui/material'
@ -22,6 +19,8 @@ import { UserAvatarGroup } from '../UserAvatarGroup'
import styles from './style.module.scss' import styles from './style.module.scss'
import { TooltipChild } from '../TooltipChild' import { TooltipChild } from '../TooltipChild'
import { getExtensionIconLabel } from '../getExtensionIconLabel' import { getExtensionIconLabel } from '../getExtensionIconLabel'
import { useSigitProfiles } from '../../hooks/useSigitProfiles'
import { useSigitMeta } from '../../hooks/useSigitMeta'
type SigitProps = { type SigitProps = {
meta: Meta meta: Meta
@ -38,62 +37,13 @@ export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => {
fileExtensions fileExtensions
} = parsedMeta } = parsedMeta
const [profiles, setProfiles] = useState<{ [key: string]: ProfileMetadata }>( const { signersStatus } = useSigitMeta(meta)
{}
)
useEffect(() => { const profiles = useSigitProfiles([
const hexKeys = new Set<string>([ ...(submittedBy ? [submittedBy] : []),
...signers.map((signer) => npubToHex(signer)!) ...signers
]) ])
if (submittedBy) {
hexKeys.add(npubToHex(submittedBy)!)
}
const metadataController = new MetadataController()
const handleMetadataEvent = (key: string) => (event: Event) => {
const metadataContent =
metadataController.extractProfileMetadataContent(event)
if (metadataContent) {
setProfiles((prev) => ({
...prev,
[key]: metadataContent
}))
}
}
const handleEventListener =
(key: string) => (kind: number, event: Event) => {
if (kind === kinds.Metadata) {
handleMetadataEvent(key)(event)
}
}
hexKeys.forEach((key) => {
if (!(key in profiles)) {
metadataController.on(key, handleEventListener(key))
metadataController
.findMetadata(key)
.then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(key)(metadataEvent)
})
.catch((err) => {
console.error(`error occurred in finding metadata for: ${key}`, err)
})
}
})
return () => {
hexKeys.forEach((key) => {
metadataController.off(key, handleEventListener(key))
})
}
}, [submittedBy, signers, profiles])
return ( return (
<div className={styles.itemWrapper}> <div className={styles.itemWrapper}>
<Link <Link
@ -130,7 +80,7 @@ export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => {
{submittedBy && signers.length ? ( {submittedBy && signers.length ? (
<Divider orientation="vertical" flexItem /> <Divider orientation="vertical" flexItem />
) : null} ) : null}
<UserAvatarGroup className={styles.signers} max={7}> <UserAvatarGroup max={7}>
{signers.map((signer) => { {signers.map((signer) => {
const pubkey = npubToHex(signer)! const pubkey = npubToHex(signer)!
const profile = profiles[pubkey] const profile = profiles[pubkey]
@ -147,7 +97,7 @@ export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => {
> >
<TooltipChild> <TooltipChild>
<DisplaySigner <DisplaySigner
meta={meta} status={signersStatus[signer]}
profile={profile} profile={profile}
pubkey={pubkey} pubkey={pubkey}
/> />

View File

@ -93,26 +93,6 @@
grid-gap: 10px; grid-gap: 10px;
} }
.signers {
padding: 0 0 0 10px;
> * {
transition: margin ease 0.2s;
margin: 0 0 0 -10px;
position: relative;
z-index: 1;
&:first-child {
margin-left: -10px !important;
}
}
> *:hover,
> *:focus-within {
margin: 0 15px 0 5px;
z-index: 2;
}
}
.details { .details {
color: rgba(0, 0, 0, 0.3); color: rgba(0, 0, 0, 0.3);
font-size: 14px; font-size: 14px;

View File

@ -1,75 +1,59 @@
import { Badge } from '@mui/material' import { Badge } from '@mui/material'
import { Event, verifyEvent } from 'nostr-tools' import { ProfileMetadata } from '../../types'
import { useState, useEffect } from 'react'
import { Meta, ProfileMetadata } from '../../types'
import { hexToNpub, parseJson } from '../../utils'
import styles from './style.module.scss' import styles from './style.module.scss'
import { UserAvatar } from '../UserAvatar' import { UserAvatar } from '../UserAvatar'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheck, faExclamation } from '@fortawesome/free-solid-svg-icons' import {
faCheck,
enum SignStatus { faEllipsis,
Signed = 'Signed', faExclamation,
Pending = 'Pending', faEye,
Invalid = 'Invalid Sign' faHourglass,
} faQuestion
} from '@fortawesome/free-solid-svg-icons'
import { SignStatus } from '../../utils'
import { Spinner } from '../Spinner'
type DisplaySignerProps = { type DisplaySignerProps = {
meta: Meta
profile: ProfileMetadata profile: ProfileMetadata
pubkey: string pubkey: string
status: SignStatus
} }
export const DisplaySigner = ({ export const DisplaySigner = ({
meta, status,
profile, profile,
pubkey pubkey
}: DisplaySignerProps) => { }: DisplaySignerProps) => {
const [signStatus, setSignedStatus] = useState<SignStatus>() const getStatusIcon = (status: SignStatus) => {
switch (status) {
case SignStatus.Signed:
return <FontAwesomeIcon icon={faCheck} />
case SignStatus.Awaiting:
return (
<Spinner>
<FontAwesomeIcon icon={faHourglass} />
</Spinner>
)
case SignStatus.Pending:
return <FontAwesomeIcon icon={faEllipsis} />
case SignStatus.Invalid:
return <FontAwesomeIcon icon={faExclamation} />
case SignStatus.Viewer:
return <FontAwesomeIcon icon={faEye} />
useEffect(() => { default:
if (!meta) return return <FontAwesomeIcon icon={faQuestion} />
const updateSignStatus = async () => {
const npub = hexToNpub(pubkey)
if (npub in meta.docSignatures) {
parseJson<Event>(meta.docSignatures[npub])
.then((event) => {
const isValidSignature = verifyEvent(event)
if (isValidSignature) {
setSignedStatus(SignStatus.Signed)
} else {
setSignedStatus(SignStatus.Invalid)
}
})
.catch((err) => {
console.log(`err in parsing the docSignatures for ${npub}:>> `, err)
setSignedStatus(SignStatus.Invalid)
})
} else {
setSignedStatus(SignStatus.Pending)
} }
} }
updateSignStatus()
}, [meta, pubkey])
return ( return (
<Badge <Badge
className={styles.signer} className={styles.signer}
overlap="circular" overlap="circular"
anchorOrigin={{ vertical: 'top', horizontal: 'right' }} anchorOrigin={{ vertical: 'top', horizontal: 'right' }}
badgeContent={ badgeContent={
signStatus !== SignStatus.Pending && ( <div className={styles.statusBadge}>{getStatusIcon(status)}</div>
<div className={styles.statusBadge}>
{signStatus === SignStatus.Signed && (
<FontAwesomeIcon icon={faCheck} />
)}
{signStatus === SignStatus.Invalid && (
<FontAwesomeIcon icon={faExclamation} />
)}
</div>
)
} }
> >
<UserAvatar pubkey={pubkey} image={profile?.picture} /> <UserAvatar pubkey={pubkey} image={profile?.picture} />

View File

@ -0,0 +1,6 @@
import { PropsWithChildren } from 'react'
import styles from './style.module.scss'
export const Spinner = ({ children }: PropsWithChildren) => (
<div className={styles.spin}>{children}</div>
)

View File

@ -0,0 +1,12 @@
.spin {
animation: spin 5s linear infinite;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}

View File

@ -28,7 +28,7 @@ export const UserAvatarGroup = ({
const childrenArray = Children.toArray(children) const childrenArray = Children.toArray(children)
return ( return (
<div {...rest}> <div className={styles.container} {...rest}>
{surplus > 1 {surplus > 1
? childrenArray.slice(0, surplus * -1).map((c) => c) ? childrenArray.slice(0, surplus * -1).map((c) => c)
: children} : children}

View File

@ -1,5 +1,25 @@
@import '../../styles/colors.scss'; @import '../../styles/colors.scss';
.container {
padding: 0 0 0 10px;
> * {
transition: margin ease 0.2s;
margin: 0 0 0 -10px;
position: relative;
z-index: 1;
&:first-child {
margin-left: -10px !important;
}
}
> *:hover,
> *:focus-within {
margin: 0 15px 0 5px;
z-index: 2;
}
}
.icon { .icon {
width: 40px; width: 40px;
height: 40px; height: 40px;

View File

@ -0,0 +1,217 @@
import { Divider, Tooltip } from '@mui/material'
import { useSigitProfiles } from '../../hooks/useSigitProfiles'
import {
extractFileExtensions,
formatTimestamp,
fromUnixTimestamp,
hexToNpub,
npubToHex,
shorten,
SignStatus
} from '../../utils'
import { UserAvatar } from '../UserAvatar'
import { useSigitMeta } from '../../hooks/useSigitMeta'
import { UserAvatarGroup } from '../UserAvatarGroup'
import styles from './style.module.scss'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import {
faCalendar,
faCalendarCheck,
faCalendarPlus,
faEye,
faFile,
faFileCircleExclamation
} from '@fortawesome/free-solid-svg-icons'
import { getExtensionIconLabel } from '../getExtensionIconLabel'
import { useSelector } from 'react-redux'
import { State } from '../../store/rootReducer'
import { TooltipChild } from '../TooltipChild'
import { DisplaySigner } from '../DisplaySigner'
import { Meta } from '../../types'
interface UsersDetailsProps {
meta: Meta
}
export const UsersDetails = ({ meta }: UsersDetailsProps) => {
const {
submittedBy,
signers,
viewers,
fileHashes,
signersStatus,
createdAt,
completedAt,
parsedSignatureEvents,
signedStatus
} = useSigitMeta(meta)
const { usersPubkey } = useSelector((state: State) => state.auth)
const profiles = useSigitProfiles([
...(submittedBy ? [submittedBy] : []),
...signers,
...viewers
])
const userCanSign =
typeof usersPubkey !== 'undefined' &&
signers.includes(hexToNpub(usersPubkey))
const ext = extractFileExtensions(Object.keys(fileHashes))
return submittedBy ? (
<div className={styles.container}>
<div className={styles.section}>
<p>Signers</p>
<div className={styles.users}>
{submittedBy &&
(function () {
const profile = profiles[submittedBy]
return (
<Tooltip
title={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(submittedBy))
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<UserAvatar pubkey={submittedBy} image={profile?.picture} />
</TooltipChild>
</Tooltip>
)
})()}
{submittedBy && signers.length ? (
<Divider orientation="vertical" flexItem />
) : null}
<UserAvatarGroup max={20}>
{signers.map((signer) => {
const pubkey = npubToHex(signer)!
const profile = profiles[pubkey]
return (
<Tooltip
key={signer}
title={
profile?.display_name || profile?.name || shorten(pubkey)
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<DisplaySigner
status={signersStatus[signer]}
profile={profile}
pubkey={pubkey}
/>
</TooltipChild>
</Tooltip>
)
})}
{viewers.map((signer) => {
const pubkey = npubToHex(signer)!
const profile = profiles[pubkey]
return (
<Tooltip
key={signer}
title={
profile?.display_name || profile?.name || shorten(pubkey)
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<DisplaySigner
status={SignStatus.Viewer}
profile={profile}
pubkey={pubkey}
/>
</TooltipChild>
</Tooltip>
)
})}
</UserAvatarGroup>
</div>
</div>
<div className={styles.section}>
<p>Details</p>
<Tooltip
title={'Publication date'}
placement="top"
arrow
disableInteractive
>
<span className={styles.detailsItem}>
<FontAwesomeIcon icon={faCalendarPlus} />{' '}
{createdAt ? formatTimestamp(createdAt) : <>&mdash;</>}
</span>
</Tooltip>
<Tooltip
title={'Completion date'}
placement="top"
arrow
disableInteractive
>
<span className={styles.detailsItem}>
<FontAwesomeIcon icon={faCalendarCheck} />{' '}
{completedAt ? formatTimestamp(completedAt) : <>&mdash;</>}
</span>
</Tooltip>
{/* User signed date */}
{userCanSign ? (
<Tooltip
title={'Your signature date'}
placement="top"
arrow
disableInteractive
>
<span className={styles.detailsItem}>
<FontAwesomeIcon icon={faCalendar} />{' '}
{hexToNpub(usersPubkey) in parsedSignatureEvents ? (
parsedSignatureEvents[hexToNpub(usersPubkey)].created_at ? (
formatTimestamp(
fromUnixTimestamp(
parsedSignatureEvents[hexToNpub(usersPubkey)].created_at
)
)
) : (
<>&mdash;</>
)
) : (
<>&mdash;</>
)}
</span>
</Tooltip>
) : null}
<span className={styles.detailsItem}>
<FontAwesomeIcon icon={faEye} /> {signedStatus}
</span>
{ext.length > 0 ? (
<span className={styles.detailsItem}>
{ext.length > 1 ? (
<>
<FontAwesomeIcon icon={faFile} /> Multiple File Types
</>
) : (
getExtensionIconLabel(ext[0])
)}
</span>
) : (
<>
<FontAwesomeIcon icon={faFileCircleExclamation} /> &mdash;
</>
)}
</div>
</div>
) : undefined
}

View File

@ -0,0 +1,46 @@
@import '../../styles/colors.scss';
.container {
border-radius: 4px;
background: $overlay-background-color;
padding: 15px;
display: flex;
flex-direction: column;
grid-gap: 25px;
font-size: 14px;
}
.section {
display: flex;
flex-direction: column;
grid-gap: 10px;
}
.users {
display: flex;
grid-gap: 10px;
}
.detailsItem {
transition: ease 0.2s;
color: rgba(0, 0, 0, 0.5);
font-size: 14px;
align-items: center;
border-radius: 4px;
padding: 5px;
display: flex;
align-items: center;
justify-content: start;
> :first-child {
padding: 5px;
margin-right: 10px;
}
&:hover {
background: $primary-main;
color: white;
}
}

View File

@ -1,9 +1,10 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { CreateSignatureEventContent, Meta } from '../types' import { CreateSignatureEventContent, Meta, SignedEventContent } from '../types'
import { Mark } from '../types/mark' import { Mark } from '../types/mark'
import { import {
fromUnixTimestamp, fromUnixTimestamp,
parseCreateSignatureEvent, hexToNpub,
parseNostrEvent,
parseCreateSignatureEventContent, parseCreateSignatureEventContent,
SigitMetaParseError, SigitMetaParseError,
SigitStatus, SigitStatus,
@ -12,11 +13,36 @@ import {
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { verifyEvent } from 'nostr-tools' import { verifyEvent } from 'nostr-tools'
import { Event } from 'nostr-tools' import { Event } from 'nostr-tools'
import store from '../store/store'
import { AuthState } from '../store/auth/types'
import { NostrController } from '../controllers'
/**
* Flattened interface that combines properties `Meta`, `CreateSignatureEventContent`,
* and `Event` (event's fields are made optional and pubkey and created_at replaced with our versions)
*/
export interface FlatMeta
extends Meta,
CreateSignatureEventContent,
Partial<Omit<Event, 'pubkey' | 'created_at'>> {
// Remove pubkey and use submittedBy as `npub1${string}`
submittedBy?: `npub1${string}`
// Remove created_at and replace with createdAt
createdAt?: number
interface FlatMeta extends Meta, CreateSignatureEventContent, Partial<Event> {
// Validated create signature event // Validated create signature event
isValid: boolean isValid: boolean
// Decryption
encryptionKey: string | null
// Parsed Document Signatures
parsedSignatureEvents: { [signer: `npub1${string}`]: Event }
// Calculated completion time
completedAt?: number
// Calculated status fields // Calculated status fields
signedStatus: SigitStatus signedStatus: SigitStatus
signersStatus: { signersStatus: {
@ -33,8 +59,8 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
const [isValid, setIsValid] = useState(false) const [isValid, setIsValid] = useState(false)
const [kind, setKind] = useState<number>() const [kind, setKind] = useState<number>()
const [tags, setTags] = useState<string[][]>() const [tags, setTags] = useState<string[][]>()
const [created_at, setCreatedAt] = useState<number>() const [createdAt, setCreatedAt] = useState<number>()
const [pubkey, setPubkey] = useState<string>() // submittedBy, pubkey from nostr event const [submittedBy, setSubmittedBy] = useState<`npub1${string}`>() // submittedBy, pubkey from nostr event
const [id, setId] = useState<string>() const [id, setId] = useState<string>()
const [sig, setSig] = useState<string>() const [sig, setSig] = useState<string>()
@ -47,6 +73,12 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
const [title, setTitle] = useState<string>('') const [title, setTitle] = useState<string>('')
const [zipUrl, setZipUrl] = useState<string>('') const [zipUrl, setZipUrl] = useState<string>('')
const [parsedSignatureEvents, setParsedSignatureEvents] = useState<{
[signer: `npub1${string}`]: Event
}>({})
const [completedAt, setCompletedAt] = useState<number>()
const [signedStatus, setSignedStatus] = useState<SigitStatus>( const [signedStatus, setSignedStatus] = useState<SigitStatus>(
SigitStatus.Partial SigitStatus.Partial
) )
@ -54,13 +86,13 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
[signer: `npub1${string}`]: SignStatus [signer: `npub1${string}`]: SignStatus
}>({}) }>({})
const [encryptionKey, setEncryptionKey] = useState<string | null>(null)
useEffect(() => { useEffect(() => {
if (!meta) return if (!meta) return
;(async function () { ;(async function () {
try { try {
const createSignatureEvent = await parseCreateSignatureEvent( const createSignatureEvent = await parseNostrEvent(meta.createSignature)
meta.createSignature
)
const { kind, tags, created_at, pubkey, id, sig, content } = const { kind, tags, created_at, pubkey, id, sig, content } =
createSignatureEvent createSignatureEvent
@ -70,7 +102,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
setTags(tags) setTags(tags)
// created_at in nostr events are stored in seconds // created_at in nostr events are stored in seconds
setCreatedAt(fromUnixTimestamp(created_at)) setCreatedAt(fromUnixTimestamp(created_at))
setPubkey(pubkey) setSubmittedBy(pubkey as `npub1${string}`)
setId(id) setId(id)
setSig(sig) setSig(sig)
@ -84,30 +116,102 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
setMarkConfig(markConfig) setMarkConfig(markConfig)
setZipUrl(zipUrl) setZipUrl(zipUrl)
// Parse each signature event and set signer status if (meta.keys) {
const { sender, keys } = meta.keys
// Retrieve the user's public key from the state
const usersPubkey = (store.getState().auth as AuthState).usersPubkey!
const usersNpub = hexToNpub(usersPubkey)
// Check if the user's public key is in the keys object
if (usersNpub in keys) {
// Instantiate the NostrController to decrypt the encryption key
const nostrController = NostrController.getInstance()
const decrypted = await nostrController
.nip04Decrypt(sender, keys[usersNpub])
.catch((err) => {
console.log(
'An error occurred in decrypting encryption key',
err
)
return null
})
setEncryptionKey(decrypted)
}
}
// Temp. map to hold events and signers
const parsedSignatureEventsMap = new Map<`npub1${string}`, Event>()
const signerStatusMap = new Map<`npub1${string}`, SignStatus>()
const getPrevSignerSig = (npub: `npub1${string}`) => {
if (signers[0] === npub) {
return sig
}
// find the index of signer
const currentSignerIndex = signers.findIndex(
(signer) => signer === npub
)
// return if could not found user in signer's list
if (currentSignerIndex === -1) return
// find prev signer
const prevSigner = signers[currentSignerIndex - 1]
// get the signature of prev signer
return parsedSignatureEventsMap.get(prevSigner)?.sig
}
for (const npub in meta.docSignatures) { for (const npub in meta.docSignatures) {
try { try {
const event = await parseCreateSignatureEvent( // Parse each signature event
const event = await parseNostrEvent(
meta.docSignatures[npub as `npub1${string}`] meta.docSignatures[npub as `npub1${string}`]
) )
const isValidSignature = verifyEvent(event)
setSignersStatus((prev) => { // Save events to a map, to save all at once outside loop
return { // We need the object to find completedAt
...prev, // Avoided using parsedSignatureEvents due to useEffect deps
[npub]: isValidSignature parsedSignatureEventsMap.set(npub as `npub1${string}`, event)
? SignStatus.Signed
: SignStatus.Invalid
}
})
} catch (error) { } catch (error) {
setSignersStatus((prev) => { signerStatusMap.set(npub as `npub1${string}`, SignStatus.Invalid)
return { }
...prev, }
[npub]: SignStatus.Invalid
parsedSignatureEventsMap.forEach((event, npub) => {
const isValidSignature = verifyEvent(event)
if (isValidSignature) {
// get the signature of prev signer from the content of current signers signedEvent
const prevSignersSig = getPrevSignerSig(npub)
try {
const obj: SignedEventContent = JSON.parse(event.content)
if (
obj.prevSig &&
prevSignersSig &&
obj.prevSig === prevSignersSig
) {
signerStatusMap.set(npub as `npub1${string}`, SignStatus.Signed)
}
} catch (error) {
signerStatusMap.set(npub as `npub1${string}`, SignStatus.Invalid)
}
} }
}) })
signers
.filter((s) => !parsedSignatureEventsMap.has(s))
.forEach((s) => signerStatusMap.set(s, SignStatus.Pending))
// Get the first signer that hasn't signed
const nextSigner = signers.find((s) => !parsedSignatureEventsMap.has(s))
if (nextSigner) {
signerStatusMap.set(nextSigner, SignStatus.Awaiting)
} }
}
setSignersStatus(Object.fromEntries(signerStatusMap))
setParsedSignatureEvents(Object.fromEntries(parsedSignatureEventsMap))
const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[] const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[]
const isCompletelySigned = signers.every((signer) => const isCompletelySigned = signers.every((signer) =>
signedBy.includes(signer) signedBy.includes(signer)
@ -115,6 +219,20 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
setSignedStatus( setSignedStatus(
isCompletelySigned ? SigitStatus.Complete : SigitStatus.Partial isCompletelySigned ? SigitStatus.Complete : SigitStatus.Partial
) )
// Check if all signers signed
if (isCompletelySigned) {
setCompletedAt(
fromUnixTimestamp(
signedBy.reduce((p, c) => {
return Math.max(
p,
parsedSignatureEventsMap.get(c)?.created_at || 0
)
}, 0)
)
)
}
} catch (error) { } catch (error) {
if (error instanceof SigitMetaParseError) { if (error instanceof SigitMetaParseError) {
toast.error(error.message) toast.error(error.message)
@ -125,15 +243,15 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
}, [meta]) }, [meta])
return { return {
modifiedAt: meta.modifiedAt, modifiedAt: meta?.modifiedAt,
createSignature: meta.createSignature, createSignature: meta?.createSignature,
docSignatures: meta.docSignatures, docSignatures: meta?.docSignatures,
keys: meta.keys, keys: meta?.keys,
isValid, isValid,
kind, kind,
tags, tags,
created_at, createdAt,
pubkey, submittedBy,
id, id,
sig, sig,
signers, signers,
@ -142,7 +260,10 @@ export const useSigitMeta = (meta: Meta): FlatMeta => {
markConfig, markConfig,
title, title,
zipUrl, zipUrl,
parsedSignatureEvents,
completedAt,
signedStatus, signedStatus,
signersStatus signersStatus,
encryptionKey
} }
} }

View File

@ -0,0 +1,70 @@
import { useEffect, useState } from 'react'
import { ProfileMetadata } from '../types'
import { MetadataController } from '../controllers'
import { npubToHex } from '../utils'
import { Event, kinds } from 'nostr-tools'
/**
* Extracts profiles from metadata events
* @param pubkeys Array of npubs to check
* @returns ProfileMetadata
*/
export const useSigitProfiles = (
pubkeys: `npub1${string}`[]
): { [key: string]: ProfileMetadata } => {
const [profileMetadata, setProfileMetadata] = useState<{
[key: string]: ProfileMetadata
}>({})
useEffect(() => {
if (pubkeys.length) {
const metadataController = new MetadataController()
// Remove duplicate keys
const users = new Set<string>([...pubkeys])
const handleMetadataEvent = (key: string) => (event: Event) => {
const metadataContent =
metadataController.extractProfileMetadataContent(event)
if (metadataContent) {
setProfileMetadata((prev) => ({
...prev,
[key]: metadataContent
}))
}
}
users.forEach((user) => {
const hexKey = npubToHex(user)
if (hexKey && !(hexKey in profileMetadata)) {
metadataController.on(hexKey, (kind: number, event: Event) => {
if (kind === kinds.Metadata) {
handleMetadataEvent(hexKey)(event)
}
})
metadataController
.findMetadata(hexKey)
.then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(hexKey)(metadataEvent)
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user}`,
err
)
})
}
})
return () => {
users.forEach((key) => {
metadataController.off(key, handleMetadataEvent(key))
})
}
}
}, [pubkeys, profileMetadata])
return profileMetadata
}

View File

@ -1,39 +1,22 @@
import { import { Box, Button, Tooltip, Typography, useTheme } from '@mui/material'
Box,
Button,
List,
ListItem,
ListSubheader,
Tooltip,
Typography,
useTheme
} 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, kinds, verifyEvent } from 'nostr-tools' import { Event, verifyEvent } from 'nostr-tools'
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { toast } from 'react-toastify' import { toast } from 'react-toastify'
import { LoadingSpinner } from '../../components/LoadingSpinner' import { LoadingSpinner } from '../../components/LoadingSpinner'
import { UserAvatar } from '../../components/UserAvatar' import { NostrController } from '../../controllers'
import { MetadataController, NostrController } from '../../controllers' import { CreateSignatureEventContent, Meta } from '../../types'
import {
CreateSignatureEventContent,
Meta,
ProfileMetadata,
SignedEventContent
} from '../../types'
import { import {
decryptArrayBuffer, decryptArrayBuffer,
extractMarksFromSignedMeta, extractMarksFromSignedMeta,
extractZipUrlAndEncryptionKey,
getHash, getHash,
hexToNpub, hexToNpub,
unixNow, unixNow,
npubToHex,
parseJson, parseJson,
readContentOfZipEntry, readContentOfZipEntry,
shorten, signEventForMetaFile,
signEventForMetaFile shorten
} from '../../utils' } from '../../utils'
import styles from './style.module.scss' import styles from './style.module.scss'
import { Cancel, CheckCircle } from '@mui/icons-material' import { Cancel, CheckCircle } from '@mui/icons-material'
@ -51,6 +34,12 @@ import { useSelector } from 'react-redux'
import { getLastSignersSig } from '../../utils/sign.ts' import { getLastSignersSig } from '../../utils/sign.ts'
import { saveAs } from 'file-saver' import { saveAs } from 'file-saver'
import { Container } from '../../components/Container' import { Container } from '../../components/Container'
import { useSigitMeta } from '../../hooks/useSigitMeta.tsx'
import { StickySideColumns } from '../../layouts/StickySideColumns.tsx'
import { UsersDetails } from '../../components/UsersDetails.tsx/index.tsx'
import { UserAvatar } from '../../components/UserAvatar/index.tsx'
import { useSigitProfiles } from '../../hooks/useSigitProfiles.tsx'
import { TooltipChild } from '../../components/TooltipChild.tsx'
export const VerifyPage = () => { export const VerifyPage = () => {
const theme = useTheme() const theme = useTheme()
@ -63,52 +52,36 @@ export const VerifyPage = () => {
* uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains meta.json * uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains meta.json
* meta will be received in navigation from create & home page in online mode * meta will be received in navigation from create & home page in online mode
*/ */
const { uploadedZip, meta: metaInNavState } = location.state || {} const { uploadedZip, meta } = location.state || {}
const { submittedBy, zipUrl, encryptionKey, signers, viewers, fileHashes } =
useSigitMeta(meta)
const profiles = useSigitProfiles([
...(submittedBy ? [submittedBy] : []),
...signers,
...viewers
])
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
const [selectedFile, setSelectedFile] = useState<File | null>(null) const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [meta, setMeta] = useState<Meta | null>(null)
const [submittedBy, setSubmittedBy] = useState<string>()
const [signers, setSigners] = useState<`npub1${string}`[]>([])
const [viewers, setViewers] = useState<`npub1${string}`[]>([])
const [creatorFileHashes, setCreatorFileHashes] = useState<{
[key: string]: string
}>({})
const [currentFileHashes, setCurrentFileHashes] = useState<{ const [currentFileHashes, setCurrentFileHashes] = useState<{
[key: string]: string | null [key: string]: string | null
}>({}) }>(fileHashes)
const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({}) const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({})
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
const usersPubkey = useSelector((state: State) => state.auth.usersPubkey) const usersPubkey = useSelector((state: State) => state.auth.usersPubkey)
const nostrController = NostrController.getInstance() const nostrController = NostrController.getInstance()
useEffect(() => { useEffect(() => {
if (uploadedZip) { if (uploadedZip) {
setSelectedFile(uploadedZip) setSelectedFile(uploadedZip)
} else if (metaInNavState) { } else if (meta && encryptionKey) {
const processSigit = async () => { const processSigit = async () => {
setIsLoading(true) setIsLoading(true)
setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta')
const res = await extractZipUrlAndEncryptionKey(metaInNavState)
if (!res) {
setIsLoading(false)
return
}
const {
zipUrl,
encryptionKey,
createSignatureEvent,
createSignatureContent
} = res
setLoadingSpinnerDesc('Fetching file from file server') setLoadingSpinnerDesc('Fetching file from file server')
axios axios
@ -175,12 +148,6 @@ export const VerifyPage = () => {
setCurrentFileHashes(fileHashes) setCurrentFileHashes(fileHashes)
setFiles(files) setFiles(files)
setSigners(createSignatureContent.signers)
setViewers(createSignatureContent.viewers)
setCreatorFileHashes(createSignatureContent.fileHashes)
setSubmittedBy(createSignatureEvent.pubkey)
setMeta(metaInNavState)
setIsLoading(false) setIsLoading(false)
} }
}) })
@ -197,49 +164,7 @@ export const VerifyPage = () => {
processSigit() processSigit()
} }
}, [uploadedZip, metaInNavState]) }, [encryptionKey, meta, uploadedZip, zipUrl])
useEffect(() => {
if (submittedBy) {
const metadataController = new MetadataController()
const users = [submittedBy, ...signers, ...viewers]
users.forEach((user) => {
const pubkey = npubToHex(user)!
if (!(pubkey in metadata)) {
const handleMetadataEvent = (event: Event) => {
const metadataContent =
metadataController.extractProfileMetadataContent(event)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[pubkey]: metadataContent
}))
}
metadataController.on(pubkey, (kind: number, event: Event) => {
if (kind === kinds.Metadata) {
handleMetadataEvent(event)
}
})
metadataController
.findMetadata(pubkey)
.then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(metadataEvent)
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user}`,
err
)
})
}
})
}
}, [submittedBy, signers, viewers, metadata])
const handleVerify = async () => { const handleVerify = async () => {
if (!selectedFile) return if (!selectedFile) return
@ -345,44 +270,9 @@ export const VerifyPage = () => {
if (!createSignatureContent) return if (!createSignatureContent) return
setSigners(createSignatureContent.signers)
setViewers(createSignatureContent.viewers)
setCreatorFileHashes(createSignatureContent.fileHashes)
setSubmittedBy(createSignatureEvent.pubkey)
setMeta(parsedMetaJson)
setIsLoading(false) setIsLoading(false)
} }
const getPrevSignersSig = (npub: string) => {
if (!meta) return null
// if user is first signer then use creator's signature
if (signers[0] === npub) {
try {
const createSignatureEvent: Event = JSON.parse(meta.createSignature)
return createSignatureEvent.sig
} catch (error) {
return null
}
}
// find the index of signer
const currentSignerIndex = signers.findIndex((signer) => signer === npub)
// return null if could not found user in signer's list
if (currentSignerIndex === -1) return null
// find prev signer
const prevSigner = signers[currentSignerIndex - 1]
// get the signature of prev signer
try {
const prevSignersEvent: Event = JSON.parse(meta.docSignatures[prevSigner])
return prevSignersEvent.sig
} catch (error) {
return null
}
}
const handleExport = async () => { const handleExport = async () => {
if (Object.entries(files).length === 0 || !meta || !usersPubkey) return if (Object.entries(files).length === 0 || !meta || !usersPubkey) return
@ -448,76 +338,6 @@ export const VerifyPage = () => {
setIsLoading(false) setIsLoading(false)
} }
const displayUser = (pubkey: string, verifySignature = false) => {
const profile = metadata[pubkey]
let isValidSignature = false
if (verifySignature) {
const npub = hexToNpub(pubkey)
const signedEventString = meta ? meta.docSignatures[npub] : null
if (signedEventString) {
try {
const signedEvent = JSON.parse(signedEventString)
const isVerifiedEvent = verifyEvent(signedEvent)
if (isVerifiedEvent) {
// get the actual signature of prev signer
const prevSignersSig = getPrevSignersSig(npub)
// get the signature of prev signer from the content of current signers signedEvent
try {
const obj: SignedEventContent = JSON.parse(signedEvent.content)
if (
obj.prevSig &&
prevSignersSig &&
obj.prevSig === prevSignersSig
) {
isValidSignature = true
}
} catch (error) {
isValidSignature = false
}
}
} catch (error) {
console.error(
`An error occurred in parsing and verifying the signature event for ${pubkey}`,
error
)
}
}
}
return (
<>
<UserAvatar
pubkey={pubkey}
name={
profile?.display_name || profile?.name || shorten(hexToNpub(pubkey))
}
image={profile?.picture}
/>
{verifySignature && (
<>
{isValidSignature && (
<Tooltip title="Valid signature">
<CheckCircle sx={{ color: theme.palette.success.light }} />
</Tooltip>
)}
{!isValidSignature && (
<Tooltip title="Invalid signature">
<Cancel sx={{ color: theme.palette.error.main }} />
</Tooltip>
)}
</>
)}
</>
)
}
const displayExportedBy = () => { const displayExportedBy = () => {
if (!meta || !meta.exportSignature) return null if (!meta || !meta.exportSignature) return null
@ -527,7 +347,24 @@ export const VerifyPage = () => {
const exportSignatureEvent = JSON.parse(exportSignatureString) as Event const exportSignatureEvent = JSON.parse(exportSignatureString) as Event
if (verifyEvent(exportSignatureEvent)) { if (verifyEvent(exportSignatureEvent)) {
return displayUser(exportSignatureEvent.pubkey) const exportedBy = exportSignatureEvent.pubkey
const profile = profiles[exportedBy]
return (
<Tooltip
title={
profile?.display_name ||
profile?.name ||
shorten(hexToNpub(exportedBy))
}
placement="top"
arrow
disableInteractive
>
<TooltipChild>
<UserAvatar pubkey={exportedBy} image={profile?.picture} />
</TooltipChild>
</Tooltip>
)
} else { } else {
toast.error(`Invalid export signature!`) toast.error(`Invalid export signature!`)
return ( return (
@ -574,113 +411,13 @@ export const VerifyPage = () => {
)} )}
{meta && ( {meta && (
<StickySideColumns
left={
<> <>
<List
sx={{
bgcolor: 'background.paper',
marginTop: 2
}}
subheader={
<ListSubheader className={styles.subHeader}>
Meta Info
</ListSubheader>
}
>
{submittedBy && (
<ListItem
sx={{
marginTop: 1,
gap: '15px'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Submitted By
</Typography>
{displayUser(submittedBy)}
</ListItem>
)}
<ListItem
sx={{
marginTop: 1,
gap: '15px'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Exported By
</Typography>
{displayExportedBy()}
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant="contained">
Export Sigit
</Button>
</Box>
</ListItem>
{signers.length > 0 && (
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Signers
</Typography>
<ul className={styles.usersList}>
{signers.map((signer) => (
<li
key={signer}
style={{
color: textColor,
display: 'flex',
alignItems: 'center',
gap: '15px'
}}
>
{displayUser(npubToHex(signer)!, true)}
</li>
))}
</ul>
</ListItem>
)}
{viewers.length > 0 && (
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Viewers
</Typography>
<ul className={styles.usersList}>
{viewers.map((viewer) => (
<li key={viewer} style={{ color: textColor }}>
{displayUser(npubToHex(viewer)!)}
</li>
))}
</ul>
</ListItem>
)}
<ListItem
sx={{
marginTop: 1,
flexDirection: 'column',
alignItems: 'flex-start'
}}
>
<Typography variant="h6" sx={{ color: textColor }}>
Files
</Typography>
<Box className={styles.filesWrapper}> <Box className={styles.filesWrapper}>
{Object.entries(currentFileHashes).map( {Object.entries(currentFileHashes).map(
([filename, hash], index) => { ([filename, hash], index) => {
const isValidHash = creatorFileHashes[filename] === hash const isValidHash = fileHashes[filename] === hash
return ( return (
<Box key={`file-${index}`} className={styles.file}> <Box key={`file-${index}`} className={styles.file}>
@ -712,9 +449,16 @@ export const VerifyPage = () => {
} }
)} )}
</Box> </Box>
</ListItem> {displayExportedBy()}
</List> <Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant="contained">
Export Sigit
</Button>
</Box>
</> </>
}
right={<UsersDetails meta={meta} />}
/>
)} )}
</Container> </Container>
</> </>

View File

@ -5,8 +5,10 @@ import { toast } from 'react-toastify'
export enum SignStatus { export enum SignStatus {
Signed = 'Signed', Signed = 'Signed',
Awaiting = 'Awaiting',
Pending = 'Pending', Pending = 'Pending',
Invalid = 'Invalid Sign' Invalid = 'Invalid',
Viewer = 'Viewer'
} }
export enum SigitStatus { export enum SigitStatus {
@ -62,38 +64,33 @@ function handleError(error: unknown): Error {
// Reuse common error messages for meta parsing // Reuse common error messages for meta parsing
export enum SigitMetaParseErrorType { export enum SigitMetaParseErrorType {
'PARSE_ERROR_SIGNATURE_EVENT' = 'error occurred in parsing the create signature event', 'PARSE_ERROR_EVENT' = 'error occurred in parsing the create signature event',
'PARSE_ERROR_SIGNATURE_EVENT_CONTENT' = "err in parsing the createSignature event's content" 'PARSE_ERROR_SIGNATURE_EVENT_CONTENT' = "err in parsing the createSignature event's content"
} }
export interface SigitCardDisplayInfo { export interface SigitCardDisplayInfo {
createdAt?: number createdAt?: number
title?: string title?: string
submittedBy?: string submittedBy?: `npub1${string}`
signers: `npub1${string}`[] signers: `npub1${string}`[]
fileExtensions: string[] fileExtensions: string[]
signedStatus: SigitStatus signedStatus: SigitStatus
} }
/** /**
* Wrapper for createSignatureEvent parse that throws custom SigitMetaParseError with cause and context * Wrapper for event parser that throws custom SigitMetaParseError with cause and context
* @param raw Raw string for parsing * @param raw Raw string for parsing
* @returns parsed Event * @returns parsed Event
*/ */
export const parseCreateSignatureEvent = async ( export const parseNostrEvent = async (raw: string): Promise<Event> => {
raw: string
): Promise<Event> => {
try { try {
const createSignatureEvent = await parseJson<Event>(raw) const event = await parseJson<Event>(raw)
return createSignatureEvent return event
} catch (error) { } catch (error) {
throw new SigitMetaParseError( throw new SigitMetaParseError(SigitMetaParseErrorType.PARSE_ERROR_EVENT, {
SigitMetaParseErrorType.PARSE_ERROR_SIGNATURE_EVENT,
{
cause: handleError(error), cause: handleError(error),
context: raw context: raw
} })
)
} }
} }
@ -135,9 +132,7 @@ export const extractSigitCardDisplayInfo = async (meta: Meta) => {
} }
try { try {
const createSignatureEvent = await parseCreateSignatureEvent( const createSignatureEvent = await parseNostrEvent(meta.createSignature)
meta.createSignature
)
// created_at in nostr events are stored in seconds // created_at in nostr events are stored in seconds
sigitInfo.createdAt = fromUnixTimestamp(createSignatureEvent.created_at) sigitInfo.createdAt = fromUnixTimestamp(createSignatureEvent.created_at)
@ -147,13 +142,7 @@ export const extractSigitCardDisplayInfo = async (meta: Meta) => {
) )
const files = Object.keys(createSignatureContent.fileHashes) const files = Object.keys(createSignatureContent.fileHashes)
const extensions = files.reduce((result: string[], file: string) => { const extensions = extractFileExtensions(files)
const extension = file.split('.').pop()
if (extension) {
result.push(extension)
}
return result
}, [])
const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[] const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[]
const isCompletelySigned = createSignatureContent.signers.every((signer) => const isCompletelySigned = createSignatureContent.signers.every((signer) =>
@ -161,7 +150,7 @@ export const extractSigitCardDisplayInfo = async (meta: Meta) => {
) )
sigitInfo.title = createSignatureContent.title sigitInfo.title = createSignatureContent.title
sigitInfo.submittedBy = createSignatureEvent.pubkey sigitInfo.submittedBy = createSignatureEvent.pubkey as `npub1${string}`
sigitInfo.signers = createSignatureContent.signers sigitInfo.signers = createSignatureContent.signers
sigitInfo.fileExtensions = extensions sigitInfo.fileExtensions = extensions
@ -179,3 +168,15 @@ export const extractSigitCardDisplayInfo = async (meta: Meta) => {
} }
} }
} }
export const extractFileExtensions = (fileNames: string[]) => {
const extensions = fileNames.reduce((result: string[], file: string) => {
const extension = file.split('.').pop()
if (extension) {
result.push(extension)
}
return result
}, [])
return extensions
}