carlos / platform Public

console: domain purchase page is a card with a step list

Paul's approved copy (copy review 2026-11-03): one card per purchase
state with a four-step checklist, a celebratory live state with a Visit
button, console tokens for light and dark, a screen-reader status line,
and polling that stops after an hour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from domains-purchase-card into main.
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 0c2ab2ef028cf625e3d49705a4ac09a3231970ea parent 87ef93e
9 files changed, +655 −55
  • approved_domains_buy_copy_test.go +23 −15
  • internal/console/apidomainbuy.go +8 −3
  • internal/console/apidomainbuy_test.go +5 −3
  • internal/console/appdomainbuy.go +65 −1
  • internal/console/domainbuy_card_test.go +311 −0
  • internal/console/domainbuy_copy.go +23 −16
  • internal/console/domainbuy_final_fix_test.go +1 −1
  • internal/console/templates/domain_buy.html +94 −16
  • internal/console/testdata/domainbuy_poll.cjs +125 −0

CI passed — run details

diff --git a/approved_domains_buy_copy_test.go b/approved_domains_buy_copy_test.go
index bb2bc0518..aa04e6571 100644
--- a/approved_domains_buy_copy_test.go
+++ b/approved_domains_buy_copy_test.go
@@ -23,10 +23,8 @@ func TestApprovedDomainsBuyCopy(t *testing.T) {
{"browser.check", "internal/console/domainbuy_copy.go", "Check availability"},
{"browser.quote", "internal/console/domainbuy_copy.go", "Price for one year"},
{"browser.paymentDetails", "internal/console/domainbuy_copy.go", "You will review the final payment details at checkout."},
- {"browser.background", "internal/console/domainbuy_copy.go", "Your purchase will continue in the background. Reload this page to check its progress."},
{"browser.contact", "internal/console/domainbuy_copy.go", "Your contact details"},
{"browser.pay", "internal/console/domainbuy_copy.go", "Continue to checkout"},
- {"browser.back", "internal/console/domainbuy_copy.go", "Back to domains"},
{"browser.contactError", "internal/console/domainbuy_copy.go", "Enter your name, email address, postal address, country code and phone number. Use digits for the phone number and calling code, and two uppercase letters for the country."},
{"browser.nameError", "internal/console/domainbuy_copy.go", "Enter a domain name that can be registered."},
{"browser.unavailable", "internal/console/domainbuy_copy.go", "buying domains is unavailable right now"},
@@ -36,19 +34,6 @@ func TestApprovedDomainsBuyCopy(t *testing.T) {
{"browser.notOffered", "internal/console/domainbuy_copy.go", "This domain ending is not offered."},
{"browser.premium", "internal/console/domainbuy_copy.go", "Premium domains are not offered."},
{"browser.taken", "internal/console/domainbuy_copy.go", "This domain is not available."},
- {"browser.progress", "internal/console/domainbuy_copy.go", "Your domain purchase"},
- {"browser.pollError", "internal/console/domainbuy_copy.go", "We could not check progress. We will try again shortly."},
- {"browser.awaiting_payment", "internal/console/domainbuy_copy.go", "Waiting for payment approval."},
- {"browser.authorised", "internal/console/domainbuy_copy.go", "Payment approved. Preparing your domain."},
- {"browser.zone_ready", "internal/console/domainbuy_copy.go", "Domain settings are ready."},
- {"browser.registering", "internal/console/domainbuy_copy.go", "Registering your domain."},
- {"browser.registered", "internal/console/domainbuy_copy.go", "Your domain is registered. Taking payment now."},
- {"browser.captured", "internal/console/domainbuy_copy.go", "Payment taken. Connecting your domain to your app."},
- {"browser.done", "internal/console/domainbuy_copy.go", "Your domain is connected. Waiting for HTTPS to be ready."},
- {"browser.live", "internal/console/domainbuy_copy.go", "Your domain is live."},
- {"browser.failed", "internal/console/domainbuy_copy.go", "We could not complete the purchase."},
- {"browser.expired", "internal/console/domainbuy_copy.go", "Checkout expired before you completed it. Nothing was charged. Start a new purchase to try again."},
- {"browser.unpaid", "internal/console/domainbuy_copy.go", "Your domain is registered, but the payment did not go through. We will contact you about paying for it."},
{"browser.FirstName", "internal/console/domainbuy_copy.go", "First name"},
{"browser.LastName", "internal/console/domainbuy_copy.go", "Last name"},
{"browser.Company", "internal/console/domainbuy_copy.go", "Company (optional)"},
@@ -124,6 +109,29 @@ func TestApprovedDomainsBuyCopy(t *testing.T) {
{"cli.failedNoReason", "domains_buy_copy.go", "purchase failed. nothing was charged"},
{"cli.expired", "domains_buy_copy.go", "checkout was not completed. nothing was charged"},
{"cli.unpaid", "domains_buy_copy.go", "the domain is registered but the payment did not go through. we will contact you about paying"},
+ // approved by Paul (copy review 2026-11-03)
+ {"browser.progressTitle", "internal/console/domainbuy_copy.go", "Setting up {domain}"},
+ {"browser.progressLede", "internal/console/domainbuy_copy.go", "Payment received, thanks. We're registering your domain and connecting it to {app}. It usually takes a minute or two, and you can leave this page."},
+ {"browser.stepPaid", "internal/console/domainbuy_copy.go", "Payment received"},
+ {"browser.stepRegister", "internal/console/domainbuy_copy.go", "Registering your domain"},
+ {"browser.stepDNS", "internal/console/domainbuy_copy.go", "Pointing it at your app"},
+ {"browser.stepHTTPS", "internal/console/domainbuy_copy.go", "Securing it with HTTPS"},
+ {"browser.cardOwnership", "internal/console/domainbuy_copy.go", "It's registered in your name, so it's yours to keep or take elsewhere."},
+ {"browser.liveTitle", "internal/console/domainbuy_copy.go", "{domain} is live"},
+ {"browser.liveLede", "internal/console/domainbuy_copy.go", "Your new domain is up and running, pointed at {app} and secured with HTTPS. Go and take a look."},
+ {"browser.visit", "internal/console/domainbuy_copy.go", "Visit {domain}"},
+ {"browser.back", "internal/console/domainbuy_copy.go", "Back to domains"},
+ {"browser.awaitingTitle", "internal/console/domainbuy_copy.go", "Almost yours"},
+ {"browser.awaitingLede", "internal/console/domainbuy_copy.go", "Finish paying to claim {domain}. Your checkout stays open for an hour."},
+ {"browser.continuePayment", "internal/console/domainbuy_copy.go", "Continue to payment"},
+ {"browser.slowLede", "internal/console/domainbuy_copy.go", "This is taking a little longer than usual. It will finish on its own, so feel free to leave and check back later."},
+ {"browser.pollError", "internal/console/domainbuy_copy.go", "We can't check on your domain just now. Setup carries on regardless, so try refreshing in a minute."},
+ {"browser.failedTitle", "internal/console/domainbuy_copy.go", "We couldn't register {domain}"},
+ {"browser.failedLede", "internal/console/domainbuy_copy.go", "Nothing was charged, and the hold on your card has been released. You can try another name whenever you like."},
+ {"browser.expiredTitle", "internal/console/domainbuy_copy.go", "Checkout timed out"},
+ {"browser.expiredLede", "internal/console/domainbuy_copy.go", "Nothing was charged. If you still want {domain}, start again and it'll take a minute."},
+ {"browser.unpaidTitle", "internal/console/domainbuy_copy.go", "{domain} is yours, but the payment didn't go through"},
+ {"browser.unpaidLede", "internal/console/domainbuy_copy.go", "Your domain is registered and working. We'll be in touch about paying for it."},
}
for _, row := range rows {
t.Run(row.key, func(t *testing.T) {
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go
index ecbaff283..231e7128e 100644
--- a/internal/console/apidomainbuy.go
+++ b/internal/console/apidomainbuy.go
@@ -156,14 +156,19 @@ func (s *Server) writeDomainPurchaseStatus(w http.ResponseWriter, r *http.Reques
out := domainPurchaseReply{ID: p.ID, Domain: p.Domain, App: p.App, State: p.State, Reason: p.Reason}
ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
defer cancel()
+ out.DomainState = s.purchaseDomainState(ctx, acct, p)
+ writeJSON(w, 200, out)
+}
+
+func (s *Server) purchaseDomainState(ctx context.Context, acct *Account, p *DomainPurchase) string {
c, err := domains.GetClaim(ctx, s.cfg.Releases, p.Domain)
if err == nil && c.Account == acct.Sqid && c.App == p.App {
now := time.Now()
- out.DomainState = s.domainItem(ctx, *c, aliasReadings(ctx, s.cfg.Releases, now), warmRecord(ctx, s.cfg.Releases, c.Host), s.dnsTargets(ctx), now, c.Wildcard && s.delegationZone != "").State
+ return s.domainItem(ctx, *c, aliasReadings(ctx, s.cfg.Releases, now), warmRecord(ctx, s.cfg.Releases, c.Host), s.dnsTargets(ctx), now, c.Wildcard && s.delegationZone != "").State
} else if err != nil && !errors.Is(err, os.ErrNotExist) {
- out.DomainState = StateUnknown
+ return StateUnknown
}
- writeJSON(w, 200, out)
+ return ""
}
func (s *Server) handleAPIDomainPurchaseStatus(w http.ResponseWriter, r *http.Request) {
_, acct, ok := s.domainBuyAPIGate(w, r)
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go
index 15598c346..a7f000c6e 100644
--- a/internal/console/apidomainbuy_test.go
+++ b/internal/console/apidomainbuy_test.go
@@ -204,11 +204,13 @@ func TestBrowserBuyRedirectsToCheckout(t *testing.T) {
if status != 200 || !strings.Contains(body, "fetch(") {
t.Fatalf("purchase page %d %s", status, body)
}
+ card := purchaseText(purchaseElement(t, body, "purchase-card"))
for _, want := range []string{
- "The domain is registered in your name, so it is yours to keep or move.",
- "Your domain usually works over HTTPS one to five minutes after payment.",
+ "Almost yours",
+ "Finish paying to claim shop.com. Your checkout stays open for an hour.",
+ "It's registered in your name, so it's yours to keep or take elsewhere.",
} {
- if !strings.Contains(body, "<p>"+want+"</p>") {
+ if !strings.Contains(card, want) {
t.Errorf("missing visible copy %q", want)
}
}
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go
index 1eb02dedb..0e4f9a593 100644
--- a/internal/console/appdomainbuy.go
+++ b/internal/console/appdomainbuy.go
@@ -6,6 +6,7 @@ import (
"net/http"
"net/url"
"strconv"
+ "strings"
"time"
"github.com/carlosframework/platform/internal/domainreg"
@@ -25,6 +26,59 @@ type domainBuyView struct {
Quote *domainreg.Quote
Fields []domainBuyField
Purchase *DomainPurchase
+ DomainState string
+ Card domainPurchaseCard
+ Stages map[PurchaseState]domainPurchaseStage
+}
+
+type domainPurchaseStage struct {
+ Kind string
+ Steps [4]string
+}
+
+var domainPurchaseStages = map[PurchaseState]domainPurchaseStage{
+ PurchaseAwaitingPayment: {Kind: "awaiting"},
+ PurchaseAuthorised: {Kind: "progress", Steps: [4]string{"done", "active", "pending", "pending"}},
+ PurchaseZoneReady: {Kind: "progress", Steps: [4]string{"done", "active", "pending", "pending"}},
+ PurchaseRegistering: {Kind: "progress", Steps: [4]string{"done", "active", "pending", "pending"}},
+ PurchaseRegistered: {Kind: "progress", Steps: [4]string{"done", "done", "active", "pending"}},
+ PurchaseCaptured: {Kind: "progress", Steps: [4]string{"done", "done", "active", "pending"}},
+ PurchaseDone: {Kind: "progress", Steps: [4]string{"done", "done", "done", "active"}},
+ PurchaseFailed: {Kind: "failed"},
+ PurchaseExpired: {Kind: "expired"},
+ PurchaseUnpaid: {Kind: "unpaid"},
+ "live": {Kind: "live", Steps: [4]string{"done", "done", "done", "done"}},
+}
+
+type domainPurchaseCard struct {
+ Stage domainPurchaseStage
+ Title, Lede string
+ Visit string
+ Status string
+ StepLabels [4]string
+}
+
+func purchaseCard(p *DomainPurchase, domainState string) domainPurchaseCard {
+ state := p.State
+ if state == PurchaseDone && domainState == StateLive {
+ state = "live"
+ }
+ stage := domainPurchaseStages[state]
+ fill := strings.NewReplacer("{domain}", p.Domain, "{app}", p.App)
+ card := domainPurchaseCard{
+ Stage: stage, Title: fill.Replace(domainBuyCopy[stage.Kind+"Title"]),
+ Lede: fill.Replace(domainBuyCopy[stage.Kind+"Lede"]), Visit: fill.Replace(domainBuyCopy["visit"]),
+ StepLabels: [4]string{domainBuyCopy["stepPaid"], domainBuyCopy["stepRegister"], domainBuyCopy["stepDNS"], domainBuyCopy["stepHTTPS"]},
+ }
+ card.Status = card.Title
+ if stage.Kind == "progress" {
+ for i, step := range stage.Steps {
+ if step == "active" {
+ card.Status = card.StepLabels[i]
+ }
+ }
+ }
+ return card
}
func domainPurchaseURL(account, app, id string) string {
@@ -71,6 +125,10 @@ func (s *Server) renderDomainBuy(w http.ResponseWriter, r *http.Request, addr, r
if v.Quote != nil {
v.Price = plans.FormatMinor(v.Quote.Currency, v.Quote.Price)
}
+ if v.Purchase != nil {
+ v.Card = purchaseCard(v.Purchase, v.DomainState)
+ v.Stages = domainPurchaseStages
+ }
p.DomainBuy = v
status := http.StatusOK
if v.PriceChanged {
@@ -157,7 +215,13 @@ func (s *Server) handleAppDomainPurchase(w http.ResponseWriter, r *http.Request)
checkout = info.URL
}
}
- s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Purchase: p, CheckoutURL: checkout, PollURL: domainPurchaseURL(acct.Sqid, app, p.ID) + "/status"})
+ var domainState string
+ if p.State == PurchaseDone {
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ domainState = s.purchaseDomainState(ctx, acct, p)
+ }
+ s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Purchase: p, DomainState: domainState, CheckoutURL: checkout, PollURL: domainPurchaseURL(acct.Sqid, app, p.ID) + "/status"})
}
func (s *Server) handleAppDomainPurchaseStatus(w http.ResponseWriter, r *http.Request) {
_, _, acct, app, ok := s.domainBuyBrowserGate(w, r)
diff --git a/internal/console/domainbuy_card_test.go b/internal/console/domainbuy_card_test.go
new file mode 100644
index 000000000..5803efbb9
--- /dev/null
+++ b/internal/console/domainbuy_card_test.go
@@ -0,0 +1,311 @@
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/status"
+ "golang.org/x/net/html"
+)
+
+func TestDomainPurchaseCardSteps(t *testing.T) {
+ for _, tc := range []struct {
+ state PurchaseState
+ domainState, kind string
+ steps [4]string
+ }{
+ {PurchaseAwaitingPayment, "", "awaiting", [4]string{}},
+ {PurchaseAuthorised, "", "progress", [4]string{"done", "active", "pending", "pending"}},
+ {PurchaseZoneReady, "", "progress", [4]string{"done", "active", "pending", "pending"}},
+ {PurchaseRegistering, "", "progress", [4]string{"done", "active", "pending", "pending"}},
+ {PurchaseRegistered, "", "progress", [4]string{"done", "done", "active", "pending"}},
+ {PurchaseCaptured, "", "progress", [4]string{"done", "done", "active", "pending"}},
+ {PurchaseDone, StateIssuingCert, "progress", [4]string{"done", "done", "done", "active"}},
+ {PurchaseDone, StateUnknown, "progress", [4]string{"done", "done", "done", "active"}},
+ {PurchaseDone, StateLive, "live", [4]string{"done", "done", "done", "done"}},
+ {PurchaseCaptured, StateLive, "progress", [4]string{"done", "done", "active", "pending"}},
+ {PurchaseFailed, "", "failed", [4]string{}},
+ {PurchaseExpired, "", "expired", [4]string{}},
+ {PurchaseUnpaid, StateLive, "unpaid", [4]string{}},
+ } {
+ t.Run(string(tc.state)+"/"+tc.domainState, func(t *testing.T) {
+ got := purchaseCard(&DomainPurchase{State: tc.state}, tc.domainState).Stage
+ if got.Kind != tc.kind || got.Steps != tc.steps {
+ t.Fatalf("stage = %+v, want %s %v", got, tc.kind, tc.steps)
+ }
+ })
+ }
+}
+
+func purchaseCardHTML(t *testing.T, f *purchaseFixture, p *DomainPurchase, domainState, checkout string) string {
+ t.Helper()
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest(http.MethodGet, "/", nil)
+ f.srv.renderDomainBuy(w, r, "buyer@example.test", "csrf-test", f.acct, p.App, &domainBuyView{
+ Purchase: p, DomainState: domainState, CheckoutURL: checkout,
+ PollURL: domainPurchaseURL(f.acct.Sqid, p.App, p.ID) + "/status",
+ })
+ if w.Code != http.StatusOK {
+ t.Fatalf("render: %d %s", w.Code, w.Body.String())
+ }
+ return w.Body.String()
+}
+
+func purchaseElement(t *testing.T, body, id string) *html.Node {
+ t.Helper()
+ doc, err := html.Parse(strings.NewReader(body))
+ if err != nil {
+ t.Fatal(err)
+ }
+ var find func(*html.Node) *html.Node
+ find = func(n *html.Node) *html.Node {
+ if purchaseAttr(n, "id") == id {
+ return n
+ }
+ for c := n.FirstChild; c != nil; c = c.NextSibling {
+ if found := find(c); found != nil {
+ return found
+ }
+ }
+ return nil
+ }
+ n := find(doc)
+ if n == nil {
+ t.Fatalf("missing #%s", id)
+ }
+ return n
+}
+
+func purchaseAttr(n *html.Node, key string) string {
+ for _, a := range n.Attr {
+ if a.Key == key {
+ return a.Val
+ }
+ }
+ return ""
+}
+
+func purchaseHidden(n *html.Node) bool {
+ for _, a := range n.Attr {
+ if a.Key == "hidden" {
+ return true
+ }
+ }
+ return false
+}
+
+func purchaseText(n *html.Node) string {
+ if n.Type == html.TextNode {
+ return n.Data
+ }
+ var s strings.Builder
+ for c := n.FirstChild; c != nil; c = c.NextSibling {
+ s.WriteString(purchaseText(c))
+ }
+ return s.String()
+}
+
+func TestDomainPurchaseCardRender(t *testing.T) {
+ f := newPurchaseFixture(t)
+ for _, tc := range []struct {
+ state PurchaseState
+ domainState, kind string
+ }{
+ {PurchaseAwaitingPayment, "", "awaiting"},
+ {PurchaseAuthorised, "", "progress"},
+ {PurchaseZoneReady, "", "progress"},
+ {PurchaseRegistering, "", "progress"},
+ {PurchaseRegistered, "", "progress"},
+ {PurchaseCaptured, "", "progress"},
+ {PurchaseDone, StateIssuingCert, "progress"},
+ {PurchaseDone, StateLive, "live"},
+ {PurchaseFailed, "", "failed"},
+ {PurchaseExpired, "", "expired"},
+ {PurchaseUnpaid, StateLive, "unpaid"},
+ } {
+ t.Run(string(tc.state)+"/"+tc.domainState, func(t *testing.T) {
+ p := &DomainPurchase{ID: "dp_card", Domain: "shop.com", App: "kass", State: tc.state}
+ checkout := ""
+ if tc.state == PurchaseAwaitingPayment {
+ checkout = "https://checkout.example.test/pay"
+ }
+ body := purchaseCardHTML(t, f, p, tc.domainState, checkout)
+ fill := strings.NewReplacer("{domain}", p.Domain, "{app}", p.App)
+ for id, want := range map[string]string{
+ "purchase-title": fill.Replace(domainBuyCopy[tc.kind+"Title"]),
+ "purchase-lede": fill.Replace(domainBuyCopy[tc.kind+"Lede"]),
+ "purchase-visit": "Visit shop.com",
+ } {
+ if got := purchaseText(purchaseElement(t, body, id)); got != want {
+ t.Errorf("%s = %q, want %q", id, got, want)
+ }
+ }
+ for id, visible := range map[string]bool{
+ "purchase-steps": tc.kind == "progress", "purchase-mark": tc.kind == "live", "purchase-visit": tc.kind == "live", "purchase-error": false,
+ } {
+ if purchaseHidden(purchaseElement(t, body, id)) == visible {
+ t.Errorf("%s visibility, want %v", id, visible)
+ }
+ }
+ if checkout != "" {
+ link := purchaseElement(t, body, "purchase-continue")
+ if purchaseHidden(link) || purchaseAttr(link, "href") != checkout || purchaseText(link) != domainBuyCopy["continuePayment"] {
+ t.Error("missing checkout action")
+ }
+ } else if strings.Contains(body, `id="purchase-continue"`) {
+ t.Error("checkout action outside awaiting payment")
+ }
+ visit := purchaseElement(t, body, "purchase-visit")
+ if purchaseAttr(visit, "href") != "https://shop.com" || purchaseAttr(visit, "target") != "_blank" || purchaseAttr(visit, "rel") != "noopener" {
+ t.Error("incorrect visit action")
+ }
+ card := purchaseElement(t, body, "purchase-card")
+ if strings.Count(purchaseText(card), domainBuyCopy["cardOwnership"]) != 1 || strings.Count(purchaseText(card), domainBuyCopy["back"]) != 1 {
+ t.Error("card needs ownership and one back link")
+ }
+ if !strings.Contains(body, `<h1>Buy a domain</h1>`) {
+ t.Error("page heading changed")
+ }
+ progress := purchaseElement(t, body, "purchase-progress")
+ if purchaseAttr(progress, "role") != "" || purchaseAttr(progress, "aria-atomic") != "" {
+ t.Error("large container must not announce the whole card")
+ }
+ announcement := purchaseElement(t, body, "purchase-status")
+ if purchaseAttr(announcement, "role") != "status" || purchaseAttr(announcement, "aria-live") != "polite" || purchaseAttr(announcement, "class") != "visually-hidden" || purchaseHidden(announcement) {
+ t.Error("missing visually hidden polite status")
+ }
+ wantStatus := fill.Replace(domainBuyCopy[tc.kind+"Title"])
+ switch tc.state {
+ case PurchaseAuthorised, PurchaseZoneReady, PurchaseRegistering:
+ wantStatus = domainBuyCopy["stepRegister"]
+ case PurchaseRegistered, PurchaseCaptured:
+ wantStatus = domainBuyCopy["stepDNS"]
+ case PurchaseDone:
+ if tc.domainState != StateLive {
+ wantStatus = domainBuyCopy["stepHTTPS"]
+ }
+ }
+ if got := purchaseText(announcement); got != wantStatus {
+ t.Errorf("status = %q, want %q", got, wantStatus)
+ }
+ if tc.kind == "progress" {
+ steps := purchaseElement(t, body, "purchase-steps")
+ i := 0
+ for n := steps.FirstChild; n != nil; n = n.NextSibling {
+ if n.Type != html.ElementNode {
+ continue
+ }
+ want := purchaseCard(p, tc.domainState).Stage.Steps[i]
+ if purchaseAttr(n, "data-state") != want || (purchaseAttr(n, "aria-current") == "step") != (want == "active") {
+ t.Errorf("step %d rendered incorrectly", i)
+ }
+ i++
+ }
+ if i != 4 {
+ t.Fatalf("got %d steps", i)
+ }
+ }
+ })
+ }
+}
+
+func TestDomainPurchaseCardEscapesPlaceholders(t *testing.T) {
+ f := newPurchaseFixture(t)
+ for _, state := range []PurchaseState{PurchaseAuthorised, PurchaseDone} {
+ p := &DomainPurchase{Domain: `shop<>&".com`, App: `<img src=x onerror=alert(1)>{domain}</script>`, State: state}
+ body := purchaseCardHTML(t, f, p, StateLive, "")
+ if strings.Contains(body, p.Domain) || strings.Contains(body, p.App) || strings.Contains(body, "<img src=x") {
+ t.Fatal("unescaped placeholder in HTML or script")
+ }
+ kind := "progress"
+ if state == PurchaseDone {
+ kind = "live"
+ }
+ want := strings.NewReplacer("{domain}", p.Domain, "{app}", p.App).Replace(domainBuyCopy[kind+"Lede"])
+ if got := purchaseText(purchaseElement(t, body, "purchase-lede")); got != want {
+ t.Fatalf("lede = %q, want %q", got, want)
+ }
+ if !strings.Contains(purchaseText(purchaseElement(t, body, "purchase-title")), p.Domain) {
+ t.Fatal("domain placeholder was lost")
+ }
+ }
+}
+
+func TestDomainPurchasePageRendersLiveBeforePolling(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ f.authorise(t, p)
+ f.until(t, p.ID, PurchaseDone)
+ c := newBrowser(t)
+ f.setUser("owner" + f.acct.Sqid + "@example.com")
+ signUp(t, f.consoleFixture, c, "live-browser")
+ path := f.ts.URL + domainPurchaseURL(f.acct.Sqid, p.App, p.ID)
+ code, _, body := get(t, c, path)
+ if code != http.StatusOK || purchaseText(purchaseElement(t, body, "purchase-title")) != "Setting up shop.com" {
+ t.Fatal("done without live domain should still show setup")
+ }
+ now := time.Now()
+ if err := status.WriteBox(context.Background(), f.rel, status.Box{
+ GeneratedAt: now, Label: "card-test", Region: "eu-west-1",
+ Metrics: &status.BoxMetrics{Aliases: map[string]status.AliasReading{
+ p.Domain: {Route: "app.example.test", DNSStatus: "pointing", DNSCheckedAt: now.Unix(), CertExpiresAt: now.Add(time.Hour).Unix()},
+ }},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ code, _, body = get(t, c, path)
+ if code != http.StatusOK || purchaseText(purchaseElement(t, body, "purchase-title")) != "shop.com is live" || purchaseHidden(purchaseElement(t, body, "purchase-visit")) {
+ t.Fatal("first render did not show live domain")
+ }
+ other := *f.acct
+ other.Sqid = "other"
+ if got := f.srv.purchaseDomainState(context.Background(), &other, p); got == StateLive {
+ t.Fatal("another account's claim supplied live status")
+ }
+}
+
+func TestDomainPurchaseCardPolling(t *testing.T) {
+ node, err := exec.LookPath("node")
+ if err != nil {
+ t.Skip("node is needed to execute the purchase polling script")
+ }
+ f := newPurchaseFixture(t)
+ fixtures := map[string]any{"copy": domainBuyCopy}
+ for _, state := range []PurchaseState{PurchaseRegistering, PurchaseAwaitingPayment, "live", PurchaseFailed, PurchaseExpired, PurchaseUnpaid} {
+ p := &DomainPurchase{ID: "dp_card", Domain: "shop.com", App: "kass", State: state}
+ domainState := ""
+ if state == "live" {
+ p.State, domainState = PurchaseDone, StateLive
+ }
+ body := purchaseCardHTML(t, f, p, domainState, "https://checkout.example.test/pay")
+ start := strings.Index(body, "(function () {")
+ end := strings.Index(body[start:], "</script>")
+ elements := map[string]any{}
+ for _, id := range []string{"purchase-card", "purchase-title", "purchase-lede", "purchase-steps", "purchase-mark", "purchase-error", "purchase-continue", "purchase-visit", "purchase-status"} {
+ n := purchaseElement(t, body, id)
+ elements[id] = map[string]any{"text": purchaseText(n), "hidden": purchaseHidden(n)}
+ }
+ fixtures[string(state)] = map[string]any{
+ "script": body[start : start+end], "elements": elements,
+ "response": map[string]string{"state": string(p.State), "domain_state": domainState},
+ }
+ }
+ data, err := json.Marshal(fixtures)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, node, "testdata/domainbuy_poll.cjs")
+ cmd.Stdin = bytes.NewReader(data)
+ if out, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("polling regression: %v\n%s", err, out)
+ }
+}
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go
index 446186a02..ea7dafbb0 100644
--- a/internal/console/domainbuy_copy.go
+++ b/internal/console/domainbuy_copy.go
@@ -27,11 +27,8 @@ var domainBuyCopy = map[string]string{
"check": "Check availability",
"quote": "Price for one year",
"paymentDetails": "You will review the final payment details at checkout.",
- "background": "Your purchase will continue in the background. Reload this page to check its progress.",
"contact": "Your contact details",
"pay": "Continue to checkout",
- "continuePayment": "continue to payment",
- "back": "Back to domains",
"contactError": "Enter your name, email address, postal address, country code and phone number. Use digits for the phone number and calling code, and two uppercase letters for the country.",
"nameError": "Enter a domain name that can be registered.",
"unavailable": "buying domains is unavailable right now",
@@ -41,19 +38,6 @@ var domainBuyCopy = map[string]string{
"notOffered": "This domain ending is not offered.",
"premium": "Premium domains are not offered.",
"taken": "This domain is not available.",
- "progress": "Your domain purchase",
- "pollError": "We could not check progress. We will try again shortly.",
- "awaiting_payment": "Waiting for payment approval.",
- "authorised": "Payment approved. Preparing your domain.",
- "zone_ready": "Domain settings are ready.",
- "registering": "Registering your domain.",
- "registered": "Your domain is registered. Taking payment now.",
- "captured": "Payment taken. Connecting your domain to your app.",
- "done": "Your domain is connected. Waiting for HTTPS to be ready.",
- "live": "Your domain is live.",
- "failed": "We could not complete the purchase.",
- "expired": "Checkout expired before you completed it. Nothing was charged. Start a new purchase to try again.",
- "unpaid": "Your domain is registered, but the payment did not go through. We will contact you about paying for it.",
"FirstName": "First name",
"LastName": "Last name",
"Company": "Company (optional)",
@@ -68,6 +52,29 @@ var domainBuyCopy = map[string]string{
"Country": "Country (two uppercase letters)",
"ownership": "The domain is registered in your name, so it is yours to keep or move.",
"timing": "Your domain usually works over HTTPS one to five minutes after payment.",
+ // approved by Paul (copy review 2026-11-03)
+ "progressTitle": "Setting up {domain}",
+ "progressLede": "Payment received, thanks. We're registering your domain and connecting it to {app}. It usually takes a minute or two, and you can leave this page.",
+ "stepPaid": "Payment received",
+ "stepRegister": "Registering your domain",
+ "stepDNS": "Pointing it at your app",
+ "stepHTTPS": "Securing it with HTTPS",
+ "cardOwnership": "It's registered in your name, so it's yours to keep or take elsewhere.",
+ "liveTitle": "{domain} is live",
+ "liveLede": "Your new domain is up and running, pointed at {app} and secured with HTTPS. Go and take a look.",
+ "visit": "Visit {domain}",
+ "back": "Back to domains",
+ "awaitingTitle": "Almost yours",
+ "awaitingLede": "Finish paying to claim {domain}. Your checkout stays open for an hour.",
+ "continuePayment": "Continue to payment",
+ "slowLede": "This is taking a little longer than usual. It will finish on its own, so feel free to leave and check back later.",
+ "pollError": "We can't check on your domain just now. Setup carries on regardless, so try refreshing in a minute.",
+ "failedTitle": "We couldn't register {domain}",
+ "failedLede": "Nothing was charged, and the hold on your card has been released. You can try another name whenever you like.",
+ "expiredTitle": "Checkout timed out",
+ "expiredLede": "Nothing was charged. If you still want {domain}, start again and it'll take a minute.",
+ "unpaidTitle": "{domain} is yours, but the payment didn't go through",
+ "unpaidLede": "Your domain is registered and working. We'll be in touch about paying for it.",
}
func domainBuyErrorRefusal(err error) *doorRefusal {
diff --git a/internal/console/domainbuy_final_fix_test.go b/internal/console/domainbuy_final_fix_test.go
index 41e17d286..d35b437c8 100644
--- a/internal/console/domainbuy_final_fix_test.go
+++ b/internal/console/domainbuy_final_fix_test.go
@@ -122,7 +122,7 @@ func TestCheckoutCancelPageOffersContinue(t *testing.T) {
t.Fatalf("cancel URL: %v", request)
}
status, _, body := get(t, c, f.ts.URL+domainPurchaseURL(f.acct.Sqid, p.App, p.ID))
- if status != 200 || !strings.Contains(body, `href="`+info.URL+`"`) || !strings.Contains(body, ">continue to payment</a>") {
+ if status != 200 || !strings.Contains(body, `href="`+info.URL+`"`) || !strings.Contains(body, ">Continue to payment</a>") {
t.Fatalf("missing continue link: status=%d", status)
}
values := url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}, "currency": {"usd"}, "price": {"1500"}}
diff --git a/internal/console/templates/domain_buy.html b/internal/console/templates/domain_buy.html
index 0a96b85bb..f61b62098 100644
--- a/internal/console/templates/domain_buy.html
+++ b/internal/console/templates/domain_buy.html
@@ -2,30 +2,108 @@
<h1>{{.DomainBuyCopy.title}}</h1>
{{with .DomainBuy}}
{{if .Purchase}}
-<h2>{{$.DomainBuyCopy.progress}}: {{.Purchase.Domain}}</h2>
-<p>{{$.DomainBuyCopy.ownership}}</p>
-<p>{{$.DomainBuyCopy.timing}}</p>
-<p id="purchase-progress" role="status">{{index $.DomainBuyCopy (printf "%s" .Purchase.State)}}</p>
-{{if .CheckoutURL}}<p id="purchase-continue"><a href="{{.CheckoutURL}}">{{$.DomainBuyCopy.continuePayment}}</a></p>{{end}}
+<style>
+ .purchase-card { box-sizing: border-box; max-width: 36rem; margin: 1.5rem auto 0; padding: 1.8rem 1.8rem 1.4rem; border: 1px solid var(--rst-line); border-radius: 0.875rem; background: var(--accent-soft); color: var(--ink); overflow-wrap: anywhere; }
+ .purchase-card [hidden] { display: none !important; }
+ .purchase-card h2 { margin: 0 0 0.5rem; font-size: 1.5rem; line-height: 1.2; }
+ .purchase-card .done-lede { margin: 0 0 1.2rem; font-size: 1.02rem; }
+ .purchase-card .done-mark { width: 3rem; height: 3rem; margin-bottom: 0.8rem; background: var(--rst-tone-positive-bg); color: var(--good); }
+ .purchase-card .done-actions { justify-content: flex-start; margin: 1.2rem 0 0; }
+ .purchase-card.done .done-actions { justify-content: center; }
+ .purchase-card .purchase-ownership, .purchase-card .purchase-error { margin: 0.9rem 0 0; color: var(--muted); font-size: 0.88rem; }
+ .purchase-steps { list-style: none; margin: 0 0 1.2rem; padding: 0; display: grid; gap: 0.55rem; text-align: left; }
+ .purchase-steps li { display: flex; align-items: center; gap: 0.6rem; }
+ .purchase-steps [data-state="pending"] { color: var(--muted); }
+ .purchase-step-mark { display: inline-grid; place-items: center; flex: none; width: 1.125rem; height: 1.125rem; color: var(--accent); }
+ .purchase-steps [data-state="done"] .purchase-step-mark { color: var(--good); }
+ .purchase-step-mark .icon { width: 1.125rem; height: 1.125rem; stroke-width: 2.6; }
+ .purchase-steps li:not([data-state="done"]) .icon { display: none; }
+ .purchase-steps [data-state="active"] .purchase-step-mark::before { content: ""; width: 1rem; height: 1rem; border: 2px solid var(--rst-line); border-top-color: var(--accent); border-radius: 50%; }
+ .purchase-steps [data-state="pending"] .purchase-step-mark::before { content: ""; width: 0.625rem; height: 0.625rem; border: 2px solid var(--rst-line-strong); border-radius: 50%; }
+ @media (prefers-reduced-motion: no-preference) {
+ .purchase-steps [data-state="active"] .purchase-step-mark::before { animation: purchase-spin 1s linear infinite; }
+ }
+ @keyframes purchase-spin { to { transform: rotate(360deg); } }
+</style>
+<section id="purchase-card" class="purchase-card{{if eq .Card.Stage.Kind "live"}} done{{end}}" aria-labelledby="purchase-title">
+ <span id="purchase-status" class="visually-hidden" role="status" aria-live="polite">{{.Card.Status}}</span>
+ <div id="purchase-progress">
+ <span id="purchase-mark" class="done-mark" aria-hidden="true" {{if ne .Card.Stage.Kind "live"}}hidden{{end}}>{{icon "check"}}</span>
+ <h2 id="purchase-title">{{.Card.Title}}</h2>
+ <p id="purchase-lede" class="done-lede">{{.Card.Lede}}</p>
+ <ol id="purchase-steps" class="purchase-steps" {{if ne .Card.Stage.Kind "progress"}}hidden{{end}}>
+ {{range $i, $label := .Card.StepLabels}}<li data-state="{{index $.DomainBuy.Card.Stage.Steps $i}}" {{if eq (index $.DomainBuy.Card.Stage.Steps $i) "active"}}aria-current="step"{{end}}><span class="purchase-step-mark" aria-hidden="true">{{icon "check"}}</span><span>{{$label}}</span></li>{{end}}
+ </ol>
+ <p id="purchase-error" class="purchase-error" hidden></p>
+ </div>
+ <div class="done-actions">
+ {{if .CheckoutURL}}<a id="purchase-continue" class="btn" href="{{.CheckoutURL}}" {{if ne .Card.Stage.Kind "awaiting"}}hidden{{end}}>{{$.DomainBuyCopy.continuePayment}}</a>{{end}}
+ <a id="purchase-visit" class="btn" href="https://{{.Purchase.Domain}}" target="_blank" rel="noopener" {{if ne .Card.Stage.Kind "live"}}hidden{{end}}>{{.Card.Visit}}</a>
+ <a class="btn btn-secondary" href="{{.Back}}">{{$.DomainBuyCopy.back}}</a>
+ </div>
+ <p class="purchase-ownership">{{$.DomainBuyCopy.cardOwnership}}</p>
+</section>
<script>
(function () {
- const endpoint = {{.PollURL}}, copy = {{$.DomainBuyCopy}};
- const progress = document.getElementById('purchase-progress');
- const payment = document.getElementById('purchase-continue');
+ const endpoint = {{.PollURL}}, copy = {{$.DomainBuyCopy}}, stages = {{.Stages}};
+ const domain = {{.Purchase.Domain}}, app = {{.Purchase.App}};
+ const card = document.getElementById('purchase-card');
+ const title = document.getElementById('purchase-title'), lede = document.getElementById('purchase-lede');
+ const steps = document.getElementById('purchase-steps'), rows = steps.querySelectorAll('li');
+ const mark = document.getElementById('purchase-mark'), error = document.getElementById('purchase-error');
+ const payment = document.getElementById('purchase-continue'), visit = document.getElementById('purchase-visit');
+ const status = document.getElementById('purchase-status'), labels = {{.Card.StepLabels}};
const started = Date.now();
+ let state = {{.Purchase.State}}, domainState = {{.DomainState}};
+ let rendered = state + ':' + domainState + ':false';
+ const fill = text => text.replace(/\{(domain|app)\}/g, (_, key) => key === 'domain' ? domain : app);
+ const terminal = () => ['failed', 'expired', 'unpaid'].includes(state) || (state === 'done' && domainState === 'live');
+ function update() {
+ const stage = stages[state === 'done' && domainState === 'live' ? 'live' : state];
+ const slow = stage.Kind === 'progress' && Date.now() - started >= 600000;
+ const key = state + ':' + domainState + ':' + slow;
+ if (key === rendered) return;
+ rendered = key;
+ card.classList.toggle('done', stage.Kind === 'live');
+ mark.hidden = stage.Kind !== 'live';
+ title.textContent = fill(copy[stage.Kind + 'Title']);
+ lede.textContent = fill(copy[slow ? 'slowLede' : stage.Kind + 'Lede']);
+ steps.hidden = stage.Kind !== 'progress';
+ rows.forEach((row, i) => {
+ row.dataset.state = stage.Steps[i];
+ if (stage.Steps[i] === 'active') row.setAttribute('aria-current', 'step');
+ else row.removeAttribute('aria-current');
+ });
+ if (payment) payment.hidden = stage.Kind !== 'awaiting';
+ visit.hidden = stage.Kind !== 'live';
+ visit.textContent = fill(copy.visit);
+ const announcement = stage.Kind === 'progress' ? labels[stage.Steps.indexOf('active')] : title.textContent;
+ if (status.textContent !== announcement) status.textContent = announcement;
+ }
async function poll() {
+ if (Date.now() - started >= 3600000) { update(); return; }
try {
const response = await fetch(endpoint, {credentials: 'same-origin', cache: 'no-store'});
if (!response.ok) throw new Error();
const purchase = await response.json();
- if (payment && purchase.state !== 'awaiting_payment') payment.hidden = true;
- progress.textContent = purchase.state === 'done' && purchase.domain_state === 'live' ? copy.live : (copy[purchase.state] || copy.pollError);
- if (['failed', 'expired', 'unpaid'].includes(purchase.state) || (purchase.state === 'done' && purchase.domain_state === 'live')) return;
- } catch (_) { progress.textContent = copy.pollError; }
- if (Date.now() - started < 600000) setTimeout(poll, 3000);
- else progress.textContent = copy.background;
+ if (!Object.prototype.hasOwnProperty.call(stages, purchase.state)) throw new Error();
+ state = purchase.state;
+ domainState = purchase.domain_state || '';
+ error.hidden = true;
+ update();
+ if (terminal()) return;
+ } catch (_) {
+ if (state !== 'awaiting_payment') {
+ update();
+ if (error.hidden) error.textContent = copy.pollError;
+ error.hidden = false;
+ }
+ }
+ const elapsed = Date.now() - started;
+ if (elapsed >= 3600000) { update(); return; }
+ setTimeout(poll, Math.min(elapsed < 600000 ? 3000 : 30000, 3600000 - elapsed));
}
- poll();
+ if (!terminal()) poll();
})();
</script>
{{else if .Quote}}
@@ -57,6 +135,6 @@
<button type="submit">{{$.DomainBuyCopy.check}}</button>
</form>
{{end}}
-<p><a href="{{.Back}}">{{$.DomainBuyCopy.back}}</a></p>
+{{if not .Purchase}}<p><a href="{{.Back}}">{{$.DomainBuyCopy.back}}</a></p>{{end}}
{{end}}
{{template "bottom" .}}{{end}}
diff --git a/internal/console/testdata/domainbuy_poll.cjs b/internal/console/testdata/domainbuy_poll.cjs
new file mode 100644
index 000000000..8f43e0c54
--- /dev/null
+++ b/internal/console/testdata/domainbuy_poll.cjs
@@ -0,0 +1,125 @@
+const assert = require('node:assert/strict');
+const vm = require('node:vm');
+const { test } = require('node:test');
+const fixtures = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
+
+function harness(name) {
+ const fixture = fixtures[name];
+ let now = 0, calls = 0, response = fixture.response;
+ const timers = [], writes = [];
+ const elements = Object.fromEntries(Object.entries(fixture.elements).map(([id, value]) => [id, {
+ ...value, dataset: {}, classList: { toggle() {} },
+ setAttribute() {}, removeAttribute() {},
+ get textContent() { return this.text; },
+ set textContent(text) { writes.push([id, text]); this.text = text; }
+ }]));
+ elements['purchase-steps'].querySelectorAll = () => Array.from({ length: 4 }, () => ({
+ dataset: {}, setAttribute() {}, removeAttribute() {}
+ }));
+ vm.runInNewContext(fixture.script, {
+ document: { getElementById: id => elements[id] || null },
+ Date: { now: () => now },
+ setTimeout: (fn, delay) => timers.push({ fn, delay }),
+ fetch: async () => {
+ calls++;
+ if (response === 'error') throw new Error('offline');
+ return { ok: true, json: async () => response };
+ }
+ });
+ return {
+ elements, timers, writes,
+ get calls() { return calls; },
+ async settle() { await new Promise(resolve => setImmediate(resolve)); },
+ async advance(time, next = response) {
+ now = time; response = next;
+ const timer = timers.shift();
+ assert.ok(timer, 'poll should be scheduled');
+ await timer.fn();
+ }
+ };
+}
+
+test('unchanged first poll does not rewrite server-rendered content', async () => {
+ const h = harness('registering');
+ await h.settle();
+ assert.deepEqual(h.writes, []);
+});
+
+test('omitted domain state and unchanged active step do not re-announce', async () => {
+ const h = harness('registering');
+ await h.settle();
+ await h.advance(3000, { state: 'registering' });
+ assert.deepEqual(h.writes, []);
+ await h.advance(6000, { state: 'zone_ready' });
+ await h.advance(600000, { state: 'registering' });
+ assert.deepEqual(h.writes.filter(([id]) => id === 'purchase-status'), []);
+});
+
+test('announces the active step and then the terminal title', async () => {
+ const h = harness('registering');
+ await h.settle();
+ for (const [state, domain_state, text] of [
+ ['registered', '', fixtures.copy.stepDNS],
+ ['done', 'issuing-cert', fixtures.copy.stepHTTPS],
+ ['done', 'live', 'shop.com is live']
+ ]) {
+ await h.advance(3000, { state, domain_state });
+ assert.equal(h.elements['purchase-status'].textContent, text);
+ }
+ assert.equal(h.timers.length, 0);
+});
+
+test('awaiting payment errors keep the last state silently', async () => {
+ const h = harness('awaiting_payment');
+ await h.settle();
+ h.writes.length = 0;
+ await h.advance(3000, 'error');
+ assert.equal(h.elements['purchase-error'].hidden, true);
+ assert.deepEqual(h.writes, []);
+ assert.equal(h.timers.length, 1);
+});
+
+test('progress errors recover and continue polling', async () => {
+ const h = harness('registering');
+ await h.settle();
+ await h.advance(3000, 'error');
+ assert.equal(h.elements['purchase-error'].hidden, false);
+ assert.equal(h.elements['purchase-error'].textContent, fixtures.copy.pollError);
+ await h.advance(6000, { state: 'registered', domain_state: '' });
+ assert.equal(h.elements['purchase-error'].hidden, true);
+ assert.equal(h.elements['purchase-status'].textContent, fixtures.copy.stepDNS);
+});
+
+for (const response of ['error', { state: 'registering', domain_state: '' }]) {
+ test(`polling stops at one hour after ${JSON.stringify(response)}`, async () => {
+ const h = harness('registering');
+ await h.settle();
+ await h.advance(600000, response);
+ assert.equal(h.elements['purchase-lede'].textContent, fixtures.copy.slowLede);
+ assert.equal(h.timers[0].delay, 30000);
+ const calls = h.calls;
+ await h.advance(3600000, response);
+ assert.equal(h.calls, calls, 'no request at or after the deadline');
+ assert.equal(h.timers.length, 0);
+ assert.equal(h.elements['purchase-lede'].textContent, fixtures.copy.slowLede);
+ });
+}
+
+for (const state of ['live', 'failed', 'expired', 'unpaid']) {
+ test(`no polling when initially ${state}`, async () => {
+ const h = harness(state);
+ await h.settle();
+ assert.equal(h.calls, 0);
+ assert.equal(h.timers.length, 0);
+ });
+}
+
+for (const state of ['failed', 'expired', 'unpaid']) {
+ test(`announces ${state} and stops polling`, async () => {
+ const h = harness('registering');
+ await h.settle();
+ await h.advance(3000, { state });
+ assert.equal(h.elements['purchase-status'].textContent, fixtures[state].elements['purchase-title'].text);
+ assert.equal(h.timers.length, 0);
+ });
+}