1 package net
2 3 import (
4 "encoding/json"
5 "os"
6 "path/filepath"
7 "strconv"
8 "strings"
9 "time"
10 11 "git.smesh.lol/torly/pkg/nostr"
12 )
13 14 // kindControl is the intercepted kind. A control message is answered and then forgotten: it is
15 // never stored, never broadcast to subscribers, and never acknowledged as a stored event.
16 const kindControl = 23199
17 18 // Control topics.
19 const (
20 controlSubscription = "subscription"
21 controlConfig = "config"
22 )
23 24 // Ledger is the relay's record of paid gateway time, written by the billing sidecar and read by
25 // the relay. It is the same file shape the sidecar produces, so the two processes agree by reading
26 // one document rather than by talking to each other.
27 type Ledger struct {
28 RateSatsPerDay int64 `json:"rate_sats_per_day"`
29 Subscriptions map[string]Subscription `json:"subscriptions"`
30 Watermarks map[string]int64 `json:"watermarks,omitempty"`
31 // Blocked gateways are refused even while paid: payment buys time, not permission, and the
32 // operator's decision does not erase what was paid.
33 Blocked map[string]bool `json:"blocked,omitempty"`
34 }
35 36 // Subscription is one gateway's paid access.
37 type Subscription struct {
38 Gateway string `json:"gateway"`
39 PaidUntil string `json:"paid_until"`
40 TotalSats int64 `json:"total_sats"`
41 }
42 43 // ledgerPath is where the relay looks for the ledger.
44 func (s *server) ledgerPath() string {
45 if path := strings.TrimSpace(os.Getenv("TORLY_LEDGER_FILE")); path != "" {
46 return path
47 }
48 49 if s.data.Cfg.DataDir == "" {
50 return ""
51 }
52 53 return filepath.Join(s.data.Cfg.DataDir, "subscriptions.json")
54 }
55 56 // ledger reads the ledger. A missing file means the relay is not charging for access, which is a
57 // policy decision, not an error.
58 func (s *server) ledger() Ledger {
59 path := s.ledgerPath()
60 61 if path == "" {
62 return Ledger{}
63 }
64 65 body, err := os.ReadFile(path)
66 67 if err != nil {
68 return Ledger{}
69 }
70 71 var ledger Ledger
72 73 if err := json.Unmarshal(body, &ledger); err != nil {
74 return Ledger{}
75 }
76 77 if ledger.Subscriptions == nil {
78 ledger.Subscriptions = map[string]Subscription{}
79 }
80 81 return ledger
82 }
83 84 // subscriptionState reports whether a gateway may publish right now, and how long it has left.
85 //
86 // The default is zero and free: a relay with no rate set — no ledger file, an empty one, or one
87 // that cannot be parsed — charges nothing and admits every gateway it authorises. Turning billing
88 // on must be a deliberate act by the operator, never a side effect of a missing or damaged file.
89 func (s *server) subscriptionState(gateway string) (allowed bool, remaining time.Duration) {
90 ledger := s.ledger()
91 92 if ledger.RateSatsPerDay <= 0 {
93 return true, 0
94 }
95 96 if ledger.Blocked[gateway] {
97 return false, 0
98 }
99 100 subscription, ok := ledger.Subscriptions[gateway]
101 102 if !ok {
103 return false, 0
104 }
105 106 until, err := time.Parse(time.RFC3339, subscription.PaidUntil)
107 108 if err != nil {
109 return false, 0
110 }
111 112 now := time.Now()
113 114 if !until.After(now) {
115 return false, 0
116 }
117 118 return true, until.Sub(now)
119 }
120 121 // authorizedGateway reports whether the policy admits this key as a back end. It is the same list
122 // the presence rule uses, so "who may announce" and "who may ask about their access" cannot drift.
123 func (s *server) authorizedGateway(key string) bool {
124 engine := s.data.Cfg.Policy
125 126 if engine == nil {
127 return false
128 }
129 130 for _, rule := range engine.Rules() {
131 if len(rule.Authors) == 0 {
132 continue
133 }
134 135 for _, kind := range rule.Kinds {
136 if kind != 30333 && kind != 23197 {
137 continue
138 }
139 140 for _, author := range rule.Authors {
141 if strings.EqualFold(author, key) {
142 return true
143 }
144 }
145 }
146 }
147 148 return false
149 }
150 151 // adminKey reports whether this key may change the relay's settings.
152 func (s *server) adminKey(key string) bool {
153 for _, admin := range strings.Split(os.Getenv("TORLY_ADMINS"), ",") {
154 if strings.EqualFold(strings.TrimSpace(admin), key) {
155 return true
156 }
157 }
158 159 return false
160 }
161 162 // handleControl answers one intercepted message and returns. It never stores anything: the caller
163 // has already verified the signature, and the answer is sent as a normal event to whoever holds a
164 // matching subscription.
165 func (s *server) handleControl(ev *nostr.Event) {
166 signer := nostr.Hex(ev.PubKey[:])
167 168 switch controlTopic(ev) {
169 case controlSubscription:
170 // A relay answers about the key that signed, and about no other key: there is nothing to
171 // spoof because the question is "how long have I got".
172 if !s.authorizedGateway(signer) && !s.adminKey(signer) {
173 return
174 }
175 176 s.replyControl(ev, signer, controlSubscription, s.subscriptionAnswer(signer))
177 case controlConfig:
178 if !s.adminKey(signer) {
179 return
180 }
181 182 applied, err := s.applyConfig(ev)
183 184 answer := map[string]any{"applied": applied}
185 186 if err != nil {
187 answer["error"] = err.Error()
188 }
189 190 s.replyControl(ev, signer, controlConfig, answer)
191 }
192 }
193 194 // subscriptionAnswer is the body of the answer to a subscription query: the ledger's arithmetic,
195 // about the key that asked.
196 func (s *server) subscriptionAnswer(gateway string) map[string]any {
197 allowed, remaining := s.subscriptionState(gateway)
198 ledger := s.ledger()
199 200 answer := map[string]any{
201 "gateway": gateway,
202 "paid": allowed,
203 "remaining_seconds": int64(remaining / time.Second),
204 "rate_sats_per_day": ledger.RateSatsPerDay,
205 "now": time.Now().UTC().Format(time.RFC3339),
206 }
207 208 if subscription, ok := ledger.Subscriptions[gateway]; ok {
209 answer["paid_until"] = subscription.PaidUntil
210 answer["total_sats"] = subscription.TotalSats
211 }
212 213 if ledger.Blocked[gateway] {
214 answer["blocked"] = true
215 }
216 217 return answer
218 }
219 220 // controlTopic reads the t tag.
221 func controlTopic(ev *nostr.Event) string {
222 for _, tag := range ev.Tags {
223 if len(tag) >= 2 && tag[0] == "t" {
224 return strings.ToLower(tag[1])
225 }
226 }
227 228 return ""
229 }
230 231 // applyConfig changes what can be changed at runtime: the daily rate, and the operator's block
232 // list. Settings that need a restart are refused rather than silently ignored.
233 func (s *server) applyConfig(ev *nostr.Event) (map[string]string, error) {
234 applied := map[string]string{}
235 236 var body struct {
237 RateSatsPerDay *int64 `json:"rate_sats_per_day"`
238 Block string `json:"block,omitempty"`
239 Unblock string `json:"unblock,omitempty"`
240 }
241 242 if err := json.Unmarshal([]byte(ev.Content), &body); err != nil {
243 return applied, err
244 }
245 246 ledger := s.ledger()
247 248 if body.RateSatsPerDay != nil {
249 rate := *body.RateSatsPerDay
250 251 if rate < 0 {
252 rate = 0
253 }
254 255 ledger.RateSatsPerDay = rate
256 applied["rate_sats_per_day"] = strconv.FormatInt(rate, 10)
257 }
258 259 if ledger.Blocked == nil {
260 ledger.Blocked = map[string]bool{}
261 }
262 263 if key := strings.ToLower(strings.TrimSpace(body.Block)); key != "" {
264 ledger.Blocked[key] = true
265 applied["blocked"] = key
266 }
267 268 if key := strings.ToLower(strings.TrimSpace(body.Unblock)); key != "" {
269 delete(ledger.Blocked, key)
270 applied["unblocked"] = key
271 }
272 273 path := s.ledgerPath()
274 275 if path == "" {
276 return applied, os.ErrNotExist
277 }
278 279 body2, err := json.MarshalIndent(ledger, "", " ")
280 281 if err != nil {
282 return applied, err
283 }
284 285 if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
286 return applied, err
287 }
288 289 if err := os.WriteFile(path, append(body2, '\n'), 0o600); err != nil {
290 return applied, err
291 }
292 293 return applied, nil
294 }
295 296 // replyControl signs an answer from the relay and broadcasts it. It reaches the asker because the
297 // asker subscribed to this kind from this relay's key; nobody else's subscription matches the
298 // p tag, so the answer is private in the only sense that matters: it is addressed.
299 func (s *server) replyControl(request *nostr.Event, to, topic string, body map[string]any) {
300 content, err := json.Marshal(body)
301 302 if err != nil {
303 return
304 }
305 306 answer := &nostr.Event{
307 Kind: kindControl,
308 CreatedAt: time.Now().Unix(),
309 Tags: nostr.Tags{
310 {"t", topic},
311 {"p", to},
312 {"e", nostr.Hex(request.ID[:])},
313 },
314 Content: string(content),
315 }
316 317 if err := answer.Sign(s.data.RelaySk); err != nil {
318 return
319 }
320 321 s.broadcast(answer)
322 }
323 324 // paidGateway decides whether a gateway may publish a stored or bulk kind. When the relay charges,
325 // an unpaid gateway is refused; the operator's block list is consulted first, so a paid gateway can
326 // still be stopped.
327 func (s *server) paidGateway(key string) (bool, string) {
328 allowed, _ := s.subscriptionState(key)
329 330 if allowed {
331 return true, ""
332 }
333 334 ledger := s.ledger()
335 336 if ledger.Blocked[key] {
337 return false, "blocked: this gateway is not permitted to serve on this relay"
338 }
339 340 return false, "payment-required: this gateway's access to this relay has lapsed"
341 }
342