From 47cc8b2b10f2fc492aac947555f38a222556d19a Mon Sep 17 00:00:00 2001 From: David Young Date: Wed, 25 Nov 2026 12:21:42 -0700 Subject: [PATCH] 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 --- PLAN.md | 19 ++- internal/db/migrations.go | 11 ++ internal/users/teams.go | 82 ++++++++++- internal/web/access.go | 2 +- internal/web/activity.go | 2 +- internal/web/approvals.go | 3 + internal/web/domain.go | 229 +++++++++++++++++++++++++++++ internal/web/server.go | 4 + internal/web/teams_test.go | 72 +++++++++ internal/web/templates/domain.html | 27 ++++ internal/web/templates/layout.html | 1 + 11 files changed, 444 insertions(+), 8 deletions(-) create mode 100644 internal/web/domain.go create mode 100644 internal/web/templates/domain.html diff --git a/PLAN.md b/PLAN.md index 8aa9b77..18cd4cc 100644 --- a/PLAN.md +++ b/PLAN.md @@ -55,7 +55,7 @@ tools over MCP, approvals, limits and visibility, and the JSON API. Schema 39. **Phase 13 (multi-tenant) is under way** on branch `phase13`, with a -Postgres schema per team (decided 2026-11-26); parts 1–3 are built. +Postgres schema per team (decided 2026-11-26); parts 1–4 are built. **Phase 12 (signing in with the Core, OIDC) is set aside for now** (2026-11-26): before it starts, the user will share the Federated Core's @@ -2848,6 +2848,23 @@ stand. - Not yet: an email address confirmed at sign-up. Domain proof (part 4) keeps an unconfirmed team from doing anything with a website. +**Part 4 built 2026-11-26** on `phase13`. +- Schema 41 (the platform's): each team's `verify_token` + (`supermarket-verify=…`), when it proved its domain and how; a unique + index on a proved domain, so one team holds it at a time. +- Settings → Domain (admins, multi-tenant only): the three ways, each with + a *Check* button: a TXT record on the domain; the file + `/.well-known/supermarket-verification.txt` on the domain or its `www.` + (3 redirects at most, the first 4 KB read); or the connected Google + account being an owner of the domain's Search Console property (a domain + property, or a site on the domain). Another team's proof stands in the + way, until it's released (the platform's admins, part 7). +- Until it's proved, the routes that crawl the site, read its Search + Console data or publish to it (an audit, a sync, a new site, adding + pages, the theme, the search-engine setup, IndexNow, SEO changes and + briefs' pull requests) send the admin to Settings → Domain; an agent's + SEO change is refused too. Background jobs are part 5. + 1. **Teams everywhere.** - Every table that holds a company's data gets `team_id`, and its unique keys include it. The settings table's key becomes diff --git a/internal/db/migrations.go b/internal/db/migrations.go index a7da0b5..f70c755 100644 --- a/internal/db/migrations.go +++ b/internal/db/migrations.go @@ -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 <> ''; `, }, } diff --git a/internal/users/teams.go b/internal/users/teams.go index 6140c09..dca4817 100644 --- a/internal/users/teams.go +++ b/internal/users/teams.go @@ -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 +} diff --git a/internal/web/access.go b/internal/web/access.go index bad74c3..400f623 100644 --- a/internal/web/access.go +++ b/internal/web/access.go @@ -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 { diff --git a/internal/web/activity.go b/internal/web/activity.go index 428d01b..87e84f3 100644 --- a/internal/web/activity.go +++ b/internal/web/activity.go @@ -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", } diff --git a/internal/web/approvals.go b/internal/web/approvals.go index 05c49c8..46341c2 100644 --- a/internal/web/approvals.go +++ b/internal/web/approvals.go @@ -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)") } diff --git a/internal/web/domain.go b/internal/web/domain.go new file mode 100644 index 0000000..96daf4f --- /dev/null +++ b/internal/web/domain.go @@ -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) +} diff --git a/internal/web/server.go b/internal/web/server.go index 3be6570..5e5abc2 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -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.", diff --git a/internal/web/teams_test.go b/internal/web/teams_test.go index 25a6ae0..b1dd89b 100644 --- a/internal/web/teams_test.go +++ b/internal/web/teams_test.go @@ -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()) + } +} diff --git a/internal/web/templates/domain.html b/internal/web/templates/domain.html new file mode 100644 index 0000000..4951c70 --- /dev/null +++ b/internal/web/templates/domain.html @@ -0,0 +1,27 @@ +{{define "content"}}{{template "settings-start" .}}{{with .Data}} +

Domain

+

This team works on {{.Team.Domain}} 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.

+{{with .Problem}}{{end}} +{{if .Team.Proved}} +

Proved {{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.

+{{else}} +{{if .Holder}}

Another team has proved {{.Team.Domain}}. If it's yours, ask the platform's admins to release it.

{{end}} +
+

1. A DNS record

+

Add a TXT record to {{.Team.Domain}} holding:

+
{{.Token}}
+
+
+
+

2. A file on the website

+

Publish https://{{.Team.Domain}}{{.Path}} (or on www.) holding the same line:

+
{{.Token}}
+
+
+
+

3. Search Console

+

If the Google account connected under Settings → Search engines is an owner of the domain's property in Search Console, that's proof enough.

+
+
+{{end}} +{{end}}{{template "settings-end"}}{{end}} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html index d4f4793..4b5d9c4 100644 --- a/internal/web/templates/layout.html +++ b/internal/web/templates/layout.html @@ -151,6 +151,7 @@ {{if $.Can "admin"}} {{template "icon" "profile"}}Profile + {{if $.Multi}}{{template "icon" "sites"}}Domain{{end}} {{template "icon" "core"}}All connections {{template "icon" "ai"}}Agents