nip-07.signer.ts raw
1 import { ISigner, TDraftEvent, TNip07 } from '@/types'
2
3 export class Nip07Signer implements ISigner {
4 private signer: TNip07 | undefined
5 private pubkey: string | null = null
6
7 async init() {
8 const checkInterval = 100
9 const maxAttempts = 50
10
11 for (let attempt = 0; attempt < maxAttempts; attempt++) {
12 if (window.nostr) {
13 this.signer = window.nostr
14 return
15 }
16 await new Promise((resolve) => setTimeout(resolve, checkInterval))
17 }
18
19 throw new Error(
20 'You need to install a nostr signer extension to login. Such as alby, nostr-keyx or nos2x.'
21 )
22 }
23
24 async getPublicKey() {
25 if (!this.signer) {
26 throw new Error('Should call init() first')
27 }
28 if (!this.pubkey) {
29 this.pubkey = await this.signer.getPublicKey()
30 }
31 return this.pubkey
32 }
33
34 async signEvent(draftEvent: TDraftEvent) {
35 if (!this.signer) {
36 throw new Error('Should call init() first')
37 }
38 return await this.signer.signEvent(draftEvent)
39 }
40
41 async nip04Encrypt(pubkey: string, plainText: string) {
42 if (!this.signer) {
43 throw new Error('Should call init() first')
44 }
45 if (!this.signer.nip04?.encrypt) {
46 throw new Error('The extension you are using does not support nip04 encryption')
47 }
48 return await this.signer.nip04.encrypt(pubkey, plainText)
49 }
50
51 async nip04Decrypt(pubkey: string, cipherText: string) {
52 if (!this.signer) {
53 throw new Error('Should call init() first')
54 }
55 if (!this.signer.nip04?.decrypt) {
56 throw new Error('The extension you are using does not support nip04 decryption')
57 }
58 return await this.signer.nip04.decrypt(pubkey, cipherText)
59 }
60
61 async nip44Encrypt(pubkey: string, plainText: string) {
62 if (!this.signer) {
63 throw new Error('Should call init() first')
64 }
65 if (!this.signer.nip44?.encrypt) {
66 throw new Error('The extension you are using does not support nip44 encryption')
67 }
68 return await this.signer.nip44.encrypt(pubkey, plainText)
69 }
70
71 async nip44Decrypt(pubkey: string, cipherText: string) {
72 if (!this.signer) {
73 throw new Error('Should call init() first')
74 }
75 if (!this.signer.nip44?.decrypt) {
76 throw new Error('The extension you are using does not support nip44 decryption')
77 }
78 return await this.signer.nip44.decrypt(pubkey, cipherText)
79 }
80 }
81