~gitpocket/gitpocket

8
afe731a9da0ddd2e2b088666b904c7cd965f48ff
mainfeed-discovery
gitpocket/forge/pages.go -rw-r--r--5.5 KiB ViewLogBlameView rawPermalink f09bf278b0 feat(pages): serve static sites from user subdomains 19 hours ago
  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
package forge

import (
	"bytes"
	"mime"
	"net"
	"net/http"
	"path"
	"regexp"
	"strings"
	"time"
)

const (
	pagesBranch = "pages"
	pagesRepo   = "pages"
	maxPage     = 32 << 20
	pagesMinAge = 24 * time.Hour
)

var pagesLabel = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]{0,37}[a-z0-9])?$`)

var pageTypes = map[string]string{
	".html":  "text/html; charset=utf-8",
	".htm":   "text/html; charset=utf-8",
	".css":   "text/css; charset=utf-8",
	".js":    "text/javascript; charset=utf-8",
	".mjs":   "text/javascript; charset=utf-8",
	".json":  "application/json",
	".map":   "application/json",
	".txt":   "text/plain; charset=utf-8",
	".md":    "text/plain; charset=utf-8",
	".xml":   "application/xml",
	".svg":   "image/svg+xml",
	".png":   "image/png",
	".jpg":   "image/jpeg",
	".jpeg":  "image/jpeg",
	".gif":   "image/gif",
	".webp":  "image/webp",
	".avif":  "image/avif",
	".ico":   "image/x-icon",
	".woff":  "font/woff",
	".woff2": "font/woff2",
	".ttf":   "font/ttf",
	".otf":   "font/otf",
	".wasm":  "application/wasm",
	".pdf":   "application/pdf",
	".mp4":   "video/mp4",
	".webm":  "video/webm",
	".mp3":   "audio/mpeg",
	".ogg":   "audio/ogg",
	".wav":   "audio/wav",
}

func pageType(name string) string {
	ext := strings.ToLower(path.Ext(name))
	if t, ok := pageTypes[ext]; ok {
		return t
	}
	if t := mime.TypeByExtension(ext); t != "" {
		return t
	}
	return "application/octet-stream"
}

func bareHost(host string) string {
	host = strings.ToLower(host)
	if h, _, err := net.SplitHostPort(host); err == nil {
		host = h
	}
	return strings.TrimSuffix(host, ".")
}

func (s *Server) pagesOwner(host string) (label string, sub bool) {
	host = bareHost(host)
	label, sub = strings.CutSuffix(host, "."+s.host)
	if !sub || !pagesLabel.MatchString(label) || reservedUsers[label] {
		return "", sub
	}
	return label, true
}

type pageSite struct {
	repo   Repo
	g      Git
	commit string
	prefix string
}

func (s *Server) pagesEnabled(owner User) bool {
	return time.Since(owner.Created) >= pagesMinAge && s.store.PagesAllowed(owner.ID)
}

func (s *Server) pageSite(owner User, name string, branchOnly bool) (pageSite, bool) {
	repo, err := s.store.RepoByPath(owner.Name, name)
	if err != nil || repo.Private {
		return pageSite{}, false
	}
	g := Git{Dir: s.repoDir(repo)}
	commit, err := g.Resolve("refs/heads/" + pagesBranch)
	if err != nil && !branchOnly {
		commit, err = g.Resolve("HEAD")
	}
	if err != nil {
		return pageSite{}, false
	}
	return pageSite{repo: repo, g: g, commit: commit}, true
}

func (g Git) pageEntry(commit, filePath string) (mode, oid string, ok bool) {
	out, err := g.run(nil, "ls-tree", "-z", "--full-tree", commit, "--", filePath)
	if err != nil || len(out) == 0 {
		return "", "", false
	}
	meta, name, found := strings.Cut(strings.TrimSuffix(string(out), "\x00"), "\t")
	f := strings.Fields(meta)
	if !found || name != filePath || len(f) != 3 {
		return "", "", false
	}
	return f[0], f[2], true
}

func (s *Server) servePages(w http.ResponseWriter, r *http.Request, label string) {
	h := w.Header()
	h.Set("X-Content-Type-Options", "nosniff")
	h.Set("Referrer-Policy", "strict-origin-when-cross-origin")
	if r.Method != "GET" && r.Method != "HEAD" {
		h.Set("Allow", "GET, HEAD")
		http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
		return
	}
	if !s.requests.allow(clientIP(r)) {
		h.Set("Retry-After", "10")
		http.Error(w, "too many requests, slow down", http.StatusTooManyRequests)
		return
	}
	notFound := func() { http.Error(w, "page not found", http.StatusNotFound) }
	owner, err := s.store.UserByName(label)
	if err != nil || s.store.IsBanned(owner.ID) || !s.pagesEnabled(owner) {
		notFound()
		return
	}
	rel, ok := cleanPath(r.URL.Path)
	if !ok {
		notFound()
		return
	}
	var site pageSite
	first, rest, _ := strings.Cut(rel, "/")
	if first != "" && first != pagesRepo && validName(first) {
		if sub, found := s.pageSite(owner, first, true); found {
			if rest == "" && !strings.HasSuffix(r.URL.Path, "/") {
				http.Redirect(w, r, "/"+first+"/", http.StatusMovedPermanently)
				return
			}
			site, rel = sub, rest
			site.prefix = "/" + first
		}
	}
	if site.commit == "" {
		root, found := s.pageSite(owner, pagesRepo, false)
		if !found {
			notFound()
			return
		}
		site = root
	}
	file := rel
	if file == "" || strings.HasSuffix(r.URL.Path, "/") {
		file = path.Join(file, "index.html")
	}
	mode, oid, found := site.g.pageEntry(site.commit, file)
	if found && mode == "040000" {
		http.Redirect(w, r, site.prefix+"/"+rel+"/", http.StatusMovedPermanently)
		return
	}
	if !found && path.Ext(file) == "" {
		mode, oid, found = site.g.pageEntry(site.commit, file+".html")
		file += ".html"
	}
	status := http.StatusOK
	if !found || (mode != "100644" && mode != "100755") {
		mode, oid, found = site.g.pageEntry(site.commit, "404.html")
		if !found || (mode != "100644" && mode != "100755") {
			notFound()
			return
		}
		file, status = "404.html", http.StatusNotFound
	}
	size := site.g.Size(site.commit, file)
	if size > maxPage {
		http.Error(w, "file too large for pages", http.StatusRequestEntityTooLarge)
		return
	}
	if size > 1<<20 && !s.heavy.allow(clientIP(r)) {
		h.Set("Retry-After", "10")
		http.Error(w, "too many requests, slow down", http.StatusTooManyRequests)
		return
	}
	data, err := site.g.run(nil, "cat-file", "blob", oid)
	if err != nil {
		notFound()
		return
	}
	h.Set("Content-Type", pageType(file))
	h.Set("Cache-Control", "public, max-age=60")
	if status != http.StatusOK {
		w.WriteHeader(status)
		if r.Method == "GET" {
			w.Write(data)
		}
		return
	}
	h.Set("ETag", `"`+oid+`"`)
	http.ServeContent(w, r, "", time.Time{}, bytes.NewReader(data))
}