verifySignature: return `false` if the id is invalid

This commit is contained in:
Alex Gleason 2023-09-02 17:31:39 -05:00
parent 34e0ad8c41
commit 54f3bedf38
No known key found for this signature in database
GPG Key ID: 7211D1F99744FBB7
2 changed files with 29 additions and 2 deletions

View File

@ -278,6 +278,27 @@ describe('Event', () => {
expect(isValid).toEqual(false)
})
it('should return false for an invalid event id', () => {
const privateKey = 'd217c1ff2f8a65c3e3a1740db3b9f58b8c848bb45e26d00ed4714e4a0f4ceecf'
const event = finishEvent(
{
kind: 1,
tags: [],
content: 'Hello, world!',
created_at: 1617932115,
},
privateKey,
)
// tamper with the id
event.id = event.id.replace(/0/g, '1')
const isValid = verifySignature(event)
expect(isValid).toEqual(false)
})
})
describe('getSignature', () => {
@ -296,9 +317,9 @@ describe('Event', () => {
const sig = getSignature(unsignedEvent, privateKey)
// verify the signature
// @ts-expect-error
const isValid = verifySignature({
...unsignedEvent,
id: getEventHash(unsignedEvent),
sig,
})

View File

@ -115,8 +115,14 @@ export function validateEvent<T>(event: T): event is T & UnsignedEvent<number> {
/** Verify the event's signature. This function mutates the event with a `verified` symbol, making it idempotent. */
export function verifySignature<K extends number>(event: Event<K>): event is VerifiedEvent<K> {
if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]
const hash = getEventHash(event)
if (hash !== event.id) {
return false
}
try {
event[verifiedSymbol] = schnorr.verify(event.sig, getEventHash(event), event.pubkey)
event[verifiedSymbol] = schnorr.verify(event.sig, hash, event.pubkey)
return event[verifiedSymbol]
} catch (err) {
return false