home   /   song   @   master
main.go
ae4659
  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
package main

import (
	"embed"
	"net/http"
	"os"
	"os/signal"
	"strings"

	_ "github.com/a-h/templ"
	"github.com/fiatjaf/eventstore"
	"github.com/fiatjaf/eventstore/badger"
	"github.com/fiatjaf/khatru"
	"github.com/kelseyhightower/envconfig"
	"github.com/nbd-wtf/go-nostr/nip19"
	"github.com/nbd-wtf/go-nostr/sdk"
	"github.com/rs/cors"
	"github.com/rs/zerolog"
)

type Settings struct {
	Domain string `envconfig:"DOMAIN" required:"true"`
	Port   string `envconfig:"PORT" default:"8484"`

	OwnerPublicKey    string `envconfig:"OWNER_PUBLIC_KEY" required:"true"`
	RepositoryDir     string `envconfig:"REPOSITORY_DIR" default:"repos"`
	RelayDatabasePath string `envconfig:"RELAY_DATABASE_PATH" default:"events"`
	SiteTitle         string `envconfig:"SITE_TITLE" default:"my git repositories"`

	SecureSchemeLetterS string `envconfig:"-"`
}

//go:embed static/*
var static embed.FS

var (
	s   Settings
	db  eventstore.Store
	log = zerolog.New(os.Stderr).Output(zerolog.ConsoleWriter{Out: os.Stdout}).With().Timestamp().Logger()
	sys *sdk.System
)

func main() {
	err := envconfig.Process("", &s)
	if err != nil {
		log.Fatal().Err(err).Msg("couldn't process envconfig")
		return
	}
	if prefix, data, err := nip19.Decode(s.OwnerPublicKey); err == nil {
		if prefix != "npub" {
			log.Fatal().Msgf("invalid OWNER_PUBLIC_KEY: '%s' -- must be npub or hex", s.OwnerPublicKey)
			return
		}
		s.OwnerPublicKey = data.(string)
	}

	if !strings.Contains(s.Domain, "localhost") {
		s.SecureSchemeLetterS = "s"
	}

	// initialize relay and relay store
	db = &badger.BadgerBackend{Path: s.RelayDatabasePath}
	if err := db.Init(); err != nil {
		log.Fatal().Err(err).Msg("failed to initialize badger db")
		return
	}
	defer db.Close()

	relay := khatru.NewRelay()
	relay.StoreEvent = append(relay.StoreEvent, db.SaveEvent)
	relay.DeleteEvent = append(relay.DeleteEvent, db.DeleteEvent)
	relay.QueryEvents = append(relay.QueryEvents, db.QueryEvents)
	relay.RejectEvent = append(relay.RejectEvent, rejectEvents)
	relay.OnEventSaved = append(relay.OnEventSaved, fetchSubmitterMetadata)
	mux := relay.Router()

	// nostr sdk
	sys = sdk.NewSystem(
		sdk.WithStore(db),
	)
	defer sys.Close()

	// initialize git repos directory
	if err := setupGitReposDirectory(); err != nil {
		log.Fatal().Err(err).Msg("failed to setup git server")
		return
	}

	// routes
	mux.Handle("/static/", http.FileServer(http.FS(static)))
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		log.Info().Str("method", r.Method).Str("url", r.URL.String()).Msg("request")

		r.URL.Path = reSlashDedup.ReplaceAllString(r.URL.Path, "/")
		if r.URL.Path == "/" {
			serveHome(w, r)
			return
		}

		spl := strings.Split(r.URL.Path, "/")

		repo := spl[1]
		if ascii.MatchString(spl[1]) == false {
			log.Warn().Str("name", spl[1]).Msg("received a request for an invalid repo")
			http.Error(w, "invalid repo name", 403)
			return
		}

		if r.URL.Query().Get("go-get") == "1" {
			serveGoGet(w, r, repo)
			return
		}

		if len(spl) == 4 && spl[2] == "info" && spl[3] == "refs" {
			getInfoRefs(w, r, repo)
			return
		}

		if len(spl) == 3 && (spl[2] == "git-upload-pack" || spl[2] == "git-receive-pack") {
			if !repoExists(repo) && spl[2] == "git-upload-pack" {
				log.Warn().Msg("trying to pull from a repository that doesn't exist")
				http.Error(w, "repository not found", 404)
				return
			}

			postRPC(w, r, repo, spl[2])
			return
		}

		if len(spl) == 2 || (len(spl) == 3 && spl[2] == "") {
			serveRepoRoot(w, r, repo)
			return
		}

		if len(spl) >= 4 && spl[2] == "+" {
			// repo at a specific tag and possibly specifying a filepath
			tag := spl[3]
			if len(spl) == 6 && spl[4] == "~" {
				// in this case it specifies a patch to be visualized
				patchId := spl[5]
				servePatch(w, r, repo, tag, patchId)
				return
			}

			// but in this case it is the repo at a specific tag
			if len(spl) == 4 {
				serveTag(w, r, repo, tag)
				return
			}
			// and in this case it is the repo at a specific tag with a file path
			serveFileOrTree(w, r, repo, tag, spl[4:])
			return
		}

		if len(spl) == 3 && spl[2] == "!" {
			// this is a call announcing the repo -- we should just return the <aside> thing
			handleAnnounce(w, r, repo, "HEAD")
			return
		}
	})

	// start
	log.Print("listening at http://0.0.0.0:" + s.Port)
	server := &http.Server{Addr: "0.0.0.0:" + s.Port, Handler: cors.AllowAll().Handler(relay)}
	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()
}