-
Notifications
You must be signed in to change notification settings - Fork 0
/
disconnect.go
133 lines (97 loc) · 2.24 KB
/
disconnect.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
package main
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
nkcli "github.com/mdzz-club/nkcli/internal"
"github.com/nbd-wtf/go-nostr"
"github.com/nbd-wtf/go-nostr/nip04"
"github.com/urfave/cli/v2"
"golang.org/x/crypto/ssh/terminal"
)
func disconnectAction(c *cli.Context) error {
dbpath := c.String("db")
db, err := nkcli.Open(dbpath)
if err != nil {
return err
}
conns, err := db.ListConnection()
if err != nil {
return err
}
if len(conns) == 0 {
fmt.Println("You don't have any connections.")
return nil
}
fmt.Printf("You have %v connections:\n\n", len(conns))
for i, c := range conns {
fmt.Printf("%v. %v\n", i+1, c.Metadata.Name)
}
fmt.Print("\n Choose one to disconnect ✂️ : ")
line := nkcli.Scanline()
if len(line) == 0 {
return nil
}
n, err := strconv.Atoi(line)
if err != nil {
return err
}
if n < 1 || n > len(conns) {
return errors.New("Invalid No. Out of range.")
}
conn := conns[n-1]
if conn.KeyInfo == nil {
fmt.Print("Enter your passphrase to unlock your private key:")
pass, err := terminal.ReadPassword(0)
if err != nil {
return err
}
info, err := db.GetKey(conn.PubKey, pass)
if err != nil {
return err
}
conn.KeyInfo = info
}
err = sendDisconnect(c.Context, conn)
if err != nil {
return err
}
db.Disconnect(conn.AppID)
fmt.Println("\nYour connection has been disconnected.")
return nil
}
func sendDisconnect(ctx context.Context, conn *nkcli.Connection) error {
relay, err := nostr.RelayConnect(ctx, conn.Relay)
if err != nil {
return err
}
rb := make([]byte, 16)
rand.Read(rb)
randomId := hex.EncodeToString(rb)
data := map[string]any{"id": randomId, "method": "disconnect", "params": []string{}}
shared, err := nip04.ComputeSharedSecret(conn.AppID, conn.KeyInfo.Privkey)
if err != nil {
fmt.Printf("%v\n", err)
return err
}
jstr, err := json.Marshal(data)
if err != nil {
return err
}
content, err := nip04.Encrypt(string(jstr), shared)
event := &nostr.Event{
PubKey: conn.PubKey,
Kind: 24133,
CreatedAt: time.Now(),
Tags: nostr.Tags{{"p", conn.AppID}},
Content: content,
}
err = event.Sign(conn.KeyInfo.Privkey)
relay.Publish(ctx, *event)
return nil
}