support relay authentication

This commit is contained in:
zappityzap 2025-01-04 20:26:01 -08:00
parent b7a49e926a
commit 696ccfaec3

View file

@ -2,8 +2,10 @@ const NotificationProvider = require("./notification-provider");
const { const {
finalizeEvent, finalizeEvent,
Relay, Relay,
kinds,
nip04, nip04,
nip19, nip19,
nip42,
} = require("nostr-tools"); } = require("nostr-tools");
// polyfills for node versions // polyfills for node versions
@ -36,7 +38,7 @@ class Nostr extends NotificationProvider {
for (const recipientPublicKey of recipientsPublicKeys) { for (const recipientPublicKey of recipientsPublicKeys) {
const ciphertext = await nip04.encrypt(senderPrivateKey, recipientPublicKey, msg); const ciphertext = await nip04.encrypt(senderPrivateKey, recipientPublicKey, msg);
let event = { let event = {
kind: 4, kind: kinds.EncryptedDirectMessage,
created_at: createdAt, created_at: createdAt,
tags: [[ "p", recipientPublicKey ]], tags: [[ "p", recipientPublicKey ]],
content: ciphertext, content: ciphertext,
@ -49,17 +51,29 @@ class Nostr extends NotificationProvider {
const relays = notification.relays.split("\n"); const relays = notification.relays.split("\n");
let successfulRelays = 0; let successfulRelays = 0;
for (const relayUrl of relays) { for (const relayUrl of relays) {
try {
const relay = await Relay.connect(relayUrl); const relay = await Relay.connect(relayUrl);
let eventIndex = 0;
// Publish events // Authenticate to the relay, if required
for (const event of events) { try {
await relay.publish(event); await relay.publish(events[0]);
eventIndex = 1;
} catch (error) {
if (relay.challenge) {
await relay.auth(async (evt) => {
return finalizeEvent(evt, senderPrivateKey);
});
}
}
try {
for (let i = eventIndex; i < events.length; i++) {
await relay.publish(events[i]);
} }
relay.close(); relay.close();
successfulRelays++; successfulRelays++;
} catch (error) { } catch (error) {
continue; console.error(`Failed to publish event to ${relayUrl}:`, error);
} }
} }
@ -70,6 +84,17 @@ class Nostr extends NotificationProvider {
return `${successfulRelays}/${relays.length} relays connected.`; return `${successfulRelays}/${relays.length} relays connected.`;
} }
/**
* Sign the authentication event
* @param {Relay} relay Relay instance
* @param {string} privateKey Sender's private key
* @returns {Promise<VerifiedEvent>} Signed authentication event
*/
async signAuthEvent(relay, privateKey) {
const authEvent = nip42.makeAuthEvent(relay.url, relay.challenge);
return finalizeEvent(authEvent, privateKey);
}
/** /**
* Get the private key for the sender * Get the private key for the sender
* @param {string} sender Sender to retrieve key for * @param {string} sender Sender to retrieve key for