diff --git a/Dockerfile b/Dockerfile index d46ba0b..08131d3 100644 --- a/Dockerfile +++ b/Dockerfile @@ -10,10 +10,19 @@ ARG VERSION=dev RUN CGO_ENABLED=0 go build -trimpath -ldflags "-s -w -X 'main.version=${VERSION}'" \ -o /out/supermarket ./cmd/supermarket +# Hugo, for the SEO and Sites modules, which build Hugo repositories to check +# a change and to preview a branch. Alpine's package lags years behind, and +# sites use newer template functions (hugo.Data needs 0.156+), so a pinned +# release is built from source; Go checks it against its checksum database. +# This is the standard edition: sites that need Sass (extended) won't build. +FROM golang:1.27-alpine AS hugo +ARG HUGO_VERSION=0.170.1 +RUN CGO_ENABLED=0 go install -trimpath -ldflags "-s -w" github.com/gohugoio/hugo@v${HUGO_VERSION} + FROM alpine:3.22 -# git and hugo: for the SEO and Sites modules, which change Hugo repositories -# and build them to check a change. -RUN apk add --no-cache ca-certificates tzdata git hugo +# git: for the SEO and Sites modules, which change Hugo repositories. +RUN apk add --no-cache ca-certificates tzdata git +COPY --from=hugo /go/bin/hugo /usr/local/bin/hugo COPY --from=build /out/supermarket /usr/local/bin/supermarket LABEL org.opencontainers.image.title="supermarket" ENV SUPERMARKET_DATA=/data diff --git a/PLAN.md b/PLAN.md index dc516f1..2dcae52 100644 --- a/PLAN.md +++ b/PLAN.md @@ -1262,6 +1262,24 @@ pages (`/sites`) reads the repository on request and shows the latest commits on the published branch. Live: federated-website has 25 section types and 59 pages (22 built from sections). +**Part 2 built (2026-11-22; no schema change).** Sites → Previews lists the +repository's branches (the published one first) and builds any of them: +a fresh read, the branch checked out, `hugo --buildDrafts --buildFuture` +for `/`, then every root-relative address in the HTML and CSS rewritten to +`/preview///`. The copy goes back to the published branch +afterwards. A failed build keeps serving the last good preview; a preview +older than its branch says so. Previews are served with a CSP `sandbox` +(no `allow-same-origin`): the site's scripts run, but each page has an +opaque origin, so the guard refuses anything it posts to the app; it can't +connect anywhere either, so analytics don't count previews. Folders show +only through their index.html. + +**The image's Hugo** was Alpine's 0.147.2, too old for federated-website +(`hugo.Data` needs 0.156+), so even the SEO build check would have failed +on it. The Dockerfile now builds Hugo v0.170.1 from source in a Go 1.27 +stage (the standard edition: sites needing Sass won't build). Hugo's +errors now show the innermost cause, with paths cut to the repository's. + ### Future enhancements Not in any phase yet; picked up when the user asks. diff --git a/TEST.md b/TEST.md index 5d8273b..6a31cb2 100644 --- a/TEST.md +++ b/TEST.md @@ -500,6 +500,23 @@ Throughout, also notice: - [ ] With the Gitea server unreachable, *Read it again* says the read failed and still shows the last good copy. +### Previews + +- [ ] Sites → Previews lists the repository's branches, the published one + first and marked *published*, each with its latest commit. +- [ ] *Build preview* on the published branch says "Built just now"; + *Open preview* opens the site in a new tab, looking like the live one. +- [ ] Links in the preview (menus, buttons, images) stay under + `/preview/…`; none lead to Supermarket's own pages. +- [ ] A branch with a draft page (e.g. a Supermarket pull request) shows the + draft in its preview. +- [ ] After new commits on a branch, *Read it again* on Sections and pages + makes the preview say the branch has moved on; *Build again* fixes it. +- [ ] A branch that doesn't build shows Hugo's error, and the last good + preview still opens. +- [ ] *Delete* removes the preview; its address then says there's none. +- [ ] Plausible doesn't count visits to a preview. + ## 9. Search - [ ] Searching for an inventory entry, a fetched item, a post, a prospect diff --git a/internal/hugorepo/repo.go b/internal/hugorepo/repo.go index d39f2e0..a5d0195 100644 --- a/internal/hugorepo/repo.go +++ b/internal/hugorepo/repo.go @@ -402,7 +402,7 @@ func (r *Repo) Build(ctx context.Context) (string, error) { cmd.Stdout, cmd.Stderr = &buf, &buf if err := cmd.Run(); err != nil { os.RemoveAll(out) - return "", fmt.Errorf("hugo couldn't build the site: %s", firstLine(buf.String())) + return "", fmt.Errorf("hugo couldn't build the site: %s", hugoError(buf.String())) } return out, nil } @@ -615,3 +615,110 @@ func (r *Repo) UpsertPage(rel string, fields []Field, body string) error { } return nil } + +// --- Previews --- + +// Branch is a branch on the server. +type Branch struct { + Name, Hash, Subject string + At time.Time +} + +// Branches are the server's branches, as of the last Sync, newest first. +func (r *Repo) Branches(ctx context.Context) ([]Branch, error) { + out, err := r.git(ctx, "for-each-ref", "--sort=-committerdate", + "--format=%(refname:strip=3)%1f%(objectname)%1f%(committerdate:unix)%1f%(subject)", "refs/remotes/origin") + if err != nil { + return nil, err + } + var bs []Branch + for _, l := range strings.Split(strings.TrimSpace(out), "\n") { + f := strings.Split(l, "\x1f") + if len(f) != 4 || f[0] == "HEAD" { + continue + } + sec, _ := strconv.ParseInt(f[2], 10, 64) + bs = append(bs, Branch{Name: f[0], Hash: f[1], At: time.Unix(sec, 0), Subject: f[3]}) + } + return bs, nil +} + +// CheckoutRemote puts a server branch's latest commit in the working copy +// (detached), and returns that commit. Sync puts the published branch back. +func (r *Repo) CheckoutRemote(ctx context.Context, branch string) (string, error) { + if strings.HasPrefix(branch, "-") { + return "", fmt.Errorf("no branch %q", branch) + } + for _, args := range [][]string{ + {"checkout", "--quiet", "--force", "--detach", "refs/remotes/origin/" + branch}, + {"clean", "-fdq"}, + {"submodule", "update", "--init", "--recursive", "--quiet"}, + } { + if _, err := r.git(ctx, args...); err != nil { + return "", err + } + } + out, err := r.git(ctx, "rev-parse", "HEAD") + return strings.TrimSpace(out), err +} + +// BuildTo builds the site as it is into dest (emptied first), for viewing +// at baseURL. Drafts and future pages are included: a preview shows +// everything. +func (r *Repo) BuildTo(ctx context.Context, dest, baseURL string) error { + if err := os.RemoveAll(dest); err != nil { + return err + } + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + cmd := exec.CommandContext(ctx, "hugo", "--quiet", "--destination", dest, "--baseURL", baseURL, + "--buildDrafts", "--buildFuture", "--cacheDir", filepath.Join(os.TempDir(), "supermarket-hugo-cache")) + cmd.Dir = r.Dir + var buf bytes.Buffer + cmd.Stdout, cmd.Stderr = &buf, &buf + if err := cmd.Run(); err != nil { + os.RemoveAll(dest) + return fmt.Errorf("hugo couldn't build the site: %s", hugoError(buf.String())) + } + return nil +} + +var hugoPath = regexp.MustCompile(`"(?:/[^"]*/)?((?:layouts|content|themes|assets|data)/[^"]*)"`) + +// hugoError picks the cause out of Hugo's output: the first ERROR line (or +// the final "Error:" line), with file paths cut to the repository's. +func hugoError(out string) string { + var pick string + for _, l := range strings.Split(out, "\n") { + l = strings.TrimSpace(l) + if strings.HasPrefix(l, "ERROR") { + pick = strings.TrimSpace(strings.TrimPrefix(l, "ERROR")) + break + } + if strings.HasPrefix(l, "Error:") && pick == "" { + pick = strings.TrimSpace(strings.TrimPrefix(l, "Error:")) + } + } + if pick == "" { + pick = firstLine(out) + } + if pick == "" { + return "no message (is the Hugo version recent enough for this site?)" + } + pick = hugoPath.ReplaceAllString(pick, `"$1"`) + // The innermost cause is what's useful; Hugo nests each template call. + if i := strings.LastIndex(pick, ": execute of template failed: "); i >= 0 { + head := pick + if j := strings.Index(head, ` failed: `); j >= 0 && j < i { + head = head[:j] + } + pick = head + ": " + pick[i+len(": execute of template failed: "):] + } + if r := []rune(pick); len(r) > 500 { + pick = string(r[:500]) + "…" + } + return pick +} diff --git a/internal/hugorepo/repo_test.go b/internal/hugorepo/repo_test.go index dbc0b49..8fddcd4 100644 --- a/internal/hugorepo/repo_test.go +++ b/internal/hugorepo/repo_test.go @@ -90,3 +90,19 @@ func TestRepo(t *testing.T) { t.Errorf("after sync: %q", v) } } + +func TestHugoError(t *testing.T) { + out := `Start building sites … +ERROR render of "/data/sites/x/content/partners.md" failed: "/data/sites/x/layouts/_default/single.html:2:5": execute of template failed: template: single.html:2:5: executing "main" at : error calling partial: "/data/sites/x/layouts/partials/sections/hero.html:104:29": execute of template failed: template: _partials/sections/hero.html:104:29: executing "_partials/sections/hero.html" at : can't evaluate field Data in type interface {} +Error: error building site: render: failed to render pages: …` + want := `render of "content/partners.md": template: _partials/sections/hero.html:104:29: executing "_partials/sections/hero.html" at : can't evaluate field Data in type interface {}` + if got := hugoError(out); got != want { + t.Errorf("got %s\nwant %s", got, want) + } + if got := hugoError("Error: config not found"); got != "config not found" { + t.Errorf("Error: line: %s", got) + } + if got := hugoError(""); !strings.Contains(got, "no message") { + t.Errorf("empty: %s", got) + } +} diff --git a/internal/sites/preview.go b/internal/sites/preview.go new file mode 100644 index 0000000..27b9d49 --- /dev/null +++ b/internal/sites/preview.go @@ -0,0 +1,98 @@ +package sites + +import ( + "io/fs" + "os" + "path/filepath" + "regexp" + "strconv" + "strings" + "time" +) + +// Preview is a built copy of one branch of a site. +type Preview struct { + Branch string `json:"branch"` + Slug string `json:"slug"` // its part of the preview's address + Commit string `json:"commit"` // what was built + At time.Time `json:"at"` + Err string `json:"error,omitempty"` +} + +var nonSlug = regexp.MustCompile(`[^a-z0-9]+`) + +// Slug names a branch in a preview's address: lower case letters, digits +// and hyphens, different from the slugs already taken by other branches. +func Slug(branch string, taken []Preview) string { + base := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(branch), "-"), "-") + if base == "" { + base = "branch" + } + slug := base + for n := 2; ; n++ { + clash := false + for _, p := range taken { + if p.Slug == slug && p.Branch != branch { + clash = true + } + } + if !clash { + return slug + } + slug = base + "-" + strconv.Itoa(n) + } +} + +var ( + attrURL = regexp.MustCompile(`(\s(?:href|src|action|poster|data-src)=["']?)/([^/]|["'\s>]|$)`) + srcsetRe = regexp.MustCompile(`(\ssrcset=)(["'])([^"']*)(["'])`) + refreshRe = regexp.MustCompile(`(?i)(content=["']?\d+\s*;\s*url=)/([^/])`) + cssURL = regexp.MustCompile(`(url\(\s*["']?)/([^/])`) +) + +// Rehome rewrites a site built for "/" to be served under prefix +// ("/preview/0/main/"): every address that starts at the site's root, in +// HTML attributes, srcsets, redirects and CSS, gets the prefix. Addresses +// to other sites are left alone. +func Rehome(dir, prefix string) error { + prefix = "/" + strings.Trim(prefix, "/") + "/" + return filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error { + if err != nil || d.IsDir() { + return err + } + ext := strings.ToLower(filepath.Ext(p)) + if ext != ".html" && ext != ".htm" && ext != ".css" { + return nil + } + raw, err := os.ReadFile(p) + if err != nil { + return err + } + s := RehomeText(string(raw), prefix, ext == ".css") + if s == string(raw) { + return nil + } + return os.WriteFile(p, []byte(s), 0o644) + }) +} + +// RehomeText does Rehome's rewriting on one file's text. +func RehomeText(s, prefix string, css bool) string { + s = cssURL.ReplaceAllString(s, "${1}"+prefix+"${2}") + if css { + return s + } + s = attrURL.ReplaceAllString(s, "${1}"+prefix+"${2}") + s = refreshRe.ReplaceAllString(s, "${1}"+prefix+"${2}") + return srcsetRe.ReplaceAllStringFunc(s, func(m string) string { + g := srcsetRe.FindStringSubmatch(m) + parts := strings.Split(g[3], ",") + for i, c := range parts { + t := strings.TrimLeft(c, " \t\n") + if strings.HasPrefix(t, "/") && !strings.HasPrefix(t, "//") { + parts[i] = c[:len(c)-len(t)] + prefix + t[1:] + } + } + return g[1] + g[2] + strings.Join(parts, ",") + g[4] + }) +} diff --git a/internal/sites/preview_test.go b/internal/sites/preview_test.go new file mode 100644 index 0000000..b93d70a --- /dev/null +++ b/internal/sites/preview_test.go @@ -0,0 +1,40 @@ +package sites + +import "testing" + +func TestRehomeText(t *testing.T) { + const p = "/preview/0/main/" + for in, want := range map[string]string{ + ``: ``, + ``: ``, + ``: ``, + ``: ``, + ``: ``, + ``: ``, + ``: ``, + ``: ``, + `
`: `
`, + `
`: ``, + } { + if got := RehomeText(in, p, false); got != want { + t.Errorf("%s\n got %s\nwant %s", in, got, want) + } + } + if got := RehomeText(`a{background:url(/x.png)} `, p, true); got != `a{background:url(/preview/0/main/x.png)} ` { + t.Errorf("css: %s", got) + } +} + +func TestSlug(t *testing.T) { + taken := []Preview{{Branch: "supermarket/page-1", Slug: "supermarket-page-1"}} + for branch, want := range map[string]string{ + "main": "main", + "supermarket/page-1": "supermarket-page-1", + "Supermarket/Page_1": "supermarket-page-1-2", + "///": "branch", + } { + if got := Slug(branch, taken); got != want { + t.Errorf("%q: %q, want %q", branch, got, want) + } + } +} diff --git a/internal/web/server.go b/internal/web/server.go index 1c12c92..e6b1876 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -178,6 +178,13 @@ func (s *Server) Handler() (http.Handler, error) { mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch) mux.HandleFunc("GET /sites", s.sitesPage) mux.HandleFunc("POST /sites/sync", s.sitesSync) + mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage) + mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild) + mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete) + mux.HandleFunc("GET /preview/{site}/{slug}/{path...}", s.previewServe) + mux.HandleFunc("GET /preview/{site}/{slug}", func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently) + }) mux.HandleFunc("GET /seo", s.seoPage) mux.HandleFunc("GET /seo/check", s.seoCheckPage) mux.HandleFunc("GET /seo/engines", s.seoEnginesPage) diff --git a/internal/web/server_test.go b/internal/web/server_test.go index 8cf05ec..6e6ef8e 100644 --- a/internal/web/server_test.go +++ b/internal/web/server_test.go @@ -100,7 +100,7 @@ func TestEveryPageRenders(t *testing.T) { "/settings/ai", "/settings/accounts", "/settings/core", "/static/app.css", "/favicon.ico", "/static/favicon.png", "/static/logo.png", "/static/apple-touch-icon.png", "/search", "/crm", "/search?q=rival", "/search?q=nothing+here", "/static/htmx.min.js", "/healthz", "/content", "/content/1", "/content/1?dismissed=1", "/posts", "/posts?msg=drafted", "/content/scheduled", "/content/published", - "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", + "/prospects", "/prospects?status=accepted", "/prospects?status=rejected", "/prospects/new", "/prospects/suppressed", "/outreach", "/outreach?tab=queued", "/outreach?tab=sent", "/outreach?tab=replied", "/outreach?tab=failed", "/settings/email", "/settings/tracking", "/settings/search", "/seo", "/seo/check", "/seo/report", "/seo/audit", "/seo/changes", "/seo/keywords", "/seo/briefs", "/seo/engines", "/metrics", "/metrics/customers", "/metrics/customers?show=all", "/metrics/spend", "/metrics/clv", "/metrics/clv?view=profit", "/metrics/publish", "/sites", "/sites?site=0", "/sites/previews", "/signals", "/signals?period=30d&channel=email", "/signals/new", "/settings/sources"} { rec := do(h, http.MethodGet, path, nil, nil) if rec.Code != http.StatusOK { diff --git a/internal/web/sites.go b/internal/web/sites.go index 6e661fc..626e799 100644 --- a/internal/web/sites.go +++ b/internal/web/sites.go @@ -2,7 +2,10 @@ package web import ( "context" + "errors" "net/http" + "net/url" + "os" "path/filepath" "strconv" "strings" @@ -153,3 +156,238 @@ func (s *Server) sitesSync(w http.ResponseWriter, r *http.Request) { } 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). +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:; style-src 'self' 'unsafe-inline'; " + + "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), "/") + http.StripPrefix(prefix, http.FileServer(noListing{http.Dir(s.previewDir(cur.Repo, slug))})).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 +} diff --git a/internal/web/sites_test.go b/internal/web/sites_test.go index d2d6ab1..a6d97d0 100644 --- a/internal/web/sites_test.go +++ b/internal/web/sites_test.go @@ -1,13 +1,18 @@ package web import ( + "context" "fmt" "net/http" "net/http/httptest" "net/url" + "os" + "os/exec" + "path/filepath" "strings" "testing" + "supermarket/internal/hugorepo" "supermarket/internal/hugorepo/hugotest" "supermarket/internal/profile" "supermarket/internal/secrets" @@ -64,3 +69,111 @@ func TestSitesPage(t *testing.T) { t.Errorf("after a failed read: %s", body) } } + +func TestSitePreviews(t *testing.T) { + if hugorepo.HugoVersion(context.Background()) == "" { + t.Skip("no hugo") + } + clone := hugotest.Site(t, map[string]string{ + "layouts/_default/single.html": `{{ define "main" }}

