2024-09-11 11:43:49 -03:00
|
|
|
package keyer
|
2024-09-10 22:37:48 -03:00
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
2025-01-17 13:44:50 -03:00
|
|
|
"errors"
|
2024-09-10 22:37:48 -03:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/nbd-wtf/go-nostr"
|
|
|
|
"github.com/nbd-wtf/go-nostr/nip46"
|
|
|
|
)
|
|
|
|
|
2025-03-04 11:08:31 -03:00
|
|
|
// BunkerSigner is a signer that delegates operations to a remote bunker using NIP-46.
|
|
|
|
// It communicates with the bunker for all cryptographic operations rather than
|
|
|
|
// handling the private key locally.
|
2024-09-10 22:37:48 -03:00
|
|
|
type BunkerSigner struct {
|
|
|
|
bunker *nip46.BunkerClient
|
|
|
|
}
|
|
|
|
|
2025-03-04 11:08:31 -03:00
|
|
|
// NewBunkerSignerFromBunkerClient creates a new BunkerSigner from an existing BunkerClient.
|
2024-09-10 22:37:48 -03:00
|
|
|
func NewBunkerSignerFromBunkerClient(bc *nip46.BunkerClient) BunkerSigner {
|
|
|
|
return BunkerSigner{bc}
|
|
|
|
}
|
|
|
|
|
2025-03-04 11:08:31 -03:00
|
|
|
// GetPublicKey retrieves the public key from the remote bunker.
|
|
|
|
// It uses a timeout to prevent hanging indefinitely.
|
2024-09-19 17:47:18 +09:00
|
|
|
func (bs BunkerSigner) GetPublicKey(ctx context.Context) (string, error) {
|
2025-01-17 13:44:50 -03:00
|
|
|
ctx, cancel := context.WithTimeoutCause(ctx, time.Second*30, errors.New("get_public_key took too long"))
|
2024-09-10 22:37:48 -03:00
|
|
|
defer cancel()
|
2024-09-19 17:47:18 +09:00
|
|
|
pk, err := bs.bunker.GetPublicKey(ctx)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
return pk, nil
|
2024-09-10 22:37:48 -03:00
|
|
|
}
|
|
|
|
|
2025-03-04 11:08:31 -03:00
|
|
|
// SignEvent sends the event to the remote bunker for signing.
|
|
|
|
// It uses a timeout to prevent hanging indefinitely.
|
2024-09-10 22:37:48 -03:00
|
|
|
func (bs BunkerSigner) SignEvent(ctx context.Context, evt *nostr.Event) error {
|
2025-01-17 13:44:50 -03:00
|
|
|
ctx, cancel := context.WithTimeoutCause(ctx, time.Second*30, errors.New("sign_event took too long"))
|
2024-09-10 22:37:48 -03:00
|
|
|
defer cancel()
|
|
|
|
return bs.bunker.SignEvent(ctx, evt)
|
|
|
|
}
|
|
|
|
|
2025-03-04 11:08:31 -03:00
|
|
|
// Encrypt encrypts a plaintext message for a recipient using the remote bunker.
|
2024-09-10 22:37:48 -03:00
|
|
|
func (bs BunkerSigner) Encrypt(ctx context.Context, plaintext string, recipient string) (string, error) {
|
|
|
|
return bs.bunker.NIP44Encrypt(ctx, recipient, plaintext)
|
|
|
|
}
|
|
|
|
|
2025-03-04 11:08:31 -03:00
|
|
|
// Decrypt decrypts a base64-encoded ciphertext from a sender using the remote bunker.
|
2024-09-10 22:37:48 -03:00
|
|
|
func (bs BunkerSigner) Decrypt(ctx context.Context, base64ciphertext string, sender string) (plaintext string, err error) {
|
|
|
|
return bs.bunker.NIP44Encrypt(ctx, sender, base64ciphertext)
|
|
|
|
}
|