main.go raw
1 // Command nostrino-admin sends one control command to a gateway that was started with
2 // -debug-admin, and prints the reply.
3 //
4 // The command is a NIP-01 event signed with the operator's key, encrypted to the gateway with
5 // NIP-44, and the gateway answers on the same kind. That is the whole channel: no ports, no shell,
6 // and the gateway only listens for it when it was told to.
7 package main
8
9 import (
10 "context"
11 "crypto/rand"
12 "encoding/hex"
13 "encoding/json"
14 "flag"
15 "fmt"
16 "os"
17 "strconv"
18 "strings"
19 "time"
20
21 "git.smesh.lol/nostrino/pkg/billing"
22 "git.smesh.lol/nostrino/pkg/crypto/secp256k1"
23 "git.smesh.lol/nostrino/pkg/nip44"
24 "git.smesh.lol/nostrino/pkg/nostr"
25 "git.smesh.lol/nostrino/pkg/relay"
26 "git.smesh.lol/nostrino/pkg/relayinfo"
27 "git.smesh.lol/nostrino/pkg/tunnel"
28 )
29
30 // version is stamped by the release build (-ldflags -X main.version=...).
31 var version = "dev"
32
33 func main() {
34 var (
35 showVersion = flag.Bool("version", false, "print the operator CLI version and exit")
36 genkey = flag.Bool("genkey", false, "print a new operator key: secret then public, hex")
37 keyHex = flag.String("key", "", "operator secret key (64 hex)")
38 gateway = flag.String("gateway", "", "gateway public key (64 hex)")
39 relayURL = flag.String("relay", "", "relay URL")
40 command = flag.String("cmd", "version", "command: version, health, billing, billing-set, listing-quote, listing-settled, listings, subscription, relay-config, update-check, update-apply, rollback")
41 timeout = flag.Duration("timeout", 60*time.Second, "how long to wait for the reply")
42 )
43 var args stringsFlag
44 flag.Var(&args, "arg", "command argument as key=value (repeatable)")
45 flag.Parse()
46
47 if *showVersion {
48 fmt.Println("nostrino-admin " + version)
49 return
50 }
51
52 if *genkey {
53 var secret [32]byte
54
55 if _, err := rand.Read(secret[:]); err != nil {
56 fail(err)
57 }
58
59 public, ok := secp256k1.PubKey(secret)
60
61 if !ok {
62 fail(fmt.Errorf("generated key is not valid"))
63 }
64
65 fmt.Println(hex.EncodeToString(secret[:]))
66 fmt.Println(hex.EncodeToString(public[:]))
67
68 return
69 }
70
71 if *keyHex == "" || *gateway == "" || *relayURL == "" {
72 fail(fmt.Errorf("need -key, -gateway and -relay (or -genkey)"))
73 }
74
75 secret, err := parseHex32(*keyHex)
76
77 if err != nil {
78 fail(err)
79 }
80
81 peer, err := parseHex32(*gateway)
82
83 if err != nil {
84 fail(err)
85 }
86
87 if *command == "subscription" {
88 queryRelay(secret, *relayURL, *timeout)
89
90 return
91 }
92
93 if *command == "relay-config" {
94 settings := map[string]string{}
95
96 for _, pair := range args {
97 key, value, ok := strings.Cut(pair, "=")
98
99 if !ok {
100 fail(fmt.Errorf("-arg %q is not key=value", pair))
101 }
102
103 settings[key] = value
104 }
105
106 relayConfig(secret, *relayURL, *timeout, settings)
107
108 return
109 }
110
111 commandArgs := map[string]string{}
112
113 for _, pair := range args {
114 key, value, ok := strings.Cut(pair, "=")
115
116 if !ok {
117 fail(fmt.Errorf("argument %q is not key=value", pair))
118 }
119
120 commandArgs[key] = value
121 }
122
123 body, err := json.Marshal(map[string]any{"cmd": *command, "args": commandArgs})
124
125 if err != nil {
126 fail(err)
127 }
128
129 conv, err := nip44.ConversationKey(secret, peer)
130
131 if err != nil {
132 fail(err)
133 }
134
135 content, err := nip44.Encrypt(conv, body)
136
137 if err != nil {
138 fail(err)
139 }
140
141 localPub, _ := secp256k1.PubKey(secret)
142
143 transport, err := relay.DialTransport(*relayURL)
144
145 if err != nil {
146 fail(err)
147 }
148
149 client, err := relay.New(transport, secret, relay.Options{RelayURL: *relayURL})
150
151 if err != nil {
152 fail(err)
153 }
154
155 defer client.Close()
156
157 session := make([]byte, 8)
158
159 if _, err := rand.Read(session); err != nil {
160 fail(err)
161 }
162
163 sub, err := client.Subscribe(nostr.Filter{
164 Kinds: []int{tunnel.KindAdmin},
165 Tags: map[string][]string{"p": {nostr.Hex(localPub[:])}},
166 })
167
168 if err != nil {
169 fail(err)
170 }
171
172 ctx, cancel := context.WithTimeout(context.Background(), *timeout)
173 defer cancel()
174
175 if err := client.WaitEOSE(ctx, sub); err != nil {
176 fail(err)
177 }
178
179 event := &nostr.Event{
180 Kind: tunnel.KindAdmin,
181 CreatedAt: time.Now().Unix(),
182 Tags: nostr.Tags{
183 {"p", nostr.Hex(peer[:])},
184 {"s", hex.EncodeToString(session)},
185 {"enc", "nip44-v2"},
186 {"v", "1"},
187 },
188 Content: content,
189 }
190
191 if err := event.Sign(secret); err != nil {
192 fail(err)
193 }
194
195 if err := client.Send(event); err != nil {
196 fail(err)
197 }
198
199 for {
200 select {
201 case <-ctx.Done():
202 fail(fmt.Errorf("no reply within %s", *timeout))
203 case answer, ok := <-sub.Events:
204 if !ok {
205 fail(fmt.Errorf("the relay subscription closed"))
206 }
207
208 if answer.Kind != tunnel.KindAdmin || answer.PubKey != peer {
209 continue
210 }
211
212 reply, err := nip44.Decrypt(conv, answer.Content)
213
214 if err != nil {
215 fail(err)
216 }
217
218 var pretty any
219
220 if err := json.Unmarshal(reply, &pretty); err == nil {
221 out, _ := json.MarshalIndent(pretty, "", " ")
222 fmt.Println(string(out))
223
224 return
225 }
226
227 fmt.Println(string(reply))
228
229 return
230 }
231 }
232 }
233
234 type stringsFlag []string
235
236 func (s *stringsFlag) String() string { return strings.Join(*s, ",") }
237
238 func (s *stringsFlag) Set(value string) error {
239 *s = append(*s, value)
240 return nil
241 }
242
243 func parseHex32(text string) ([32]byte, error) {
244 var out [32]byte
245
246 raw, err := hex.DecodeString(strings.TrimSpace(text))
247
248 if err != nil || len(raw) != 32 {
249 return out, fmt.Errorf("%q is not 32 bytes of hex", text)
250 }
251
252 copy(out[:], raw)
253
254 return out, nil
255 }
256
257 // queryRelay asks a relay how much access the key that signs has left. The signature is the
258 // identity, so nothing in the request names a gateway: the relay answers about the signer.
259 // relayConfig sends a t=config control message: the relay's daily rate, and its block list. Only a
260 // relay admin key is answered, and the relay refuses the rest by staying silent.
261 func relayConfig(secret [32]byte, relayURL string, timeout time.Duration, args map[string]string) {
262 body := map[string]any{}
263
264 if rate, ok := args["rate_sats_per_day"]; ok {
265 n, err := strconv.ParseInt(rate, 10, 64)
266
267 if err != nil {
268 fail(fmt.Errorf("relay-config: rate_sats_per_day: %w", err))
269 }
270
271 body["rate_sats_per_day"] = n
272 }
273
274 if key, ok := args["block"]; ok {
275 body["block"] = key
276 }
277
278 if key, ok := args["unblock"]; ok {
279 body["unblock"] = key
280 }
281
282 content, _ := json.Marshal(body)
283
284 relayControl(secret, relayURL, timeout, billing.TopicConfig, string(content))
285 }
286
287 // relayControl publishes one intercepted control request and prints the relay's answer.
288 func relayControl(secret [32]byte, relayURL string, timeout time.Duration, topic, content string) {
289 info, err := relayinfo.Fetch(context.Background(), nil, relayURL)
290
291 if err != nil {
292 fail(fmt.Errorf("%s: %w", topic, err))
293 }
294
295 raw, err := hex.DecodeString(info.PubKey)
296
297 if err != nil || len(raw) != 32 {
298 fail(fmt.Errorf("%s: the relay did not publish a usable pubkey", topic))
299 }
300
301 var relayPub [32]byte
302
303 copy(relayPub[:], raw)
304
305 transport, err := relay.DialTransport(relayURL)
306
307 if err != nil {
308 fail(fmt.Errorf("%s: %w", topic, err))
309 }
310
311 client, err := relay.New(transport, secret, relay.Options{RelayURL: relayURL})
312
313 if err != nil {
314 fail(fmt.Errorf("%s: %w", topic, err))
315 }
316
317 defer client.Close()
318
319 ctx, cancel := context.WithTimeout(context.Background(), timeout)
320 defer cancel()
321
322 self, _ := secp256k1.PubKey(secret)
323
324 sub, err := client.Subscribe(nostr.Filter{
325 Kinds: []int{billing.KindControl},
326 Authors: []string{nostr.Hex(relayPub[:])},
327 Tags: map[string][]string{"p": {nostr.Hex(self[:])}},
328 })
329
330 if err != nil {
331 fail(fmt.Errorf("%s: %w", topic, err))
332 }
333
334 if err := client.WaitEOSE(ctx, sub); err != nil {
335 fail(fmt.Errorf("%s: %w", topic, err))
336 }
337
338 event := &nostr.Event{
339 Kind: billing.KindControl,
340 CreatedAt: time.Now().Unix(),
341 Tags: nostr.Tags{{billing.TagTopic, topic}, {"p", nostr.Hex(relayPub[:])}},
342 Content: content,
343 }
344
345 if err := event.Sign(secret); err != nil {
346 fail(fmt.Errorf("%s: sign: %w", topic, err))
347 }
348
349 if err := client.Publish(ctx, event); err != nil {
350 fail(fmt.Errorf("%s: %w", topic, err))
351 }
352
353 want := nostr.Hex(event.ID[:])
354
355 for {
356 select {
357 case <-ctx.Done():
358 fmt.Printf("{\"ok\":false,\"error\":\"the relay did not answer the %s request (is this key a relay admin?)\"}\n", topic)
359
360 os.Exit(1)
361 case answer, ok := <-sub.Events:
362 if !ok {
363 fmt.Println(`{"ok":false,"error":"the relay connection closed"}`)
364
365 os.Exit(1)
366 }
367
368 for _, tag := range answer.Tags {
369 if len(tag) >= 2 && tag[0] == "e" && tag[1] == want {
370 fmt.Println(string(answer.Content))
371
372 return
373 }
374 }
375 }
376 }
377 }
378
379 func queryRelay(secret [32]byte, relayURL string, timeout time.Duration) {
380 // The relay's own key is in its NIP-11 document; the gateway key is not it, and subscribing
381 // for the wrong author is the difference between an answer and a silent timeout.
382 info, err := relayinfo.Fetch(context.Background(), nil, relayURL)
383
384 if err != nil {
385 fail(fmt.Errorf("subscription: %w", err))
386 }
387
388 raw, err := hex.DecodeString(info.PubKey)
389
390 if err != nil || len(raw) != 32 {
391 fail(fmt.Errorf("subscription: the relay did not publish a usable pubkey"))
392 }
393
394 var relayPub [32]byte
395
396 copy(relayPub[:], raw)
397
398 transport, err := relay.DialTransport(relayURL)
399
400 if err != nil {
401 fail(fmt.Errorf("subscription: %w", err))
402 }
403
404 client, err := relay.New(transport, secret, relay.Options{RelayURL: relayURL})
405
406 if err != nil {
407 fail(fmt.Errorf("subscription: %w", err))
408 }
409
410 defer client.Close()
411
412 ctx, cancel := context.WithTimeout(context.Background(), timeout)
413 defer cancel()
414
415 self, _ := secp256k1.PubKey(secret)
416
417 sub, err := client.Subscribe(nostr.Filter{
418 Kinds: []int{billing.KindControl},
419 Authors: []string{nostr.Hex(relayPub[:])},
420 Tags: map[string][]string{"p": {nostr.Hex(self[:])}},
421 })
422
423 if err != nil {
424 fail(fmt.Errorf("subscription: %w", err))
425 }
426
427 if err := client.WaitEOSE(ctx, sub); err != nil {
428 fail(fmt.Errorf("subscription: %w", err))
429 }
430
431 event := &nostr.Event{
432 Kind: billing.KindControl,
433 CreatedAt: time.Now().Unix(),
434 Tags: nostr.Tags{{billing.TagTopic, billing.TopicSubscription}, {"p", nostr.Hex(relayPub[:])}},
435 Content: "{}",
436 }
437
438 if err := event.Sign(secret); err != nil {
439 fail(fmt.Errorf("subscription: %w", err))
440 }
441
442 if err := client.Publish(ctx, event); err != nil {
443 fail(fmt.Errorf("subscription: %w", err))
444 }
445
446 want := nostr.Hex(event.ID[:])
447
448 for {
449 select {
450 case <-ctx.Done():
451 fmt.Println(`{"ok":false,"error":"the relay did not answer the subscription query"}`)
452
453 os.Exit(1)
454 case answer, ok := <-sub.Events:
455 if !ok {
456 fmt.Println(`{"ok":false,"error":"the relay connection closed"}`)
457
458 os.Exit(1)
459 }
460
461 matched := false
462
463 for _, tag := range answer.Tags {
464 if len(tag) >= 2 && tag[0] == "e" && tag[1] == want {
465 matched = true
466 }
467 }
468
469 if !matched {
470 continue
471 }
472
473 fmt.Println(string(answer.Content))
474
475 return
476 }
477 }
478 }
479
480 func fail(err error) {
481 fmt.Fprintln(os.Stderr, "nostrino-admin:", err)
482 os.Exit(1)
483 }
484