From 454366f6a28eb20b5c99a320d77cb3f7ea1b5cac Mon Sep 17 00:00:00 2001 From: fiatjaf Date: Wed, 12 Jan 2022 22:32:45 -0300 Subject: [PATCH] allow signing events with a custom signing function on pool.publish() --- package.json | 2 +- pool.js | 21 +++++++++++++++++++-- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 9b94ef6..7ef5cfc 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "nostr-tools", - "version": "0.18.0", + "version": "0.19.0", "description": "Tools for making a Nostr client.", "repository": { "type": "git", diff --git a/pool.js b/pool.js index f178e13..10ba67f 100644 --- a/pool.js +++ b/pool.js @@ -1,8 +1,10 @@ -import {getEventHash, signEvent} from './event' +import {getEventHash, verifySignature, signEvent} from './event' import {relayConnect, normalizeRelayURL} from './relay' export function relayPool() { var globalPrivateKey + var globalSigningFunction + const poolPolicy = { // setting this to a number will cause events to be published to a random // set of relays only, instead of publishing to all relays all the time @@ -76,6 +78,9 @@ export function relayPool() { setPrivateKey(privateKey) { globalPrivateKey = privateKey }, + registerSigningFunction(fn) { + globalSigningFunction = fn + }, setPolicy(key, value) { poolPolicy[key] = value }, @@ -123,9 +128,21 @@ export function relayPool() { if (globalPrivateKey) { event.sig = await signEvent(event, globalPrivateKey) + } else if (globalSigningFunction) { + event.sig = await globalSigningFunction(event) + if (!event.sig) { + // abort here + return + } else { + // check + if (!(await verifySignature(event))) + throw new Error( + 'signature provided by custom signing function is invalid.' + ) + } } else { throw new Error( - "can't publish unsigned event. either sign this event beforehand or pass a private key while initializing this relay pool so it can be signed automatically." + "can't publish unsigned event. either sign this event beforehand, provide a signing function or pass a private key while initializing this relay pool so it can be signed automatically." ) } }