-
Notifications
You must be signed in to change notification settings - Fork 24
/
main.go
190 lines (168 loc) · 5.31 KB
/
main.go
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
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"html/template"
"net/http"
"net/http/pprof"
"os"
"os/signal"
"strings"
"github.com/fiatjaf/khatru"
"github.com/kelseyhightower/envconfig"
"github.com/nbd-wtf/go-nostr"
"github.com/rs/cors"
"github.com/rs/zerolog"
)
type Settings struct {
Port string `envconfig:"PORT" default:"2999"`
Domain string `envconfig:"DOMAIN" default:"njump.me"`
InternalDBPath string `envconfig:"DISK_CACHE_PATH" default:"/tmp/njump-internal"`
EventStorePath string `envconfig:"EVENT_STORE_PATH" default:"/tmp/njump-db"`
HintsMemoryDumpPath string `envconfig:"HINTS_SAVE_PATH" default:"/tmp/njump-hints.json"`
TailwindDebug bool `envconfig:"TAILWIND_DEBUG"`
RelayConfigPath string `envconfig:"RELAY_CONFIG_PATH"`
TrustedPubKeys []string `envconfig:"TRUSTED_PUBKEYS"`
}
//go:embed static/*
var static embed.FS
var (
s Settings
log = zerolog.New(os.Stderr).Output(zerolog.ConsoleWriter{Out: os.Stdout}).
With().Timestamp().Logger()
internal *InternalDB
tailwindDebugStuff template.HTML
)
func main() {
err := envconfig.Process("", &s)
if err != nil {
log.Fatal().Err(err).Msg("couldn't process envconfig")
return
} else {
if canonicalHost := os.Getenv("CANONICAL_HOST"); canonicalHost != "" {
s.Domain = canonicalHost
}
}
if len(s.TrustedPubKeys) == 0 {
s.TrustedPubKeys = defaultTrustedPubKeys
}
// eventstore and nostr system
defer initSystem()()
if s.RelayConfigPath != "" {
configr, err := os.ReadFile(s.RelayConfigPath)
if err != nil {
log.Fatal().Err(err).Msgf("failed to load %q", s.RelayConfigPath)
return
}
err = json.Unmarshal(configr, &relayConfig)
if err != nil {
log.Fatal().Err(err).Msgf("failed to load %q", s.RelayConfigPath)
return
}
if len(relayConfig.Everything) > 0 {
sys.FallbackRelays.URLs = relayConfig.Everything
}
if len(relayConfig.Profiles) > 0 {
sys.MetadataRelays.URLs = relayConfig.Profiles
}
}
// if we're in tailwind debug mode, initialize the runtime tailwind stuff
if s.TailwindDebug {
configb, err := os.ReadFile("tailwind.config.js")
if err != nil {
log.Fatal().Err(err).Msg("failed to load tailwind.config.js")
return
}
config := strings.Replace(
strings.Replace(
string(configb),
"plugins: [require('@tailwindcss/typography')]", "", 1,
),
"module.exports", "tailwind.config", 1,
)
styleb, err := os.ReadFile("base.css")
if err != nil {
log.Fatal().Err(err).Msg("failed to load base.css")
return
}
style := string(styleb)
tailwindDebugStuff = template.HTML(fmt.Sprintf("<script src=\"https://cdn.tailwindcss.com?plugins=typography\"></script><script>\n%s</script><style type=\"text/tailwindcss\">%s</style>", config, style))
}
// image rendering stuff
initializeImageDrawingStuff()
// internal db
internal, err = NewInternalDB(s.InternalDBPath)
if err != nil {
log.Fatal().Err(err).Msg("failed to start internal db")
return
}
// initialize routines
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go updateArchives(ctx)
go deleteOldCachedEvents(ctx)
go outboxHintsFileLoaderSaver(ctx)
// expose our internal cache as a relay (mostly for debugging purposes)
relay := khatru.NewRelay()
relay.QueryEvents = append(relay.QueryEvents, sys.Store.QueryEvents)
relay.DeleteEvent = append(relay.DeleteEvent, sys.Store.DeleteEvent)
relay.RejectEvent = append(relay.RejectEvent,
func(context.Context, *nostr.Event) (bool, string) {
return true, "this relay is not writable"
},
)
// routes
mux := relay.Router()
mux.Handle("/njump/static/", http.StripPrefix("/njump/", http.FileServer(http.FS(static))))
mux.HandleFunc("/relays-archive.xml", renderArchive)
mux.HandleFunc("/npubs-archive.xml", renderArchive)
mux.HandleFunc("/npubs-sitemaps.xml", renderSitemapIndex)
mux.HandleFunc("/services/oembed", renderOEmbed)
mux.HandleFunc("/njump/image/", renderImage)
mux.HandleFunc("/njump/proxy/", proxy)
mux.HandleFunc("/robots.txt", renderRobots)
mux.HandleFunc("/r/", renderRelayPage)
mux.HandleFunc("/random", redirectToRandom)
mux.HandleFunc("/e/", redirectFromESlash)
mux.HandleFunc("/p/", redirectFromPSlash)
mux.HandleFunc("/favicon.ico", redirectToFavicon)
mux.HandleFunc("/debug/pprof/", pprof.Index)
mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/debug/pprof/profile", pprof.Profile)
mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/debug/pprof/trace", pprof.Trace)
mux.HandleFunc("/embed/{code}", renderEmbedjs)
mux.HandleFunc("/about", renderAbout)
mux.HandleFunc("/{code}", renderEvent)
mux.HandleFunc("/{$}", renderHomepage)
corsH := cors.Default()
corsM := func(next http.HandlerFunc) http.HandlerFunc {
return corsH.Handler(next).ServeHTTP
}
var mainHandler http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
ipBlock(
agentBlock(
loggingMiddleware(
queueMiddleware(
corsM(
relay.ServeHTTP,
),
),
),
),
)(w, r)
}
log.Print("listening at http://0.0.0.0:" + s.Port)
server := &http.Server{Addr: "0.0.0.0:" + s.Port, Handler: mainHandler}
go func() {
if err := server.ListenAndServe(); err != nil {
log.Error().Err(err).Msg("")
}
}()
sc := make(chan os.Signal, 1)
signal.Notify(sc, os.Interrupt)
<-sc
server.Close()
}