From 6565aa6fa0fbafe3ac769d9cc6153092cd595cdd Mon Sep 17 00:00:00 2001 From: ennmichael Date: Tue, 28 Feb 2023 21:46:31 +0100 Subject: [PATCH] allow publishing without a private key --- packages/nostr/src/client/conn.ts | 6 ++++-- packages/nostr/src/client/index.ts | 34 +++++++++++++++++++++++++----- 2 files changed, 33 insertions(+), 7 deletions(-) diff --git a/packages/nostr/src/client/conn.ts b/packages/nostr/src/client/conn.ts index 543e127..c897ce6 100644 --- a/packages/nostr/src/client/conn.ts +++ b/packages/nostr/src/client/conn.ts @@ -139,7 +139,7 @@ export const enum OutgoingKind { */ export interface OutgoingEvent { kind: OutgoingKind.Event - signed: SignedEvent + event: SignedEvent | RawEvent } /** @@ -221,7 +221,9 @@ async function parseIncomingMessage(data: string): Promise { function serializeOutgoingMessage(msg: OutgoingMessage): string { if (msg.kind === OutgoingKind.Event) { - return JSON.stringify(["EVENT", msg.signed.serialize()]) + const raw = + msg.event instanceof SignedEvent ? msg.event.serialize() : msg.event + return JSON.stringify(["EVENT", raw]) } else if (msg.kind === OutgoingKind.Subscription) { return JSON.stringify([ "REQ", diff --git a/packages/nostr/src/client/index.ts b/packages/nostr/src/client/index.ts index d7dc29b..70981ed 100644 --- a/packages/nostr/src/client/index.ts +++ b/packages/nostr/src/client/index.ts @@ -202,18 +202,42 @@ export class Nostr { /** * Publish an event. */ - async publish(event: Event, key: PrivateKey): Promise { - if (event.pubkey.toString() !== key.pubkey.toString()) { - throw new Error("invalid private key") + async publish(event: SignedEvent): Promise + async publish(event: RawEvent): Promise + // TODO This will need to change when I add NIP-44 AUTH support - the key should be optional + async publish(event: Event, key: PrivateKey): Promise + async publish( + event: SignedEvent | RawEvent | Event, + key?: PrivateKey + ): Promise { + // Validate the parameters. + if (event instanceof SignedEvent || "sig" in event) { + if (key !== undefined) { + throw new Error( + "when calling publish with a SignedEvent, private key should not be specified" + ) + } + } else { + if (key === undefined) { + throw new Error( + "publish called with an unsigned Event, private key must be specified" + ) + } + if (event.pubkey.toString() !== key.pubkey.toString()) { + throw new Error("invalid private key") + } } + for (const { conn, write } of this.#conns.values()) { if (!write) { continue } - const signed = await SignedEvent.sign(event, key) + if (!(event instanceof SignedEvent) && !("sig" in event)) { + event = await SignedEvent.sign(event, key) + } conn.send({ kind: OutgoingKind.Event, - signed: signed, + event, }) } }