-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathmain.go
More file actions
1986 lines (1700 loc) · 55.8 KB
/
Copy pathmain.go
File metadata and controls
1986 lines (1700 loc) · 55.8 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
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/fiatjaf/eventstore/badger"
"github.com/fiatjaf/eventstore/lmdb"
"github.com/fiatjaf/eventstore/postgresql"
"github.com/fiatjaf/khatru"
"github.com/fiatjaf/khatru/blossom"
"github.com/joho/godotenv"
"github.com/nbd-wtf/go-nostr"
"github.com/spf13/afero"
)
type Config struct {
RelayName string
RelayPubkey string
RelayDescription string
DBEngine *string
DBPath *string
PostgresUser *string
PostgresPassword *string
PostgresDB *string
PostgresHost *string
PostgresPort *string
DatabaseURL *string
TeamDomain string
NPUBDomain string
BlossomEnabled bool
BlossomPath *string
BlossomURL *string
WebSocketURL *string
AllowedKinds []int
PublicAllowedKinds []int
TrustedClientName string
TrustedClientKinds []int
TrustedClientAllKinds bool
MaxUploadSizeMB int
RelayPort string
AllowedMirrorHosts []string
// S3 Storage Configuration
StorageBackend string
S3Endpoint string
S3Bucket string
S3Region string
S3PublicURL string
}
// resolveDashboardAdminPubkey picks the operator key for dashboard auth.
// Priority: in-memory data("_"), local public/.well-known/nostr.json("_"), then RELAY_PUBKEY fallback.
func resolveDashboardAdminPubkey(config Config) string {
if pk, ok := data.Names["_"]; ok && pk != "" {
return pk
}
body, err := os.ReadFile("./public/.well-known/nostr.json")
if err == nil {
var localData NostrData
if err := json.Unmarshal(body, &localData); err == nil {
if pk, ok := localData.Names["_"]; ok && pk != "" {
return pk
}
}
}
return config.RelayPubkey
}
func truncatePubkey(pk string) string {
if len(pk) <= 8 {
return pk
}
return pk[:8]
}
type NostrData struct {
Names map[string]string `json:"names"`
Relays map[string][]string `json:"relays"`
}
var data NostrData
var relay *khatru.Relay
var db DBBackend
var fs afero.Fs
var config Config
var s3Storage *S3Storage
func main() {
relay = khatru.NewRelay()
config := LoadConfig()
// Initialize nostr.json with relay pubkey as root if needed
if err := initializeNostrJson(config); err != nil {
log.Printf("Warning: Failed to initialize nostr.json: %s", err)
}
relay.StoreEvent = append(relay.StoreEvent, db.SaveEvent)
relay.QueryEvents = append(relay.QueryEvents, db.QueryEvents)
relay.DeleteEvent = append(relay.DeleteEvent, db.DeleteEvent)
fetchNostrData(config.NPUBDomain)
// Apply spam protection policies
applySpamProtection(relay, config)
go func() {
for {
time.Sleep(1 * time.Hour)
fetchNostrData(config.NPUBDomain)
}
}()
relay.RejectEvent = append(relay.RejectEvent, func(ctx context.Context, event *nostr.Event) (reject bool, msg string) {
// Check for trusted client exception: allow specific kinds (or all kinds) from a specific client
trustedClientException := false
if config.TrustedClientName != "" {
for _, tag := range event.Tags {
if len(tag) >= 2 && tag[0] == "client" && tag[1] == config.TrustedClientName {
// If all kinds allowed for trusted client, allow immediately
if config.TrustedClientAllKinds {
trustedClientException = true
break
}
// Otherwise check specific kinds
for _, kc := range config.TrustedClientKinds {
if event.Kind == kc {
trustedClientException = true
break
}
}
if trustedClientException {
break
}
}
}
}
if trustedClientException {
return false, "" // allow event from trusted client for configured kinds
}
// Check if this is a delete event (kind 5)
if event.Kind == 5 {
// Team members can delete any events
for _, pubkey := range data.Names {
if event.PubKey == pubkey {
return false, "" // allow team members to delete any events
}
}
// Public users can delete their own posts if they have "e" tags referencing events
// and the original event was posted via PUBLIC_ALLOWED_KINDS
if len(config.PublicAllowedKinds) > 0 {
// Check if the delete event has "e" tags (references to events being deleted)
hasEventRefs := false
for _, tag := range event.Tags {
if len(tag) >= 2 && tag[0] == "e" {
hasEventRefs = true
break
}
}
if hasEventRefs {
// Allow public users to delete (they can only delete their own events
// as the relay will verify ownership when processing the delete)
return false, "" // allow public users to delete their own events
}
}
return true, "only team members can delete events, or users can delete their own posts"
}
// Check if this is a public allowed kind (any pubkey can post these)
if len(config.PublicAllowedKinds) > 0 {
for _, publicKind := range config.PublicAllowedKinds {
if event.Kind == publicKind {
return false, "" // allow public posting for this kind
}
}
}
// Check if user is part of the team
isTeamMember := false
for _, pubkey := range data.Names {
if event.PubKey == pubkey {
isTeamMember = true
break
}
}
if !isTeamMember {
return true, "you are not part of the team"
}
// Check if event kind is allowed for team members
if len(config.AllowedKinds) > 0 {
isKindAllowed := false
for _, allowedKind := range config.AllowedKinds {
if event.Kind == allowedKind {
isKindAllowed = true
break
}
}
if !isKindAllowed {
return true, fmt.Sprintf("event kind %d is not allowed for team members", event.Kind)
}
}
return false, "" // allow
})
// Setup front page handler
setupFrontPageHandler(relay, config)
// Setup dashboard handlers
setupDashboardHandlers(relay, config)
// Add handler for all public assets
relay.Router().HandleFunc("/public/", func(w http.ResponseWriter, r *http.Request) {
// Get the requested file path (remove /public/ prefix)
requestedPath := strings.TrimPrefix(r.URL.Path, "/public/")
// Prevent directory traversal attacks
if strings.Contains(requestedPath, "..") {
http.Error(w, "Invalid path", http.StatusBadRequest)
return
}
// Serve the file from public directory
filePath := "./public/" + requestedPath
if _, err := os.Stat(filePath); os.IsNotExist(err) {
http.NotFound(w, r)
return
}
http.ServeFile(w, r, filePath)
})
setupConvertHandlers(relay, config)
// Setup Scheduler - use configured DB path
schedulerDataPath := *config.DBPath
scheduler, err := NewScheduler(schedulerDataPath)
if err != nil {
log.Printf("Failed to initialize scheduler: %v", err)
} else {
scheduler.Start()
relay.Router().HandleFunc("/api/scheduler/schedule", scheduler.HandleSchedule)
relay.Router().HandleFunc("/api/scheduler/list", scheduler.HandleList)
relay.Router().HandleFunc("/api/scheduler/delete", scheduler.HandleDelete)
}
// Health check endpoint for scheduler API
relay.Router().HandleFunc("/api/health", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})
})
// Add NIP-05 service handlers
// setupNIP05Handlers(relay, config)
if !config.BlossomEnabled {
// Configure HTTP server with timeouts suitable for large file uploads
server := &http.Server{
Addr: ":" + config.RelayPort,
Handler: relay,
ReadTimeout: 15 * time.Minute, // Increased to 15 minutes for very large files
WriteTimeout: 15 * time.Minute, // Increased to 15 minutes
IdleTimeout: 5 * time.Minute, // Increased idle timeout
ReadHeaderTimeout: 30 * time.Second, // Prevent slow header attacks
MaxHeaderBytes: 1 << 20, // 1MB max header size
}
fmt.Println("running on :" + config.RelayPort + " with extended timeouts for large uploads")
server.ListenAndServe()
return
}
bl := blossom.New(relay, *config.BlossomURL)
bl.Store = blossom.EventStoreBlobIndexWrapper{Store: db, ServiceURL: bl.ServiceURL}
if config.StorageBackend == "s3" && s3Storage != nil {
// S3 Storage Backend
bl.StoreBlob = append(bl.StoreBlob, func(ctx context.Context, sha256 string, body []byte) error {
return s3Storage.StoreBlob(ctx, sha256, body)
})
bl.LoadBlob = append(bl.LoadBlob, func(ctx context.Context, sha256 string) (io.ReadSeeker, error) {
reader, redirectURL, err := s3Storage.LoadBlob(ctx, sha256)
if err != nil {
return nil, err
}
// If we have a redirect URL, we need to handle it differently
// The khatru blossom library expects just ReadSeeker, so we return the reader
// For S3 with public URL, the redirect is handled via the public URL config
if redirectURL != nil {
log.Printf("LoadBlob: S3 redirect URL available: %s", redirectURL.String())
}
return reader, nil
})
bl.DeleteBlob = append(bl.DeleteBlob, func(ctx context.Context, sha256 string) error {
return s3Storage.DeleteBlob(ctx, sha256)
})
} else {
// Filesystem Storage Backend
bl.StoreBlob = append(bl.StoreBlob, func(ctx context.Context, sha256 string, body []byte) error {
// Create context with timeout for large file operations
storeCtx, cancel := context.WithTimeout(ctx, 10*time.Minute)
defer cancel()
file, err := fs.Create(*config.BlossomPath + sha256)
if err != nil {
return err
}
defer file.Close()
// Use streaming copy with context checking for large files
reader := bytes.NewReader(body)
buffer := make([]byte, 32*1024) // 32KB buffer for efficient copying
for {
select {
case <-storeCtx.Done():
return storeCtx.Err()
default:
}
n, err := reader.Read(buffer)
if n > 0 {
if _, writeErr := file.Write(buffer[:n]); writeErr != nil {
return writeErr
}
}
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return file.Sync() // Ensure data is written to disk
})
bl.LoadBlob = append(bl.LoadBlob, func(ctx context.Context, sha256 string) (io.ReadSeeker, error) {
filePath := *config.BlossomPath + sha256
log.Printf("LoadBlob: Attempting to open file at path: %s", filePath)
file, err := fs.Open(filePath)
if err != nil {
log.Printf("LoadBlob: Failed to open file %s: %v", filePath, err)
return nil, err
}
log.Printf("LoadBlob: Successfully opened file %s", filePath)
return file, nil
})
bl.DeleteBlob = append(bl.DeleteBlob, func(ctx context.Context, sha256 string) error {
return fs.Remove(*config.BlossomPath + sha256)
})
}
bl.RejectUpload = append(bl.RejectUpload, func(ctx context.Context, event *nostr.Event, size int, ext string) (bool, string, int) {
// Check for configurable size limit
maxSize := config.MaxUploadSizeMB * 1024 * 1024
if size > maxSize {
return true, fmt.Sprintf("file size exceeds %dMB limit", config.MaxUploadSizeMB), 413
}
for _, pubkey := range data.Names {
if pubkey == event.PubKey {
return false, ext, size
}
}
return true, "you are not part of the team", 403
})
// Add custom list endpoint for Sakura health checks
relay.Router().HandleFunc("/list/", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Extract pubkey from URL path
pubkey := strings.TrimPrefix(r.URL.Path, "/list/")
if pubkey == "" {
http.Error(w, "Missing pubkey", http.StatusBadRequest)
return
}
log.Printf("List blobs request for pubkey: %s", pubkey)
// Read all files from storage backend
blobs := []map[string]interface{}{}
if config.StorageBackend == "s3" && s3Storage != nil {
// S3 Storage Backend
s3Blobs, err := s3Storage.ListBlobs(r.Context())
if err != nil {
log.Printf("Error listing S3 blobs: %v", err)
} else {
for _, blob := range s3Blobs {
blobs = append(blobs, map[string]interface{}{
"sha256": blob.SHA256,
"size": blob.Size,
"type": blob.Type,
"url": blob.URL,
"uploaded": blob.Uploaded,
})
}
}
} else if config.BlossomPath != nil {
// Filesystem Storage Backend
file, err := fs.Open(*config.BlossomPath)
if err != nil {
log.Printf("Error opening blossom directory: %v", err)
} else {
defer file.Close()
fileInfos, err := file.Readdir(-1)
if err != nil {
log.Printf("Error reading blossom directory: %v", err)
} else {
for _, fileInfo := range fileInfos {
if !fileInfo.IsDir() {
fileName := fileInfo.Name()
// Validate that it looks like a SHA256 hash (64 hex characters)
if len(fileName) == 64 {
isValidHash := true
for _, char := range fileName {
if !((char >= '0' && char <= '9') || (char >= 'a' && char <= 'f') || (char >= 'A' && char <= 'F')) {
isValidHash = false
break
}
}
if isValidHash {
// Detect MIME type by reading the first 512 bytes
contentType := "application/octet-stream" // Default fallback
filePath := *config.BlossomPath + fileName
if blobFile, err := fs.Open(filePath); err == nil {
buffer := make([]byte, 512)
if n, err := blobFile.Read(buffer); err == nil && n > 0 {
detectedType := http.DetectContentType(buffer[:n])
if detectedType != "" {
contentType = detectedType
}
}
blobFile.Close()
}
blob := map[string]interface{}{
"sha256": strings.ToLower(fileName),
"size": fileInfo.Size(),
"type": contentType,
"url": *config.BlossomURL + "/" + strings.ToLower(fileName),
"uploaded": fileInfo.ModTime().Unix(),
}
blobs = append(blobs, blob)
log.Printf("Found blob: %s (size: %d, type: %s)", fileName, fileInfo.Size(), contentType)
}
}
}
}
}
}
}
log.Printf("Returning %d blobs for pubkey %s", len(blobs), pubkey)
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(blobs)
})
// Add custom mirror endpoint handler for Sakura compatibility
relay.Router().HandleFunc("/mirror", func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
// Parse the request body to get source URL
var mirrorRequest struct {
URL string `json:"url"`
}
if err := json.NewDecoder(r.Body).Decode(&mirrorRequest); err != nil {
http.Error(w, "Invalid JSON body", http.StatusBadRequest)
return
}
if mirrorRequest.URL == "" {
http.Error(w, "Missing source URL", http.StatusBadRequest)
return
}
// Validate URL against allowlist to prevent SSRF attacks
if !isAllowedMirrorURL(mirrorRequest.URL, config.AllowedMirrorHosts) {
http.Error(w, "Source URL host not in allowed list", http.StatusForbidden)
return
}
// Store validated URL to make it clear to static analysis that it's safe
validatedURL := mirrorRequest.URL
// Extract blob hash from source URL
blobHash := extractSha256FromURL(validatedURL)
if blobHash == "" {
http.Error(w, "Cannot extract blob hash from source URL", http.StatusBadRequest)
return
}
// Check if blob already exists
if _, err := fs.Open(*config.BlossomPath + blobHash); err == nil {
// Blob already exists, return success
response := map[string]interface{}{
"sha256": blobHash,
"url": *config.BlossomURL + "/" + blobHash,
"size": 0, // We don't know the size without reading the file
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
return
}
// Download blob from validated source URL
resp, err := http.Get(validatedURL)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to fetch source blob: %v", err), http.StatusBadGateway)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
http.Error(w, fmt.Sprintf("Source server returned %d", resp.StatusCode), http.StatusBadGateway)
return
}
// Read and verify the blob content
blobData, err := io.ReadAll(resp.Body)
if err != nil {
http.Error(w, fmt.Sprintf("Failed to read blob data: %v", err), http.StatusInternalServerError)
return
}
// Verify the hash matches
hasher := sha256.New()
hasher.Write(blobData)
actualHash := hex.EncodeToString(hasher.Sum(nil))
if actualHash != blobHash {
http.Error(w, "Blob hash mismatch", http.StatusBadRequest)
return
}
// Store the blob using the existing StoreBlob functionality
ctx := r.Context()
for _, storeFunc := range bl.StoreBlob {
if err := storeFunc(ctx, blobHash, blobData); err != nil {
http.Error(w, fmt.Sprintf("Failed to store blob: %v", err), http.StatusInternalServerError)
return
}
}
// Return success response
response := map[string]interface{}{
"sha256": blobHash,
"url": *config.BlossomURL + "/" + blobHash,
"size": len(blobData),
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(response)
log.Printf("Successfully mirrored blob %s from %s", blobHash, validatedURL)
})
// Configure HTTP server with timeouts suitable for large file uploads
server := &http.Server{
Addr: ":" + config.RelayPort,
Handler: relay,
ReadTimeout: 15 * time.Minute, // Increased to 15 minutes for very large files
WriteTimeout: 15 * time.Minute, // Increased to 15 minutes
IdleTimeout: 5 * time.Minute, // Increased idle timeout
ReadHeaderTimeout: 30 * time.Second, // Prevent slow header attacks
MaxHeaderBytes: 1 << 20, // 1MB max header size
}
fmt.Println("running on :" + config.RelayPort + " with extended timeouts for large uploads")
server.ListenAndServe()
}
func fetchNostrData(npubDomain string) {
var body []byte
var err error
if npubDomain == "" {
// Fall back to local file
body, err = os.ReadFile("./public/.well-known/nostr.json")
if err != nil {
log.Printf("Error reading local nostr.json: %v", err)
return
}
log.Println("Using local public/.well-known/nostr.json")
} else {
// Fetch from remote domain
// First try /public/.well-known/nostr.json
urls := []string{
"https://" + npubDomain + "/public/.well-known/nostr.json",
"https://" + npubDomain + "/.well-known/nostr.json",
}
var lastErr error
for _, url := range urls {
response, err := http.Get(url)
if err != nil {
lastErr = err
continue
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
lastErr = fmt.Errorf("HTTP %d", response.StatusCode)
continue
}
body, err = io.ReadAll(response.Body)
if err != nil {
lastErr = err
continue
}
// Basic JSON validation
if len(body) > 0 && body[0] == '{' {
log.Printf("Successfully fetched nostr.json from %s", url)
lastErr = nil
break
}
lastErr = fmt.Errorf("invalid JSON response from %s", url)
}
if lastErr != nil {
log.Printf("Error fetching nostr.json from %s: %v", npubDomain, lastErr)
return
}
}
var newData NostrData
err = json.Unmarshal(body, &newData)
if err != nil {
log.Printf("Error unmarshalling JSON: %v", err)
return
}
data = newData
for pubkey, names := range data.Names {
fmt.Println(pubkey, names)
}
if npubDomain == "" {
log.Println("Updated NostrData from local .well-known file")
} else {
log.Println("Updated NostrData from remote .well-known file")
}
}
func LoadConfig() Config {
// Load .env file if it exists, but don't overwrite existing environment variables
// This allows docker-compose environment variables to take precedence
if envMap, err := godotenv.Read(".env"); err == nil {
for key, value := range envMap {
if os.Getenv(key) == "" {
os.Setenv(key, value)
}
}
}
config = Config{
RelayName: getEnv("RELAY_NAME"),
RelayPubkey: getEnv("RELAY_PUBKEY"),
RelayDescription: getEnv("RELAY_DESCRIPTION"),
DBEngine: getEnvNullable("DB_ENGINE"),
DBPath: getEnvNullable("DB_PATH"),
PostgresUser: getEnvNullable("POSTGRES_USER"),
PostgresPassword: getEnvNullable("POSTGRES_PASSWORD"),
PostgresDB: getEnvNullable("POSTGRES_DB"),
PostgresHost: getEnvNullable("POSTGRES_HOST"),
PostgresPort: getEnvNullable("POSTGRES_PORT"),
DatabaseURL: getEnvNullable("DATABASE_URL"),
TeamDomain: getEnvWithDefault("TEAM_DOMAIN", ""),
NPUBDomain: getEnvWithDefault("NPUB_DOMAIN", ""),
BlossomEnabled: getEnvBool("BLOSSOM_ENABLED"),
BlossomPath: getEnvWithDefaultPtr("BLOSSOM_PATH", "blossom/"),
BlossomURL: getEnvWithDefaultPtr("BLOSSOM_URL", "http://localhost:3334"),
WebSocketURL: getEnvWithDefaultPtr("WEBSOCKET_URL", "wss://localhost:3334"),
AllowedKinds: parseAllowedKinds(getEnvNullable("ALLOWED_KINDS")),
PublicAllowedKinds: parseAllowedKinds(getEnvNullable("PUBLIC_ALLOWED_KINDS")),
TrustedClientName: getEnvWithDefault("TRUSTED_CLIENT_NAME", ""),
TrustedClientKinds: parseTrustedClientKinds(getEnvNullable("TRUSTED_CLIENT_KINDS")),
TrustedClientAllKinds: isTrustedClientAllKinds(getEnvNullable("TRUSTED_CLIENT_KINDS")),
MaxUploadSizeMB: getEnvIntWithDefault("MAX_UPLOAD_SIZE_MB", 200),
RelayPort: getEnvWithDefault("RELAY_PORT", "3334"),
AllowedMirrorHosts: parseAllowedMirrorHosts(getEnvNullable("ALLOWED_MIRROR_HOSTS")),
// S3 Storage Configuration
StorageBackend: getEnvWithDefault("STORAGE_BACKEND", "filesystem"),
S3Endpoint: getEnvWithDefault("S3_ENDPOINT", ""),
S3Bucket: getEnvWithDefault("S3_BUCKET", ""),
S3Region: getEnvWithDefault("S3_REGION", "auto"),
S3PublicURL: getEnvWithDefault("S3_PUBLIC_URL", ""),
}
relay.Info.Name = config.RelayName
relay.Info.PubKey = config.RelayPubkey
relay.Info.Description = config.RelayDescription
if config.DBPath == nil {
defaultPath := "db/"
config.DBPath = &defaultPath
}
db = newDBBackend(*config.DBPath)
if err := db.Init(); err != nil {
panic(err)
}
fs = afero.NewOsFs()
if config.BlossomEnabled {
if config.StorageBackend == "s3" {
// Initialize S3 storage
s3Cfg := getS3ConfigFromEnv()
if s3Cfg == nil {
log.Fatalf("S3 storage backend selected but missing required environment variables (S3_ENDPOINT, S3_BUCKET, AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)")
}
s3Cfg.ServiceURL = *config.BlossomURL
var err error
s3Storage, err = NewS3Storage(*s3Cfg)
if err != nil {
log.Fatalf("Failed to initialize S3 storage: %v", err)
}
log.Printf("Blossom using S3 storage backend: %s/%s", s3Cfg.Endpoint, s3Cfg.Bucket)
} else {
// Filesystem storage
if config.BlossomPath == nil {
log.Fatalf("Blossom enabled but no path set")
}
fs.MkdirAll(*config.BlossomPath, 0755)
log.Printf("Blossom using filesystem storage backend: %s", *config.BlossomPath)
}
}
return config
}
// Rate limiting data structures
type rateLimiter struct {
mu sync.RWMutex
counters map[string][]time.Time
limit int
window time.Duration
}
func newRateLimiter(limit int, window time.Duration) *rateLimiter {
return &rateLimiter{
counters: make(map[string][]time.Time),
limit: limit,
window: window,
}
}
func (rl *rateLimiter) isAllowed(key string) bool {
rl.mu.Lock()
defer rl.mu.Unlock()
now := time.Now()
cutoff := now.Add(-rl.window)
// Clean old entries
times := rl.counters[key]
var validTimes []time.Time
for _, t := range times {
if t.After(cutoff) {
validTimes = append(validTimes, t)
}
}
// Check if under limit
if len(validTimes) >= rl.limit {
return false
}
// Add current request
validTimes = append(validTimes, now)
rl.counters[key] = validTimes
return true
}
// Global rate limiters
var (
pubkeyRateLimit *rateLimiter
ipRateLimit *rateLimiter
connRateLimit *rateLimiter
queryRateLimit *rateLimiter
)
// applySpamProtection applies rate limiting and spam protection policies
func applySpamProtection(relay *khatru.Relay, config Config) {
pubkeyRateLimit = newRateLimiterFromEnv("PUBKEY_RATE_LIMIT", time.Minute)
ipRateLimit = newRateLimiterFromEnv("IP_RATE_LIMIT", time.Minute)
connRateLimit = newRateLimiterFromEnv("CONN_RATE_LIMIT", 2*time.Minute)
queryRateLimit = newRateLimiterFromEnv("QUERY_RATE_LIMIT", time.Minute)
// Rate limit events by pubkey (applies to all users)
relay.RejectEvent = append(relay.RejectEvent, func(ctx context.Context, event *nostr.Event) (reject bool, msg string) {
// Check if user is team member (more lenient limits)
isTeamMember := false
for _, pubkey := range data.Names {
if event.PubKey == pubkey {
isTeamMember = true
break
}
}
// Apply stricter rate limits to non-team members
if !isTeamMember {
if pubkeyRateLimit != nil && !pubkeyRateLimit.isAllowed(event.PubKey) {
return true, "rate-limited: too many events from this pubkey, slow down please"
}
}
return false, ""
})
// Rate limit events by IP
relay.RejectEvent = append(relay.RejectEvent, func(ctx context.Context, event *nostr.Event) (reject bool, msg string) {
ip := khatru.GetIP(ctx)
if ip != "" && ipRateLimit != nil && !ipRateLimit.isAllowed(ip) {
return true, "rate-limited: too many events from this IP, slow down please"
}
return false, ""
})
// Rate limit connections
relay.RejectConnection = append(relay.RejectConnection, func(r *http.Request) bool {
if connRateLimit == nil {
return false
}
ip := khatru.GetIPFromRequest(r)
return !connRateLimit.isAllowed(ip)
})
// Rate limit queries/filters
relay.RejectFilter = append(relay.RejectFilter, func(ctx context.Context, filter nostr.Filter) (reject bool, msg string) {
ip := khatru.GetIP(ctx)
if ip != "" && queryRateLimit != nil && !queryRateLimit.isAllowed(ip) {
return true, "rate-limited: too many queries from this IP"
}
return false, ""
})
// Reject events with base64 media (common spam vector)
relay.RejectEvent = append(relay.RejectEvent, func(ctx context.Context, event *nostr.Event) (reject bool, msg string) {
if strings.Contains(event.Content, "data:image/") || strings.Contains(event.Content, "data:video/") {
return true, "rejected: base64 media not allowed"
}
return false, ""
})
log.Println("Applied spam protection policies with configurable rate limiting")
logRateLimiterConfig("PUBKEY_RATE_LIMIT", pubkeyRateLimit, "events/min per pubkey")
logRateLimiterConfig("IP_RATE_LIMIT", ipRateLimit, "events/min per IP")
logRateLimiterConfig("CONN_RATE_LIMIT", connRateLimit, "connections/2min per IP")
logRateLimiterConfig("QUERY_RATE_LIMIT", queryRateLimit, "queries/min per IP")
}
func getEnv(key string) string {
value, exists := os.LookupEnv(key)
if !exists {
log.Fatalf("Environment variable %s not set", key)
}
return value
}
func getEnvBool(key string) bool {
value, exists := os.LookupEnv(key)
if !exists {
return false
}
return value == "true"
}
func getEnvNullable(key string) *string {
value, exists := os.LookupEnv(key)
if !exists {
return nil
}
return &value
}
func getEnvIntWithDefault(key string, defaultValue int) int {
value, exists := os.LookupEnv(key)
if !exists {
return defaultValue
}
intValue, err := strconv.Atoi(value)
if err != nil {
log.Printf("Warning: Invalid integer value '%s' for %s, using default %d", value, key, defaultValue)
return defaultValue
}
return intValue
}
func getEnvOptionalInt(key string) *int {
value, exists := os.LookupEnv(key)
if !exists || strings.TrimSpace(value) == "" {
return nil
}
intValue, err := strconv.Atoi(value)
if err != nil {
log.Printf("Warning: Invalid integer value '%s' for %s, disabling this rate limiter", value, key)
return nil
}
if intValue <= 0 {
log.Printf("Warning: Non-positive value %d for %s, disabling this rate limiter", intValue, key)
return nil
}
return &intValue
}
func newRateLimiterFromEnv(key string, window time.Duration) *rateLimiter {
limit := getEnvOptionalInt(key)
if limit == nil {
return nil
}
return newRateLimiter(*limit, window)
}
func logRateLimiterConfig(envKey string, rl *rateLimiter, description string) {
if rl == nil {
log.Printf("%s not set: %s rate limit disabled", envKey, description)
return
}
log.Printf("%s=%d: %s enabled", envKey, rl.limit, description)
}
func getEnvWithDefaultPtr(key string, defaultValue string) *string {
value, exists := os.LookupEnv(key)
if !exists || strings.TrimSpace(value) == "" {
return &defaultValue
}
return &value
}
func getEnvWithDefault(key string, defaultValue string) string {
value, exists := os.LookupEnv(key)
if !exists || strings.TrimSpace(value) == "" {
return defaultValue
}
return value
}
func parseAllowedKinds(allowedKindsStr *string) []int {
if allowedKindsStr == nil || strings.TrimSpace(*allowedKindsStr) == "" {
return []int{} // Empty slice means allow all kinds
}
kindsStr := strings.TrimSpace(*allowedKindsStr)
kindStrings := strings.Split(kindsStr, ",")
var kinds []int
for _, kindStr := range kindStrings {
kindStr = strings.TrimSpace(kindStr)
if kindStr == "" {
continue
}
kind, err := strconv.Atoi(kindStr)
if err != nil {
log.Printf("Warning: Invalid kind '%s' in ALLOWED_KINDS, skipping", kindStr)
continue
}
kinds = append(kinds, kind)