Phase 13, part 4: proving a team's domain

Before Supermarket crawls a team's website, reads its Search Console data
or publishes to it, the team proves the domain is theirs: a DNS TXT
record, a file on the site, or owning its Search Console property. One
team holds a domain at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 12:21:42 -07:00
co-authored by Claude Opus 5.5
parent d5fb1898e8
commit 47cc8b2b10
11 changed files with 444 additions and 8 deletions
+229
View File
@@ -0,0 +1,229 @@
package web
import (
"context"
"errors"
"io"
"net"
"net/http"
"strings"
"time"
"supermarket/internal/users"
)
// Proving a team's domain (the multi-tenant edition). Before Supermarket
// crawls a website, reads its Search Console data or publishes to it, the
// team proves the domain is theirs: a DNS TXT record, a file on the site,
// or a Search Console property its connected Google account owns. One team
// holds a domain at a time; proving it covers its subdomains.
const verifyPath = "/.well-known/supermarket-verification.txt"
// needsDomain are the routes that wait for the proof: they crawl the site,
// read its Search Console data, or publish to it.
var needsDomain = map[string]bool{
"POST /seo/audit": true,
"POST /settings/search/sync": true,
"POST /sites/new": true,
"POST /sites/pages/add": true,
"POST /sites/theme/update": true,
"POST /seo/engines/setup": true,
"POST /seo/engines/ping": true,
"POST /seo/changes/{id}/{action}": true,
"POST /seo/briefs/{id}/{action}": true,
}
// domainProved says whether the team may work on its website: always,
// except on the multi-tenant edition before the proof.
func (s *Server) domainProved() bool {
if !s.multi() {
return true
}
t, err := users.GetTeam(s.platform(), s.team())
return err == nil && t.Proved()
}
// guardDomain wraps a route that needs the proof.
func (s *Server) guardDomain(pattern string, next http.Handler) http.Handler {
if !needsDomain[pattern] {
return next
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
ts, err := s.teamServer(r)
if err == nil && !ts.domainProved() {
if r.Header.Get("HX-Request") != "" {
http.Error(w, "Prove the team's domain first, under Settings → Domain.", http.StatusForbidden)
return
}
redirect(w, r, "/settings/domain", "prove-first")
return
}
next.ServeHTTP(w, r)
})
}
type domainData struct {
Team *users.TeamInfo
Token string
Path string
Problem string
Holder bool // another team holds it
}
func (s *Server) domainPage(w http.ResponseWriter, r *http.Request) {
if !s.multi() {
http.NotFound(w, r)
return
}
if s.admin(w, r) == nil {
return
}
s.renderDomain(w, r, "", http.StatusOK)
}
func (s *Server) renderDomain(w http.ResponseWriter, r *http.Request, problem string, code int) {
t, err := users.GetTeam(s.platform(), s.team())
if err != nil {
s.serverError(w, err)
return
}
tok, err := users.VerifyToken(s.platform(), t.ID)
if err != nil {
s.serverError(w, err)
return
}
d := domainData{Team: t, Token: tok, Path: verifyPath, Problem: problem}
if h, _ := users.DomainHolder(s.platform(), t.Domain); h != 0 && h != t.ID {
d.Holder = true
}
if code != http.StatusOK {
w.WriteHeader(code)
}
s.render(w, r, "domain", page{Title: "Domain", Nav: "settings/domain", Data: d})
}
// domainCheck tries one way of proving it: dns, file or search-console.
func (s *Server) domainCheck(w http.ResponseWriter, r *http.Request) {
if !s.multi() {
http.NotFound(w, r)
return
}
if s.admin(w, r) == nil {
return
}
t, err := users.GetTeam(s.platform(), s.team())
if err != nil {
s.serverError(w, err)
return
}
tok, err := users.VerifyToken(s.platform(), t.ID)
if err != nil {
s.serverError(w, err)
return
}
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
defer cancel()
method := r.PathValue("method")
var why error
switch method {
case "dns":
why = checkDNS(ctx, t.Domain, tok)
case "file":
why = checkFile(ctx, t.Domain, tok)
case "search-console":
why = s.checkSearchConsole(ctx, t.Domain)
default:
http.NotFound(w, r)
return
}
if why != nil {
s.renderDomain(w, r, sentence(why.Error())+".", http.StatusUnprocessableEntity)
return
}
if err := users.Prove(s.platform(), t.ID, method, time.Now()); err != nil {
if errors.Is(err, users.ErrDomainTaken) {
s.renderDomain(w, r, "Another team has proved "+t.Domain+" is theirs. If it's yours, ask the platform's admins to release it.", http.StatusConflict)
return
}
s.serverError(w, err)
return
}
s.audit(r, "domain-proved", t.Domain, "by "+method)
redirect(w, r, "/settings/domain", "domain-proved")
}
// lookupTXT is the resolver's; tests replace it.
var lookupTXT = net.DefaultResolver.LookupTXT
func checkDNS(ctx context.Context, domain, token string) error {
recs, err := lookupTXT(ctx, domain)
if err != nil {
return errors.New("no TXT records were found for " + domain + " (DNS can take a few minutes to show a new one)")
}
for _, r := range recs {
if strings.TrimSpace(r) == token {
return nil
}
}
return errors.New("the TXT records of " + domain + " don't include " + token + " yet (DNS can take a few minutes)")
}
// fileClient fetches the proof file; tests replace it.
var fileClient = &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(req *http.Request, via []*http.Request) error {
if len(via) >= 3 {
return errors.New("too many redirects")
}
return nil
}}
// fileBase is where the proof file is looked for; tests point it elsewhere.
var fileBase = func(host string) string { return "https://" + host }
func checkFile(ctx context.Context, domain, token string) error {
var last error
for _, host := range []string{domain, "www." + domain} {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, fileBase(host)+verifyPath, nil)
if err != nil {
return err
}
resp, err := fileClient.Do(req)
if err != nil {
last = err
continue
}
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
resp.Body.Close()
if resp.StatusCode == http.StatusOK && strings.Contains(string(body), token) {
return nil
}
last = errors.New("https://" + host + verifyPath + " doesn't hold the code")
}
if last == nil {
last = errors.New("the file wasn't found")
}
return last
}
// checkSearchConsole: the team's Google account owns the domain's property
// (a domain property, or the site's address on it).
func (s *Server) checkSearchConsole(ctx context.Context, domain string) error {
c := s.gsc()
if c == nil {
return errors.New("connect Google Search Console first, under Settings → Search engines")
}
sites, err := c.Sites(ctx)
if err != nil {
return err
}
for _, st := range sites {
if st.Permission != "siteOwner" {
continue
}
u := strings.TrimPrefix(st.URL, "sc-domain:")
if u == domain || (strings.Contains(st.URL, "://") && onDomain(st.URL, domain)) {
return nil
}
}
return errors.New("the connected Google account doesn't own a Search Console property for " + domain)
}