feat(seo): metadata, previews and sitemaps for status pages and the app
ci / lint (push) Skipped
ci / test (push) Skipped
ci / build (push) Skipped
ci / image (push) Skipped
ci / lint (pull_request) Successful in 6m23s
ci / test (pull_request) Successful in 12m44s
ci / build (pull_request) Successful in 16m9s
ci / image (pull_request) Successful in 3m24s

Status pages describe themselves to search engines and link previews:
description (from the page's text, else its status), canonical address,
language versions via ?lang= with hreflang and x-default, Open Graph and
Twitter tags, and a 1200x630 preview image per page and language showing
its name and current status (/og.png). Each page has a sitemap.xml, and
robots.txt keeps crawlers off feeds, the API and subscription forms.
Component, legal and subscription pages are noindex.

In the cloud edition the app's sign-in, sign-up and legal pages get the
same tags with a preview image of their own, plus robots.txt and a
sitemap. Everything signed in stays noindex, and self-hosted
installations keep the whole app out of search engines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-28 22:50:34 +01:00
1 parent 918c71f283
commit 3baeb98ee2
23 files changed
+1546 -129

No files matched your search

+143
View File
@@ -0,0 +1,143 @@
package statuspage
import (
"image/color"
"net/http"
"strings"
"sync"
"time"
"github.com/gin-gonic/gin"
"git.zb-server.de/ZB-Server/uptimesebi/internal/agentapi"
"git.zb-server.de/ZB-Server/uptimesebi/internal/i18n"
"git.zb-server.de/ZB-Server/uptimesebi/internal/ogimage"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// maxDescription bounds a page's description, about what search results
// show.
const maxDescription = 160
// origin is the scheme and host the visitor reached the server at.
func origin(c *gin.Context) string {
scheme := "http"
if c.Request.TLS != nil || strings.EqualFold(c.GetHeader("X-Forwarded-Proto"), "https") {
scheme = "https"
}
return scheme + "://" + c.Request.Host
}
var statusAccent = map[string]color.Color{
agentapi.PageOperational: ogimage.Up,
agentapi.PageDegraded: ogimage.Degraded,
agentapi.PageOutage: ogimage.Down,
agentapi.PageUnderMaintenance: ogimage.Maintenance,
agentapi.PageUnknown: ogimage.Unknown,
}
// pageMeta describes the status page at base for search engines and link
// previews, in the language the request was localized to.
func (s *Server) pageMeta(c *gin.Context, snap agentapi.PageSnapshot, base string) *web.PageMeta {
ctx := c.Request.Context()
lang := i18n.Lang(ctx)
desc := web.PlainText(snap.Description, maxDescription)
if desc == "" {
desc = i18n.T(ctx, "page.meta_description", "Title", snap.Title, "Status", i18n.T(ctx, "page.status."+snap.Status))
}
abs := origin(c) + base
image := web.LangURL(abs+"og.png", lang)
_, chosen := c.GetQuery("lang")
return web.NewPageMeta(snap.Title, desc, abs, image, snap.Title, lang, chosen && s.catalog.IsSupported(c.Query("lang")), s.catalog.Supported())
}
// ogCache keeps each page's preview image until its title, status or
// language changes.
type ogCache struct {
mu sync.Mutex
images map[string]ogEntry
}
type ogEntry struct {
sig string
png []byte
}
// serveOG draws the page's preview image: its name and current status.
func (s *Server) serveOG(c *gin.Context, e entry, base string) {
s.localizeRequest(c)
ctx := c.Request.Context()
snap := e.Snap.WithMaintenance(s.now())
card := ogimage.Card{
Title: snap.Title,
Subtitle: i18n.T(ctx, "page.status."+snap.Status),
Footer: strings.TrimSuffix(c.Request.Host+base, "/"),
Accent: statusAccent[snap.Status],
}
sig := strings.Join([]string{card.Title, card.Subtitle, card.Footer, snap.Status}, "\x00")
key := e.Key + "\x00" + i18n.Lang(ctx)
s.og.mu.Lock()
cached, ok := s.og.images[key]
s.og.mu.Unlock()
if !ok || cached.sig != sig {
png, err := ogimage.Render(card)
if err != nil {
s.log.Warn("drawing preview image failed", "page", e.Key, "error", err)
c.Status(http.StatusInternalServerError)
return
}
cached = ogEntry{sig: sig, png: png}
s.og.mu.Lock()
if s.og.images == nil {
s.og.images = map[string]ogEntry{}
}
s.og.images[key] = cached
s.og.mu.Unlock()
}
c.Header("Cache-Control", "public, max-age=300")
c.Data(http.StatusOK, "image/png", cached.png)
}
func (s *Server) forgetOG(key string) {
s.og.mu.Lock()
defer s.og.mu.Unlock()
for k := range s.og.images {
if strings.HasPrefix(k, key+"\x00") {
delete(s.og.images, k)
}
}
}
func (s *Server) serveSitemap(c *gin.Context, base string) {
// No lastmod: a snapshot is regenerated every minute, which says
// nothing about whether the page changed.
body, err := web.Sitemap([]string{origin(c) + base}, s.catalog.Supported(), time.Time{})
if err != nil {
c.Status(http.StatusInternalServerError)
return
}
c.Header("Cache-Control", "public, max-age=3600")
c.Data(http.StatusOK, "application/xml; charset=utf-8", body)
}
// serveRobots lets crawlers read the pages but not the feeds, the API or
// the subscription forms. A custom domain serves one page, so its sitemap
// can be named; the shared hosts serve many under their slugs.
func (s *Server) serveRobots(c *gin.Context) {
var b strings.Builder
b.WriteString("User-agent: *\n")
prefix := "/*"
custom := s.IsCustomDomain(hostOnly(c.Request.Host))
if custom {
prefix = ""
}
for _, p := range []string{"/api/", "/subscribe", "/unsubscribe", "/feed.rss"} {
b.WriteString("Disallow: " + prefix + p + "\n")
}
b.WriteString("Allow: /\n")
if custom {
b.WriteString("\nSitemap: " + origin(c) + "/sitemap.xml\n")
}
c.Header("Cache-Control", "public, max-age=3600")
c.Data(http.StatusOK, "text/plain; charset=utf-8", []byte(b.String()))
}
+6
View File
@@ -34,6 +34,8 @@ const (
routeSubscribe
routeConfirm
routeUnsubscribe
routeOG
routeSitemap
)
// posts reports whether the route takes form posts.
@@ -63,6 +65,10 @@ func routeOf(parts []string) (route, bool) {
return route{kind: routeConfirm}, true
case len(parts) == 1 && parts[0] == "unsubscribe":
return route{kind: routeUnsubscribe}, true
case len(parts) == 1 && parts[0] == "og.png":
return route{kind: routeOG}, true
case len(parts) == 1 && parts[0] == "sitemap.xml":
return route{kind: routeSitemap}, true
case len(parts) == 3 && parts[0] == "api" && parts[1] == "v1" && apiResources[parts[2]]:
return route{kind: routeAPI, arg: parts[2]}, true
case len(parts) == 1 && parts[0] != "" && parts[0] != "api":
+26 -5
View File
@@ -73,6 +73,8 @@ type Server struct {
src Source
catalog *i18n.Catalog
log *slog.Logger
// og keeps the pages' preview images.
og ogCache
// ownHosts are the hosts that serve pages by slug; any other host is
// looked up as a custom domain.
ownHosts map[string]bool
@@ -221,6 +223,7 @@ func (s *Server) persist(e entry) {
}
func (s *Server) forget(key string) {
s.forgetOG(key)
s.mu.Lock()
delete(s.cache, key)
delete(s.visited, key)
@@ -261,6 +264,10 @@ func hostOnly(h string) string {
}
func (s *Server) serve(c *gin.Context) {
if c.Request.URL.Path == "/robots.txt" && (c.Request.Method == http.MethodGet || c.Request.Method == http.MethodHead) {
s.serveRobots(c)
return
}
host := hostOnly(c.Request.Host)
var parts []string
if trimmed := strings.Trim(c.Request.URL.Path, "/"); trimmed != "" {
@@ -295,16 +302,23 @@ func (s *Server) serve(c *gin.Context) {
}
e, ok := s.lookup(c.Request.Context(), key, host, slug)
if !ok {
if rt.kind == routeFeed || rt.kind == routeAPI {
if rt.kind == routeFeed || rt.kind == routeAPI || rt.kind == routeOG || rt.kind == routeSitemap {
c.Status(http.StatusNotFound)
} else {
s.notFound(c)
}
return
}
if rt.kind == routeLegal {
switch rt.kind {
case routeLegal:
s.serveLegal(c, e, rt.arg, base)
return
case routeOG:
s.serveOG(c, e, base)
return
case routeSitemap:
s.serveSitemap(c, base)
return
}
var staleSince time.Time
if s.now().Sub(e.Fetched) > staleNoticeAfter {
@@ -319,6 +333,7 @@ func (s *Server) serve(c *gin.Context) {
}
switch rt.kind {
case routeComponent:
assets.NoIndex = true
s.serveComponent(c, e, rt.arg, assets)
return
case routeFeed:
@@ -328,6 +343,7 @@ func (s *Server) serve(c *gin.Context) {
s.serveAPI(c, e, rt.arg, base)
return
case routeSubscribe, routeConfirm, routeUnsubscribe:
assets.NoIndex = true
s.serveSubscription(c, e, rt.kind, host, slug, base, assets)
return
}
@@ -339,7 +355,9 @@ func (s *Server) serve(c *gin.Context) {
assets.Query = q
}
assets.OnlyProblems = c.Query("problems") == "1"
web.Render(c, http.StatusOK, web.PublicStatusPage(e.Snap.WithMaintenance(s.now()), assets))
snap := e.Snap.WithMaintenance(s.now())
assets.Meta = s.pageMeta(c, snap, base)
web.Render(c, http.StatusOK, web.PublicStatusPage(snap, assets))
}
// componentsPerPage is how many of its own components a section of a
@@ -403,14 +421,17 @@ func (s *Server) serveLegal(c *gin.Context, e entry, kind, base string) {
}
s.localizeRequest(c)
c.Header("Cache-Control", "public, max-age=300")
web.Render(c, http.StatusOK, web.PublicLegalPage(e.Snap, web.PublicAssets{CSSHref: "/static/dist/app.css"}, kind, html, base))
web.Render(c, http.StatusOK, web.PublicLegalPage(e.Snap, web.PublicAssets{CSSHref: "/static/dist/app.css", NoIndex: true}, kind, html, base))
}
}
// localizeRequest shows the language ?lang= names, else the visitor's
// preferred one; each language has its own address for search engines.
func (s *Server) localizeRequest(c *gin.Context) {
l := s.catalog.Match(c.GetHeader("Accept-Language"))
l := s.catalog.Match(c.Query("lang"), c.GetHeader("Accept-Language"))
c.Request = c.Request.WithContext(i18n.NewContext(c.Request.Context(), l))
c.Header("Content-Language", l.Lang())
c.Writer.Header().Add("Vary", "Accept-Language")
}
// lookup answers from the cache whenever possible and refreshes in the
+86
View File
@@ -1,6 +1,7 @@
package statuspage
import (
"bytes"
"context"
"errors"
"fmt"
@@ -690,3 +691,88 @@ func TestComponentPagingAndSearch(t *testing.T) {
t.Errorf("component page lacks the bar tooltips")
}
}
func (h harness) getFull(host, path string) *httptest.ResponseRecorder {
req := httptest.NewRequest(http.MethodGet, path, nil)
req.Host = host
req.Header.Set("Accept-Language", "de")
w := httptest.NewRecorder()
h.r.ServeHTTP(w, req)
return w
}
func TestSearchAndPreviewMetadata(t *testing.T) {
now := time.Now()
src := newSource()
src.set(func(f *fakeSource) {
p := f.pages["|acme"]
p.Description = "Status of **Acme** services.\n\nSecond paragraph."
p.ShowDetails = true
p.Sections = []agentapi.Section{{Components: []agentapi.Component{{ID: "c1", Name: "API", Status: agentapi.PageOperational}}}}
f.pages["|acme"] = p
})
h := newHarness(t, src, t.TempDir(), &now)
_, body := h.get("status.example.test", "/acme")
for _, want := range []string{
`<meta name="description" content="Status of Acme services. Second paragraph.">`,
`<link rel="canonical" href="http://status.example.test/acme/">`,
`<link rel="alternate" hreflang="en" href="http://status.example.test/acme/?lang=en">`,
`<link rel="alternate" hreflang="x-default" href="http://status.example.test/acme/">`,
`<meta property="og:title" content="Acme status">`,
`<meta property="og:image" content="http://status.example.test/acme/og.png?lang=de">`,
`<meta property="og:locale" content="de_DE">`,
`<meta name="twitter:card" content="summary_large_image">`,
} {
if !strings.Contains(body, want) {
t.Errorf("status page lacks %s", want)
}
}
if strings.Contains(body, "noindex") {
t.Errorf("status page is noindex")
}
// ?lang= picks the language and becomes the canonical address.
_, body = h.get("status.example.test", "/acme?lang=en&q=api")
if !strings.Contains(body, "All systems operational") || !strings.Contains(body, `<link rel="canonical" href="http://status.example.test/acme/?lang=en">`) {
t.Errorf("?lang=en does not show English with its own canonical address")
}
// A page without a description describes itself by its status.
_, body = h.get("status.acme.test", "/")
if !strings.Contains(body, `<meta name="description" content="Aktueller Status von Acme on own domain: Größere Störung. Störungen`) {
t.Errorf("custom domain page lacks the generated description")
}
if !strings.Contains(body, `<link rel="canonical" href="http://status.acme.test/">`) {
t.Errorf("custom domain canonical address missing")
}
for _, path := range []string{"/acme/components/c1", "/acme/subscribe"} {
if code, body := h.get("status.example.test", path); code == 200 && !strings.Contains(body, `<meta name="robots" content="noindex, nofollow">`) {
t.Errorf("GET %s is indexable", path)
}
}
w := h.getFull("status.example.test", "/acme/og.png")
if w.Code != 200 || w.Header().Get("Content-Type") != "image/png" || !bytes.HasPrefix(w.Body.Bytes(), []byte("\x89PNG")) {
t.Errorf("preview image = %d %s", w.Code, w.Header().Get("Content-Type"))
}
if code, _ := h.get("status.example.test", "/missing/og.png"); code != 404 {
t.Errorf("preview image of a missing page = %d, want 404", code)
}
w = h.getFull("status.acme.test", "/sitemap.xml")
sm := w.Body.String()
if w.Code != 200 || !strings.Contains(sm, "<loc>http://status.acme.test/</loc>") || !strings.Contains(sm, `hreflang="de" href="http://status.acme.test/?lang=de"`) {
t.Errorf("sitemap = %d %s", w.Code, sm)
}
_, robots := h.get("status.acme.test", "/robots.txt")
if !strings.Contains(robots, "Disallow: /api/") || !strings.Contains(robots, "Sitemap: http://status.acme.test/sitemap.xml") {
t.Errorf("custom domain robots.txt = %q", robots)
}
_, robots = h.get("status.example.test", "/robots.txt")
if !strings.Contains(robots, "Disallow: /*/api/") || strings.Contains(robots, "Sitemap:") {
t.Errorf("shared host robots.txt = %q", robots)
}
}