{{ .Title }}

Prices{{ .Content }}{{ end }}`, + "static/logo.png": "png", + }) + // A second branch, as a pull request would have. + work := t.TempDir() + for _, args := range [][]string{ + {"clone", "-q", clone, work}, + {"-C", work, "checkout", "-qb", "supermarket/page-1"}, + } { + if out, err := exec.Command("git", args...).CombinedOutput(); err != nil { + t.Fatalf("git %v: %s", args, out) + } + } + os.WriteFile(filepath.Join(work, "content", "new.md"), []byte("---\ntitle: Brand new\ndraft: true\n---\nFresh.\n"), 0o644) + for _, args := range [][]string{ + {"-C", work, "add", "."}, + {"-C", work, "-c", "user.name=T", "-c", "user.email=t@example.com", "commit", "-qm", "Add a page"}, + {"-C", work, "push", "-q", "origin", "supermarket/page-1"}, + } { + if out, err := exec.Command("git", args...).CombinedOutput(); err != nil { + t.Fatalf("git %v: %s", args, out) + } + } + g := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api/v1/repos/Us/site" { + fmt.Fprintf(w, `{"full_name":"Us/site","default_branch":"main","clone_url":%q,"permissions":{"push":true}}`, clone) + return + } + http.NotFound(w, r) + })) + defer g.Close() + s, h := newTestServer(t, nil) + profile.Save(s.DB, &profile.Profile{Name: "Us", Websites: []profile.Website{{URL: "https://us.example/", Repo: "Us/site"}}}) + postForm(h, "/settings/search", url.Values{"gitea_url": {g.URL}, secrets.GiteaToken: {"tok"}}) + + if body := do(h, http.MethodGet, "/sites/previews", nil, nil).Body.String(); !strings.Contains(body, "under Sections and pages first") { + t.Errorf("before reading: %s", body) + } + postForm(h, "/sites/sync", url.Values{"site": {"0"}}) + body := do(h, http.MethodGet, "/sites/previews", nil, nil).Body.String() + if !strings.Contains(body, "main ") || !strings.Contains(body, "supermarket/page-1") || + !strings.Contains(body, "Add a page") || strings.Contains(body, "Open preview") { + t.Errorf("branches: %s", body) + } + if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1/", nil, nil); rec.Code != http.StatusNotFound { + t.Errorf("before building: %d", rec.Code) + } + + rec := postForm(h, "/sites/previews/build", url.Values{"site": {"0"}, "branch": {"supermarket/page-1"}}) + if rec.Code != http.StatusSeeOther { + t.Fatalf("build: %d %s", rec.Code, rec.Body.String()) + } + body = do(h, http.MethodGet, "/sites/previews", nil, nil).Body.String() + if !strings.Contains(body, `href="/preview/0/supermarket-page-1/"`) || strings.Contains(body, "moved on") { + t.Errorf("after building: %s", body) + } + // The draft page is there, its links stay inside the preview, and the + // page is sandboxed. + rec = do(h, http.MethodGet, "/preview/0/supermarket-page-1/new/", nil, nil) + got := rec.Body.String() + if rec.Code != http.StatusOK || !strings.Contains(got, "

Brand new

") || !strings.Contains(got, `href="/preview/0/supermarket-page-1/pricing/"`) || + !strings.Contains(got, `src="/preview/0/supermarket-page-1/logo.png"`) { + t.Errorf("preview page: %d %s", rec.Code, got) + } + if csp := rec.Header().Get("Content-Security-Policy"); !strings.HasPrefix(csp, "sandbox allow-scripts") || strings.Contains(csp, "allow-same-origin") { + t.Errorf("csp: %s", csp) + } + if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1/logo.png", nil, nil); rec.Code != http.StatusOK || rec.Body.String() != "png" { + t.Errorf("static file: %d", rec.Code) + } + if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1", nil, nil); rec.Code != http.StatusMovedPermanently { + t.Errorf("no slash: %d", rec.Code) + } + if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1/../../../app.db", nil, nil); rec.Code == http.StatusOK { + t.Errorf("escaped the preview: %d", rec.Code) + } + // The working copy is back on the published branch. + if _, err := os.Stat(filepath.Join(s.siteDir("Us/site"), "content", "new.md")); err == nil { + t.Error("the working copy was left on the branch") + } + // A post from a preview page (its origin is "null") is refused. + if rec := do(h, http.MethodPost, "/sites/previews/delete", strings.NewReader("site=0&branch=supermarket/page-1"), + map[string]string{"Origin": "null", "Content-Type": "application/x-www-form-urlencoded"}); rec.Code != http.StatusForbidden { + t.Errorf("post from a preview: %d", rec.Code) + } + // The branch moves on: the preview says so. + os.WriteFile(filepath.Join(work, "content", "new.md"), []byte("---\ntitle: Newer\n---\n"), 0o644) + exec.Command("git", "-C", work, "-c", "user.name=T", "-c", "user.email=t@example.com", "commit", "-qam", "Again").Run() + exec.Command("git", "-C", work, "push", "-q", "origin", "supermarket/page-1").Run() + postForm(h, "/sites/sync", url.Values{"site": {"0"}}) + if body := do(h, http.MethodGet, "/sites/previews", nil, nil).Body.String(); !strings.Contains(body, "moved on") { + t.Errorf("stale: %s", body) + } + + postForm(h, "/sites/previews/delete", url.Values{"site": {"0"}, "branch": {"supermarket/page-1"}}) + if rec := do(h, http.MethodGet, "/preview/0/supermarket-page-1/new/", nil, nil); rec.Code != http.StatusNotFound { + t.Errorf("after deleting: %d", rec.Code) + } + if _, err := os.Stat(s.previewDir("Us/site", "supermarket-page-1")); err == nil { + t.Error("the files are still there") + } +} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index 8d88996..05f2085 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -62,6 +62,7 @@ {{if eq .ID "sites"}} {{end}} {{if eq .ID "prospects"}} diff --git a/internal/web/templates/sites-previews.html b/internal/web/templates/sites-previews.html new file mode 100644 index 0000000..84a3b1f --- /dev/null +++ b/internal/web/templates/sites-previews.html @@ -0,0 +1,53 @@ +{{define "content"}}{{with .Data}}{{$d := .}} +

Previews

+

See a branch of your website before it's merged. Supermarket builds the branch with Hugo, drafts included, and serves it here. Your live site isn't touched. Pull requests from Supermarket are branches too, so this is where you check a new page.

+ +{{if not .Sites}} +

Add your website and its Hugo repository under Settings → Profile first.

+{{else}} +{{if gt (len .Sites) 1}}{{end}} +{{if not .Hugo}}

There's no Hugo in Supermarket's image, so previews can't be built.

{{end}} +{{with .Current}}{{$cur := .}} +{{if .Err}} +

{{.URL}}: {{.Err}}. Set it under Settings → Profile.

+{{else if not $d.HasSynced}} +

Read {{.Repo}} under Sections and pages first.

+{{else}} +

Branches of {{.Repo}}, as of the last read {{ago $d.Synced.At}}. Building reads the repository again first, so it builds the branch's latest commit. A preview can't send anything anywhere or change anything in Supermarket, and analytics don't count it.

+
+ + + {{range $d.Rows}} + + + + + + + {{end}} + +
BranchLatest commitPreview
{{.Name}}{{if .Published}} published{{end}}{{.Subject}}
{{ago .At}}
+ {{with .Preview}} + {{if .Commit}}Built {{ago .At}}{{end}} + {{with .Err}}
The last build failed: {{.}}{{end}} + {{else}}None yet{{end}} + {{if .Stale}}
The branch has moved on since.{{end}} +
+
+ {{with .Link}}Open preview ↗{{end}} + + + + + {{if .Preview}} +
+ + +
+ {{end}} +
+
+{{end}} +{{end}} +{{end}} +{{end}}{{end}}