story-research-zapwall/lib/nostrRemoteSigner.ts
2025-12-23 02:20:57 +01:00

66 lines
1.8 KiB
TypeScript

import type { EventTemplate, Event } from 'nostr-tools'
import { getEventHash, signEvent } from 'nostr-tools'
import { nostrConnectService } from './nostrconnect'
import { nostrService } from './nostr'
/**
* Remote signer using NostrConnect
* Supports both direct signing (if private key available) and remote signing via bridge
*/
export class NostrRemoteSigner {
/**
* Sign an event template
* Requires private key to be available
*/
signEvent(eventTemplate: EventTemplate): Event | null {
// Get the event hash first
const pubkey = nostrService.getPublicKey()
if (!pubkey) {
throw new Error('Public key required for signing. Please connect a Nostr wallet.')
}
const unsignedEvent = {
pubkey,
...eventTemplate,
created_at: eventTemplate.created_at ?? Math.floor(Date.now() / 1000),
}
const eventId = getEventHash(unsignedEvent)
// Try to get private key from nostrService (if available from NostrConnect)
const privateKey = nostrService.getPrivateKey()
if (!privateKey) {
throw new Error(
'Private key required for signing. ' +
'Please use a NostrConnect wallet that provides signing capabilities, ' +
'or ensure your wallet is properly connected.'
)
}
const event = {
...unsignedEvent,
id: eventId,
sig: signEvent(unsignedEvent, privateKey),
} as Event
return event
}
/**
* Check if remote signing is available
*/
isAvailable(): boolean {
const state = nostrConnectService.getState()
return state.connected && !!state.pubkey
}
/**
* Check if direct signing (with private key) is available
*/
isDirectSigningAvailable(): boolean {
return !!nostrService.getPrivateKey()
}
}
export const nostrRemoteSigner = new NostrRemoteSigner()