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
+11
View File
@@ -271,6 +271,17 @@ CREATE TABLE teams (
delete_at TEXT NOT NULL DEFAULT '' -- deleting: when its data goes for good
);
ALTER TABLE sessions ADD COLUMN team_id INTEGER NOT NULL DEFAULT 1;
`,
},
// 41
{
Note: "proving a team's domain is theirs (multi-tenant edition)",
Platform: true,
SQLite: `
ALTER TABLE teams ADD COLUMN verify_token TEXT NOT NULL DEFAULT ''; -- what the TXT record or the file must hold
ALTER TABLE teams ADD COLUMN verified_at TEXT NOT NULL DEFAULT ''; -- '' until proved
ALTER TABLE teams ADD COLUMN verified_by TEXT NOT NULL DEFAULT ''; -- dns, file or search-console
CREATE UNIQUE INDEX teams_proved_domain ON teams(domain) WHERE verified_at <> '';
`,
},
}
+77 -5
View File
@@ -28,20 +28,27 @@ type TeamInfo struct {
Status string
Created time.Time
DeleteAt time.Time
VerifyToken string // what proves the domain: a TXT record's or a file's
Verified time.Time // zero until the domain is proved
VerifiedBy string // dns, file or search-console
}
const teamCols = `id, name, domain, status, created_at, delete_at`
// Proved says whether the team proved its domain.
func (t *TeamInfo) Proved() bool { return !t.Verified.IsZero() }
const teamCols = `id, name, domain, status, created_at, delete_at, verify_token, verified_at, verified_by`
func scanTeam(row interface{ Scan(...any) error }) (*TeamInfo, error) {
var t TeamInfo
var created, del string
if err := row.Scan(&t.ID, &t.Name, &t.Domain, &t.Status, &created, &del); err != nil {
var created, del, verified string
if err := row.Scan(&t.ID, &t.Name, &t.Domain, &t.Status, &created, &del, &t.VerifyToken, &verified, &t.VerifiedBy); err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
return nil, err
}
t.Created, t.DeleteAt = parseTS(created), parseTS(del)
t.Created, t.DeleteAt, t.Verified = parseTS(created), parseTS(del), parseTS(verified)
return &t, nil
}
@@ -69,7 +76,7 @@ func ListTeams(d *db.DB) ([]TeamInfo, error) {
// TeamsOf are the teams a user belongs to, by name.
func TeamsOf(d *db.DB, user int64) ([]TeamInfo, error) {
return queryTeams(d, `SELECT t.id, t.name, t.domain, t.status, t.created_at, t.delete_at FROM teams t
return queryTeams(d, `SELECT t.id, t.name, t.domain, t.status, t.created_at, t.delete_at, t.verify_token, t.verified_at, t.verified_by FROM teams t
JOIN memberships m ON m.team_id = t.id WHERE m.user_id = ? ORDER BY t.name COLLATE NOCASE, t.id`, user)
}
@@ -111,3 +118,68 @@ func AgentTeam(d *db.DB, agent int64) (int64, error) {
}
return t, err
}
// ErrDomainTaken is a domain another team has proved.
var ErrDomainTaken = errors.New("another team has proved this domain is theirs")
// VerifyToken is the team's token for proving its domain, made the first
// time it's asked for.
func VerifyToken(d *db.DB, team int64) (string, error) {
t, err := GetTeam(d, team)
if err != nil {
return "", err
}
if t.VerifyToken != "" {
return t.VerifyToken, nil
}
tok, err := NewToken()
if err != nil {
return "", err
}
tok = "supermarket-verify=" + tok[:32]
_, err = d.Exec(`UPDATE teams SET verify_token = ? WHERE id = ? AND verify_token = ''`, tok, team)
if err != nil {
return "", err
}
t, err = GetTeam(d, team)
if err != nil {
return "", err
}
return t.VerifyToken, nil
}
// DomainHolder is the team that proved a domain, or 0.
func DomainHolder(d *db.DB, domain string) (int64, error) {
var id int64
err := d.QueryRow(`SELECT id FROM teams WHERE domain = ? AND verified_at <> ''`, strings.ToLower(domain)).Scan(&id)
if errors.Is(err, sql.ErrNoRows) {
return 0, nil
}
return id, err
}
// Prove records that a team proved its domain; another team's proof of
// the same domain stands in the way.
func Prove(d *db.DB, team int64, method string, now time.Time) error {
t, err := GetTeam(d, team)
if err != nil {
return err
}
if holder, err := DomainHolder(d, t.Domain); err != nil {
return err
} else if holder != 0 && holder != team {
return ErrDomainTaken
}
_, err = d.Exec(`UPDATE teams SET verified_at = ?, verified_by = ? WHERE id = ?`, ts(now), method, team)
if err != nil && strings.Contains(strings.ToLower(err.Error()), "unique") {
return ErrDomainTaken
}
return err
}
// ReleaseDomain forgets a team's proof (the platform's admin, or the team
// leaving it).
func ReleaseDomain(d *db.DB, team int64) error {
_, err := d.Exec(`UPDATE teams SET verified_at = '', verified_by = '' WHERE id = ?`, team)
return err
}
+1 -1
View File
@@ -144,7 +144,7 @@ func (rt *routes) Handle(pattern string, h http.Handler) {
rt.unmapped = append(rt.unmapped, pattern)
return
}
rt.mux.Handle(pattern, rt.s.allow(area, rt.s.audited(pattern, h)))
rt.mux.Handle(pattern, rt.s.allow(area, rt.s.guardDomain(pattern, rt.s.audited(pattern, h))))
}
func (rt *routes) err() error {
+1 -1
View File
@@ -180,7 +180,7 @@ var actionLabels = map[string]string{
"key-made": "made a new key for", "key-revoked": "revoked a key of",
"asked-approval": "asked for approval to", "did-on-its-own": "did on its own:", "approved": "approved", "refused": "refused",
"allowed-on-its-own": "let an agent act on its own:", "withdrew-on-its-own": "took back what an agent may do on its own:",
"team-created": "set up the team", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of",
"team-created": "set up the team", "domain-proved": "proved the domain", "agent-paused": "paused the agent", "agent-resumed": "resumed the agent", "agent-limits": "changed the limits of",
"wrote-draft": "wrote a draft:", "edited-draft": "edited a draft:", "edited-change": "edited a proposed change to", "market-added": "added to the Market", "market-changed": "changed in the Market",
}
+3
View File
@@ -185,6 +185,9 @@ func (s *Server) carryOut(ctx context.Context, r *approvals.Request, as *viewer)
}
return "added to the mailing list", nil
case "seo-change":
if !s.domainProved() {
return "", errors.New("the team hasn't proved its domain yet (Settings → Domain)")
}
if s.gitea() == nil {
return "", errors.New("Gitea isn't connected (Settings → Search engines)")
}
+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)
}
+4
View File
@@ -452,6 +452,8 @@ func (s *Server) Handler() (http.Handler, error) {
mux.HandleFunc("POST /settings/backups/upload", (*Server).backupUpload)
mux.HandleFunc("GET /settings/about", (*Server).aboutPage)
mux.HandleFunc("GET /settings/connections", (*Server).connectionsPage)
mux.HandleFunc("GET /settings/domain", (*Server).domainPage)
mux.HandleFunc("POST /settings/domain/check/{method}", (*Server).domainCheck)
mux.HandleFunc("GET /settings/activity", (*Server).activityPage)
mux.HandleFunc("GET /api/v1/docs", (*Server).apiDocs)
mux.HandleFunc("GET /api/v1/tools", (*Server).apiTools)
@@ -835,6 +837,8 @@ var flashes = map[string]string{
"agent-resumed": "Resumed.",
"team-created": "Your team is set up. Start with the company's profile.",
"added": "Added: they're told by email, and sign in as they do.",
"prove-first": "First prove the team's domain is yours: Supermarket only crawls, reads or publishes to a website its team has proved.",
"domain-proved": "Proved: the domain is the team's.",
"account-removed": "Signed out: posts scheduled to it are back in Posts.",
"own-account-connected": "Connected: you can post as it, and an admin can let others.",
"deleted": "Deleted.",
+72
View File
@@ -1,7 +1,11 @@
package web
import (
"context"
"errors"
"net"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
@@ -248,3 +252,71 @@ func newTeamOwnerCookie(t *testing.T, s *Server, team int64) (*users.User, int64
t.Fatal("no owner")
return nil, 0, nil
}
func TestProvingTheDomain(t *testing.T) {
s, h := newMultiEdition(t)
a, _, ac := newTeam(t, s, "Acme", "olu@acme.example")
// Before the proof, what touches the site waits.
rec := as(h, ac, http.MethodPost, "/seo/audit?site=0", url.Values{})
if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/settings/domain?msg=prove-first" {
t.Errorf("audit before the proof: %d %s", rec.Code, rec.Header().Get("Location"))
}
body := as(h, ac, http.MethodGet, "/settings/domain", nil).Body.String()
team, _ := users.GetTeam(s.platform(), a.ID)
if team.VerifyToken == "" || !strings.Contains(body, team.VerifyToken) || !strings.Contains(body, "acme.example") {
t.Fatalf("domain page: %s", body)
}
// DNS: wrong, then right.
records := []string{"v=spf1 -all"}
lookupTXT = func(_ context.Context, name string) ([]string, error) {
if name != "acme.example" {
return nil, errors.New("nxdomain")
}
return records, nil
}
defer func() { lookupTXT = net.DefaultResolver.LookupTXT }()
if rec := as(h, ac, http.MethodPost, "/settings/domain/check/dns", url.Values{}); rec.Code != http.StatusUnprocessableEntity {
t.Errorf("no record: %d", rec.Code)
}
records = append(records, team.VerifyToken)
if rec := as(h, ac, http.MethodPost, "/settings/domain/check/dns", url.Values{}); rec.Code != http.StatusSeeOther {
t.Fatalf("record: %d %s", rec.Code, rec.Body.String())
}
if tm, _ := users.GetTeam(s.platform(), a.ID); !tm.Proved() || tm.VerifiedBy != "dns" {
t.Errorf("not proved: %+v", tm)
}
if rec := as(h, ac, http.MethodPost, "/seo/audit?site=0", url.Values{}); rec.Header().Get("Location") == "/settings/domain?msg=prove-first" {
t.Error("still waiting after the proof")
}
// Another team on the same domain can't prove it while Acme holds it,
// even with the file in place.
other, _ := users.CreateTeam(s.platform(), "Impostor", "acme.example", time.Now())
s.Teams.Create(other.ID)
imp := &users.User{Email: "eve@evil.example", Status: users.Active}
users.Create(s.platform(), imp, time.Now())
users.Join(s.platform(), other.ID, imp.ID, users.Owner, nil, time.Now())
tok, _, _ := users.StartSessionIn(s.platform(), imp.ID, other.ID, "", "", time.Now())
ic := &http.Cookie{Name: sessionCookie, Value: tok}
otherTok, _ := users.VerifyToken(s.platform(), other.ID)
site := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == verifyPath {
w.Write([]byte(otherTok + "\n"))
return
}
http.NotFound(w, r)
}))
defer site.Close()
fileBase = func(string) string { return site.URL }
defer func() { fileBase = func(host string) string { return "https://" + host } }()
rec = as(h, ic, http.MethodPost, "/settings/domain/check/file", url.Values{})
if rec.Code != http.StatusConflict || !strings.Contains(rec.Body.String(), "Another team") {
t.Errorf("second team: %d %s", rec.Code, rec.Body.String())
}
// Released, the file proves it.
users.ReleaseDomain(s.platform(), a.ID)
if rec := as(h, ic, http.MethodPost, "/settings/domain/check/file", url.Values{}); rec.Code != http.StatusSeeOther {
t.Errorf("file: %d %s", rec.Code, rec.Body.String())
}
}
+27
View File
@@ -0,0 +1,27 @@
{{define "content"}}{{template "settings-start" .}}{{with .Data}}
<h2>Domain</h2>
<p class="lede">This team works on <strong>{{.Team.Domain}}</strong> and its subdomains. Before Supermarket crawls the website, reads its Search Console data or publishes to it, prove the domain is yours, one of three ways.</p>
{{with .Problem}}<p class="error" role="alert">{{.}}</p>{{end}}
{{if .Team.Proved}}
<section class="card"><p><span class="pill ok">Proved</span> {{ago .Team.Verified}}, {{if eq .Team.VerifiedBy "dns"}}by a DNS record{{else if eq .Team.VerifiedBy "file"}}by a file on the site{{else}}through Search Console{{end}}. You can remove the record or the file now.</p></section>
{{else}}
{{if .Holder}}<p class="warn-text">Another team has proved {{.Team.Domain}}. If it's yours, ask the platform's admins to release it.</p>{{end}}
<section class="card">
<h3>1. A DNS record</h3>
<p>Add a <strong>TXT</strong> record to <code>{{.Team.Domain}}</code> holding:</p>
<pre id="txt">{{.Token}}</pre> <button type="button" class="secondary small" data-copy="txt">Copy</button>
<form method="post" action="/settings/domain/check/dns"><button type="submit">Check the record</button></form>
</section>
<section class="card">
<h3>2. A file on the website</h3>
<p>Publish <code>https://{{.Team.Domain}}{{.Path}}</code> (or on <code>www.</code>) holding the same line:</p>
<pre>{{.Token}}</pre>
<form method="post" action="/settings/domain/check/file"><button type="submit">Check the file</button></form>
</section>
<section class="card">
<h3>3. Search Console</h3>
<p>If the Google account connected under <a href="/settings/search">Settings → Search engines</a> is an <em>owner</em> of the domain's property in Search Console, that's proof enough.</p>
<form method="post" action="/settings/domain/check/search-console"><button type="submit">Check Search Console</button></form>
</section>
{{end}}
{{end}}{{template "settings-end"}}{{end}}
+1
View File
@@ -151,6 +151,7 @@
{{if $.Can "admin"}}
<div class="nav-label">Company</div>
<a href="/settings/profile" {{if eq .Nav "settings/profile"}}aria-current="page"{{end}}>{{template "icon" "profile"}}Profile</a>
{{if $.Multi}}<a href="/settings/domain" {{if eq .Nav "settings/domain"}}aria-current="page"{{end}}>{{template "icon" "sites"}}Domain</a>{{end}}
<div class="nav-label">Connections</div>
<a href="/settings/connections" {{if eq .Nav "settings/connections"}}aria-current="page"{{end}}>{{template "icon" "core"}}All connections</a>
<a href="/settings/agents" {{if eq .Nav "settings/agents"}}aria-current="page"{{end}}>{{template "icon" "ai"}}Agents</a>