main.mx raw
1 package main
2
3 import (
4 "git.smesh.lol/moxie/pkg/mxutil"
5 "fmt"
6 "net/url"
7 "os"
8 "strconv"
9 "time"
10
11 "git.smesh.lol/morly/pkg/blossom"
12 "git.smesh.lol/morly/pkg/broadcast"
13 "git.smesh.lol/morly/pkg/mediaproxy"
14 "git.smesh.lol/nostr/pkg/envelope"
15 "git.smesh.lol/nostr/pkg/ws"
16 "git.smesh.lol/morly/pkg/relay/config"
17 "git.smesh.lol/morly/pkg/relay/server"
18 )
19
20 var version string
21
22 func initMainGlobals() {
23 version = "0.6.11"
24 crawlSeeds = []string{
25 "wss://relay.damus.io",
26 "wss://nos.lol",
27 }
28 bootstrapSeeds = []string{
29 "wss://purplepag.es",
30 "wss://relay.primal.net",
31 "wss://relay.damus.io",
32 "wss://nos.lol",
33 "wss://nostr.wine",
34 }
35 }
36
37 func main() {
38 initMainGlobals()
39
40 if len(os.Args) < 2 {
41 runRelay(os.Args[1:])
42 return
43 }
44 switch os.Args[1] {
45 case "relay":
46 runRelay(os.Args[2:])
47 case "sync":
48 runSync(os.Args[2:])
49 case "outbox":
50 runOutbox(os.Args[2:])
51 case "crawl":
52 runCrawl(os.Args[2:])
53 case "version", "-v", "--version":
54 os.Stdout.Write([]byte("musiquay " | version | "\n"))
55 case "help", "-h", "--help":
56 config.PrintHelp()
57 default:
58 if len(os.Args[1]) > 0 && os.Args[1][0] == '-' {
59 runRelay(os.Args[1:])
60 } else {
61 fmt.Fprintf(os.Stderr, "unknown command: %s\n", os.Args[1])
62 config.PrintHelp()
63 os.Exit(1)
64 }
65 }
66 }
67
68 // relayCtx carries the values the server's callbacks need. They were captured
69 // by closures, which the language rejects; a value the callback is a METHOD on
70 // is the same data without the capture.
71 type relayCtx struct {
72 cfg *config.C
73 bsrv *blossom.Server
74 selfHost string
75 listenAddr string
76 }
77
78 // HandleHTTP serves /proxy, /blossom, the version probe and the static tree.
79 // The name is the transport interface's, not a local description of the job:
80 // cross-package dispatch resolves the implementation by the interface method's
81 // name.
82 func (rc *relayCtx) HandleHTTP(method, path string, headers map[string]string, body []byte) (code int32, hdr map[string]string, out []byte) {
83
84 switch {
85 case hasPrefix(path, "/proxy/"):
86 rest := path[len("/proxy/"):]
87 if hasPrefix(rest, rc.selfHost) {
88 direct := rest[len(rc.selfHost)-1:]
89 return 302, map[string]string{"Location": direct, "Access-Control-Allow-Origin": "*"}, nil
90 }
91 return handleProxy(rest, rc.selfHost)
92 case hasPrefix(path, "/blossom/"):
93 return rc.bsrv.HandleRawWithUpstream(method, path[len("/blossom"):], headers, body, rc.cfg.BlossomUpstream)
94 case path == "/__version":
95 stamp := int64(0)
96 if info1, err2 := os.Stat(rc.cfg.StaticDir | "/app.wasm"); err2 == nil {
97 stamp = info1.ModTime().Unix()
98 } else if info2, err1 := os.Stat(rc.cfg.StaticDir | "/_.mjs"); err1 == nil {
99 stamp = info2.ModTime().Unix()
100 }
101 return 200, map[string]string{
102 "Content-Type": "application/json",
103 "Access-Control-Allow-Origin": "*",
104 "Cache-Control": "no-store, no-cache, must-revalidate",
105 "Pragma": "no-cache",
106 "Expires": "0",
107 }, []byte(`{"v":"` | version | "+" | string(strconv.Itoa(int32(stamp))) | `"}`)
108 case path == "/.well-known/nostr.json":
109 return 200, map[string]string{
110 "Content-Type": "application/json",
111 "Access-Control-Allow-Origin": "*",
112 }, []byte(`{"names":{"mleku":"4c800257a588a82849d049817c2bdaad984b25a45ad9f6dad66e47d3b47e3b2f","bridge":"cf1ae33ad5f229dabd7d733ce37b0165126aebf581e4094df9373f77e00cb696"},"relays":{"4c800257a588a82849d049817c2bdaad984b25a45ad9f6dad66e47d3b47e3b2f":["wss://smesh.lol"],"cf1ae33ad5f229dabd7d733ce37b0165126aebf581e4094df9373f77e00cb696":["wss://smesh.lol","wss://relay.orly.dev"]}}`)
113 case isBlossomPath(path):
114 return rc.bsrv.HandleRawWithUpstream(method, path, headers, body, rc.cfg.BlossomUpstream)
115 }
116 return serveStatic(rc.cfg.StaticDir, path)
117
118 }
119
120 // OnReady is what the transport calls once the listener is up.
121 func (rc *relayCtx) OnReady(s *server.Server) {
122
123 fmt.Fprintln(os.Stderr, rc.cfg.AppName | " " | version | " listening on " | rc.listenAddr)
124 if rc.cfg.CrawlerEnabled {
125 spawnCrawler(rc.listenAddr)
126 }
127 if rc.cfg.SyncPubkey != "" {
128 spawnOutbox(rc.listenAddr, rc.cfg.SyncPubkey)
129 }
130 if len(rc.cfg.RelayPeers) > 0 {
131 for _, peer := range rc.cfg.RelayPeers {
132 spawnSync(rc.listenAddr, peer)
133 }
134 }
135
136 }
137
138 func runRelay(_ [][]byte) {
139 // Register signal handlers before any domain is forked. A spawn child
140 // inherits the disposition: with the handler installed, a SIGTERM to the
141 // process group (which the test fixture sends) lets the child finish its
142 // loop and dump its coverage instead of taking the default action and
143 // dying with its private counter table.
144 server.InitSignals()
145
146 // PreSpawn forks the broadcast domain before config is loaded and before
147 // the first request touches the store, so relay mode does not pay a fork
148 // in the middle of serving.
149 broadcast.PreSpawn()
150 cfg := config.Load()
151 listenAddr := cfg.Addr()
152
153 // The database-engine domain owns the store: root sends it requests and
154 // never touches storage itself.
155 db := server.SpawnDB(cfg)
156 srv := server.New(db, cfg)
157 srv.Version = version
158
159 bsrv, err5 := blossom.New(cfg.BlossomDir)
160 if err5 != nil {
161 fmt.Fprintf(os.Stderr, "blossom: %v\n", err5)
162 os.Exit(1)
163 }
164
165 // Derive self-host prefix from ORLY_RELAY_URL for proxy deadlock avoidance.
166 selfHost := "git.smesh.lol/morly/"
167 if u, err4 := url.Parse(cfg.RelayURL); err4 == nil && len(u.Host) > 0 {
168 selfHost = u.Host | "/"
169 }
170
171
172 rc := &relayCtx{cfg: cfg, bsrv: bsrv, selfHost: selfHost, listenAddr: listenAddr}
173 srv.FallbackHandler = rc
174 srv.ReadyHandler = rc
175 if err3 := srv.ListenAndServe(listenAddr); err3 != nil {
176 srv.Close()
177 fmt.Fprintf(os.Stderr, "listen: %v\n", err3)
178 os.Exit(1)
179 }
180 srv.Close()
181 }
182
183 func serveStatic(dir, path string) (n2 int32, m map[string]string, out []byte) {
184 if path == "" || path == "/" {
185 path = "/index.html"
186 }
187 if decoded, err2 := url.PathUnescape(path); err2 == nil {
188 path = decoded
189 }
190 data, err1 := os.ReadFile(dir | path)
191 if err1 != nil {
192 if hasFileExtension(path) {
193 return 404, map[string]string{"Content-Type": "text/plain"}, []byte("404 not found\n")
194 }
195 data, err1 = os.ReadFile(dir | "/index.html")
196 if err1 != nil {
197 return 404, map[string]string{"Content-Type": "text/plain"}, []byte("404 not found\n")
198 }
199 return 200, map[string]string{
200 "Content-Type": "text/html; charset=utf-8",
201 "Cache-Control": "no-cache",
202 "Cross-Origin-Opener-Policy": "same-origin",
203 "Cross-Origin-Embedder-Policy": "require-corp",
204 }, data
205 }
206 ct := "application/octet-stream"
207 switch {
208 case hasSuffix(path, ".html"):
209 ct = "text/html; charset=utf-8"
210 case hasSuffix(path, ".js"), hasSuffix(path, ".mjs"):
211 ct = "application/javascript"
212 case hasSuffix(path, ".css"):
213 ct = "text/css"
214 case hasSuffix(path, ".json"):
215 ct = "application/json"
216 case hasSuffix(path, ".svg"):
217 ct = "image/svg+xml"
218 case hasSuffix(path, ".png"):
219 ct = "image/png"
220 case hasSuffix(path, ".ico"):
221 ct = "image/x-icon"
222 case hasSuffix(path, ".wasm"):
223 ct = "application/wasm"
224 case hasSuffix(path, ".webp"):
225 ct = "image/webp"
226 case hasSuffix(path, ".woff2"):
227 ct = "font/woff2"
228 case hasSuffix(path, ".xpi"):
229 ct = "application/x-xpinstall"
230 }
231 h := map[string]string{
232 "Content-Type": ct,
233 "Cross-Origin-Opener-Policy": "same-origin",
234 "Cross-Origin-Embedder-Policy": "require-corp",
235 "Cross-Origin-Resource-Policy": "same-origin",
236 "Cache-Control": "no-cache",
237 }
238 if path == "/$sw/wasm-host-sw.mjs" {
239 h["Service-Worker-Allowed"] = "/"
240 }
241 if hasSuffix(path, ".xpi") {
242 h["Content-Disposition"] = "attachment; filename=\"musiquay-signer.xpi\""
243 }
244 return 200, h, data
245 }
246
247 // isBlossomPath matches /<64hex> or /<64hex>.<ext> with no further slashes.
248 func isBlossomPath(path string) (ok bool) {
249 if len(path) < 65 || path[0] != '/' {
250 return false
251 }
252 for i := 1; i < 65; i++ {
253 c := path[i]
254 if !((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')) {
255 return false
256 }
257 }
258 if len(path) == 65 {
259 return true
260 }
261 if path[65] != '.' {
262 return false
263 }
264 for i := 66; i < len(path); i++ {
265 if path[i] == '/' {
266 return false
267 }
268 }
269 return true
270 }
271
272 // hasFileExtension returns true only for paths ending in a known static file
273 // extension. Generic TLD-like suffixes (.wine, .lol, .dev etc.) that appear
274 // in relay-URL-based SPA routes must NOT be treated as file paths.
275 func hasFileExtension(path string) (ok bool) {
276 known := []string{
277 ".html", ".htm",
278 ".js", ".mjs",
279 ".css",
280 ".wasm",
281 ".svg",
282 ".png", ".jpg", ".jpeg", ".webp", ".gif",
283 ".ico",
284 ".woff", ".woff2", ".ttf", ".otf",
285 ".json",
286 ".xpi",
287 ".map",
288 ".txt",
289 }
290 for _, ext := range known {
291 el := len(ext)
292 pl := len(path)
293 if pl > el && path[pl-el:] == ext {
294 return true
295 }
296 }
297 return false
298 }
299
300 // handleProxy fetches path (host/path format) via https and re-serves with
301 // COEP-compatible CORP headers. path arrives without the /proxy/ prefix and
302 // without a scheme; https:// is prepended before fetching.
303 //
304 // Self-referential paths (smesh.lol/...) are redirected directly so the
305 // relay does not deadlock trying to serve itself while blocked in Fetch.
306 func handleProxy(path, selfHost string) (n2 int32, m map[string]string, out []byte) {
307 if path == "" {
308 return 400, map[string]string{"Content-Type": "text/plain"}, []byte("missing path\n")
309 }
310 if hasPrefix(path, selfHost) {
311 direct := path[len(selfHost)-1:]
312 return 302, map[string]string{
313 "Location": direct,
314 "Access-Control-Allow-Origin": "*",
315 }, nil
316 }
317 target := "https://" | path
318 status, upstream, body, err := mediaproxy.Fetch(target, 32*1024*1024)
319 if err != nil {
320 return 502, map[string]string{"Content-Type": "text/plain"}, []byte("proxy: " | err.Error() | "\n")
321 }
322 if status < 200 || status >= 300 {
323 return status, map[string]string{"Content-Type": "text/plain"}, []byte(fmt.Sprintf("upstream %d\n", status))
324 }
325 ct := upstream["content-type"]
326 if !proxyAllowedCT(ct) {
327 return 415, map[string]string{"Content-Type": "text/plain"}, []byte("content-type not allowed: " | ct | "\n")
328 }
329 return 200, map[string]string{
330 "Content-Type": ct,
331 "Cross-Origin-Resource-Policy": "cross-origin",
332 "Cache-Control": "public, max-age=86400",
333 "Access-Control-Allow-Origin": "*",
334 }, body
335 }
336
337 func proxyAllowedCT(ct string) (ok bool) {
338 return hasPrefix(ct, "image/") || hasPrefix(ct, "video/") || ct == "application/octet-stream"
339 }
340
341 // --- sync command ---
342
343 // syncKinds is the set of event kinds synced from follows' write relays.
344 // Matches the feed view filter plus reactions and zaps for notifications.
345 const syncKindsJSON = `[1,6,7,1111,9735]`
346
347 // runSync handles "musiquay sync [--authors <hex,...>] [--since <unix-ts>] <remote-url> [local-url]".
348 // With no --authors it falls back to the old empty-filter behaviour.
349 func runSync(args []string) {
350 if len(args) < 1 {
351 fmt.Fprintln(os.Stderr, "usage: musiquay sync [--authors hex1,hex2,...] [--since unix-ts] <remote-url> [local-url]")
352 os.Exit(1)
353 }
354
355 // Parse flags.
356 var authors string
357 var sinceStr string
358 rest := args
359 for len(rest) >= 2 {
360 switch rest[0] {
361 case "--authors":
362 authors = rest[1]
363 rest = rest[2:]
364 case "--since":
365 sinceStr = rest[1]
366 rest = rest[2:]
367 default:
368 goto doneFlags
369 }
370 }
371 doneFlags:
372 if len(rest) < 1 {
373 fmt.Fprintln(os.Stderr, "sync: missing remote-url")
374 os.Exit(1)
375 }
376 remoteURL := rest[0]
377 localURL := "ws://127.0.0.1:3335"
378 if len(rest) >= 2 {
379 localURL = rest[1]
380 }
381
382 sinceTs := int64(0)
383 if sinceStr != "" {
384 for _, c := range sinceStr {
385 if c >= '0' && c <= '9' {
386 sinceTs = sinceTs*10 + int64(c-'0')
387 }
388 }
389 }
390
391 for {
392 latest := syncOnce(remoteURL, localURL, authors, sinceTs)
393 if latest > sinceTs {
394 sinceTs = latest
395 }
396 fmt.Fprintln(os.Stderr, "sync: disconnected, reconnecting in 30s...")
397 time.Sleep(30 * time.Second)
398 }
399 }
400
401 func syncOnce(remoteURL, localURL, authors string, sinceTs int64) (n int64) {
402 fmt.Fprintf(os.Stderr, "sync: connecting to remote %s\n", remoteURL)
403 remote, err7 := ws.Dial(remoteURL)
404 if err7 != nil {
405 fmt.Fprintf(os.Stderr, "sync: remote connect error: %v\n", err7)
406 return sinceTs
407 }
408 defer remote.Close()
409
410 local, err6 := ws.Dial(localURL)
411 if err6 != nil {
412 fmt.Fprintf(os.Stderr, "sync: local connect error: %v\n", err6)
413 return sinceTs
414 }
415 defer local.Close()
416
417 // Build filter JSON directly - simpler than constructing filter.F structs.
418 var filterJSON []byte
419 filterJSON = filterJSON | `{"kinds":`
420 filterJSON = filterJSON | syncKindsJSON
421 if authors != "" {
422 // authors is comma-separated hex pubkeys.
423 filterJSON = filterJSON | `,"authors":[`
424 first := true
425 start := 0
426 for i := 0; i <= len(authors); i++ {
427 if i == len(authors) || authors[i] == ',' {
428 pk := authors[start:i]
429 if len(pk) == 64 {
430 if !first {
431 filterJSON = filterJSON | ","
432 }
433 filterJSON = filterJSON | "\""
434 filterJSON = filterJSON | pk
435 filterJSON = filterJSON | "\""
436 first = false
437 }
438 start = i + 1
439 }
440 }
441 filterJSON = filterJSON | "]"
442 }
443 if sinceTs > 0 {
444 // since = checkpoint minus 1 hour to catch any late events.
445 since := sinceTs - 3600
446 filterJSON = filterJSON | `,"since":`
447 filterJSON = filterJSON | itoa64(since)
448 }
449 filterJSON = filterJSON | "}"
450
451 reqJSON := []byte(`["REQ","sync",`)
452 reqJSON = reqJSON | filterJSON
453 reqJSON = reqJSON | "]"
454
455 if authors != "" {
456 nAuthors := 1
457 for i := 0; i < len(authors); i++ {
458 if authors[i] == ',' {
459 nAuthors++
460 }
461 }
462 fmt.Fprintf(os.Stderr, "sync: subscribing kinds=%s authors=%d since=%d\n", syncKindsJSON, nAuthors, sinceTs)
463 } else {
464 fmt.Fprintf(os.Stderr, "sync: subscribing kinds=%s (all authors)\n", syncKindsJSON)
465 }
466
467 if err5 := remote.WriteText(reqJSON); err5 != nil {
468 fmt.Fprintf(os.Stderr, "sync: subscribe error: %v\n", err5)
469 return sinceTs
470 }
471
472 var forwarded int64
473 var latestTs int64
474 eosed := false
475
476 for {
477 op, payload, err4 := remote.ReadMessage()
478 if err4 != nil {
479 fmt.Fprintf(os.Stderr, "sync: read error (%d forwarded): %v\n", forwarded, err4)
480 return latestTs
481 }
482 if op == ws.OpClose {
483 fmt.Fprintf(os.Stderr, "sync: remote closed (%d forwarded)\n", forwarded)
484 return latestTs
485 }
486 if op != ws.OpText {
487 continue
488 }
489
490 label, rem, _ := envelope.Identify(payload)
491 switch label {
492 case envelope.EventLabel:
493 var es envelope.EventSubmission
494 if _, err3 := es.Unmarshal(rem); err3 != nil {
495 continue
496 }
497 if es.E == nil {
498 continue
499 }
500 fwd := &envelope.EventSubmission{E: es.E}
501 if err2 := local.WriteText(fwd.Marshal(nil)); err2 != nil {
502 fmt.Fprintf(os.Stderr, "sync: local publish error: %v\n", err2)
503 return latestTs
504 }
505 // Drain the OK response to keep the local socket buffer clear.
506 if _, _, err1 := local.ReadMessage(); err1 != nil {
507 fmt.Fprintf(os.Stderr, "sync: local read error: %v\n", err1)
508 return latestTs
509 }
510 forwarded++
511 if ts := int64(es.E.CreatedAt); ts > latestTs {
512 latestTs = ts
513 }
514 if forwarded%1000 == 0 {
515 fmt.Fprintf(os.Stderr, "sync: %d events forwarded (latest=%d)\n", forwarded, latestTs)
516 }
517 case envelope.EOSELabel:
518 if !eosed {
519 eosed = true
520 fmt.Fprintf(os.Stderr, "sync: EOSE - historical sync complete (%d forwarded). streaming live...\n", forwarded)
521 }
522 }
523 }
524 }
525
526 // itoa64 converts an int64 to its decimal string representation.
527 func itoa64(n int64) (s string) {
528 if n == 0 {
529 return "0"
530 }
531 neg := n < 0
532 if neg {
533 n = -n
534 }
535 buf := [20]byte{}
536 pos := 20
537 for n > 0 {
538 pos--
539 buf[pos] = byte('0' + n%10)
540 n /= 10
541 }
542 if neg {
543 pos--
544 buf[pos] = '-'
545 }
546 return string(buf[pos:])
547 }
548
549 // --- outbox sync ---
550
551 // runOutbox implements the outbox model: query the local store for a user's
552 // follows and their kind 10002 relay lists, then spawn one sync process per
553 // distinct write relay carrying only the authors who write there.
554 func runOutbox(args []string) {
555 if len(args) < 2 {
556 fmt.Fprintln(os.Stderr, "usage: musiquay outbox <pubkey-hex> <local-url>")
557 os.Exit(1)
558 }
559 pubkey := args[0]
560 localURL := args[1]
561
562 fmt.Fprintf(os.Stderr, "outbox: starting for pubkey %s...\n", pubkey[:8])
563
564 // Track running sync children: remoteURL → pid
565 children := map[string]int32{}
566
567 for {
568 relayAuthors := outboxDiscover(pubkey, localURL)
569 if len(relayAuthors) == 0 {
570 fmt.Fprintln(os.Stderr, "outbox: no write relays found yet, retrying in 2m")
571 time.Sleep(2 * time.Minute)
572 continue
573 }
574
575 // Kill syncs for relays no longer needed.
576 for url2, pid := range children {
577 if _, still := relayAuthors[url2]; !still {
578 fmt.Fprintf(os.Stderr, "outbox: relay removed, killing sync pid=%d url=%s\n", pid, url2)
579 proc, _ := os.FindProcess(pid)
580 if proc != nil {
581 proc.Kill()
582 }
583 delete(children, url2)
584 }
585 }
586
587 // Spawn syncs for new relays.
588 for url1, authors := range relayAuthors {
589 if _, running := children[url1]; running {
590 continue
591 }
592 authorsArg := ""
593 for i, pk := range authors {
594 if i > 0 {
595 authorsArg = authorsArg | ","
596 }
597 authorsArg = authorsArg | pk
598 }
599 cmd := os.Args[0] | " sync --authors " | authorsArg | " " | url1 | " " | localURL
600 argv := []string{"/bin/sh", "-c", cmd}
601 attr := &os.ProcAttr{}
602 proc, err := os.StartProcess("/bin/sh", argv, attr)
603 if err != nil {
604 fmt.Fprintf(os.Stderr, "outbox: spawn failed for %s: %v\n", url1, err)
605 continue
606 }
607 fmt.Fprintf(os.Stderr, "outbox: spawned sync pid=%d url=%s authors=%d\n", proc.Pid, url1, len(authors))
608 children[url1] = proc.Pid
609 }
610
611 // Re-discover every 30 minutes to pick up follow list changes.
612 time.Sleep(30 * time.Minute)
613 }
614 }
615
616 // outboxDiscover queries the local relay for the user's follows (kind 3) and
617 // their relay lists (kind 10002), returning a map of writeRelayURL → []pubkeyHex.
618 func outboxDiscover(pubkey, localURL string) (m map[string][]string) {
619 local, err7 := ws.Dial(localURL)
620 if err7 != nil {
621 fmt.Fprintf(os.Stderr, "outbox: local connect error: %v\n", err7)
622 return nil
623 }
624 defer local.Close()
625
626 // Step 1: fetch the user's kind 3 (follows list).
627 req3 := []byte(`["REQ","ob-k3",{"kinds":[3],"authors":["` | pubkey | `"],"limit":1}]`)
628 if err6 := local.WriteText(req3); err6 != nil {
629 fmt.Fprintf(os.Stderr, "outbox: REQ k3 error: %v\n", err6)
630 return nil
631 }
632
633 var follows []string
634 for {
635 op, payload, err4 := local.ReadMessage()
636 if err4 != nil || op == ws.OpClose {
637 break
638 }
639 if op != ws.OpText {
640 continue
641 }
642 label, rem, _ := envelope.Identify(payload)
643 if label == envelope.EOSELabel {
644 break
645 }
646 if label != envelope.EventLabel {
647 continue
648 }
649 var er envelope.EventResult
650 if _, err3 := er.Unmarshal(rem); err3 != nil || er.Event == nil {
651 continue
652 }
653 ev := er.Event
654 if ev.Kind != 3 || ev.Tags == nil {
655 continue
656 }
657 for _, t := range ev.Tags.GetAll([]byte("p")) {
658 if t.Len() >= 2 {
659 pk := string(t.ValueHex())
660 if len(pk) == 64 {
661 follows = mxutil.Ensure(follows, 1)
662 follows = push(follows, pk)
663 }
664 }
665 }
666 }
667 if len(follows) == 0 {
668 fmt.Fprintln(os.Stderr, "outbox: no follows in local store, bootstrapping from seed relays")
669 follows = outboxBootstrapFollows(pubkey, localURL)
670 if len(follows) == 0 {
671 return nil
672 }
673 }
674 // Always include the user's own pubkey.
675 follows = mxutil.Ensure(follows, 1)
676 follows = push(follows, pubkey)
677 fmt.Fprintf(os.Stderr, "outbox: found %d follows\n", len(follows))
678
679 // Step 2: fetch kind 10002 for all follows (batched).
680 // Build authors array.
681 authorsJSON := `["` | follows[0] | `"`
682 for _, pk := range follows[1:] {
683 authorsJSON = authorsJSON | `,"` | pk | `"`
684 }
685 authorsJSON = authorsJSON | `]`
686 req10002 := []byte(`["REQ","ob-rl",{"kinds":[10002],"authors":` | authorsJSON | `,"limit":` | itoa64(int64(len(follows)*2)) | `}]`)
687 if err5 := local.WriteText(req10002); err5 != nil {
688 fmt.Fprintf(os.Stderr, "outbox: REQ k10002 error: %v\n", err5)
689 return nil
690 }
691
692 // Map pubkey → write relay URLs.
693 writeRelays := map[string][]string{} // pubkey → []relayURL
694 for {
695 op, payload, err2 := local.ReadMessage()
696 if err2 != nil || op == ws.OpClose {
697 break
698 }
699 if op != ws.OpText {
700 continue
701 }
702 label, rem, _ := envelope.Identify(payload)
703 if label == envelope.EOSELabel {
704 break
705 }
706 if label != envelope.EventLabel {
707 continue
708 }
709 var er envelope.EventResult
710 if _, err1 := er.Unmarshal(rem); err1 != nil || er.Event == nil {
711 continue
712 }
713 ev := er.Event
714 if ev.Kind != 10002 || ev.Tags == nil {
715 continue
716 }
717 // Key by the hex spelling the follow list uses: a p-tag's
718 // ValueHex is hex, so a raw 32-byte event pubkey never matched a
719 // follow and every author fell back to the default relay.
720 pk := hexEnc(ev.Pubkey)
721 for _, t := range ev.Tags.GetAll([]byte("r")) {
722 if t.Len() < 2 {
723 continue
724 }
725 relayURL := string(t.Value())
726 if !hasPrefix(relayURL, "wss://") && !hasPrefix(relayURL, "ws://") {
727 continue
728 }
729 // marker is t.T[2] if present: "read", "write", or absent (both).
730 marker := ""
731 if t.Len() >= 3 {
732 marker = string(t.T[2])
733 }
734 isWrite := marker == "write" || marker == ""
735 if isWrite {
736 writeRelays[pk] = push(writeRelays[pk], relayURL)
737 }
738 }
739 }
740
741 // Invert: relayURL → []pubkeys that write there.
742 relayAuthors := map[string][]string{}
743 for _, pk := range follows {
744 urls, ok := writeRelays[pk]
745 if !ok {
746 // No kind 10002 found: fall back to the default outbox relay.
747 urls = []string{"wss://relay.damus.io"}
748 }
749 for _, u := range urls {
750 relayAuthors[u] = push(relayAuthors[u], pk)
751 }
752 }
753 fmt.Fprintf(os.Stderr, "outbox: %d write relays discovered\n", len(relayAuthors))
754 return relayAuthors
755 }
756
757 func spawnOutbox(localAddr, pubkey string) {
758 host := localAddr
759 if hasPrefix(host, "0.0.0.0:") {
760 host = "127.0.0.1:" | host[len("0.0.0.0:"):]
761 }
762 // Small delay so the relay's epoll loop is accepting before we connect.
763 cmd := "sleep 3 && " | os.Args[0] | " outbox " | pubkey | " ws://" | host
764 argv := []string{"/bin/sh", "-c", cmd}
765 attr := &os.ProcAttr{}
766 _, err := os.StartProcess("/bin/sh", argv, attr)
767 if err != nil {
768 fmt.Fprintf(os.Stderr, "outbox: spawn failed: %v\n", err)
769 }
770 }
771
772 // outboxBootstrapFollows fetches the user's kind 3 from seed relays and
773 // publishes it into the local store so outboxDiscover can find it.
774 // Returns the extracted follow pubkeys.
775 func outboxBootstrapFollows(pubkey, localURL string) (ss []string) {
776 for _, seed := range bootstrapSeeds {
777 fmt.Fprintf(os.Stderr, "outbox: bootstrap: trying %s\n", seed)
778 remote, err4 := ws.Dial(seed)
779 if err4 != nil {
780 continue
781 }
782 req := []byte(`["REQ","ob-boot",{"kinds":[3,10002],"authors":["` | pubkey | `"],"limit":2}]`)
783 if err3 := remote.WriteText(req); err3 != nil {
784 remote.Close()
785 continue
786 }
787 local, lerr := ws.Dial(localURL)
788 if lerr != nil {
789 remote.Close()
790 continue
791 }
792 var follows []string
793 evCount := 0
794 for {
795 op, payload, err2 := remote.ReadMessage()
796 if err2 != nil || op == ws.OpClose {
797 fmt.Fprintf(os.Stderr, "outbox: bootstrap: %s closed after %d events (err=%v)\n", seed, evCount, err2)
798 break
799 }
800 if op != ws.OpText {
801 continue
802 }
803 label, rem, _ := envelope.Identify(payload)
804 if label == envelope.EOSELabel {
805 fmt.Fprintf(os.Stderr, "outbox: bootstrap: %s EOSE after %d events\n", seed, evCount)
806 break
807 }
808 if label != envelope.EventLabel {
809 continue
810 }
811 var er envelope.EventResult
812 if _, err1 := er.Unmarshal(rem); err1 != nil || er.Event == nil {
813 continue
814 }
815 ev := er.Event
816 evCount++
817 fmt.Fprintf(os.Stderr, "outbox: bootstrap: %s event kind=%d\n", seed, ev.Kind)
818 // Publish to local store.
819 fwd := &envelope.EventSubmission{E: ev}
820 local.WriteText(fwd.Marshal(nil))
821 local.ReadMessage() // drain OK
822 // Extract follows from kind 3. Use ValueHex() because "p" tag values
823 // may be binary-encoded (32 bytes) rather than hex strings (64 chars).
824 if ev.Kind == 3 && ev.Tags != nil {
825 for _, t := range ev.Tags.GetAll([]byte("p")) {
826 if t.Len() >= 2 {
827 pk := string(t.ValueHex())
828 if len(pk) == 64 {
829 follows = mxutil.Ensure(follows, 1)
830 follows = push(follows, pk)
831 }
832 }
833 }
834 }
835 }
836 remote.Close()
837 local.Close()
838 if len(follows) > 0 {
839 fmt.Fprintf(os.Stderr, "outbox: bootstrap: found %d follows from %s\n", len(follows), seed)
840 // Second pass: fetch kind 10002 for all follows so outboxDiscover
841 // can map them to write relays without another bootstrap cycle.
842 outboxBootstrapRelayLists(follows, localURL, seed)
843 return follows
844 }
845 }
846 fmt.Fprintln(os.Stderr, "outbox: bootstrap: no follows found in seed relays")
847 return nil
848 }
849
850 // outboxBootstrapRelayLists fetches kind 10002 for all follows from one relay
851 // and publishes them to local so outboxDiscover can build the write relay map.
852 func outboxBootstrapRelayLists(follows []string, localURL, seedURL string) {
853 if len(follows) == 0 {
854 return
855 }
856 remote, err4 := ws.Dial(seedURL)
857 if err4 != nil {
858 return
859 }
860 defer remote.Close()
861 local, lerr := ws.Dial(localURL)
862 if lerr != nil {
863 return
864 }
865 defer local.Close()
866
867 // Build authors JSON for all follows.
868 authorsJSON := `["` | follows[0] | `"`
869 for _, pk := range follows[1:] {
870 authorsJSON = authorsJSON | `,"` | pk | `"`
871 }
872 authorsJSON = authorsJSON | `]`
873 lim := itoa64(int64(len(follows) * 2))
874 req := []byte(`["REQ","ob-rl2",{"kinds":[10002],"authors":` | authorsJSON | `,"limit":` | lim | `}]`)
875 if err3 := remote.WriteText(req); err3 != nil {
876 return
877 }
878 count := 0
879 for {
880 op, payload, err2 := remote.ReadMessage()
881 if err2 != nil || op == ws.OpClose {
882 break
883 }
884 if op != ws.OpText {
885 continue
886 }
887 label, rem, _ := envelope.Identify(payload)
888 if label == envelope.EOSELabel {
889 break
890 }
891 if label != envelope.EventLabel {
892 continue
893 }
894 var er envelope.EventResult
895 if _, err1 := er.Unmarshal(rem); err1 != nil || er.Event == nil {
896 continue
897 }
898 fwd := &envelope.EventSubmission{E: er.Event}
899 local.WriteText(fwd.Marshal(nil))
900 local.ReadMessage() // drain OK
901 count++
902 }
903 fmt.Fprintf(os.Stderr, "outbox: bootstrap: stored %d kind 10002 events from %s\n", count, seedURL)
904 }
905
906 func hasPrefix(s, prefix string) (ok bool) {
907 return len(s) >= len(prefix) && s[:len(prefix)] == prefix
908 }
909
910 func hasSuffix(s, suffix string) (ok bool) {
911 return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
912 }
913
914 func spawnCrawler(listenAddr string) {
915 host := listenAddr
916 if hasPrefix(host, "0.0.0.0:") {
917 host = "127.0.0.1:" | host[len("0.0.0.0:"):]
918 }
919 cmd := os.Args[0] | " crawl ws://" | host
920 argv := []string{"/bin/sh", "-c", cmd}
921 attr := &os.ProcAttr{}
922 _, err := os.StartProcess("/bin/sh", argv, attr)
923 if err != nil {
924 fmt.Fprintf(os.Stderr, "crawl: spawn failed: %v\n", err)
925 }
926 }
927
928 func spawnSync(listenAddr, remoteURL string) {
929 host := listenAddr
930 if hasPrefix(host, "0.0.0.0:") {
931 host = "127.0.0.1:" | host[len("0.0.0.0:"):]
932 }
933 cmd := os.Args[0] | " sync " | remoteURL | " ws://" | host
934 argv := []string{"/bin/sh", "-c", cmd}
935 attr := &os.ProcAttr{}
936 _, err := os.StartProcess("/bin/sh", argv, attr)
937 if err != nil {
938 fmt.Fprintf(os.Stderr, "sync: spawn failed: %v\n", err)
939 }
940 }
941
942 // --- crawl command ---
943
944 var crawlSeeds []string
945
946 // bootstrapSeeds are tried specifically for kind 3/10002 lookups.
947 // purplepag.es is designed for profile and contact list events.
948 var bootstrapSeeds []string
949
950 // Directory event kinds to fetch.
951 const crawlKindsFilter = `[0,3,5,1984,10000,10002,10050]`
952
953 func clog(out *os.File, format string, args ...fmt.Stringer) {
954 ts := time.Now().Format("15:04:05")
955 fmt.Fprintf(out, ts|" "|format|"\n", args)
956 }
957
958 // relayDB tracks known relays with frequency scores.
959 // Higher score = seen more often in kind 10002/10050 events = higher priority.
960 type relayDB struct {
961 score map[string]int32
962 order []string // URLs sorted by descending score
963 }
964
965 func newRelayDB() (p *relayDB) {
966 return &relayDB{score: map[string]int32{}}
967 }
968
969 func (db *relayDB) add(relayURL string, weight int32) {
970 db.score[relayURL] += weight
971 }
972
973 // sorted returns relay URLs ordered by descending frequency.
974 func (db *relayDB) sorted() (ss []string) {
975 urls := []string{:0:len(db.score)}
976 for u := range db.score {
977 urls = mxutil.Ensure(urls, 1)
978 urls = push(urls, u)
979 }
980 // Simple insertion sort by score descending.
981 for i := 1; i < len(urls); i++ {
982 for j := i; j > 0 && db.score[urls[j]] > db.score[urls[j-1]]; j-- {
983 urls[j], urls[j-1] = urls[j-1], urls[j]
984 }
985 }
986 return urls
987 }
988
989 func runCrawl(args []string) {
990 var err error
991 var out *os.File
992 out, err = os.OpenFile("/tmp/musiquay-crawl.log",
993 os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0644)
994 if err != nil {
995 out = os.Stderr
996 }
997
998 localURL := "ws://127.0.0.1:3334"
999 if len(args) >= 1 {
1000 localURL = args[0]
1001 }
1002 clog(out, "started pid=%d local=%s", os.Getpid(), localURL)
1003
1004 db := newRelayDB()
1005 // Seed relays get a high initial score.
1006 for _, s := range crawlSeeds {
1007 db.add(s, 100)
1008 }
1009
1010 pass := 0
1011 for {
1012 pass++
1013 clog(out, "=== pass %d, %d relays known ===", pass, len(db.score))
1014 ok := crawlPass(localURL, db, out)
1015 if ok {
1016 clog(out, "pass complete, sleeping 5m")
1017 time.Sleep(5 * time.Minute)
1018 } else {
1019 clog(out, "pass failed, retrying in 30s")
1020 time.Sleep(30 * time.Second)
1021 }
1022 }
1023 }
1024
1025 func crawlPass(localURL string, db *relayDB, out *os.File) (ok bool) {
1026 relays := db.sorted()
1027 if len(relays) == 0 {
1028 clog(out, "no relays known")
1029 return false
1030 }
1031
1032 totalEvents := 0
1033 for i, relayURL := range relays {
1034 clog(out, "[%d/%d] crawling %s (score %d)", i+1, len(relays), relayURL, db.score[relayURL])
1035
1036 events := crawlRelay(relayURL, out)
1037 if len(events) == 0 {
1038 clog(out, " %s → 0 events", relayURL)
1039 time.Sleep(1 * time.Second)
1040 continue
1041 }
1042 clog(out, " %s → %d events", relayURL, len(events))
1043
1044 // Extract new relay URLs from the events before publishing.
1045 for _, raw := range events {
1046 crawlExtractRelays(raw, db)
1047 }
1048
1049 // Publish batch to local relay.
1050 published := crawlPublishBatch(localURL, events, out)
1051 clog(out, " published %d/%d to local", published, len(events))
1052 totalEvents += published
1053
1054 time.Sleep(1 * time.Second)
1055 }
1056
1057 clog(out, "total %d events from %d relays", totalEvents, len(relays))
1058 return true
1059 }
1060
1061 // crawlRelay connects to one relay and subscribes to directory events.
1062 // Returns raw EVENT messages suitable for republishing.
1063 func crawlRelay(relayURL string, out *os.File) (ss [][]byte) {
1064 remote, err4 := ws.Dial(relayURL)
1065 if err4 != nil {
1066 clog(out, " dial %s FAILED: %v", relayURL, err4)
1067 return nil
1068 }
1069 defer remote.Close()
1070
1071 reqJSON := []byte(`["REQ","cr",{"kinds":` | crawlKindsFilter | `,"limit":200}]`)
1072 if err3 := remote.WriteText(reqJSON); err3 != nil {
1073 clog(out, " write REQ to %s failed: %v", relayURL, err3)
1074 return nil
1075 }
1076
1077 var events [][]byte
1078 for {
1079 op, payload, err2 := remote.ReadMessage()
1080 if err2 != nil {
1081 break
1082 }
1083 if op != ws.OpText {
1084 continue
1085 }
1086 label, rem, _ := envelope.Identify(payload)
1087 if label == envelope.EOSELabel {
1088 break
1089 }
1090 if label == envelope.EventLabel {
1091 var er envelope.EventResult
1092 if _, err1 := er.Unmarshal(rem); err1 == nil && er.Event != nil {
1093 es := &envelope.EventSubmission{E: er.Event}
1094 events = mxutil.Ensure(events, 1)
1095 events = push(events, es.Marshal(nil))
1096 }
1097 }
1098 _ = rem
1099 }
1100 return events
1101 }
1102
1103 // crawlExtractRelays parses an EVENT submission and adds discovered relay
1104 // URLs to the database with a frequency bump.
1105 func crawlExtractRelays(raw []byte, db *relayDB) {
1106 _, rem, err2 := envelope.Identify(raw)
1107 if err2 != nil {
1108 return
1109 }
1110 var es envelope.EventSubmission
1111 if _, err1 := es.Unmarshal(rem); err1 != nil || es.E == nil {
1112 return
1113 }
1114 ev := es.E
1115 if (ev.Kind != 10002 && ev.Kind != 10050) || ev.Tags == nil {
1116 return
1117 }
1118 for _, t := range ev.Tags.GetAll([]byte("r")) {
1119 if t.Len() >= 2 {
1120 relayURL := string(t.Value())
1121 if len(relayURL) > 5 && (hasPrefix(relayURL, "wss://") || hasPrefix(relayURL, "ws://")) {
1122 db.add(relayURL, 1)
1123 }
1124 }
1125 }
1126 }
1127
1128 // crawlPublishBatch publishes a batch of EVENT messages to the local relay.
1129 func crawlPublishBatch(localURL string, events [][]byte, out *os.File) (n int32) {
1130 local, err2 := ws.Dial(localURL)
1131 if err2 != nil {
1132 clog(out, " local connect failed: %v", err2)
1133 return 0
1134 }
1135 defer local.Close()
1136
1137 for _, evBytes := range events {
1138 local.WriteText(evBytes)
1139 }
1140
1141 // Drain OKs - one per event sent.
1142 count := 0
1143 for count < len(events) {
1144 _, _, err1 := local.ReadMessage()
1145 if err1 != nil {
1146 break
1147 }
1148 count++
1149 }
1150 return count
1151 }
1152
1153 func hexEnc(b []byte) (s string) {
1154 const hx = "0123456789abcdef"
1155 out := []byte{:len(b)*2}
1156 for i, v := range b {
1157 out[i*2] = hx[v>>4]
1158 out[i*2+1] = hx[v&0x0f]
1159 }
1160 return string(out)
1161 }
1162
1163 func i64str(n int64) (s string) {
1164 if n == 0 {
1165 return "0"
1166 }
1167 neg := false
1168 if n < 0 {
1169 neg = true
1170 n = -n
1171 }
1172 var buf [20]byte
1173 i := 19
1174 for n > 0 {
1175 buf[i] = byte('0' + n%10)
1176 i--
1177 n /= 10
1178 }
1179 if neg {
1180 buf[i] = '-'
1181 i--
1182 }
1183 return string(buf[i+1:])
1184 }
1185
1186 func crawlAppendUniq(ss []string, s string) (ss2 []string) {
1187 for _, x := range ss {
1188 if x == s {
1189 return ss
1190 }
1191 }
1192 return push(ss, s)
1193 }
1194
1195