1// Package web implements the HTTP server and web UI for Soft Serve.
2package web
3
4//go:generate go run gen_syntax_css.go
5
6import (
7 "context"
8 "embed"
9 "fmt"
10 "html/template"
11 "mime"
12 "net/http"
13 "path/filepath"
14 "strings"
15 "time"
16
17 "github.com/charmbracelet/log/v2"
18 "github.com/charmbracelet/soft-serve/pkg/proto"
19 "github.com/dustin/go-humanize"
20 "github.com/gorilla/mux"
21)
22
23//go:embed templates/*.html
24var templatesFS embed.FS
25
26//go:embed static/*
27var staticFS embed.FS
28
29const (
30 // defaultCommitsPerPage is the number of commits shown per page in commit history view.
31 defaultCommitsPerPage = 50
32 // defaultReposPerPage is the number of repositories shown per page on the home page.
33 defaultReposPerPage = 20
34 // defaultTagsPerPage is the number of tags shown per page on the tags page.
35 defaultTagsPerPage = 20
36 // defaultBranchesPerPage is the number of branches shown per page on the branches page.
37 defaultBranchesPerPage = 20
38)
39
40// BaseData contains common fields for all web UI pages.
41type BaseData struct {
42 ServerName string
43 ActiveTab string
44 Title string
45 Description string
46}
47
48// RepoBaseData contains common fields for repository-specific pages.
49type RepoBaseData struct {
50 BaseData
51 Repo proto.Repository
52 DefaultBranch string
53}
54
55// PaginationData contains common fields for paginated views.
56type PaginationData struct {
57 Page int
58 TotalPages int
59 HasPrevPage bool
60 HasNextPage bool
61}
62
63// templateFuncs defines template helper functions available in HTML templates.
64// Functions include: splitPath (split path into components), joinPath (join path components),
65// parentPath (get parent directory), shortHash (truncate commit hash), formatDate (format timestamp),
66// and humanizeSize (format file size in human-readable format).
67var templateFuncs = template.FuncMap{
68 "splitPath": func(path string) []string {
69 if path == "." {
70 return []string{}
71 }
72 return strings.Split(path, "/")
73 },
74 "joinPath": func(index int, data interface{}) string {
75 var path string
76
77 switch v := data.(type) {
78 case BlobData:
79 path = v.Path
80 case TreeData:
81 path = v.Path
82 default:
83 return ""
84 }
85
86 parts := strings.Split(path, "/")
87 if index >= len(parts) {
88 return path
89 }
90 return strings.Join(parts[:index+1], "/")
91 },
92 "parentPath": func(path string) string {
93 if path == "." || !strings.Contains(path, "/") {
94 return "."
95 }
96 return filepath.Dir(path)
97 },
98 "shortHash": func(hash interface{}) string {
99 var hashStr string
100 switch v := hash.(type) {
101 case string:
102 hashStr = v
103 case fmt.Stringer:
104 hashStr = v.String()
105 default:
106 hashStr = fmt.Sprintf("%v", hash)
107 }
108 if len(hashStr) > 7 {
109 return hashStr[:7]
110 }
111 return hashStr
112 },
113 "formatDate": func(t interface{}) string {
114 if time, ok := t.(fmt.Stringer); ok {
115 return time.String()
116 }
117 return fmt.Sprintf("%v", t)
118 },
119 "humanizeSize": func(size int64) string {
120 const unit = 1024
121 if size < unit {
122 return fmt.Sprintf("%d B", size)
123 }
124 div, exp := int64(unit), 0
125 for n := size / unit; n >= unit; n /= unit {
126 div *= unit
127 exp++
128 }
129 return fmt.Sprintf("%.1f %ciB", float64(size)/float64(div), "KMGTPE"[exp])
130 },
131 "inc": func(i int) int {
132 return i + 1
133 },
134 "dec": func(i int) int {
135 return i - 1
136 },
137 "commitSubject": func(message string) string {
138 lines := strings.Split(message, "\n")
139 if len(lines) > 0 {
140 return lines[0]
141 }
142 return message
143 },
144 "commitBody": func(message string) string {
145 lines := strings.Split(message, "\n")
146 if len(lines) <= 1 {
147 return ""
148 }
149 // Skip the subject line and join the rest
150 body := strings.Join(lines[1:], "\n")
151 return strings.TrimSpace(body)
152 },
153 "rfc3339": func(t interface{}) string {
154 switch v := t.(type) {
155 case time.Time:
156 return v.Format(time.RFC3339)
157 default:
158 return ""
159 }
160 },
161 "relativeTime": func(t interface{}) string {
162 switch v := t.(type) {
163 case time.Time:
164 return humanize.Time(v)
165 default:
166 return ""
167 }
168 },
169}
170
171// renderHTML renders an HTML template with the given data.
172func renderHTML(w http.ResponseWriter, templateName string, data interface{}) {
173 tmpl, err := template.New("").Funcs(templateFuncs).ParseFS(templatesFS, "templates/base.html", "templates/"+templateName)
174 if err != nil {
175 log.Debug("failed to parse template", "template", templateName, "err", err)
176 renderInternalServerError(w, nil)
177 return
178 }
179
180 w.Header().Set("Content-Type", "text/html; charset=utf-8")
181 if err := tmpl.ExecuteTemplate(w, "layout", data); err != nil {
182 log.Debug("template execution failed", "template", templateName, "err", err)
183 // Already started writing response, so we can't render an error page
184 }
185}
186
187// staticFiles handles static file serving.
188func staticFiles(w http.ResponseWriter, r *http.Request) {
189 // Strip /static/ prefix
190 path := strings.TrimPrefix(r.URL.Path, "/static/")
191
192 data, err := staticFS.ReadFile("static/" + path)
193 if err != nil {
194 renderNotFound(w, r)
195 return
196 }
197
198 // Set cache headers
199 w.Header().Set("Cache-Control", "public, max-age=31536000")
200
201 // Detect content type from extension
202 contentType := mime.TypeByExtension(filepath.Ext(path))
203 if contentType != "" {
204 w.Header().Set("Content-Type", contentType)
205 }
206
207 w.Write(data)
208}
209
210// withWebUIAccess wraps withAccess and hides 401/403 as 404 for Web UI routes.
211func withWebUIAccess(next http.Handler) http.Handler {
212 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
213 ctx := r.Context()
214 logger := log.FromContext(ctx)
215 logger.Debug("withWebUIAccess called", "path", r.URL.Path)
216
217 // Wrap the writer to suppress 401/403
218 hrw := &hideAuthWriter{ResponseWriter: w}
219 // Run access first so repo/user are injected into context
220 withAccess(next).ServeHTTP(hrw, r)
221
222 if hrw.suppressed {
223 logger.Debug("suppressed 401/403, rendering 404")
224 // Remove auth challenge headers so we don't leak private info
225 w.Header().Del("WWW-Authenticate")
226 w.Header().Del("LFS-Authenticate")
227 // Now render 404 once; no double WriteHeader occurs
228 renderNotFound(w, r)
229 }
230 })
231}
232
233// hideAuthWriter suppresses 401/403 responses to convert them to 404.
234type hideAuthWriter struct {
235 http.ResponseWriter
236 suppressed bool
237}
238
239func (w *hideAuthWriter) WriteHeader(code int) {
240 if code == http.StatusUnauthorized || code == http.StatusForbidden {
241 // Suppress original status/body; we'll render 404 afterwards
242 w.suppressed = true
243 return
244 }
245 w.ResponseWriter.WriteHeader(code)
246}
247
248func (w *hideAuthWriter) Write(p []byte) (int, error) {
249 if w.suppressed {
250 // Drop body of 401/403
251 return len(p), nil
252 }
253 return w.ResponseWriter.Write(p)
254}
255
256// WebUIController registers HTTP routes for the web-based repository browser.
257// It provides HTML views for repository overview, file browsing, commits, and references.
258func WebUIController(ctx context.Context, r *mux.Router) {
259 basePrefix := "/{repo:.*}"
260
261 // Static files (most specific, should be first)
262 r.PathPrefix("/static/").HandlerFunc(staticFiles).Methods(http.MethodGet)
263
264 // Home page (root path, before other routes)
265 r.HandleFunc("/", home).Methods(http.MethodGet)
266
267 // About page
268 r.HandleFunc("/about", about).Methods(http.MethodGet)
269
270 // More specific routes must be registered before catch-all patterns
271 // Middleware order: withRepoVars (set vars) -> withWebUIAccess (auth + load context) -> handler
272 // Tree routes - use catch-all pattern and parse ref/path in handler to support refs with slashes
273 r.Handle(basePrefix+"/tree/{refAndPath:.+}", withRepoVars(withWebUIAccess(http.HandlerFunc(repoTree)))).
274 Methods(http.MethodGet)
275 r.Handle(basePrefix+"/tree", withRepoVars(withWebUIAccess(http.HandlerFunc(repoTree)))).
276 Methods(http.MethodGet)
277
278 // Blob routes - use catch-all pattern and parse ref/path in handler to support refs with slashes
279 r.Handle(basePrefix+"/blob/{refAndPath:.+}", withRepoVars(withWebUIAccess(http.HandlerFunc(repoBlob)))).
280 Methods(http.MethodGet)
281
282 // Commits routes - use catch-all pattern to support refs with slashes
283 r.Handle(basePrefix+"/commits/{ref:.+}", withRepoVars(withWebUIAccess(http.HandlerFunc(repoCommits)))).
284 Methods(http.MethodGet)
285 r.Handle(basePrefix+"/commits", withRepoVars(withWebUIAccess(http.HandlerFunc(repoCommits)))).
286 Methods(http.MethodGet)
287
288 // Commit route
289 r.Handle(basePrefix+"/commit/{hash:[0-9a-f]+}", withRepoVars(withWebUIAccess(http.HandlerFunc(repoCommit)))).
290 Methods(http.MethodGet)
291
292 // Commit patch and diff routes
293 r.Handle(basePrefix+"/commit/{hash:[0-9a-f]+}.patch", withRepoVars(withWebUIAccess(http.HandlerFunc(repoCommitPatch)))).
294 Methods(http.MethodGet)
295 r.Handle(basePrefix+"/commit/{hash:[0-9a-f]+}.diff", withRepoVars(withWebUIAccess(http.HandlerFunc(repoCommitDiff)))).
296 Methods(http.MethodGet)
297
298 // Branches route
299 r.Handle(basePrefix+"/branches", withRepoVars(withWebUIAccess(http.HandlerFunc(repoBranches)))).
300 Methods(http.MethodGet)
301
302 // Tags route
303 r.Handle(basePrefix+"/tags", withRepoVars(withWebUIAccess(http.HandlerFunc(repoTags)))).
304 Methods(http.MethodGet)
305
306 // Repository overview (catch-all, must be last)
307 r.Handle(basePrefix, withRepoVars(withWebUIAccess(http.HandlerFunc(repoOverview)))).
308 Methods(http.MethodGet)
309}