67 lines
1.6 KiB
TypeScript
67 lines
1.6 KiB
TypeScript
import { Event, nip04 } from 'nostr-tools'
|
|
import { SimplePool } from 'nostr-tools'
|
|
|
|
const RELAY_URL = process.env.NEXT_PUBLIC_NOSTR_RELAY_URL || 'wss://relay.damus.io'
|
|
|
|
/**
|
|
* Get private content for an article (encrypted message from author)
|
|
*/
|
|
export async function getPrivateContent(
|
|
pool: SimplePool,
|
|
eventId: string,
|
|
authorPubkey: string,
|
|
privateKey: string,
|
|
publicKey: string
|
|
): Promise<string | null> {
|
|
if (!privateKey || !pool || !publicKey) {
|
|
throw new Error('Private key not set or pool not initialized')
|
|
}
|
|
|
|
return new Promise(async (resolve) => {
|
|
const filters = [
|
|
{
|
|
kinds: [4], // Encrypted direct messages
|
|
'#p': [publicKey],
|
|
'#e': [eventId], // Filter by event ID to find relevant private messages
|
|
authors: [authorPubkey], // Filter by author of the original article
|
|
limit: 10, // Limit to recent messages
|
|
},
|
|
]
|
|
|
|
let resolved = false
|
|
const sub = pool.sub([RELAY_URL], filters)
|
|
|
|
sub.on('event', async (event: Event) => {
|
|
if (!resolved) {
|
|
try {
|
|
// Decrypt the content using nip04
|
|
const content = await nip04.decrypt(privateKey, event.pubkey, event.content)
|
|
if (content) {
|
|
resolved = true
|
|
sub.unsub()
|
|
resolve(content)
|
|
}
|
|
} catch (e) {
|
|
console.error('Error decrypting content:', e)
|
|
}
|
|
}
|
|
})
|
|
|
|
sub.on('eose', () => {
|
|
if (!resolved) {
|
|
resolved = true
|
|
sub.unsub()
|
|
resolve(null)
|
|
}
|
|
})
|
|
|
|
setTimeout(() => {
|
|
if (!resolved) {
|
|
resolved = true
|
|
sub.unsub()
|
|
resolve(null)
|
|
}
|
|
}, 5000)
|
|
})
|
|
}
|