package web import ( "context" "errors" "net/http" "net/url" "os" "path" "path/filepath" "strconv" "strings" "time" "supermarket/internal/api/gitea" "supermarket/internal/hugorepo" "supermarket/internal/profile" "supermarket/internal/sites" ) // siteRepo is a website with a Hugo repository, from the profile. type siteRepo struct { Index int URL string Base string // the URL without a trailing slash, for links Repo string // owner/name Branch string // as set in the profile; "" for the default Err string // why the repository can't be read } // siteSynced is what the last sync of a site's working copy found. type siteSynced struct { At time.Time `json:"at"` Branch string `json:"branch"` Err string `json:"error,omitempty"` } func siteSyncKey(full string) string { return "sites:synced:" + full } func (s *Server) siteRepos() []siteRepo { p, _ := profile.Load(s.DB) if p == nil { return nil } var out []siteRepo for i, w := range p.Websites { sr := siteRepo{Index: i, URL: w.URL, Base: strings.TrimRight(w.URL, "/"), Branch: w.Branch} if w.Repo == "" { sr.Err = "no Hugo repository set" } else if _, full, err := gitea.ParseRepo(w.Repo); err != nil { sr.Err = err.Error() } else { sr.Repo = full } out = append(out, sr) } return out } func (s *Server) siteDir(full string) string { return filepath.Join(s.DataDir, "sites", strings.ReplaceAll(full, "/", "__")) } func (s *Server) currentSite(r *http.Request) ([]siteRepo, *siteRepo) { all := s.siteRepos() want, err := strconv.Atoi(r.URL.Query().Get("site")) if err != nil { want, err = strconv.Atoi(r.PostFormValue("site")) } for i := range all { if err == nil && all[i].Index == want { return all, &all[i] } } for i := range all { if all[i].Repo != "" { return all, &all[i] } } return all, nil } func (s *Server) sitesPage(w http.ResponseWriter, r *http.Request) { s.renderSites(w, r, "") } func (s *Server) renderSites(w http.ResponseWriter, r *http.Request, errMsg string) { all, cur := s.currentSite(r) data := map[string]any{"Sites": all, "Current": cur, "Gitea": s.gitea() != nil, "Synced": siteSynced{}} if cur != nil { data["Conv"] = s.pageConv(cur.URL) } if cur != nil && cur.Repo != "" { var synced siteSynced if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok { data["Synced"], data["HasSynced"] = synced, true if !synced.At.IsZero() { wc := &hugorepo.Repo{Dir: s.siteDir(cur.Repo), Branch: synced.Branch} wc.Acquire() cat, err := sites.Read(wc.Dir, wc.PathOf) if err == nil { ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) data["Commits"], _ = wc.Log(ctx, 8) cancel() } wc.Release() if ts := sites.ReadTheme(wc.Dir); ts.Has { data["Theme"] = ts var pr formsPR if ok, _ := s.DB.GetJSON(themePRKey(cur.Repo), &pr); ok { data["ThemePR"] = pr } data["Kinds"] = []string{"home", "about", "contact"} if p, _ := profile.Load(s.DB); p != nil { data["Products"] = p.Products } } if err != nil { errMsg = "Couldn't read the working copy: " + err.Error() } else { data["Catalog"] = cat data["SectionPages"], data["OtherPages"] = splitPages(cat.Pages) } } } } s.render(w, r, "sites", page{Title: "Sites", Nav: "sites/site", Error: errMsg, Data: data}) } func splitPages(ps []sites.Page) (withSections, other []sites.Page) { for _, p := range ps { if p.Sections { withSections = append(withSections, p) } else { other = append(other, p) } } return } // sitesSync brings the site's working copy up to date with its published // branch. func (s *Server) sitesSync(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } _, cur := s.currentSite(r) if cur == nil || cur.Repo == "" { s.renderSites(w, r, "Set this website's Hugo repository in Settings → Profile first.") return } ctx, cancel := context.WithTimeout(r.Context(), 5*time.Minute) defer cancel() ap := s.applier(seoSite{Index: cur.Index, URL: cur.URL}) synced := siteSynced{At: time.Now()} wc, _, branch, err := ap.WorkingCopy(ctx) if err != nil { var old siteSynced if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &old); ok { synced = old // keep showing the last good copy } synced.Err = err.Error() } else { wc.Release() synced.Branch = branch } if err := s.DB.PutJSON(siteSyncKey(cur.Repo), synced); err != nil { s.serverError(w, err) return } http.Redirect(w, r, "/sites?site="+strconv.Itoa(cur.Index), http.StatusSeeOther) } // --- Previews --- func sitePreviewsKey(full string) string { return "sites:previews:" + full } func (s *Server) previewDir(full, slug string) string { return filepath.Join(s.DataDir, "previews", strings.ReplaceAll(full, "/", "__"), slug) } func previewPrefix(site int, slug string) string { return "/preview/" + strconv.Itoa(site) + "/" + slug + "/" } func (s *Server) previews(full string) []sites.Preview { var ps []sites.Preview _, _ = s.DB.GetJSON(sitePreviewsKey(full), &ps) return ps } // previewRow is a branch on the previews page. type previewRow struct { hugorepo.Branch Published bool Preview *sites.Preview Link string Stale bool // the branch has moved on since the preview was built } func (s *Server) sitesPreviewsPage(w http.ResponseWriter, r *http.Request) { s.renderPreviews(w, r, "") } func (s *Server) renderPreviews(w http.ResponseWriter, r *http.Request, errMsg string) { all, cur := s.currentSite(r) data := map[string]any{"Sites": all, "Current": cur, "Gitea": s.gitea() != nil, "Hugo": hugorepo.HugoVersion(r.Context()) != ""} if cur != nil && cur.Repo != "" { var synced siteSynced if ok, _ := s.DB.GetJSON(siteSyncKey(cur.Repo), &synced); ok && !synced.At.IsZero() { data["HasSynced"], data["Synced"] = true, synced ps := s.previews(cur.Repo) wc := &hugorepo.Repo{Dir: s.siteDir(cur.Repo), Branch: synced.Branch} wc.Acquire() ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) branches, err := wc.Branches(ctx) cancel() wc.Release() if err != nil { errMsg = "Couldn't list the branches: " + err.Error() } var rows []previewRow for _, b := range branches { row := previewRow{Branch: b, Published: b.Name == synced.Branch} for i := range ps { if ps[i].Branch == b.Name { row.Preview = &ps[i] if ps[i].Commit != "" { row.Link = previewPrefix(cur.Index, ps[i].Slug) row.Stale = ps[i].Commit != b.Hash } } } if row.Published { rows = append([]previewRow{row}, rows...) } else { rows = append(rows, row) } } data["Rows"] = rows } } s.render(w, r, "sites-previews", page{Title: "Previews", Nav: "sites/previews", Error: errMsg, Data: data}) } // sitesPreviewBuild builds a branch's preview: a fresh read of the // repository, the branch checked out, Hugo built, and the result moved to // where /preview/ serves it. func (s *Server) sitesPreviewBuild(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } _, cur := s.currentSite(r) branch := r.PostFormValue("branch") if cur == nil || cur.Repo == "" || branch == "" { s.renderPreviews(w, r, "Choose a website and a branch.") return } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) defer cancel() p, err := s.buildPreview(ctx, *cur, branch) if err != nil { s.renderPreviews(w, r, err.Error()) return } http.Redirect(w, r, "/sites/previews?site="+strconv.Itoa(cur.Index)+"&built="+url.QueryEscape(p.Slug), http.StatusSeeOther) } func (s *Server) buildPreview(ctx context.Context, cur siteRepo, branch string) (*sites.Preview, error) { if hugorepo.HugoVersion(ctx) == "" { return nil, errors.New("there's no Hugo in Supermarket's image, so previews can't be built") } ap := s.applier(seoSite{Index: cur.Index, URL: cur.URL}) wc, _, published, err := ap.WorkingCopy(ctx) if err != nil { return nil, err } defer wc.Release() _ = s.DB.PutJSON(siteSyncKey(cur.Repo), siteSynced{At: time.Now(), Branch: published}) ps := s.previews(cur.Repo) p := sites.Preview{Branch: branch, Slug: sites.Slug(branch, ps), At: time.Now()} commit, err := wc.CheckoutRemote(ctx, branch) if err == nil { tmp := s.previewDir(cur.Repo, "."+p.Slug+".building") if err = wc.BuildTo(ctx, tmp, "/"); err == nil { if err = sites.Rehome(tmp, previewPrefix(cur.Index, p.Slug)); err == nil { dest := s.previewDir(cur.Repo, p.Slug) os.RemoveAll(dest) err = os.Rename(tmp, dest) } os.RemoveAll(tmp) } } // Leave the working copy on the published branch for the next job. _ = wc.Sync(ctx) if err != nil { p.Err = err.Error() } else { p.Commit = commit } kept := []sites.Preview{p} for _, old := range ps { if old.Branch != branch { kept = append(kept, old) } else if err != nil && old.Commit != "" { // A failed build keeps serving the last good one. kept[0].Commit, kept[0].Slug = old.Commit, old.Slug } } if perr := s.DB.PutJSON(sitePreviewsKey(cur.Repo), kept); perr != nil { return nil, perr } if err != nil { return nil, err } return &p, nil } // sitesPreviewDelete removes a branch's preview. func (s *Server) sitesPreviewDelete(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } _, cur := s.currentSite(r) if cur == nil || cur.Repo == "" { http.Redirect(w, r, "/sites/previews", http.StatusSeeOther) return } var kept []sites.Preview for _, p := range s.previews(cur.Repo) { if p.Branch == r.PostFormValue("branch") { os.RemoveAll(s.previewDir(cur.Repo, p.Slug)) continue } kept = append(kept, p) } if err := s.DB.PutJSON(sitePreviewsKey(cur.Repo), kept); err != nil { s.serverError(w, err) return } http.Redirect(w, r, "/sites/previews?site="+strconv.Itoa(cur.Index), http.StatusSeeOther) } // previewCSP is the policy for previewed pages. They're the site's own // pages, scripts and all, but whatever a branch holds mustn't be able to // act on Supermarket: sandbox gives each page an origin of its own, so // its requests to the app are cross-site (and refused), and nothing is // sent anywhere else (no analytics from previews). Stylesheets and fonts // may come from elsewhere, as web fonts do, so the page looks like the // live one; scripts may not. const previewCSP = "sandbox allow-scripts allow-popups allow-popups-to-escape-sandbox; default-src 'self'; " + "img-src 'self' data: https:; media-src 'self' https:; font-src 'self' data: https:; style-src 'self' 'unsafe-inline' https:; " + "script-src 'self' 'unsafe-inline'; connect-src 'none'; form-action 'none'; frame-ancestors 'none'" // previewServe serves a built preview. func (s *Server) previewServe(w http.ResponseWriter, r *http.Request) { site, err := strconv.Atoi(r.PathValue("site")) if err != nil { http.NotFound(w, r) return } var cur *siteRepo for _, sr := range s.siteRepos() { if sr.Index == site && sr.Repo != "" { cur = &sr } } slug := r.PathValue("slug") if cur == nil || strings.HasPrefix(slug, ".") { http.NotFound(w, r) return } found := false for _, p := range s.previews(cur.Repo) { if p.Slug == slug && p.Commit != "" { found = true } } if !found { http.Error(w, "No preview of that branch. Build one under Sites → Previews.", http.StatusNotFound) return } h := w.Header() h.Set("Content-Security-Policy", previewCSP) h.Set("Cache-Control", "no-store") prefix := strings.TrimSuffix(previewPrefix(site, slug), "/") dir := s.previewDir(cur.Repo, slug) // A page gets the site's icon sprites inlined (see inlineSprites). if rest := strings.TrimPrefix(r.URL.Path, prefix); rest != r.URL.Path && !strings.Contains(rest, "..") { file := rest if strings.HasSuffix(file, "/") { file += "index.html" } if strings.HasSuffix(file, ".html") { if raw, err := os.ReadFile(filepath.Join(dir, filepath.FromSlash(path.Clean(file)))); err == nil { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Write(inlineSprites(raw, dir, rest)) return } } } http.StripPrefix(prefix, http.FileServer(noListing{http.Dir(dir)})).ServeHTTP(w, r) } // noListing serves files, and folders only through their index.html. type noListing struct{ fs http.FileSystem } func (n noListing) Open(name string) (http.File, error) { f, err := n.fs.Open(name) if err != nil { return nil, err } if st, err := f.Stat(); err == nil && st.IsDir() { idx, err := n.fs.Open(strings.TrimSuffix(name, "/") + "/index.html") if err != nil { f.Close() return nil, os.ErrNotExist } idx.Close() } return f, nil } func themePRKey(repo string) string { return "sites:theme-pr:" + repo } // sitesThemeUpdate opens the pull request that brings a site's copy of the // theme up to date. func (s *Server) sitesThemeUpdate(w http.ResponseWriter, r *http.Request) { if err := r.ParseForm(); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } _, cur := s.currentSite(r) if cur == nil || cur.Repo == "" { s.renderSites(w, r, "Choose a website with a Hugo repository.") return } if s.gitea() == nil { s.renderSites(w, r, "Save a Gitea token under Settings → Search engines first.") return } ctx, cancel := context.WithTimeout(r.Context(), 10*time.Minute) defer cancel() pull, d, err := sites.UpdateTheme(ctx, s.applier(seoSite{Index: cur.Index, URL: cur.URL})) if err != nil { s.renderSites(w, r, err.Error()) return } pr := formsPR{Number: pull.Number, URL: pull.HTMLURL, At: time.Now(), State: "open", Capture: strconv.Itoa(d.To)} if err := s.DB.PutJSON(themePRKey(cur.Repo), pr); err != nil { s.serverError(w, err) return } http.Redirect(w, r, "/sites?site="+strconv.Itoa(cur.Index), http.StatusSeeOther) }