-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathscheduler.go
More file actions
635 lines (544 loc) · 15.6 KB
/
scheduler.go
File metadata and controls
635 lines (544 loc) · 15.6 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
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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
package main
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/nbd-wtf/go-nostr"
)
// ScheduledPost represents a post scheduled for future publication
type ScheduledPost struct {
ID string `json:"id"`
UserPubkey string `json:"user_pubkey"`
Kind int `json:"kind"`
SignedEvent *nostr.Event `json:"signed_event"`
Relays []string `json:"relays"`
ScheduledFor time.Time `json:"scheduled_for"`
Status string `json:"status"` // pending, processing, published, failed
PublishedAt *time.Time `json:"published_at,omitempty"`
ErrorMessage string `json:"error_message,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
// copy returns a deep copy of the ScheduledPost to prevent data races
func (p *ScheduledPost) copy() *ScheduledPost {
copy := *p
if copy.SignedEvent != nil {
eventCopy := *p.SignedEvent
copy.SignedEvent = &eventCopy
}
if copy.PublishedAt != nil {
t := *p.PublishedAt
copy.PublishedAt = &t
}
if copy.Relays != nil {
copy.Relays = make([]string, len(p.Relays))
copyRelays(copy.Relays, p.Relays)
}
return ©
}
func copyRelays(dst, src []string) {
copy(dst, src)
}
// SchedulerStore handles persistence of scheduled posts
type SchedulerStore struct {
mu sync.RWMutex
filePath string
posts map[string]*ScheduledPost
}
func NewSchedulerStore(dataDir string) (*SchedulerStore, error) {
filePath := filepath.Join(dataDir, "scheduled_posts.json")
store := &SchedulerStore{
filePath: filePath,
posts: make(map[string]*ScheduledPost),
}
// Create directory if it doesn't exist
if err := os.MkdirAll(dataDir, 0755); err != nil {
return nil, err
}
// Load existing data
if err := store.load(); err != nil {
return nil, err
}
return store, nil
}
func (s *SchedulerStore) load() error {
s.mu.Lock()
defer s.mu.Unlock()
data, err := os.ReadFile(s.filePath)
if err != nil {
if os.IsNotExist(err) {
return nil // New file
}
return err
}
return json.Unmarshal(data, &s.posts)
}
func (s *SchedulerStore) save() error {
s.mu.Lock()
defer s.mu.Unlock()
data, err := json.MarshalIndent(s.posts, "", " ")
if err != nil {
return err
}
return os.WriteFile(s.filePath, data, 0644)
}
func (s *SchedulerStore) Add(post *ScheduledPost) error {
s.mu.Lock()
s.posts[post.ID] = post
s.mu.Unlock()
return s.save()
}
func (s *SchedulerStore) Get(id string) (*ScheduledPost, error) {
s.mu.RLock()
defer s.mu.RUnlock()
if post, ok := s.posts[id]; ok {
return post.copy(), nil
}
return nil, fmt.Errorf("post not found")
}
func (s *SchedulerStore) Update(post *ScheduledPost) error {
s.mu.Lock()
s.posts[post.ID] = post
s.mu.Unlock()
return s.save()
}
func (s *SchedulerStore) Delete(id string) error {
s.mu.Lock()
delete(s.posts, id)
s.mu.Unlock()
return s.save()
}
func (s *SchedulerStore) ListByUser(pubkey string) []*ScheduledPost {
s.mu.RLock()
defer s.mu.RUnlock()
var result []*ScheduledPost
for _, post := range s.posts {
if post.UserPubkey == pubkey {
result = append(result, post.copy())
}
}
return result
}
func (s *SchedulerStore) ListPending() []*ScheduledPost {
s.mu.Lock()
defer s.mu.Unlock()
var result []*ScheduledPost
now := time.Now()
for _, post := range s.posts {
if post.Status == "pending" &&
(post.ScheduledFor.Before(now) || post.ScheduledFor.Equal(now)) {
// Atomically transition to "processing" to prevent duplicate work
post.Status = "processing"
result = append(result, post.copy())
}
}
// Persist status changes atomically
go s.save()
return result
}
// validateRelayURL performs SSRF protection by validating relay URLs
func validateRelayURL(relayURL string) error {
// Parse URL to ensure it's well-formed
u, err := url.Parse(relayURL)
if err != nil {
return fmt.Errorf("invalid relay URL: %w", err)
}
// Only allow ws://, wss://, http://, https:// schemes
if u.Scheme != "ws" && u.Scheme != "wss" && u.Scheme != "http" && u.Scheme != "https" {
return fmt.Errorf("unsupported relay scheme: %s", u.Scheme)
}
// Block private/local network addresses (basic SSRF protection)
host := u.Hostname()
if host == "localhost" || host == "127.0.0.1" || host == "::1" ||
strings.HasPrefix(host, "192.168.") ||
strings.HasPrefix(host, "10.") ||
strings.HasPrefix(host, "172.16.") ||
strings.HasPrefix(host, "169.254.") {
return fmt.Errorf("blocked relay address: %s", host)
}
return nil
}
// Scheduler handles the background processing of scheduled posts
type Scheduler struct {
store *SchedulerStore
}
func NewScheduler(dataDir string) (*Scheduler, error) {
store, err := NewSchedulerStore(dataDir)
if err != nil {
return nil, err
}
return &Scheduler{store: store}, nil
}
// logWithFields is a simple structured logging helper
func logWithFields(level, message string, fields map[string]interface{}) {
fieldStrs := make([]string, 0, len(fields))
for k, v := range fields {
fieldStrs = append(fieldStrs, fmt.Sprintf("%s=%v", k, v))
}
log.Printf("[%s] %s %s", level, message, strings.Join(fieldStrs, " "))
}
func (s *Scheduler) Start() {
ticker := time.NewTicker(1 * time.Minute)
go func() {
for range ticker.C {
s.processPendingPosts()
}
}()
logWithFields("info", "Scheduler started", map[string]interface{}{
"interval": "1 minute",
})
}
func (s *Scheduler) processPendingPosts() {
posts := s.store.ListPending()
for _, post := range posts {
go s.publishPost(post)
}
}
func (s *Scheduler) publishPost(post *ScheduledPost) {
logWithFields("info", "Publishing scheduled post", map[string]interface{}{
"post_id": post.ID,
"user_pubkey": post.UserPubkey,
})
ctx := context.Background()
successCount := 0
var lastErr error
// Publish to local relay first
if relay != nil {
added, err := relay.AddEvent(ctx, post.SignedEvent)
if err != nil {
logWithFields("error", "Failed to add event to local relay", map[string]interface{}{
"post_id": post.ID,
"error": err.Error(),
})
lastErr = err
} else if added {
successCount++
logWithFields("info", "Added event to local relay", map[string]interface{}{
"post_id": post.ID,
})
}
}
// Validate and publish to external relays
for _, relayURL := range post.Relays {
// SSRF protection: validate relay URL
if err := validateRelayURL(relayURL); err != nil {
logWithFields("warn", "Skipping invalid relay URL", map[string]interface{}{
"post_id": post.ID,
"relay_url": relayURL,
"error": err.Error(),
})
if lastErr == nil {
lastErr = err
}
continue
}
r, err := nostr.RelayConnect(ctx, relayURL)
if err != nil {
logWithFields("error", "Failed to connect to relay", map[string]interface{}{
"post_id": post.ID,
"relay_url": relayURL,
"error": err.Error(),
})
lastErr = err
continue
}
err = r.Publish(ctx, *post.SignedEvent)
r.Close()
if err != nil {
logWithFields("error", "Failed to publish to relay", map[string]interface{}{
"post_id": post.ID,
"relay_url": relayURL,
"error": err.Error(),
})
lastErr = err
continue
}
successCount++
logWithFields("info", "Published to relay", map[string]interface{}{
"post_id": post.ID,
"relay_url": relayURL,
})
}
// Update status based on actual publish results
post.Status = "published"
if successCount == 0 {
post.Status = "failed"
if lastErr != nil {
post.ErrorMessage = "Publish failed"
} else {
post.ErrorMessage = "No valid relays specified"
}
}
now := time.Now()
post.PublishedAt = &now
if err := s.store.Update(post); err != nil {
logWithFields("error", "Failed to update post status", map[string]interface{}{
"post_id": post.ID,
"status": post.Status,
"error": err.Error(),
})
}
logWithFields("info", "Finished publishing scheduled post", map[string]interface{}{
"post_id": post.ID,
"final_status": post.Status,
"success_count": successCount,
})
}
// HTTP Handlers
func (s *Scheduler) enableCORS(w http.ResponseWriter) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
}
func (s *Scheduler) HandleSchedule(w http.ResponseWriter, r *http.Request) {
s.enableCORS(w)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Auth Check (NIP-98)
userPubkey, err := checkAuth(r)
if err != nil {
logWithFields("warn", "Unauthorized schedule attempt", map[string]interface{}{
"error": err.Error(),
})
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// Parse Body
var req struct {
SignedEvent nostr.Event `json:"signed_event"`
Relays []string `json:"relays"`
ScheduledFor time.Time `json:"scheduled_for"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
logWithFields("warn", "Invalid JSON in schedule request", map[string]interface{}{
"user_pubkey": userPubkey,
"error": err.Error(),
})
http.Error(w, "Invalid JSON", http.StatusBadRequest)
return
}
// Validate User (must match signed event pubkey)
if req.SignedEvent.PubKey != userPubkey {
logWithFields("warn", "Event pubkey mismatch", map[string]interface{}{
"user_pubkey": userPubkey,
"event_pubkey": req.SignedEvent.PubKey,
})
http.Error(w, "Event pubkey mismatch", http.StatusBadRequest)
return
}
// Validate signature
ok, err := req.SignedEvent.CheckSignature()
if !ok || err != nil {
logWithFields("warn", "Invalid event signature", map[string]interface{}{
"user_pubkey": userPubkey,
})
http.Error(w, "Invalid event signature", http.StatusBadRequest)
return
}
// Validate relay URLs (SSRF protection)
for _, relayURL := range req.Relays {
if err := validateRelayURL(relayURL); err != nil {
logWithFields("warn", "Invalid relay URL in request", map[string]interface{}{
"user_pubkey": userPubkey,
"relay_url": relayURL,
"error": err.Error(),
})
http.Error(w, "Invalid relay URL", http.StatusBadRequest)
return
}
}
// Create ScheduledPost
post := &ScheduledPost{
ID: nostr.GeneratePrivateKey(),
UserPubkey: userPubkey,
Kind: req.SignedEvent.Kind,
SignedEvent: &req.SignedEvent,
Relays: req.Relays,
ScheduledFor: req.ScheduledFor,
Status: "pending",
CreatedAt: time.Now(),
}
if err := s.store.Add(post); err != nil {
logWithFields("error", "Failed to save scheduled post", map[string]interface{}{
"user_pubkey": userPubkey,
"post_id": post.ID,
"error": err.Error(),
})
http.Error(w, "Failed to save schedule", http.StatusInternalServerError)
return
}
logWithFields("info", "Scheduled post created", map[string]interface{}{
"user_pubkey": userPubkey,
"post_id": post.ID,
"scheduled_for": req.ScheduledFor,
"relay_count": len(req.Relays),
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(post)
}
func (s *Scheduler) HandleList(w http.ResponseWriter, r *http.Request) {
s.enableCORS(w)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
userPubkey, err := checkAuth(r)
if err != nil {
logWithFields("warn", "Unauthorized list attempt", map[string]interface{}{
"error": err.Error(),
})
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
posts := s.store.ListByUser(userPubkey)
logWithFields("info", "Listed scheduled posts", map[string]interface{}{
"user_pubkey": userPubkey,
"post_count": len(posts),
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(posts)
}
func (s *Scheduler) HandleDelete(w http.ResponseWriter, r *http.Request) {
s.enableCORS(w)
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
if r.Method != "DELETE" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
userPubkey, err := checkAuth(r)
if err != nil {
logWithFields("warn", "Unauthorized delete attempt", map[string]interface{}{
"error": err.Error(),
})
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
id := r.URL.Query().Get("id")
if id == "" {
http.Error(w, "Missing id", http.StatusBadRequest)
return
}
post, err := s.store.Get(id)
if err != nil {
logWithFields("warn", "Post not found for deletion", map[string]interface{}{
"user_pubkey": userPubkey,
"post_id": id,
})
http.Error(w, "Post not found", http.StatusNotFound)
return
}
if post.UserPubkey != userPubkey {
logWithFields("warn", "Forbidden deletion attempt", map[string]interface{}{
"user_pubkey": userPubkey,
"post_owner": post.UserPubkey,
"post_id": id,
})
http.Error(w, "Not allowed", http.StatusForbidden)
return
}
if err := s.store.Delete(id); err != nil {
logWithFields("error", "Failed to delete scheduled post", map[string]interface{}{
"user_pubkey": userPubkey,
"post_id": id,
"error": err.Error(),
})
http.Error(w, "Failed to delete", http.StatusInternalServerError)
return
}
logWithFields("info", "Deleted scheduled post", map[string]interface{}{
"user_pubkey": userPubkey,
"post_id": id,
})
w.WriteHeader(http.StatusOK)
}
// CheckAuth verifies NIP-98 header and checks if user is allowed in nostr.json
func checkAuth(r *http.Request) (string, error) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
return "", fmt.Errorf("missing Authorization header")
}
// Parse NIP-98 token inline (no nip98 subpackage available)
prefix := "Nostr "
if !strings.HasPrefix(authHeader, prefix) || len(authHeader) <= len(prefix) {
return "", fmt.Errorf("invalid header format")
}
token := authHeader[len(prefix):]
// Decode base64 event
eventJSON, err := base64.StdEncoding.DecodeString(token)
if err != nil {
return "", fmt.Errorf("invalid base64 token: %w", err)
}
var event nostr.Event
if err := json.Unmarshal(eventJSON, &event); err != nil {
return "", fmt.Errorf("invalid event JSON: %w", err)
}
// Validate NIP-98 requirements
if event.Kind != 27235 {
return "", fmt.Errorf("invalid event kind for NIP-98: %d", event.Kind)
}
ok, err := event.CheckSignature()
if !ok || err != nil {
return "", fmt.Errorf("invalid event signature")
}
// Reconstruct full request URL for comparison
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
if fwdProto := r.Header.Get("X-Forwarded-Proto"); fwdProto != "" {
scheme = fwdProto
}
fullURL := scheme + "://" + r.Host + r.URL.RequestURI()
// Check u tag matches request URL (fix potential panic)
uTag := event.Tags.GetFirst([]string{"u", ""})
if uTag == nil || len(*uTag) < 2 {
return "", fmt.Errorf("missing or malformed u tag in NIP-98 token")
}
if (*uTag)[1] != fullURL {
return "", fmt.Errorf("URL mismatch in NIP-98 token")
}
// Check method tag
methodTag := event.Tags.GetFirst([]string{"method", ""})
if methodTag == nil || len(*methodTag) < 2 {
return "", fmt.Errorf("missing or malformed method tag in NIP-98 token")
}
if !strings.EqualFold((*methodTag)[1], r.Method) {
return "", fmt.Errorf("method mismatch in NIP-98 token")
}
pubkey := event.PubKey
// Check against allowed list (data.Names)
// Access the global 'data' variable
allowed := false
// Check if user is in data.Names
for _, pk := range data.Names {
if pk == pubkey {
allowed = true
break
}
}
if !allowed {
return "", fmt.Errorf("pubkey not allowed in nostr.json")
}
return pubkey, nil
}