mirror of
https://github.com/nbd-wtf/nostr-tools.git
synced 2025-12-08 16:28:49 +00:00
verifySignature: return false if the id is invalid
This commit is contained in:
@@ -278,6 +278,27 @@ describe('Event', () => {
|
|||||||
|
|
||||||
expect(isValid).toEqual(false)
|
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', () => {
|
describe('getSignature', () => {
|
||||||
@@ -296,9 +317,9 @@ describe('Event', () => {
|
|||||||
const sig = getSignature(unsignedEvent, privateKey)
|
const sig = getSignature(unsignedEvent, privateKey)
|
||||||
|
|
||||||
// verify the signature
|
// verify the signature
|
||||||
// @ts-expect-error
|
|
||||||
const isValid = verifySignature({
|
const isValid = verifySignature({
|
||||||
...unsignedEvent,
|
...unsignedEvent,
|
||||||
|
id: getEventHash(unsignedEvent),
|
||||||
sig,
|
sig,
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
8
event.ts
8
event.ts
@@ -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. */
|
/** 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> {
|
export function verifySignature<K extends number>(event: Event<K>): event is VerifiedEvent<K> {
|
||||||
if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]
|
if (typeof event[verifiedSymbol] === 'boolean') return event[verifiedSymbol]
|
||||||
|
|
||||||
|
const hash = getEventHash(event)
|
||||||
|
if (hash !== event.id) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
event[verifiedSymbol] = schnorr.verify(event.sig, getEventHash(event), event.pubkey)
|
event[verifiedSymbol] = schnorr.verify(event.sig, hash, event.pubkey)
|
||||||
return event[verifiedSymbol]
|
return event[verifiedSymbol]
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return false
|
return false
|
||||||
|
|||||||
Reference in New Issue
Block a user