-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathaccount_deletion.go
More file actions
103 lines (83 loc) · 2.21 KB
/
Copy pathaccount_deletion.go
File metadata and controls
103 lines (83 loc) · 2.21 KB
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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"time"
"fiatjaf.com/nostr"
"fiatjaf.com/nostr/khatru"
)
const kindVanish nostr.Kind = 62
const accountDeletionTimeout = 5 * time.Second
type accountDeletionConfig struct {
Endpoint string
Client *http.Client
}
type accountDeletionPayload struct {
Event nostr.Event `json:"event"`
}
func configureAccountDeletionFromEnv(relay *khatru.Relay) {
cfg := accountDeletionConfig{
Endpoint: os.Getenv("ACCOUNT_DELETION_URL"),
}
if cfg.Endpoint == "" {
return
}
attachAccountDeletion(relay, cfg)
log.Printf("account deletion forwarding enabled for %s", cfg.Endpoint)
}
func attachAccountDeletion(relay *khatru.Relay, cfg accountDeletionConfig) {
if cfg.Client == nil {
cfg.Client = &http.Client{Timeout: accountDeletionTimeout}
}
prev := relay.OnEventSaved
relay.OnEventSaved = func(ctx context.Context, event nostr.Event) {
if prev != nil {
prev(ctx, event)
}
payload, ok := buildAccountDeletionPayload(event)
if !ok {
return
}
go func() {
if err := sendAccountDeletion(cfg, payload); err != nil {
log.Printf("account deletion forwarding failed for event %s pubkey %s: %v", event.ID.Hex(), event.PubKey.Hex(), err)
}
}()
}
}
func buildAccountDeletionPayload(event nostr.Event) (accountDeletionPayload, bool) {
if event.Kind != kindVanish {
return accountDeletionPayload{}, false
}
return accountDeletionPayload{Event: event}, true
}
func sendAccountDeletion(cfg accountDeletionConfig, payload accountDeletionPayload) error {
body, err := json.Marshal(payload)
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), accountDeletionTimeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodPost, cfg.Endpoint, bytes.NewReader(body))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
resp, err := cfg.Client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusAccepted {
msg, _ := io.ReadAll(io.LimitReader(resp.Body, 1024))
return fmt.Errorf("unexpected status %d: %s", resp.StatusCode, strings.TrimSpace(string(msg)))
}
return nil
}