allow publishing without a private key

This commit is contained in:
ennmichael 2023-02-28 21:46:31 +01:00
parent 02a7418d47
commit 6565aa6fa0
No known key found for this signature in database
GPG Key ID: 6E6E183431A26AF7
2 changed files with 33 additions and 7 deletions

View File

@ -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<IncomingMessage> {
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",

View File

@ -202,18 +202,42 @@ export class Nostr {
/**
* Publish an event.
*/
async publish(event: Event, key: PrivateKey): Promise<void> {
if (event.pubkey.toString() !== key.pubkey.toString()) {
throw new Error("invalid private key")
async publish(event: SignedEvent): Promise<void>
async publish(event: RawEvent): Promise<void>
// 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<void>
async publish(
event: SignedEvent | RawEvent | Event,
key?: PrivateKey
): Promise<void> {
// 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,
})
}
}