1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3// Package web is the HTML front of ermite: the pages of the read-only
4// showcase, rendered with templ from the data of the use cases.
5//
6// Like every other inbound adapter, the package reads and writes through the
7// use case interfaces of package ports (ADR 0024), never through the API. The
8// caller of every use case call is passed explicitly: the principal of the
9// request, which is anonymous unless the request carries a valid owner session
10// (ServeHTTP sets it in the context, principal reads it). The use cases then
11// show public repositories only to an anonymous caller; a private repository
12// is indistinguishable from a missing one (domain.ErrNotFound), here as
13// everywhere.
14//
15// Adding a page: a handler on Server, a route in routes, a templ page in
16// pages.templ and its view model in view.go.
17package web
18
19import (
20 "bytes"
21 "context"
22 "crypto/rand"
23 "encoding/hex"
24 "errors"
25 "fmt"
26 "net/http"
27 "net/netip"
28 "net/url"
29 "strings"
30 "time"
31
32 "github.com/a-h/templ"
33 "github.com/bnema/zerowrap"
34
35 "bnema.dev/ermite/internal/domain"
36 "bnema.dev/ermite/internal/ports"
37)
38
39// Patterns are the ServeMux patterns the handler serves: everything. The
40// router of the package answers the paths it does not know with its 404
41// page, and the more specific patterns of the server (health, API, Git) win
42// over this one.
43var Patterns = []string{"/"}
44
45// requestTimeout bounds the use case calls that build one page.
46const requestTimeout = 30 * time.Second
47
48// Config configures a Server.
49type Config struct {
50 // VideoHosts are exact external video hosts; nil uses the defaults.
51 VideoHosts []string
52 // Mirrors answers the push mirror badge shown to repository admins. Without it there is
53 // no badge. Leave it unset rather than assigning a typed nil pointer.
54 Mirrors ports.MirrorWarner
55 // Repos and Browse are the use cases the pages are built from.
56 Repos ports.RepoService
57 Browse ports.BrowseService
58 // MergeRequests serves the merge request pages (ADR 0017). Without it
59 // there are no such pages, nor section for them. Leave it unset rather
60 // than assigning a typed nil pointer.
61 MergeRequests ports.MergeRequestService
62 // Issues serves the issue pages (ADR 0031). Without it there are no such
63 // pages, nor tab for them. Leave it unset rather than assigning a typed
64 // nil pointer.
65 Issues ports.IssueService
66 // IssueNumbers tells whether a number names an issue or a merge request,
67 // so that the page of the wrong kind redirects to the right one. Without
68 // it there is no such redirect. Leave it unset rather than assigning a
69 // typed nil pointer.
70 IssueNumbers ports.IssueNumberResolver
71 // IssueForm serves the public issue form of repositories whose issues
72 // mode is public (GET and POST /<repo>/issues/new for a visitor). Without
73 // it there is no such form. Leave it unset rather than assigning a typed
74 // nil pointer.
75 IssueForm ports.IssueSubmissionService
76 // Moderation serves the Approve, Reject and Reject-and-ban buttons of the
77 // pending issues in the inbox. It needs Inbox. Without it there are no
78 // such routes. Leave it unset rather than assigning a typed nil pointer.
79 Moderation ports.IssueModerationService
80 // Inbox serves the owner's inbox page (/-/inbox) and the button that
81 // leads to it. Without it there is neither. Leave it unset rather than
82 // assigning a typed nil pointer.
83 Inbox ports.InboxService
84 // SigningKey tells the key that signs the squash and merge commits, shown
85 // in the merge box. Without it the box does not name the key. Leave it
86 // unset rather than assigning a typed nil pointer.
87 SigningKey ports.SigningKeyService
88 // Runs serves the CI pages (/<repo>/actions) and the checks shown next to
89 // commits and merge requests. Without it there are no such pages. Leave it
90 // unset rather than assigning a typed nil pointer.
91 Runs ports.RunService
92 // Artifacts serves the artifacts of the runs: a section of the run page,
93 // their download and their deletion. It needs Runs. Without it there is
94 // neither. Leave it unset rather than assigning a typed nil pointer.
95 Artifacts ports.ArtifactService
96 // Releases serves the release pages and streamed assets. Nil disables them.
97 Releases ports.ReleaseService
98 // Events is the source of the event stream behind /-/events. Without
99 // it the pages are not live and the route answers 404. Leave it unset
100 // rather than assigning a typed nil pointer.
101 Events ports.EventService
102 // Heartbeat is how often an idle event stream gets a comment line;
103 // DefaultHeartbeat when zero.
104 Heartbeat time.Duration
105 // Owner is the owner login the GitHub-shaped URLs of CI show
106 // (<server>/<owner>/<repo>/...). A GET or HEAD of /<owner>/<rest> is
107 // redirected to /<rest> unless a repository named like the owner is
108 // visible to the caller. Empty: no redirect.
109 Owner string
110 // PublicURL is the base URL of the instance, without a trailing slash:
111 // the clone URLs are built on it, and its host is the instance name.
112 PublicURL string
113 // SourceURL is the link to the source of the running version (AGPL §13).
114 SourceURL string
115 // Version is the version of the running server.
116 Version string
117 // Now is the clock of relative dates; time.Now when nil.
118 Now func() time.Time
119 // Sessions signs the owner in (ADR 0018). Without it there are no login
120 // routes and every visitor is anonymous.
121 Sessions ports.WebSessionService
122 // Passkeys signs the owner in with a passkey and manages the passkeys
123 // (ADR 0026). Without it, or without Sessions, there are no passkey
124 // routes and no link to them. Leave it unset rather than assigning a typed
125 // nil pointer.
126 Passkeys ports.WebPasskeyService
127 // Limiter counts the failed logins; required with Sessions. Share it with
128 // the API and Git, so that a client has one budget of failures.
129 Limiter ports.FailureLimiter
130 // TrustedProxies are the networks allowed to set X-Forwarded-For, to find
131 // the address of the client that fails a login.
132 TrustedProxies []netip.Prefix
133}
134
135// Server serves the pages. It is an http.Handler.
136type Server struct {
137 cfg Config
138 instance string
139 origin string // scheme://host of the public URL, what a POST must come from
140 assets *assetSet
141 md *markdown
142 // pathCache holds the path lists the file finder fetches.
143 pathCache *pathCache
144 // licenses holds small display results, including missing licenses.
145 licenses *pathCache
146 // hl holds the colours of highlighted diffs.
147 hl *hlCache
148 mux *http.ServeMux
149 // ownerRepo is the owner login as a repository name, zero when it is not
150 // a valid one (then no repository can be named like the owner).
151 ownerRepo domain.RepoName
152 // refsFan shares the fragments of the refs page between the watchers of
153 // a push; entries are few and short-lived.
154 refsFan fanout
155 // pulses holds the activity curves of the home rows.
156 pulses pulseCache
157}
158
159// New builds the web handler.
160func New(cfg Config) (*Server, error) {
161 if cfg.Repos == nil || cfg.Browse == nil {
162 return nil, errors.New("web: the repository and browse use cases are required")
163 }
164 u, err := url.Parse(cfg.PublicURL)
165 if err != nil || u.Host == "" {
166 return nil, fmt.Errorf("web: public URL %q is not a valid base URL", cfg.PublicURL)
167 }
168 if cfg.Now == nil {
169 cfg.Now = time.Now
170 }
171 assets, err := loadAssets()
172 if err != nil {
173 return nil, fmt.Errorf("web: load assets: %w", err)
174 }
175 if cfg.Sessions != nil && cfg.Limiter == nil {
176 return nil, errors.New("web: sessions need a failure limiter")
177 }
178 s := &Server{
179 cfg: cfg, instance: u.Host, assets: assets, md: newMarkdown(cfg.VideoHosts...),
180 pathCache: newPathCache(pathCacheBytes, pathBuilds),
181 licenses: newPathCache(1<<20, homeWorkers),
182 hl: newHLCache(hlCacheBytes),
183 origin: originOf(u),
184 }
185 s.ownerRepo, _ = domain.ParseRepoName(cfg.Owner)
186 s.mux = s.routes()
187 return s, nil
188}
189
190// routes is the router of the web. Any path that is not a page is the 404
191// page.
192func (s *Server) routes() *http.ServeMux {
193 mux := http.NewServeMux()
194 mux.HandleFunc("GET "+StaticPrefix, s.assets.serve)
195 mux.HandleFunc("GET /-/events", s.events)
196 mux.HandleFunc("GET "+ServiceWorkerPath, s.assets.sw.serve)
197 if s.cfg.Sessions != nil {
198 mux.HandleFunc("GET "+loginPrefix+"{nonce}", s.loginConfirm)
199 mux.HandleFunc("POST "+loginPrefix+"{nonce}", s.loginPost)
200 mux.HandleFunc("POST /-/logout", s.logout)
201 }
202 if s.passkeysOn() {
203 s.passkeyRoutes(mux)
204 }
205 if s.cfg.Inbox != nil {
206 mux.HandleFunc("GET "+inboxPath, s.page(s.inbox))
207 if s.cfg.Moderation != nil {
208 mux.HandleFunc("POST "+inboxPath+"/pending/{repo}/{id}/approve", s.mrAction(s.pendingApprove))
209 mux.HandleFunc("POST "+inboxPath+"/pending/{repo}/{id}/reject", s.mrAction(s.pendingReject(false)))
210 mux.HandleFunc("POST "+inboxPath+"/pending/{repo}/{id}/ban", s.mrAction(s.pendingReject(true)))
211 }
212 }
213 mux.HandleFunc("GET /{$}", s.page(s.home))
214 mux.HandleFunc("GET /{repo}", s.page(s.summary))
215 mux.HandleFunc("GET /{repo}/{$}", s.page(s.summary))
216 mux.HandleFunc("GET /{repo}/refs", s.page(s.refs))
217 mux.HandleFunc("GET /{repo}/commits", s.page(s.commits))
218 mux.HandleFunc("GET /{repo}/commits/{rest...}", s.page(s.commits))
219 mux.HandleFunc("GET /{repo}/commit/{sha}", s.page(s.commit))
220 mux.HandleFunc("GET /{repo}/commit/{sha}/files", s.page(s.commitFiles))
221 mux.HandleFunc("GET /{repo}/tree", s.page(s.tree))
222 mux.HandleFunc("GET /{repo}/tree/{rest...}", s.page(s.tree))
223 mux.HandleFunc("GET /{repo}/blob/{rest...}", s.page(s.blob))
224 mux.HandleFunc("GET /{repo}/raw/{rest...}", s.raw)
225 mux.HandleFunc("GET /{repo}/paths/{sha}", s.paths)
226 mux.HandleFunc("GET /{repo}/context/{sha}", s.page(s.diffContext))
227 if s.cfg.MergeRequests != nil {
228 mux.HandleFunc("GET /{repo}/merge-requests", s.page(s.mrList))
229 mux.HandleFunc("GET /{repo}/merge-requests/{$}", s.page(s.mrList))
230 mux.HandleFunc("GET /{repo}/merge-requests/{n}", s.pageOrRedirect(s.mrShow, s.mrToIssue))
231 mux.HandleFunc("GET /{repo}/merge-requests/{n}/since", s.page(s.mrSince))
232 mux.HandleFunc("GET /{repo}/merge-requests/{n}/files", s.page(s.mrFiles))
233 mux.HandleFunc("GET /{repo}/compare/{rest...}", s.page(s.compare))
234 // The writes: POST only, behind the gate (ServeHTTP).
235 mux.HandleFunc("POST /{repo}/merge-requests", s.mrAction(s.mrCreate))
236 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments", s.mrAction(s.mrComment))
237 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments/{id}/resolve", s.mrAction(s.mrResolve))
238 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments/{id}/edit", s.mrAction(s.mrEditComment))
239 mux.HandleFunc("POST /{repo}/merge-requests/{n}/comments/{id}/delete", s.mrAction(s.mrDeleteComment))
240 mux.HandleFunc("POST /{repo}/merge-requests/{n}/merge", s.mrAction(s.mrMerge))
241 mux.HandleFunc("POST /{repo}/merge-requests/{n}/auto-merge", s.mrAction(s.mrAutoMerge))
242 mux.HandleFunc("POST /{repo}/merge-requests/{n}/auto-merge/cancel", s.mrAction(s.mrCancelAutoMerge))
243 mux.HandleFunc("POST /{repo}/merge-requests/{n}/close", s.mrAction(s.mrClose))
244 mux.HandleFunc("POST /{repo}/merge-requests/{n}/ready", s.mrAction(s.mrReady))
245 mux.HandleFunc("POST /{repo}/merge-requests/{n}/read", s.mrAction(s.mrRead))
246 }
247 if s.cfg.Issues != nil {
248 mux.HandleFunc("GET /{repo}/issues", s.page(s.issueList))
249 mux.HandleFunc("GET /{repo}/issues/{$}", s.page(s.issueList))
250 mux.HandleFunc("GET /{repo}/issues/new", s.issueNewRoute)
251 mux.HandleFunc("GET /{repo}/issues/{n}", s.pageOrRedirect(s.issueShow, s.issueToMR))
252 // The writes: POST only, behind the gate (ServeHTTP).
253 mux.HandleFunc("POST /{repo}/issues", s.issueAction(s.issueCreate))
254 mux.HandleFunc("POST /{repo}/issues/{n}/comments", s.issueAction(s.issueComment))
255 mux.HandleFunc("POST /{repo}/issues/{n}/close", s.issueAction(s.issueClose))
256 mux.HandleFunc("POST /{repo}/issues/{n}/reopen", s.issueAction(s.issueReopen))
257 }
258 if s.cfg.IssueForm != nil {
259 mux.HandleFunc("GET /{repo}/issues/submitted", s.issueSubmittedPage)
260 mux.HandleFunc("POST /{repo}/issues/new", s.issueFormPost)
261 }
262 if s.cfg.Releases != nil {
263 mux.HandleFunc("GET /{repo}/releases", s.page(s.releaseList))
264 mux.HandleFunc("GET /{repo}/releases/{$}", s.page(s.releaseList))
265 mux.HandleFunc("GET /{repo}/releases/tag/{tag...}", s.page(s.releaseShow))
266 mux.HandleFunc("GET /{repo}/releases/latest", s.releaseLatest)
267 mux.HandleFunc("GET /{repo}/releases/download/{tag}/{asset}", s.releaseDownload)
268 mux.HandleFunc("GET /{repo}/releases/latest/download/{asset}", s.releaseDownload)
269 mux.HandleFunc("GET /{repo}/releases/assets/{id}", s.releaseDownload)
270 }
271 if s.cfg.Runs != nil {
272 mux.HandleFunc("GET /{repo}/actions", s.page(s.actions))
273 mux.HandleFunc("GET /{repo}/actions/{$}", s.page(s.actions))
274 mux.HandleFunc("GET /{repo}/actions/runs/{id}", s.page(s.run))
275 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}", s.page(s.job))
276 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}/raw", s.rawLog)
277 mux.HandleFunc("GET /{repo}/actions/runs/{id}/job/{job}/stream", s.logStream)
278 mux.HandleFunc("POST /{repo}/actions/runs/{id}/cancel", s.ciAction(s.runCancel))
279 mux.HandleFunc("POST /{repo}/actions/runs/{id}/rerun", s.ciAction(s.runRerun(false)))
280 mux.HandleFunc("POST /{repo}/actions/runs/{id}/rerun-failed", s.ciAction(s.runRerun(true)))
281 if s.cfg.Artifacts != nil {
282 mux.HandleFunc("GET /{repo}/actions/runs/{id}/artifacts/{artifact}", s.artifactDownload)
283 mux.HandleFunc("POST /{repo}/actions/runs/{id}/artifacts/{artifact}/delete", s.ciAction(s.artifactDelete))
284 }
285 }
286 mux.HandleFunc(catchAll, s.page(s.notFound))
287 return mux
288}
289
290// ServeHTTP implements http.Handler.
291func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
292 // Whatever the context carried, the caller is anonymous until a valid
293 // session says otherwise (withSession).
294 r = r.WithContext(domain.ContextWithPrincipal(r.Context(), domain.Anonymous()))
295 r = s.withSession(w, r)
296 if !s.gate(w, r) {
297 return
298 }
299 if to, ok := s.ownerRedirect(r); ok {
300 http.Redirect(w, r, to, http.StatusPermanentRedirect)
301 return
302 }
303 s.mux.ServeHTTP(w, r)
304}
305
306// catchAll is the pattern of the paths that are no page.
307const catchAll = "GET /{repo}/{rest...}"
308
309// ownerRedirect maps /<owner>/<repo>[.git][/rest] to /<repo>[.git][/rest]: the
310// URLs that the github context of CI shows (html_url, commit and compare
311// URLs, clone_url) have the owner of the instance in front, like GitHub's.
312//
313// The rule is by repository, not by route: when no repository named like the
314// owner is visible to the caller, every GET or HEAD of /<owner>/<rest> is
315// redirected, so /<owner>/actions reaches the repository named "actions". A
316// repository named like the owner keeps its own pages. A private one is seen
317// as missing by an anonymous caller (the use case answers ErrNotFound), so the
318// redirect is the same as for a name nobody has and tells nothing.
319//
320// The target is built from a segment that parses as a repository name, which
321// has no slash, backslash, percent sign or dot-dot: it can only be a path on
322// this origin, never a "//host" one.
323func (s *Server) ownerRedirect(r *http.Request) (string, bool) {
324 if s.cfg.Owner == "" || (r.Method != http.MethodGet && r.Method != http.MethodHead) {
325 return "", false
326 }
327 first, rest, ok := strings.Cut(strings.TrimPrefix(r.URL.EscapedPath(), "/"), "/")
328 if !ok || !domain.OwnerMatches(s.cfg.Owner, first) || rest == "" {
329 return "", false
330 }
331 repo, _, _ := strings.Cut(rest, "/")
332 if _, err := domain.ParseRepoPath(repo); err != nil {
333 return "", false
334 }
335 if s.ownerNamesARepo(r) {
336 return "", false
337 }
338 to := "/" + rest
339 if r.URL.RawQuery != "" {
340 to += "?" + r.URL.RawQuery
341 }
342 return to, true
343}
344
345// ownerNamesARepo tells whether the caller can see a repository named like
346// the owner. A lookup that fails otherwise counts as yes: the request is then
347// served as it was before, without a redirect.
348func (s *Server) ownerNamesARepo(r *http.Request) bool {
349 if s.ownerRepo.IsZero() {
350 return false // the owner login is not a repository name
351 }
352 ctx := r.Context()
353 _, err := s.cfg.Repos.Get(ctx, principal(ctx), s.ownerRepo)
354 switch {
355 case err == nil:
356 return true
357 case errors.Is(err, domain.ErrNotFound):
358 return false
359 }
360 log := zerowrap.FromCtx(ctx)
361 log.Debug().Err(err).Msg("owner redirect: the lookup of the repository named like the owner failed")
362 return true
363}
364
365// handler builds a page. It returns the component and its status, or an
366// error, which becomes the 404 or 500 page.
367type handler func(ctx context.Context, r *http.Request) (templ.Component, int, error)
368
369// page adapts a handler: it bounds the use case calls, renders the component into
370// a buffer (so that a failure never leaves half a page), and maps errors to
371// the state pages.
372func (s *Server) page(h handler) http.HandlerFunc {
373 return func(w http.ResponseWriter, r *http.Request) {
374 ctx, cancel := context.WithTimeout(r.Context(), requestTimeout)
375 defer cancel()
376 c, status, err := h(ctx, r)
377 if err != nil {
378 s.fail(ctx, w, r, err)
379 return
380 }
381 s.write(ctx, w, r, status, c)
382 }
383}
384
385// write renders c with the given status.
386func (s *Server) write(ctx context.Context, w http.ResponseWriter, r *http.Request, status int, c templ.Component) {
387 var buf bytes.Buffer
388 if err := c.Render(ctx, &buf); err != nil {
389 // The error page itself failed: a bare answer is all that is left.
390 log := zerowrap.FromCtx(ctx)
391 log.Error().Err(err).Str("path", logPath(r.URL.Path)).Msg("render page")
392 http.Error(w, "internal error", http.StatusInternalServerError)
393 return
394 }
395 h := w.Header()
396 h.Set("Content-Type", "text/html; charset=utf-8")
397 // Links on this origin are prefetched on hover, so a click shows the page
398 // at once. Every GET page is safe to load (nothing is marked read on GET).
399 h.Set("Speculation-Rules", `"`+s.assets.urls.Rules+`"`)
400 // Public pages: the browser and any proxy revalidate each time. A page
401 // rendered for the owner is private and never stored; a handler that set
402 // its own Cache-Control keeps it.
403 if h.Get("Cache-Control") == "" {
404 cacheHeaders(ctx, h, "no-cache", sessionCache)
405 }
406 body := buf.Bytes()
407 // Whether the body is sent gzipped follows from its size and the request
408 // alone, so that the tag is known before the compression is spent.
409 gz := len(body) >= minCompress && acceptsGzip(r.Header) &&
410 !noTransform(h) && h.Get("Content-Encoding") == ""
411 addVary(h, "Accept-Encoding")
412 readOnly := r.Method == http.MethodGet || r.Method == http.MethodHead
413 // A page that may be stored gets a validator: the browser then
414 // revalidates with If-None-Match and a page that did not change costs a
415 // 304. A no-store page (the owner's) is never revalidated.
416 if readOnly && status == http.StatusOK && h.Get("ETag") == "" && !hasCacheDirective(h, noStore) {
417 tag := pageETag(body, SignedIn(ctx), gz)
418 h.Set("ETag", tag)
419 if etagMatches(strings.Join(r.Header.Values("If-None-Match"), ","), tag) {
420 h.Del("Content-Type")
421 w.WriteHeader(http.StatusNotModified)
422 return
423 }
424 }
425 if gz {
426 if z, err := gzipPage(body); err == nil && len(z) < len(body) {
427 body = z
428 h.Set("Content-Encoding", "gzip")
429 }
430 }
431 h.Set("Content-Length", itoa(len(body)))
432 w.WriteHeader(status)
433 if r.Method != http.MethodHead {
434 _, _ = w.Write(body)
435 }
436}
437
438// fail answers an error of a use case: not found (and a name or revision the
439// use case refuses, which no page can show either) gives the 404 page, a
440// visitor that left gives nothing, anything else gives the 500 page with an id
441// to find the cause in the log.
442func (s *Server) fail(ctx context.Context, w http.ResponseWriter, r *http.Request, err error) {
443 switch {
444 case errors.Is(err, domain.ErrNotFound), domain.IsInvalid(err):
445 s.write(ctx, w, r, http.StatusNotFound, s.notFoundPage())
446 case errors.Is(err, context.Canceled):
447 // The client is gone; there is nobody to answer.
448 default:
449 id := requestID()
450 log := zerowrap.FromCtx(ctx)
451 log.Error().Err(err).Str("request_id", id).Str("path", logPath(r.URL.Path)).Msg("web request failed")
452 s.write(ctx, w, r, http.StatusInternalServerError, s.errorPage(id))
453 }
454}
455
456// errNotFound is returned by handlers for a resource that does not exist
457// although the use case did not say so (a ref or a path that is not there).
458var errNotFound = domain.ErrNotFound
459
460// requestID is a short random id, shown on the 500 page and logged.
461func requestID() string {
462 var b [4]byte
463 _, _ = rand.Read(b[:])
464 return hex.EncodeToString(b[:])
465}
466
467// notFound is the handler of the paths without a page.
468func (s *Server) notFound(context.Context, *http.Request) (templ.Component, int, error) {
469 return nil, 0, errNotFound
470}
471
472// base is the Layout every page starts from.
473func (s *Server) base() Layout {
474 return Layout{
475 Owner: s.cfg.Owner,
476 Version: s.cfg.Version,
477 SourceURL: s.cfg.SourceURL,
478 Assets: s.assets.urls,
479 Passkeys: s.passkeysOn(),
480 }
481}
482
483// stateLayout is the layout of a state page: only the way home.
484func (s *Server) stateLayout(title string, crumbs []Crumb) Layout {
485 l := s.base()
486 l.Title = title + " · " + s.instance
487 l.Crumbs = crumbs
488 l.Cmd = []CmdItem{{Kind: "go", Label: "home", Href: "/"}}
489 return l
490}
491
492func (s *Server) notFoundPage() templ.Component {
493 l := s.stateLayout("404", []Crumb{{Label: "not found", Current: true}})
494 return State(l, StatePage{
495 Code: "404", Title: "not found",
496 Lines: []string{"no such page, ref or path.", "check the URL, or start from the repo list."},
497 Back: []Link{{Label: "home", Href: "/"}},
498 })
499}
500
501func (s *Server) errorPage(id string) templ.Component {
502 l := s.stateLayout("error", []Crumb{{Label: "error", Current: true}})
503 return State(l, StatePage{
504 Code: "500", Title: "internal error",
505 Lines: []string{
506 "the server failed to answer this request.",
507 "request id: " + id,
508 "retry in a moment; if it persists, the owner has the log.",
509 },
510 Back: []Link{{Label: "home", Href: "/"}},
511 })
512}
513
514// originOf is the origin of a URL as a browser writes it in the Origin
515// header: scheme and host in lower case, the port only when it is not the
516// default of the scheme.
517func originOf(u *url.URL) string {
518 scheme, host, port := strings.ToLower(u.Scheme), strings.ToLower(u.Hostname()), u.Port()
519 if strings.Contains(host, ":") {
520 host = "[" + host + "]"
521 }
522 defaultPort := (scheme == "http" && port == "80") || (scheme == "https" && port == "443")
523 if port != "" && !defaultPort {
524 host += ":" + port
525 }
526 return scheme + "://" + host
527}