carlos / platform Public

console: three-step buy and saved contacts at the account

Buying moves from an app's Settings to the account. GET /a/{sqid}/domains/buy
is three steps (Name, App, Details and pay), state in the query and hidden
fields: POST .../buy/check runs Plan 1's check and goes to step 2; step 2
picks an app (app= preselects, changeable) or Not yet (notyet=1; neither is
step 2 again, never a silent default); POST .../buy starts the purchase
with a saved contact (most recently used preselected) or a new one, and
goes to Checkout. Step 1 asks the country only with no billing currency
and no saved contact; step 3 filters contacts only past five.

The purchase card and its poll are at /a/{sqid}/domains/purchases/{id};
domainPurchaseURL(account, id) is Checkout's success and cancel URL and
the Domains page's link. A purchase with no app, or one unpointing,
shows two steps and ends "ready to point at an app", never "connecting
it to {app}". The old app-scoped routes only redirect (303): they check
membership and the purchase's account, never that the app exists; the
stale posts check CSRF and start nothing.

Saved contacts are added, edited and removed from the Domains page
(POST /a/{sqid}/domains/contacts[/{id}[/remove]]). Every door is owner
only with CSRF on each post; members, strangers and another account's
purchase or contact get the same 404. Plan 1's browser tests move to the
new doors; parity, linked-body, perf and no-bucket registers updated.
Copy is a draft.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 76cddb50e39c7c6c73895b2e56adbcc62a6c89e1 parent 36ddc44
26 files changed, +1,694 −265
  • docs/console-mockup-kit/shell.html +10 −0
  • docs/parity.md +4 −3
  • internal/console/accountdomainbuy.go +603 −0
  • internal/console/accountdomainbuy_test.go +543 −0
  • internal/console/accountdomains_copy.go +58 −0
  • internal/console/accountdomainspage.go +41 −6
  • internal/console/accountdomainspage_test.go +1 −1
  • internal/console/apidomainbuy_test.go +27 −15
  • internal/console/apilinks_test.go +7 −1
  • internal/console/appdomainbuy.go +173 −154
  • internal/console/domainbuy.go +1 −1
  • internal/console/domainbuy_admission_test.go +3 −3
  • internal/console/domainbuy_card_test.go +4 −4
  • internal/console/domainbuy_final_fix_test.go +6 −6
  • internal/console/domainbuy_fix_test.go +1 −1
  • internal/console/domainbuy_round1_test.go +4 −5
  • internal/console/domainbuy_round2_test.go +3 −3
  • internal/console/domainbuy_test.go +1 −1
  • internal/console/nobucket_posts_test.go +2 −2
  • internal/console/perfwalk_test.go +11 −3
  • internal/console/routedecls.go +26 −7
  • internal/console/templates/account_domain_buy.html +104 −0
  • internal/console/templates/account_domains.html +21 −4
  • internal/console/templates/console_chrome.html +14 −0
  • internal/console/templates/domain_buy.html +24 −44
  • parity/parity.tsv +2 −1

CI cancelled — superseded by a newer push — run details

diff --git a/docs/console-mockup-kit/shell.html b/docs/console-mockup-kit/shell.html
index 5ad1b70ff..69f6b7472 100644
--- a/docs/console-mockup-kit/shell.html
+++ b/docs/console-mockup-kit/shell.html
@@ -418,6 +418,16 @@
.domain-head .envvar-value { flex: 1 1 14rem; white-space: normal; }
.domain-head .chip { margin: 0; }
+ .contact-pick .envvar-row { align-items: center; cursor: pointer; }
+ .contact-pick input { margin: 0; accent-color: var(--accent); }
+ .contact-find { margin: 0 0 0.6rem; width: 100%; max-width: 24rem; box-sizing: border-box; }
+ .newcontact { display: none; }
+ form:has(#contact-new:checked) .newcontact { display: block; }
+ .fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr)); gap: 0.75rem 1rem; margin: 0.25rem 0 1rem; }
+ .fields p { margin: 0; }
+ .fields label { display: block; font-size: 0.9rem; font-weight: 600; margin: 0 0 0.25rem; }
+ .fields :is(input, select) { width: 100%; box-sizing: border-box; }
+
.addr-rows .envvar > summary, .addr-rows .envvar-row { flex-wrap: wrap; row-gap: 0.3rem; }
.addr-rows .envvar-value { flex: 1 0 auto; }
.envhead { margin: 1.75rem 0 0.15rem; }
diff --git a/docs/parity.md b/docs/parity.md
index cef8a5a11..1cd189213 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -14,8 +14,8 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
| partial | 9 |
| gap | 65 |
| cli-only | 17 |
-| console-only | 20 |
-| Total | 155 |
+| console-only | 21 |
+| Total | 156 |
## account
@@ -107,7 +107,8 @@ CLI rows are checked against the command registry (`parity/cli.tsv`).
| domains-account-page | console-only | | `GET /a/{sqid}/domains/{domain}` | | One domain's addresses, expiry and the records to set; the CLI list comes later. |
| domains-attach | both | `domains attach`<br>`domains detach` | `POST /a/{sqid}/apps/{app}/domains/attach`<br>`POST /a/{sqid}/apps/{app}/domains/detach` | | |
| domains-verify | partial | `domains verify` | `POST /a/{sqid}/apps/{app}/domains/attach` | | There is no Verify button; attaching again verifies. |
-| domains-buy | both | `domains check`<br>`domains buy` | `GET /a/{sqid}/apps/{app}/domains/buy`<br>`POST /a/{sqid}/apps/{app}/domains/check`<br>`POST /a/{sqid}/apps/{app}/domains/buy`<br>`GET /a/{sqid}/apps/{app}/domains/purchases/{id}`<br>`GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status` | | |
+| domains-buy | both | `domains check`<br>`domains buy` | `GET /a/{sqid}/domains/buy`<br>`POST /a/{sqid}/domains/buy/check`<br>`POST /a/{sqid}/domains/buy`<br>`GET /a/{sqid}/domains/purchases/{id}`<br>`GET /a/{sqid}/domains/purchases/{id}/status`<br>`GET /a/{sqid}/apps/{app}/domains/buy`<br>`POST /a/{sqid}/apps/{app}/domains/check`<br>`POST /a/{sqid}/apps/{app}/domains/buy`<br>`GET /a/{sqid}/apps/{app}/domains/purchases/{id}`<br>`GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status` | | The app-scoped routes only redirect to the account's. |
+| domains-contacts | console-only | | `POST /a/{sqid}/domains/contacts`<br>`POST /a/{sqid}/domains/contacts/{id}`<br>`POST /a/{sqid}/domains/contacts/{id}/remove` | | Saved contacts are added, edited and removed on the Domains page; the CLI buys with the most recently used one. |
| domains-point | console-only | | `POST /a/{sqid}/apps/{app}/domains/point` | | Pointing a bought domain at an app; the CLI verb comes later. |
| domains-paths | gap | `domains paths` | | [wp-settings](#wp-settings) | |
| domains-placements | gap | `domains placements` | | [wp-settings](#wp-settings) | |
diff --git a/internal/console/accountdomainbuy.go b/internal/console/accountdomainbuy.go
new file mode 100644
index 000000000..33bb2b8a7
--- /dev/null
+++ b/internal/console/accountdomainbuy.go
@@ -0,0 +1,603 @@
+package console
+
+// Buying a domain at the account (spec §11.4; Plan 2a Task 9): three steps,
+// Name, App and Details and pay, then Checkout and the purchase card. Step
+// state travels in the query and in hidden fields; nothing is stored until
+// the last step starts the purchase, which checks everything again (the
+// quote included: a changed price comes back for confirmation). Owners
+// only, CSRF on every POST, and every refusal of a member, a stranger or
+// another account's purchase is the same 404.
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "net/url"
+ "sort"
+ "strconv"
+ "strings"
+ "time"
+
+ "golang.org/x/net/publicsuffix"
+
+ "github.com/carlosframework/platform/internal/domainreg"
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+// accountBuyView is one step of the buy page.
+type accountBuyView struct {
+ Step string // "name", "app" or "pay"
+ Base string // the buy page; its forms post to Base and Base/check
+ Eyebrow string
+ Chips []buyStepChip
+ Name string // the domain (as typed, on step 1)
+ App string // the chosen app; "" with NotYet
+ NotYet bool
+ Country string
+ Alert string // a refusal or a request to choose, shown on the step
+
+ // Step 1: the country, asked only when nothing else sets the currency.
+ AskCountry bool
+ Countries []countryOption
+
+ // Steps 2 and 3: the quote.
+ Quote domainreg.Quote
+ PerYear string
+ Back string
+
+ // Step 2.
+ Apps []buyAppChoice
+ NotYetPicked bool
+ PointNote string
+
+ // Step 3.
+ Tiles []domainTile
+ Contacts []buyContactChoice
+ NewPicked bool
+ NewFields []domainBuyField
+ Filter bool // a filter over a long contact list
+ PriceChanged bool
+}
+
+type buyStepChip struct {
+ N int
+ Label string
+ Done, Current bool
+}
+
+type buyAppChoice struct {
+ App string
+ Checked bool
+}
+
+type buyContactChoice struct {
+ ID, Name, Detail string
+ Checked bool
+}
+
+// buyContactFilterAt is the contact count above which step 3 offers a
+// filter over the list.
+const buyContactFilterAt = 5
+
+// countryOptions is every country by name, with selected chosen.
+func countryOptions(selected string) []countryOption {
+ out := make([]countryOption, 0, len(countryNames))
+ for code, name := range countryNames {
+ out = append(out, countryOption{Code: code, Name: name, Selected: code == selected})
+ }
+ sort.Slice(out, func(i, j int) bool { return out[i].Name < out[j].Name })
+ return out
+}
+
+// buyStepURL is a step of the buy page. Only the parameters that are set
+// travel, in a fixed order.
+func buyStepURL(acct *Account, step, name, app string, notYet bool, country string) string {
+ u := domainsBase(acct) + "/domains/buy?step=" + url.QueryEscape(step) + "&name=" + url.QueryEscape(name)
+ if app != "" {
+ u += "&app=" + url.QueryEscape(app)
+ }
+ if notYet {
+ u += "&notyet=1"
+ }
+ if country != "" {
+ u += "&country=" + url.QueryEscape(country)
+ }
+ return u
+}
+
+// domainBuyAccountGate is every buy and purchase door's gate: a member's
+// session, CSRF on a POST, then the owner with buying configured (anyone
+// else, and every owner when it is not, gets the neutral 404), then the
+// domains rate ceiling. Plan 1's app gate, without the app.
+func (s *Server) domainBuyAccountGate(w http.ResponseWriter, r *http.Request) (string, string, *Account, bool) {
+ addr, raw, acct, role, ok := s.account(w, r)
+ if !ok {
+ return "", "", nil, false
+ }
+ if r.Method == http.MethodPost && !csrfFormOK(r, raw) {
+ s.renderMessage(w, r, http.StatusForbidden, domainBuyCopy["refused"], domainBuyCopy["csrf"])
+ return "", "", nil, false
+ }
+ if role != RoleOwner || !s.domainBuyReady() {
+ http.NotFound(w, r)
+ return "", "", nil, false
+ }
+ if !s.allowDomains(Principal{Kind: PrincipalUser, Address: addr}, time.Now()) {
+ s.renderDoorRefusal(w, r, &doorRefusal{Status: http.StatusTooManyRequests, Msg: domainBuyCopy["rate"]})
+ return "", "", nil, false
+ }
+ w.Header().Set("Cache-Control", "no-store")
+ return addr, raw, acct, true
+}
+
+// buyStepQuote is the price steps 2 and 3 show and step 3 confirms: the
+// catalog's, in the currency the purchase would choose (the account's,
+// else the country's, else the most recently used contact's). It asks the
+// registrar nothing; the purchase checks availability and the price again.
+// An owner's purchase of the name already under way keeps its price.
+func (s *Server) buyStepQuote(ctx context.Context, acct *Account, name, country string) (domainreg.Quote, *doorRefusal) {
+ name, err := domainreg.Normalize(name)
+ if err != nil {
+ return domainreg.Quote{}, domainBuyErrorRefusal(err)
+ }
+ own, err := s.ownLiveDomainPurchase(ctx, acct.ID, name)
+ if err != nil {
+ return domainreg.Quote{}, domainBuyUnavailable()
+ }
+ if own != nil {
+ return domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}, nil
+ }
+ suffix, _ := publicsuffix.PublicSuffix(name)
+ tld, offered := s.cfg.DomainCatalog.TLDs[suffix]
+ if !offered {
+ return domainreg.Quote{}, domainBuyErrorRefusal(domainreg.ErrTLDNotOffered)
+ }
+ currency := s.domainCurrency(acct)
+ if currency == "" {
+ if country == "" {
+ country = s.defaultQuoteCountry(acct)
+ }
+ if currency, err = s.billing.cfg.Book.ChooseCurrency("", country); err != nil {
+ return domainreg.Quote{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
+ }
+ }
+ price := tld.Register[currency]
+ if price <= 0 {
+ return domainreg.Quote{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity)
+ }
+ return domainreg.Quote{Domain: name, TLD: suffix, Currency: currency, Price: price}, nil
+}
+
+// newAccountBuyView is a step's view, its chips drawn.
+func newAccountBuyView(acct *Account, step string) *accountBuyView {
+ v := &accountBuyView{Step: step, Base: domainsBase(acct) + "/domains/buy",
+ Eyebrow: domainsFill(domainsPageCopy.PageEyebrow, "{account}", acct.Name)}
+ current := map[string]int{"name": 1, "app": 2, "pay": 3}[step]
+ for i, label := range []string{accountBuyCopy.StepName, accountBuyCopy.StepApp, accountBuyCopy.StepPay} {
+ v.Chips = append(v.Chips, buyStepChip{N: i + 1, Label: label, Done: i+1 < current, Current: i+1 == current})
+ }
+ return v
+}
+
+func (s *Server) renderAccountBuy(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, status int, v *accountBuyView) {
+ p := s.accountPage(w, r, addr, raw, acct, RoleOwner)
+ p.Title = domainBuyCopy["title"]
+ p.ActiveNav = "domains"
+ p.MobileParent = &navLink{Label: domainsPageCopy.Title, Href: p.Nav + "/domains"}
+ p.AccountBuy = v
+ s.render(w, status, "account_domain_buy", p)
+}
+
+// handleAccountDomainBuy is the buy page: step 1 by default, ?step=app or
+// ?step=pay with the name. app= (from an app's Settings) preselects step 2
+// and stays changeable; "Not yet" is notyet=1 with no app, and step 3 with
+// neither is step 2 again, so no choice is ever made by default.
+func (s *Server) handleAccountDomainBuy(w http.ResponseWriter, r *http.Request) {
+ addr, raw, acct, ok := s.domainBuyAccountGate(w, r)
+ if !ok {
+ return
+ }
+ q := r.URL.Query()
+ name, app, country := q.Get("name"), q.Get("app"), q.Get("country")
+ notYet := q.Get("notyet") == "1"
+ // Step 2's radios post one "choice": an app, or Not yet. It becomes
+ // the step's own parameters.
+ if choice := q.Get("choice"); choice != "" {
+ app, notYet = "", choice == "notyet"
+ if a, ok := strings.CutPrefix(choice, "app:"); ok {
+ app = a
+ }
+ step := q.Get("step")
+ if step != "app" {
+ step = "pay"
+ }
+ http.Redirect(w, r, buyStepURL(acct, step, name, app, notYet, country), http.StatusSeeOther)
+ return
+ }
+ step := q.Get("step")
+ if step != "app" && step != "pay" {
+ s.renderAccountBuy(w, r, addr, raw, acct, http.StatusOK, s.buyNameStep(r.Context(), acct, name, app, country))
+ return
+ }
+ quote, ref := s.buyStepQuote(r.Context(), acct, name, country)
+ if ref != nil {
+ v := s.buyNameStep(r.Context(), acct, name, app, country)
+ v.Alert = ref.Msg
+ s.renderAccountBuy(w, r, addr, raw, acct, ref.Status, v)
+ return
+ }
+ apps := s.domainActionApps(r.Context(), acct)
+ chosen := notYet != (app != "") && (notYet || containsString(apps, app))
+ if step == "app" || !chosen {
+ v := s.buyAppStep(acct, quote, apps, app, notYet, country)
+ if step == "pay" {
+ v.Alert = accountBuyCopy.ChooseApp
+ }
+ s.renderAccountBuy(w, r, addr, raw, acct, http.StatusOK, v)
+ return
+ }
+ v, err := s.buyPayStep(r.Context(), acct, quote, app, country, "", nil)
+ if err != nil {
+ s.renderDoorRefusal(w, r, domainBuyUnavailable())
+ return
+ }
+ s.renderAccountBuy(w, r, addr, raw, acct, http.StatusOK, v)
+}
+
+func containsString(list []string, s string) bool {
+ for _, v := range list {
+ if v == s {
+ return true
+ }
+ }
+ return false
+}
+
+// buyNameStep is step 1. The country is asked only when neither the
+// account's currency nor a saved contact sets the price's currency.
+func (s *Server) buyNameStep(ctx context.Context, acct *Account, name, app, country string) *accountBuyView {
+ v := newAccountBuyView(acct, "name")
+ v.Name, v.App, v.Country = name, app, country
+ if s.domainCurrency(acct) == "" {
+ contacts, err := s.store.SavedContacts(ctx, acct.ID)
+ if err != nil {
+ log.Printf("console: domain buy %s: saved contacts: %v", acct.Sqid, err)
+ }
+ if err == nil && len(contacts) == 0 {
+ v.AskCountry, v.Countries = true, countryOptions(country)
+ }
+ }
+ return v
+}
+
+func quoteView(v *accountBuyView, q domainreg.Quote) {
+ v.Quote, v.Name = q, q.Domain
+ v.PerYear = domainsFill(accountBuyCopy.PerYear, "{price}", plans.FormatMinor(q.Currency, q.Price))
+}
+
+// buyAppStep is step 2: the account's apps that can take a domain, and Not
+// yet. Nothing is picked unless app= named one of them or notyet=1.
+func (s *Server) buyAppStep(acct *Account, q domainreg.Quote, apps []string, app string, notYet bool, country string) *accountBuyView {
+ v := newAccountBuyView(acct, "app")
+ quoteView(v, q)
+ v.Country = country
+ for _, a := range apps {
+ v.Apps = append(v.Apps, buyAppChoice{App: a, Checked: !notYet && a == app})
+ }
+ v.NotYetPicked = notYet && app == ""
+ v.PointNote = domainsFill(domainsPageCopy.PointNote, "{domain}", q.Domain)
+ v.Back = domainsBase(acct) + "/domains/buy?name=" + url.QueryEscape(q.Domain)
+ if app != "" {
+ v.Back += "&app=" + url.QueryEscape(app)
+ }
+ if country != "" {
+ v.Back += "&country=" + url.QueryEscape(country)
+ }
+ return v
+}
+
+// buyPayStep is step 3: the order and who the domain is registered to.
+// picked is the contact chosen ("" for the most recently used, "new" for a
+// new one), entered the new contact's fields as posted.
+func (s *Server) buyPayStep(ctx context.Context, acct *Account, q domainreg.Quote, app, country, picked string, entered *registrar.Contact) (*accountBuyView, error) {
+ v := newAccountBuyView(acct, "pay")
+ quoteView(v, q)
+ v.App, v.NotYet, v.Country = app, app == "", country
+ v.Back = buyStepURL(acct, "app", q.Domain, app, app == "", country)
+ price := domainTile{Label: accountBuyCopy.TilePrice, Value: plans.FormatMinor(q.Currency, q.Price),
+ Detail: domainsFill(accountBuyCopy.PriceDetail, "{domain}", q.Domain)}
+ points := domainTile{Label: accountBuyCopy.TilePointsAt, Value: app, Detail: domainsFill(accountBuyCopy.PointsAtDetail, "{domain}", q.Domain)}
+ if app == "" {
+ points.Value, points.Detail = accountBuyCopy.NotYet, accountBuyCopy.NotYetDetail
+ }
+ v.Tiles = []domainTile{price, points}
+ contacts, err := s.store.SavedContacts(ctx, acct.ID)
+ if err != nil {
+ return nil, err
+ }
+ known := false
+ for i, c := range contacts {
+ checked := c.ID == picked || (picked == "" && i == 0)
+ known = known || checked
+ v.Contacts = append(v.Contacts, buyContactChoice{ID: c.ID, Checked: checked,
+ Name: strings.TrimSpace(c.Contact.FirstName + " " + c.Contact.LastName), Detail: c.Contact.Email + " · " + c.Contact.Country})
+ }
+ v.NewPicked = !known
+ v.Filter = len(contacts) > buyContactFilterAt
+ contact := registrar.Contact{Country: country}
+ if entered != nil {
+ contact = *entered
+ }
+ fields := buyContactFields(contact)
+ for i := range fields {
+ fields[i].ID = "buy-" + fields[i].Name
+ // Hidden behind a saved contact, the fields cannot be required in
+ // HTML; the purchase checks a new contact itself.
+ fields[i].Required = fields[i].Required && len(contacts) == 0
+ }
+ v.NewFields = fields
+ return v, nil
+}
+
+// handleAccountDomainBuyCheck is step 1's search: it checks the name with
+// the registrar (Plan 1's check, its refusals unchanged) and goes on to
+// step 2.
+func (s *Server) handleAccountDomainBuyCheck(w http.ResponseWriter, r *http.Request) {
+ _, _, acct, ok := s.domainBuyAccountGate(w, r)
+ if !ok {
+ return
+ }
+ // The app only travels on to step 2's preselection; nothing here acts
+ // on it.
+ app, country := r.FormValue("app"), r.FormValue("country")
+ ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
+ defer cancel()
+ q, ref := s.checkDomainBuy(ctx, acct, r.FormValue("name"), country)
+ if ref != nil {
+ s.renderDoorRefusal(w, r, ref)
+ return
+ }
+ http.Redirect(w, r, buyStepURL(acct, "app", q.Domain, app, false, country), http.StatusSeeOther)
+}
+
+// handleAccountDomainBuyPay is step 3's form: it starts the purchase
+// (Plan 1's startDomainPurchase, every check again) and sends the owner to
+// Checkout. A form with neither an app nor notyet=1 (or both) goes back to
+// step 2 and starts nothing.
+func (s *Server) handleAccountDomainBuyPay(w http.ResponseWriter, r *http.Request) {
+ addr, raw, acct, ok := s.domainBuyAccountGate(w, r)
+ if !ok {
+ return
+ }
+ name, app, country := r.FormValue("name"), r.FormValue("app"), r.FormValue("country")
+ if notYet := r.FormValue("notyet") == "1"; notYet == (app != "") {
+ http.Redirect(w, r, buyStepURL(acct, "app", name, app, false, country), http.StatusSeeOther)
+ return
+ }
+ if ref := s.customDomainRefusal(acct, name); ref != nil {
+ s.renderDoorRefusal(w, r, ref)
+ return
+ }
+ picked := r.FormValue("contact")
+ entered := contactFromForm(r)
+ sel := purchaseContactSelection{ID: picked}
+ if picked == "new" {
+ sel = purchaseContactSelection{New: &entered}
+ }
+ price, err := strconv.ParseInt(r.FormValue("price"), 10, 64)
+ if err != nil {
+ price = 0
+ }
+ ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
+ defer cancel()
+ p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, app, name, sel, addr, domainreg.Quote{Currency: r.FormValue("currency"), Price: price})
+ if changed != nil || (ref != nil && ref.Status == http.StatusUnprocessableEntity && ref.Msg == domainBuyCopy["contactError"]) {
+ s.buyPayAgain(w, r, addr, raw, acct, changed, ref, app, country, picked, &entered)
+ return
+ }
+ if ref != nil {
+ s.renderDoorRefusal(w, r, ref)
+ return
+ }
+ if checkout == "" {
+ checkout = domainPurchaseURL(acct.Sqid, p.ID)
+ }
+ http.Redirect(w, r, checkout, http.StatusSeeOther)
+}
+
+// buyPayAgain is step 3 again, as posted: with the changed price to
+// confirm (409), or the contact to correct (422).
+func (s *Server) buyPayAgain(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, changed *domainreg.Quote, ref *doorRefusal, app, country, picked string, entered *registrar.Contact) {
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ var q domainreg.Quote
+ if changed != nil {
+ q = *changed
+ } else {
+ var qref *doorRefusal
+ if q, qref = s.buyStepQuote(ctx, acct, r.FormValue("name"), country); qref != nil {
+ s.renderDoorRefusal(w, r, ref)
+ return
+ }
+ }
+ if picked != "new" {
+ entered = nil
+ }
+ v, err := s.buyPayStep(ctx, acct, q, app, country, picked, entered)
+ if err != nil {
+ s.renderDoorRefusal(w, r, domainBuyUnavailable())
+ return
+ }
+ v.Alert, v.PriceChanged = ref.Msg, changed != nil
+ s.renderAccountBuy(w, r, addr, raw, acct, ref.Status, v)
+}
+
+// ---- the purchase card --------------------------------------------------------
+
+// accountPurchase reads the path's purchase for the gate's account: an
+// unknown one and another account's are the same 404.
+func (s *Server) accountPurchase(w http.ResponseWriter, r *http.Request, acct *Account) *DomainPurchase {
+ return s.purchaseForAccount(w, r, acct, "")
+}
+
+// handleAccountDomainPurchase is a purchase's card: Plan 1's, at the
+// account, the page Checkout returns to.
+func (s *Server) handleAccountDomainPurchase(w http.ResponseWriter, r *http.Request) {
+ addr, raw, acct, ok := s.domainBuyAccountGate(w, r)
+ if !ok {
+ return
+ }
+ p := s.accountPurchase(w, r, acct)
+ if p == nil {
+ return
+ }
+ var checkout string
+ if p.State == PurchaseAwaitingPayment && p.CheckoutSession != "" && time.Now().Before(p.CheckoutExpires) {
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ info, err := s.billing.cfg.Provider.PaymentCheckout(ctx, p.CheckoutSession)
+ if err == nil && info.Status == "open" {
+ checkout = info.URL
+ }
+ }
+ var domainState string
+ if p.State == PurchaseDone {
+ ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
+ defer cancel()
+ domainState = s.purchaseDomainState(ctx, acct, p)
+ }
+ s.renderPurchaseCard(w, r, addr, raw, acct, &domainBuyView{Purchase: p, DomainState: domainState, CheckoutURL: checkout,
+ PollURL: domainPurchaseURL(acct.Sqid, p.ID) + "/status"})
+}
+
+// handleAccountDomainPurchaseStatus is the card's poll. A purchase whose
+// app went away reads as having none from the moment it knows, so the
+// card stops saying it is connecting the domain to that app.
+func (s *Server) handleAccountDomainPurchaseStatus(w http.ResponseWriter, r *http.Request) {
+ _, _, acct, ok := s.domainBuyAccountGate(w, r)
+ if !ok {
+ return
+ }
+ p := s.accountPurchase(w, r, acct)
+ if p == nil {
+ return
+ }
+ if p.Unpointing {
+ cp := *p
+ cp.App = ""
+ p = &cp
+ }
+ s.writeDomainPurchaseStatus(w, r, acct, p)
+}
+
+// ---- saved contacts -------------------------------------------------------------
+
+// contactsGate is the saved-contact doors' gate: a member's session, CSRF,
+// then the owner (anyone else gets the neutral 404). Saved contacts are
+// personal data, so they stay editable and removable even while buying is
+// not configured.
+func (s *Server) contactsGate(w http.ResponseWriter, r *http.Request) (*Account, bool) {
+ _, raw, acct, role, ok := s.account(w, r)
+ if !ok {
+ return nil, false
+ }
+ if !csrfFormOK(r, raw) {
+ s.renderMessage(w, r, http.StatusForbidden, domainBuyCopy["refused"], domainBuyCopy["csrf"])
+ return nil, false
+ }
+ if role != RoleOwner {
+ http.NotFound(w, r)
+ return nil, false
+ }
+ return acct, true
+}
+
+func contactsBack(acct *Account) string { return domainsBase(acct) + "/domains#contacts" }
+
+// savedContactOf is the path's saved contact of acct, or nil after the
+// neutral 404 (an unknown contact and another account's are the same).
+func (s *Server) savedContactOf(w http.ResponseWriter, r *http.Request, acct *Account) *SavedContact {
+ c, err := s.store.SavedContact(r.Context(), acct.ID, r.PathValue("id"))
+ if err != nil {
+ log.Printf("console: saved contact %s: %v", acct.Sqid, err)
+ s.renderMessage(w, r, http.StatusServiceUnavailable, "Error", accountBuyCopy.ContactFailed)
+ return nil
+ }
+ if c == nil {
+ http.NotFound(w, r)
+ }
+ return c
+}
+
+func (s *Server) handleDomainContactAdd(w http.ResponseWriter, r *http.Request) {
+ acct, ok := s.contactsGate(w, r)
+ if !ok {
+ return
+ }
+ c := contactFromForm(r)
+ switch {
+ case c.Validate() != nil:
+ s.setFlash(w, "err", domainBuyCopy["contactError"])
+ default:
+ if _, err := s.store.AddSavedContact(r.Context(), acct.ID, c, time.Now()); err != nil {
+ log.Printf("console: add saved contact %s: %v", acct.Sqid, err)
+ s.setFlash(w, "err", accountBuyCopy.ContactFailed)
+ } else {
+ s.setFlash(w, "ok", accountBuyCopy.ContactAdded)
+ }
+ }
+ http.Redirect(w, r, contactsBack(acct), http.StatusSeeOther)
+}
+
+// handleDomainContactEdit saves a contact's new details. The store bumps
+// its version and clears its registrar handle, so purchases started from
+// now on use the new details; purchases already started keep their copy.
+func (s *Server) handleDomainContactEdit(w http.ResponseWriter, r *http.Request) {
+ acct, ok := s.contactsGate(w, r)
+ if !ok {
+ return
+ }
+ saved := s.savedContactOf(w, r, acct)
+ if saved == nil {
+ return
+ }
+ c := contactFromForm(r)
+ if c.Validate() != nil {
+ s.setFlash(w, "err", domainBuyCopy["contactError"])
+ http.Redirect(w, r, contactsBack(acct), http.StatusSeeOther)
+ return
+ }
+ err := s.store.EditSavedContact(r.Context(), acct.ID, saved.ID, c)
+ switch {
+ case errors.Is(err, ErrSavedContactNotFound):
+ http.NotFound(w, r)
+ return
+ case err != nil:
+ log.Printf("console: edit saved contact %s: %v", acct.Sqid, err)
+ s.setFlash(w, "err", accountBuyCopy.ContactFailed)
+ default:
+ s.setFlash(w, "ok", accountBuyCopy.ContactSaved)
+ }
+ http.Redirect(w, r, contactsBack(acct), http.StatusSeeOther)
+}
+
+func (s *Server) handleDomainContactRemove(w http.ResponseWriter, r *http.Request) {
+ acct, ok := s.contactsGate(w, r)
+ if !ok {
+ return
+ }
+ err := s.store.RemoveSavedContact(r.Context(), acct.ID, r.PathValue("id"))
+ switch {
+ case errors.Is(err, ErrSavedContactNotFound):
+ http.NotFound(w, r)
+ return
+ case err != nil:
+ log.Printf("console: remove saved contact %s: %v", acct.Sqid, err)
+ s.setFlash(w, "err", accountBuyCopy.ContactFailed)
+ default:
+ s.setFlash(w, "ok", accountBuyCopy.ContactRemoved)
+ }
+ http.Redirect(w, r, contactsBack(acct), http.StatusSeeOther)
+}
diff --git a/internal/console/accountdomainbuy_test.go b/internal/console/accountdomainbuy_test.go
new file mode 100644
index 000000000..45056643d
--- /dev/null
+++ b/internal/console/accountdomainbuy_test.go
@@ -0,0 +1,543 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/url"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/billing"
+ "github.com/carlosframework/platform/internal/registrar"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// The account's three-step buy, its saved contacts, the account-scoped
+// purchase card and the old app-scoped routes' redirects (Plan 2a Task 9).
+
+func (f *purchaseFixture) acctURL(path string) string {
+ return f.ts.URL + "/a/" + f.acct.Sqid + path
+}
+
+// contactForm is a contact as the browser forms post it.
+func contactForm(c registrar.Contact) url.Values {
+ return url.Values{
+ "FirstName": {c.FirstName}, "LastName": {c.LastName}, "Company": {c.Company}, "Email": {c.Email},
+ "PhoneCountryCode": {c.PhoneCountryCode}, "Phone": {c.Phone}, "Street": {c.Street}, "HouseNumber": {c.HouseNumber},
+ "City": {c.City}, "State": {c.State}, "PostalCode": {c.PostalCode}, "Country": {c.Country},
+ }
+}
+
+func withValues(base url.Values, kv ...string) url.Values {
+ out := url.Values{}
+ for k, v := range base {
+ out[k] = append([]string(nil), v...)
+ }
+ for i := 0; i+1 < len(kv); i += 2 {
+ out.Set(kv[i], kv[i+1])
+ }
+ return out
+}
+
+// lastCheckout is the last Checkout request the provider fake was sent.
+func (f *purchaseFixture) lastCheckout(t *testing.T) billing.PaymentCheckoutRequest {
+ t.Helper()
+ for i := len(f.fake.Sent) - 1; i >= 0; i-- {
+ if f.fake.Sent[i].Kind != billing.PreparedPaymentCheckout {
+ continue
+ }
+ var body struct {
+ Request billing.PaymentCheckoutRequest
+ }
+ if err := json.Unmarshal(f.fake.Sent[i].Body, &body); err != nil {
+ t.Fatal(err)
+ }
+ return body.Request
+ }
+ t.Fatal("no checkout sent")
+ return billing.PaymentCheckoutRequest{}
+}
+
+func (f *purchaseFixture) purchaseCount(t *testing.T) int {
+ t.Helper()
+ var n int
+ if err := f.st.db.QueryRow(`SELECT count(*) FROM domain_purchases WHERE account_id=?`, f.acct.ID).Scan(&n); err != nil {
+ t.Fatal(err)
+ }
+ return n
+}
+
+// assertStartedNothing: no purchase row, no registrar call, no Checkout.
+func (f *purchaseFixture) assertStartedNothing(t *testing.T) {
+ t.Helper()
+ if n := f.purchaseCount(t); n != 0 {
+ t.Fatalf("%d purchase(s) written", n)
+ }
+ if len(f.reg.Calls) != 0 {
+ t.Fatalf("registrar calls: %v", f.reg.Calls)
+ }
+ if n := f.sent(billing.PreparedPaymentCheckout); n != 0 {
+ t.Fatalf("%d checkout(s) sent", n)
+ }
+}
+
+func TestAccountBuyThreeStepsToCheckout(t *testing.T) {
+ for _, saved := range []bool{false, true} {
+ t.Run(map[bool]string{false: "new contact", true: "saved contact"}[saved], func(t *testing.T) {
+ f := newPurchaseFixture(t)
+ if _, err := f.st.CreateAppIn(f.acct.ID, "blog", "buyer@example.test", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ var savedID string
+ if saved {
+ sc, err := f.st.AddSavedContact(context.Background(), f.acct.ID, purchaseContact(), time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ savedID = sc.ID
+ }
+ c, csrf := f.ownerBrowser(t)
+ base := "/a/" + f.acct.Sqid + "/domains/buy"
+
+ // Step 1, preselected from an app's Settings.
+ status, _, body := get(t, c, f.acctURL("/domains/buy?app=kass"))
+ if status != 200 || !strings.Contains(body, `action="`+base+`/check"`) || !strings.Contains(body, `name="app" value="kass"`) {
+ t.Fatalf("step 1: %d %s", status, body)
+ }
+ // Step 1 -> quote -> step 2.
+ status, loc, body := postForm(t, c, f.acctURL("/domains/buy/check"), url.Values{"csrf": {csrf}, "name": {"SHOP.com"}, "app": {"kass"}})
+ if status != http.StatusSeeOther || loc != base+"?step=app&name=shop.com&app=kass" {
+ t.Fatalf("check: %d %q %s", status, loc, body)
+ }
+ if n := purchaseCalls(f.reg.Calls, "check:"); n != 1 {
+ t.Fatalf("registrar checks %d, want 1", n)
+ }
+ status, _, body = get(t, c, f.ts.URL+loc)
+ if status != 200 || !strings.Contains(body, "<code>shop.com</code>") || !strings.Contains(body, "$15") ||
+ !strings.Contains(body, `value="app:kass" checked`) || !strings.Contains(body, `value="app:blog"`) || !strings.Contains(body, `value="notyet"`) {
+ t.Fatalf("step 2: %d %s", status, body)
+ }
+ // The app stays changeable: choosing blog goes to step 3 for blog.
+ status, loc, _ = get(t, c, f.acctURL("/domains/buy?step=pay&name=shop.com&choice=app:blog"))
+ if status != http.StatusSeeOther || loc != base+"?step=pay&name=shop.com&app=blog" {
+ t.Fatalf("choice: %d %q", status, loc)
+ }
+ status, _, body = get(t, c, f.ts.URL+loc)
+ if status != 200 || !strings.Contains(body, `action="`+base+`"`) || !strings.Contains(body, `name="currency" value="usd"`) ||
+ !strings.Contains(body, `name="price" value="1500"`) || !strings.Contains(body, `name="app" value="blog"`) || !strings.Contains(body, `value="new"`) {
+ t.Fatalf("step 3: %d %s", status, body)
+ }
+ if saved && !strings.Contains(body, `value="`+savedID+`" checked`) {
+ t.Fatal("step 3 does not preselect the most recently used saved contact")
+ }
+ if !saved && !strings.Contains(body, `name="contact" value="new"`) {
+ t.Fatal("step 3 with no saved contact does not ask for a new one")
+ }
+ // Step 3 -> purchase -> Checkout.
+ form := url.Values{"csrf": {csrf}, "name": {"shop.com"}, "app": {"blog"}, "currency": {"usd"}, "price": {"1500"}}
+ if saved {
+ form.Set("contact", savedID)
+ } else {
+ form = withValues(contactForm(purchaseContact()), "csrf", csrf, "name", "shop.com", "app", "blog", "currency", "usd", "price", "1500", "contact", "new")
+ }
+ status, loc, body = postForm(t, c, f.acctURL("/domains/buy"), form)
+ p, err := f.srv.ownLiveDomainPurchase(context.Background(), f.acct.ID, "shop.com")
+ if err != nil || p == nil {
+ t.Fatalf("no purchase: %d %s %v", status, body, err)
+ }
+ info, err := f.fake.PaymentCheckout(context.Background(), p.CheckoutSession)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if status != http.StatusSeeOther || loc != info.URL {
+ t.Fatalf("buy: %d %q, want 303 to %q", status, loc, info.URL)
+ }
+ if p.App != "blog" || p.Contact.Email != purchaseContact().Email {
+ t.Fatalf("purchase app %q contact %+v", p.App, p.Contact)
+ }
+ back := f.srv.cfg.Origin + "/a/" + f.acct.Sqid + "/domains/purchases/" + p.ID
+ if r := f.lastCheckout(t); r.SuccessURL != back || r.CancelURL != back {
+ t.Fatalf("checkout return %q / %q, want %q", r.SuccessURL, r.CancelURL, back)
+ }
+ if contacts, _ := f.st.SavedContacts(context.Background(), f.acct.ID); len(contacts) != 1 {
+ t.Fatalf("saved contacts after the purchase: %d, want 1", len(contacts))
+ }
+ })
+ }
+}
+
+func TestAccountBuyNotYetNeedsExplicitChoice(t *testing.T) {
+ f := newPurchaseFixture(t)
+ c, csrf := f.ownerBrowser(t)
+ base := "/a/" + f.acct.Sqid + "/domains/buy"
+ // No app and no notyet=1 is never a silent "Not yet": step 2 again.
+ for _, q := range []string{"?step=pay&name=shop.com", "?step=pay&name=shop.com&app=", "?step=pay&name=shop.com&notyet=0", "?step=pay&name=shop.com&app=nosuch"} {
+ status, _, body := get(t, c, f.acctURL("/domains/buy"+q))
+ if status != 200 || !strings.Contains(body, `name="choice"`) || strings.Contains(body, `name="contact"`) {
+ t.Fatalf("%s: %d %s", q, status, body)
+ }
+ if strings.Contains(body, `value="notyet" checked`) {
+ t.Fatalf("%s: Not yet is preselected", q)
+ }
+ }
+ status, loc, _ := get(t, c, f.acctURL("/domains/buy?step=pay&name=shop.com&choice=notyet"))
+ if status != http.StatusSeeOther || loc != base+"?step=pay&name=shop.com&notyet=1" {
+ t.Fatalf("choice notyet: %d %q", status, loc)
+ }
+ status, _, body := get(t, c, f.ts.URL+loc)
+ if status != 200 || !strings.Contains(body, `name="notyet" value="1"`) || !strings.Contains(body, accountBuyCopy.NotYet) || strings.Contains(body, `name="app" value="kass"`) {
+ t.Fatalf("step 3 not yet: %d %s", status, body)
+ }
+ // The purchase door refuses the same way: back to step 2, nothing started.
+ form := withValues(contactForm(purchaseContact()), "csrf", csrf, "name", "shop.com", "currency", "usd", "price", "1500", "contact", "new")
+ status, loc, _ = postForm(t, c, f.acctURL("/domains/buy"), form)
+ if status != http.StatusSeeOther || loc != base+"?step=app&name=shop.com" {
+ t.Fatalf("buy without a choice: %d %q", status, loc)
+ }
+ f.assertStartedNothing(t)
+ // An explicit Not yet buys with no app.
+ status, _, body = postForm(t, c, f.acctURL("/domains/buy"), withValues(form, "notyet", "1"))
+ p, err := f.srv.ownLiveDomainPurchase(context.Background(), f.acct.ID, "shop.com")
+ if status != http.StatusSeeOther || err != nil || p == nil || p.App != "" {
+ t.Fatalf("not yet: %d %s %+v %v", status, body, p, err)
+ }
+}
+
+func TestNotYetCheckoutReturnsToAccountPath(t *testing.T) {
+ f := newPurchaseFixture(t)
+ c, csrf := f.ownerBrowser(t)
+ form := withValues(contactForm(purchaseContact()), "csrf", csrf, "name", "shop.com", "notyet", "1", "currency", "usd", "price", "1500", "contact", "new")
+ if status, _, body := postForm(t, c, f.acctURL("/domains/buy"), form); status != http.StatusSeeOther {
+ t.Fatalf("buy: %d %s", status, body)
+ }
+ p, err := f.srv.ownLiveDomainPurchase(context.Background(), f.acct.ID, "shop.com")
+ if err != nil || p == nil {
+ t.Fatal(p, err)
+ }
+ path := "/a/" + f.acct.Sqid + "/domains/purchases/" + p.ID
+ if got := domainPurchaseURL(f.acct.Sqid, p.ID); got != path {
+ t.Fatalf("domainPurchaseURL = %q, want %q", got, path)
+ }
+ if r := f.lastCheckout(t); r.SuccessURL != f.srv.cfg.Origin+path || r.CancelURL != f.srv.cfg.Origin+path {
+ t.Fatalf("checkout return %q / %q", r.SuccessURL, r.CancelURL)
+ }
+ status, _, body := get(t, c, f.ts.URL+path)
+ if status != 200 || purchaseAttr(purchaseElement(t, body, "purchase-continue"), "href") == "" {
+ t.Fatalf("card: %d %s", status, body)
+ }
+ if status, _, body := get(t, c, f.ts.URL+path+"/status"); status != 200 || !strings.Contains(body, `"state":"awaiting_payment"`) {
+ t.Fatalf("status: %d %s", status, body)
+ }
+ f.authorise(t, p)
+ f.until(t, p.ID, PurchaseDone)
+ status, _, body = get(t, c, f.ts.URL+path)
+ want := strings.NewReplacer("{domain}", "shop.com").Replace(accountBuyCopy.ReadyTitle)
+ if status != 200 || purchaseText(purchaseElement(t, body, "purchase-title")) != want ||
+ purchaseText(purchaseElement(t, body, "purchase-lede")) != accountBuyCopy.ReadyLede {
+ t.Fatalf("done card: %d %s", status, body)
+ }
+ point := purchaseElement(t, body, "purchase-point")
+ if purchaseHidden(point) || purchaseAttr(point, "href") != "/a/"+f.acct.Sqid+"/domains/shop.com#point" {
+ t.Fatal("done card has no Point at an app")
+ }
+ if purchaseAttr(purchaseElement(t, body, "purchase-back"), "href") != "/a/"+f.acct.Sqid+"/domains" {
+ t.Fatal("the card does not go back to the account's domains")
+ }
+}
+
+// TestPurchaseCardNoAppReadyLede: a purchase with no app, or one whose app
+// went away (Unpointing), never says it is connecting to an app.
+func TestPurchaseCardNoAppReadyLede(t *testing.T) {
+ for _, p := range []*DomainPurchase{
+ {Domain: "shop.com", App: "kass", State: PurchaseCaptured, purchaseDetails: purchaseDetails{Unpointing: true}},
+ {Domain: "shop.com", App: "", State: PurchaseCaptured},
+ {Domain: "shop.com", App: "", State: PurchaseRegistered},
+ } {
+ card := purchaseCard(p, "")
+ if card.Lede != accountBuyCopy.ReadyLede || strings.Contains(card.Lede, "kass") {
+ t.Errorf("%+v: lede %q", p, card.Lede)
+ }
+ }
+ card := purchaseCard(&DomainPurchase{Domain: "shop.com", State: PurchaseRegistering}, "")
+ if card.Lede != accountBuyCopy.NoAppProgressLede || card.Stage.Steps != [4]string{"done", "active", "", ""} {
+ t.Errorf("registering with no app: %+v", card)
+ }
+}
+
+func TestAccountBuyMemberAndServiceTokenRefused(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ sc, err := f.st.AddSavedContact(context.Background(), f.acct.ID, purchaseContact(), time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := f.st.AddMember(f.acct.ID, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ gets := []string{"/domains/buy", "/domains/buy?step=app&name=shop.com", "/domains/buy?step=pay&name=shop.com&app=kass",
+ "/domains/purchases/" + p.ID, "/domains/purchases/" + p.ID + "/status"}
+ posts := []string{"/domains/buy/check", "/domains/buy", "/domains/contacts", "/domains/contacts/" + sc.ID, "/domains/contacts/" + sc.ID + "/remove"}
+ form := withValues(contactForm(purchaseContact()), "name", "shop.com", "app", "kass", "currency", "usd", "price", "1500", "contact", sc.ID)
+ for _, addr := range []string{"member@example.com", "stranger@example.com"} {
+ c := newBrowser(t)
+ f.setUser(addr)
+ signUp(t, f.consoleFixture, c, "acct-buy-"+addr)
+ for _, path := range gets {
+ if status, _, body := get(t, c, f.acctURL(path)); status != 404 || body != "404 page not found\n" {
+ t.Fatalf("%s GET %s: %d %q", addr, path, status, body)
+ }
+ }
+ for _, path := range posts {
+ a := rawPost(t, c, f.acctURL(path), withValues(form, "csrf", sessionToken(t, f.consoleFixture, c)), "")
+ if a.Status != 404 || a.Body != "404 page not found\n" {
+ t.Fatalf("%s POST %s: %+v", addr, path, a)
+ }
+ }
+ }
+ // A service credential is not a session: every door sends it to sign in.
+ service := serviceToken(t, f.st, f.acct.ID, "pub", "kass", svcrole.Publish)
+ anon := newBrowser(t)
+ for _, path := range posts {
+ if a := rawPost(t, anon, f.acctURL(path), form, service); a.Status != http.StatusFound || a.Location != "/" {
+ t.Fatalf("service POST %s: %+v", path, a)
+ }
+ }
+ for _, path := range gets {
+ req, _ := http.NewRequest(http.MethodGet, f.acctURL(path), nil)
+ req.Header.Set("Authorization", "Bearer "+service)
+ res, err := anon.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ res.Body.Close()
+ if res.StatusCode != http.StatusFound || res.Header.Get("Location") != "/" {
+ t.Fatalf("service GET %s: %d %q", path, res.StatusCode, res.Header.Get("Location"))
+ }
+ }
+ if n := f.purchaseCount(t); n != 1 {
+ t.Fatalf("purchases %d, want the one started", n)
+ }
+ if got, _ := f.st.SavedContact(context.Background(), f.acct.ID, sc.ID); got == nil || got.Version != 1 {
+ t.Fatalf("saved contact changed: %+v", got)
+ }
+}
+
+func TestAccountBuyCSRFRequired(t *testing.T) {
+ f := newPurchaseFixture(t)
+ sc, err := f.st.AddSavedContact(context.Background(), f.acct.ID, purchaseContact(), time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ c, _ := f.ownerBrowser(t)
+ form := withValues(contactForm(purchaseContact()), "name", "shop.com", "app", "kass", "currency", "usd", "price", "1500", "contact", sc.ID)
+ for _, path := range []string{"/domains/buy/check", "/domains/buy", "/domains/contacts", "/domains/contacts/" + sc.ID, "/domains/contacts/" + sc.ID + "/remove",
+ "/apps/kass/domains/check", "/apps/kass/domains/buy"} {
+ for _, token := range []string{"", "forged"} {
+ a := rawPost(t, c, f.acctURL(path), withValues(form, "csrf", token), "")
+ if a.Status != http.StatusForbidden || !strings.Contains(a.Body, domainBuyCopy["csrf"]) {
+ t.Fatalf("POST %s csrf=%q: %+v", path, token, a)
+ }
+ }
+ }
+ f.assertStartedNothing(t)
+ contacts, err := f.st.SavedContacts(context.Background(), f.acct.ID)
+ if err != nil || len(contacts) != 1 || contacts[0].Version != 1 {
+ t.Fatalf("saved contacts changed: %+v %v", contacts, err)
+ }
+}
+
+func TestOldPurchaseURLsRedirect(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ c, _ := f.ownerBrowser(t)
+ sqid := f.acct.Sqid
+ check := func(t *testing.T) {
+ t.Helper()
+ for old, want := range map[string]string{
+ "/apps/kass/domains/buy": "/a/" + sqid + "/domains/buy?app=kass",
+ "/apps/kass/domains/purchases/" + p.ID: "/a/" + sqid + "/domains/purchases/" + p.ID,
+ "/apps/kass/domains/purchases/" + p.ID + "/status": "/a/" + sqid + "/domains/purchases/" + p.ID + "/status",
+ "/apps/gone-app/domains/purchases/" + p.ID: "/a/" + sqid + "/domains/purchases/" + p.ID,
+ "/apps/gone-app/domains/purchases/" + p.ID + "/status": "/a/" + sqid + "/domains/purchases/" + p.ID + "/status",
+ } {
+ if status, loc, _ := get(t, c, f.acctURL(old)); status != http.StatusSeeOther || loc != want {
+ t.Errorf("GET %s: %d %q, want 303 %q", old, status, loc, want)
+ }
+ }
+ for _, old := range []string{"/apps/kass/domains/purchases/dp_unknown", "/apps/kass/domains/purchases/dp_unknown/status"} {
+ if status, _, body := get(t, c, f.acctURL(old)); status != 404 || body != "404 page not found\n" {
+ t.Errorf("GET %s: %d %q", old, status, body)
+ }
+ }
+ }
+ check(t)
+ // A Checkout return after the app was purged still lands.
+ if err := f.st.TrashAppRow(f.acct.ID, "kass", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.st.PurgeAppRow(f.acct.ID, "kass"); err != nil {
+ t.Fatal(err)
+ }
+ check(t)
+ if status, _, _ := get(t, c, f.acctURL("/domains/purchases/"+p.ID)); status != 200 {
+ t.Fatalf("the account card after the purge: %d", status)
+ }
+}
+
+func TestOldBuyPostsRedirectAndStartNothing(t *testing.T) {
+ f := newPurchaseFixture(t)
+ c, csrf := f.ownerBrowser(t)
+ form := withValues(contactForm(purchaseContact()), "csrf", csrf, "name", "shop.com", "currency", "usd", "price", "1500")
+ for _, path := range []string{"/apps/kass/domains/check", "/apps/kass/domains/buy"} {
+ status, loc, body := postForm(t, c, f.acctURL(path), form)
+ if status != http.StatusSeeOther || loc != "/a/"+f.acct.Sqid+"/domains/buy?app=kass" {
+ t.Fatalf("POST %s: %d %q %s", path, status, loc, body)
+ }
+ }
+ f.assertStartedNothing(t)
+ if contacts, _ := f.st.SavedContacts(context.Background(), f.acct.ID); len(contacts) != 0 {
+ t.Fatalf("a stale form saved a contact: %+v", contacts)
+ }
+}
+
+func TestPurchaseCardOtherAccount404(t *testing.T) {
+ f := newPurchaseFixture(t)
+ p := f.start(t)
+ other := planAccount(t, f.consoleFixture, 502)
+ if _, err := f.st.CreateAppIn(other.ID, "kass", "other@example.com", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ c := newBrowser(t)
+ f.setUser("owner" + other.Sqid + "@example.com")
+ signUp(t, f.consoleFixture, c, "card-other")
+ for _, prefix := range []string{"/a/" + other.Sqid + "/domains/purchases/", "/a/" + other.Sqid + "/apps/kass/domains/purchases/"} {
+ for _, suffix := range []string{"", "/status"} {
+ s1, _, b1 := get(t, c, f.ts.URL+prefix+p.ID+suffix)
+ s2, _, b2 := get(t, c, f.ts.URL+prefix+"dp_unknown"+suffix)
+ if s1 != 404 || s2 != 404 || b1 != b2 {
+ t.Fatalf("%s%s: foreign %d %q, unknown %d %q", prefix, suffix, s1, b1, s2, b2)
+ }
+ }
+ }
+}
+
+func TestContactsEditRemoveOwnerOnly(t *testing.T) {
+ f := newPurchaseFixture(t)
+ ctx := context.Background()
+ sc, err := f.st.AddSavedContact(ctx, f.acct.ID, purchaseContact(), time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := f.st.db.Exec(`UPDATE domain_saved_contacts SET handle='H-1' WHERE id=?`, sc.ID); err != nil {
+ t.Fatal(err)
+ }
+ other := planAccount(t, f.consoleFixture, 502)
+ foreign, err := f.st.AddSavedContact(ctx, other.ID, purchaseContact(), time.Now())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := f.st.AddMember(f.acct.ID, "member@example.com", RoleMember, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ edited := purchaseContact()
+ edited.FirstName, edited.City = "Janet", "Cork"
+ member := newBrowser(t)
+ f.setUser("member@example.com")
+ signUp(t, f.consoleFixture, member, "contacts-member")
+ memberCSRF := sessionToken(t, f.consoleFixture, member)
+ for _, path := range []string{"/domains/contacts", "/domains/contacts/" + sc.ID, "/domains/contacts/" + sc.ID + "/remove"} {
+ if a := rawPost(t, member, f.acctURL(path), withValues(contactForm(edited), "csrf", memberCSRF), ""); a.Status != 404 {
+ t.Fatalf("member POST %s: %+v", path, a)
+ }
+ }
+ c, csrf := f.ownerBrowser(t)
+ // Another account's contact is the same 404 as an unknown one.
+ for _, id := range []string{foreign.ID, "dc_000000000000"} {
+ for _, suffix := range []string{"", "/remove"} {
+ if a := rawPost(t, c, f.acctURL("/domains/contacts/"+id+suffix), withValues(contactForm(edited), "csrf", csrf), ""); a.Status != 404 || a.Body != "404 page not found\n" {
+ t.Fatalf("POST contact %s%s: %+v", id, suffix, a)
+ }
+ }
+ }
+ if got, _ := f.st.SavedContact(ctx, other.ID, foreign.ID); got == nil || got.Version != 1 {
+ t.Fatalf("foreign contact changed: %+v", got)
+ }
+ back := "/a/" + f.acct.Sqid + "/domains#contacts"
+ // An invalid edit changes nothing.
+ bad := edited
+ bad.Country = "Ireland"
+ if a := rawPost(t, c, f.acctURL("/domains/contacts/"+sc.ID), withValues(contactForm(bad), "csrf", csrf), ""); a.Status != http.StatusSeeOther || a.Location != back {
+ t.Fatalf("invalid edit: %+v", a)
+ }
+ if got, _ := f.st.SavedContact(ctx, f.acct.ID, sc.ID); got.Version != 1 || got.Contact.FirstName != "Jane" {
+ t.Fatalf("invalid edit changed the contact: %+v", got)
+ }
+ // Edit: new details, the version bumped and the handle cleared.
+ if a := rawPost(t, c, f.acctURL("/domains/contacts/"+sc.ID), withValues(contactForm(edited), "csrf", csrf), ""); a.Status != http.StatusSeeOther || a.Location != back {
+ t.Fatalf("edit: %+v", a)
+ }
+ got, _ := f.st.SavedContact(ctx, f.acct.ID, sc.ID)
+ if got == nil || got.Contact != edited || got.Version != 2 || got.RegistrarHandle != "" {
+ t.Fatalf("edited: %+v", got)
+ }
+ // Add.
+ added := purchaseContact()
+ added.FirstName, added.Email = "Sam", "sam@example.test"
+ if a := rawPost(t, c, f.acctURL("/domains/contacts"), withValues(contactForm(added), "csrf", csrf), ""); a.Status != http.StatusSeeOther || a.Location != back {
+ t.Fatalf("add: %+v", a)
+ }
+ contacts, _ := f.st.SavedContacts(ctx, f.acct.ID)
+ if len(contacts) != 2 {
+ t.Fatalf("contacts after add: %+v", contacts)
+ }
+ // The Domains page lists both with their edit forms.
+ status, _, body := get(t, c, f.acctURL("/domains"))
+ if status != 200 || !strings.Contains(body, `action="/a/`+f.acct.Sqid+`/domains/contacts/`+sc.ID+`"`) ||
+ !strings.Contains(body, `formaction="/a/`+f.acct.Sqid+`/domains/contacts/`+sc.ID+`/remove"`) || !strings.Contains(body, `action="/a/`+f.acct.Sqid+`/domains/contacts"`) {
+ t.Fatalf("domains page contacts: %d %s", status, body)
+ }
+ // Remove.
+ if a := rawPost(t, c, f.acctURL("/domains/contacts/"+sc.ID+"/remove"), url.Values{"csrf": {csrf}}, ""); a.Status != http.StatusSeeOther || a.Location != back {
+ t.Fatalf("remove: %+v", a)
+ }
+ if got, _ := f.st.SavedContact(ctx, f.acct.ID, sc.ID); got != nil {
+ t.Fatalf("removed contact still there: %+v", got)
+ }
+}
+
+// browserBuyDoor posts to the account's buy doors as Plan 1's browser
+// forms did: door "check" is step 1's search; "buy" is step 3's purchase,
+// for kass with a new contact from the form's fields unless the form
+// names its own.
+func (f *purchaseFixture) browserBuyDoor(t *testing.T, c *http.Client, door string, values url.Values) (int, string, string) {
+ t.Helper()
+ if door == "check" {
+ return postForm(t, c, f.acctURL("/domains/buy/check"), values)
+ }
+ v := withValues(values)
+ if v.Get("app") == "" && v.Get("notyet") == "" {
+ v.Set("app", "kass")
+ }
+ if v.Get("contact") == "" {
+ v.Set("contact", "new")
+ }
+ return postForm(t, c, f.acctURL("/domains/buy"), v)
+}
+
+// browserQuote is step 1's search followed on to step 3 for kass: the page
+// that shows the quote and confirms it. A refused search is its own answer.
+func (f *purchaseFixture) browserQuote(t *testing.T, c *http.Client, values url.Values) (int, string) {
+ t.Helper()
+ status, loc, body := f.browserBuyDoor(t, c, "check", values)
+ if status != http.StatusSeeOther {
+ return status, body
+ }
+ loc = strings.Replace(loc, "step=app", "step=pay", 1)
+ if !strings.Contains(loc, "&app=") {
+ loc += "&app=kass"
+ }
+ status, _, body = get(t, c, f.ts.URL+loc)
+ return status, body
+}
diff --git a/internal/console/accountdomains_copy.go b/internal/console/accountdomains_copy.go
index d9bd6b2a6..4692f550d 100644
--- a/internal/console/accountdomains_copy.go
+++ b/internal/console/accountdomains_copy.go
@@ -107,3 +107,61 @@ var domainStateChips = map[string][2]string{
StateRegional: {"Per region", "chip-env"},
StateChecking: {"Checking", "chip-env"},
}
+
+// accountBuyCopy is the account's three-step buy, its saved-contact forms
+// and the purchase card's words for a domain bought with no app (Plan 2a
+// Task 9). DRAFTS (2026-11-19) from the domains-account kit, awaiting the
+// copy pass (Task 11). {domain} and {price} are filled by the page.
+var accountBuyCopy = struct {
+ Steps, StepName, StepApp, StepPay string
+ Country, Choose, PerYear string
+ PointAt, NotYet, NotYetNote, ChooseApp string
+ Back, Next string
+ TilePrice, PriceDetail string
+ TilePointsAt, PointsAtDetail, NotYetDetail string
+ Order, OrderNotYet string
+ RegisteredNote, FindContact, AddContact string
+ SavedForNext, Pay string
+ Edit, Save, Remove, SaveContact string
+ ContactSaved, ContactAdded, ContactRemoved string
+ ContactFailed string
+ NoAppProgressLede, ReadyTitle, ReadyLede string
+}{
+ Steps: "Steps",
+ StepName: "Name",
+ StepApp: "App",
+ StepPay: "Details and pay",
+ Country: "Country",
+ Choose: "Choose",
+ PerYear: "{price} a year",
+ PointAt: "Point it at",
+ NotYet: "Not yet",
+ NotYetNote: "Point it at an app later.",
+ ChooseApp: "Choose an app, or Not yet.",
+ Back: "Back",
+ Next: "Next",
+ TilePrice: "Price",
+ PriceDetail: "{domain} for one year",
+ TilePointsAt: "Points at",
+ PointsAtDetail: "{domain} and www",
+ NotYetDetail: "not pointed at an app yet",
+ Order: "Your order",
+ OrderNotYet: "Your order, not pointed at an app",
+ RegisteredNote: "The domain is legally theirs.",
+ FindContact: "Find a contact",
+ AddContact: "Add a new contact",
+ SavedForNext: "Saved for next time.",
+ Pay: "Continue to payment",
+ Edit: "Edit",
+ Save: "Save",
+ Remove: "Remove",
+ SaveContact: "Save contact",
+ ContactSaved: "Contact saved.",
+ ContactAdded: "Contact added.",
+ ContactRemoved: "Contact removed.",
+ ContactFailed: "Could not save your contacts. Try again.",
+
+ NoAppProgressLede: "Payment received, thanks. We’re registering your domain. It usually takes a minute or two, and you can leave this page.",
+ ReadyTitle: "{domain} is yours",
+ ReadyLede: "It’s registered and ready to point at an app.",
+}
diff --git a/internal/console/accountdomainspage.go b/internal/console/accountdomainspage.go
index 6b4b5593d..a05d0d6dd 100644
--- a/internal/console/accountdomainspage.go
+++ b/internal/console/accountdomainspage.go
@@ -21,12 +21,14 @@ import (
"golang.org/x/net/publicsuffix"
"github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/registrar"
)
// domainPageFields is what a page carries for domains: Plan 1's buy flow
// and the account's Domains pages. page embeds it.
type domainPageFields struct {
DomainBuy *domainBuyView
+ AccountBuy *accountBuyView
DomainBuyCopy map[string]string
AccountDomains *accountDomainsView
DomainPage *domainPageView
@@ -35,6 +37,9 @@ type domainPageFields struct {
// DomainsCopy is the Domains pages' strings, for the templates.
func (p page) DomainsCopy() any { return domainsPageCopy }
+// AccountBuyCopy is the account buy page's and saved contacts' strings.
+func (p page) AccountBuyCopy() any { return accountBuyCopy }
+
// domainAddressView is one address row.
type domainAddressView struct {
Host, App, AppHref string
@@ -66,8 +71,13 @@ func (c domainCardView) Unpointed() bool { return c.Bought && len(c.Addresses) =
// domainAppAction is one app an owner can send a form to.
type domainAppAction struct{ App, Action, Label string }
-// domainContactRow is one saved contact, as the list shows it.
-type domainContactRow struct{ Name, Detail string }
+// domainContactRow is one saved contact, as the list shows it, with its
+// edit form's door, remove door and fields when the owner can edit it.
+type domainContactRow struct {
+ Name, Detail string
+ Action, RemoveAction string
+ Fields []domainBuyField
+}
// domainTile is one stat tile. Href, when set, is a link under its value.
type domainTile struct {
@@ -86,6 +96,11 @@ type accountDomainsView struct {
CanAdd bool
ShowContacts bool
Contacts []domainContactRow
+ // ContactsAction is the add form's door and AddFields its fields, set
+ // where the saved-contact doors are registered (not on a host-claim
+ // console).
+ ContactsAction string
+ AddFields []domainBuyField
}
type domainPageView struct {
@@ -241,8 +256,8 @@ func (s *Server) domainCardFor(acct *Account, c domainCard, currency string, own
if p := c.Purchase; p != nil {
v.Buying = true
v.PurchaseStatus = purchaseCard(p, "").Status
- if owner && ready && p.App != "" {
- v.PurchaseHref = domainPurchaseURL(acct.Sqid, p.App, p.ID)
+ if owner && ready {
+ v.PurchaseHref = domainPurchaseURL(acct.Sqid, p.ID)
}
}
if r := c.Registration; r != nil {
@@ -346,10 +361,30 @@ func (s *Server) domainsContacts(ctx context.Context, acct *Account, ready bool,
return
}
v.ShowContacts = ready || len(contacts) > 0
- for _, c := range contacts {
+ editable := !s.cfg.HostClaim
+ if editable {
+ v.ContactsAction = domainsBase(acct) + "/domains/contacts"
+ v.AddFields = contactFormFields("cnew", registrar.Contact{})
+ }
+ for i, c := range contacts {
name := strings.TrimSpace(c.Contact.FirstName + " " + c.Contact.LastName)
- v.Contacts = append(v.Contacts, domainContactRow{Name: name, Detail: c.Contact.Email + " · " + c.Contact.Country})
+ row := domainContactRow{Name: name, Detail: c.Contact.Email + " · " + c.Contact.Country}
+ if editable {
+ row.Action = v.ContactsAction + "/" + url.PathEscape(c.ID)
+ row.RemoveAction = row.Action + "/remove"
+ row.Fields = contactFormFields("c"+strconv.Itoa(i+1), c.Contact)
+ }
+ v.Contacts = append(v.Contacts, row)
+ }
+}
+
+// contactFormFields is a saved contact's form fields, their ids prefixed.
+func contactFormFields(prefix string, c registrar.Contact) []domainBuyField {
+ fields := buyContactFields(c)
+ for i := range fields {
+ fields[i].ID = prefix + "-" + fields[i].Name
}
+ return fields
}
func (s *Server) handleAccountDomain(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/console/accountdomainspage_test.go b/internal/console/accountdomainspage_test.go
index 3248493ac..58d0e1577 100644
--- a/internal/console/accountdomainspage_test.go
+++ b/internal/console/accountdomainspage_test.go
@@ -137,7 +137,7 @@ func TestDomainsOverviewCards(t *testing.T) {
inflight := adSection(t, main, "shop.com")
for _, want := range []string{
`<span class="chip chip-canary">` + domainsPageCopy.Buying + `</span>`,
- `href="` + domainPurchaseURL(acct.Sqid, "kass", buying.ID) + `"`,
+ `href="` + domainPurchaseURL(acct.Sqid, buying.ID) + `"`,
} {
if !strings.Contains(inflight, want) {
t.Errorf("in-flight card lacks %q:\n%s", want, inflight)
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go
index ab7985071..6e9f1e410 100644
--- a/internal/console/apidomainbuy_test.go
+++ b/internal/console/apidomainbuy_test.go
@@ -175,16 +175,13 @@ func TestBrowserBuyRedirectsToCheckout(t *testing.T) {
f.setUser("owner" + f.acct.Sqid + "@example.com")
signUp(t, f.consoleFixture, c, "buy-browser")
csrf := sessionToken(t, f.consoleFixture, c)
- base := f.ts.URL + "/a/" + f.acct.Sqid + "/apps/kass/domains"
- status, _, body := postForm(t, c, base+"/check", url.Values{"csrf": {csrf}, "name": {"shop.com"}})
+ base := f.ts.URL + "/a/" + f.acct.Sqid + "/domains"
+ status, body := f.browserQuote(t, c, url.Values{"csrf": {csrf}, "name": {"shop.com"}})
if status != 200 || !strings.Contains(body, "$15") || strings.Contains(body, "$15 usd") || !strings.Contains(body, "PhoneCountryCode") {
t.Fatalf("quote status=%d, has price=%v, duplicate currency=%v, has phone=%v", status, strings.Contains(body, "$15"), strings.Contains(body, "$15 usd"), strings.Contains(body, "PhoneCountryCode"))
}
- 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.",
- } {
- if !strings.Contains(body, "<p>"+want+"</p>") {
+ for _, want := range []string{accountBuyCopy.RegisteredNote, accountBuyCopy.SavedForNext} {
+ if !strings.Contains(body, `<p class="small">`+want+"</p>") {
t.Errorf("missing visible copy %q", want)
}
}
@@ -192,7 +189,7 @@ func TestBrowserBuyRedirectsToCheckout(t *testing.T) {
for _, field := range buyContactFields(purchaseContact()) {
values.Set(field.Name, field.Value)
}
- status, loc, body := postForm(t, c, base+"/buy", values)
+ status, loc, body := f.browserBuyDoor(t, c, "buy", values)
if status != 303 || !strings.HasPrefix(loc, "https://") {
t.Fatalf("checkout %d %q %s", status, loc, body)
}
@@ -221,7 +218,7 @@ func TestBrowserBuyCSRF(t *testing.T) {
f.setUser("owner" + f.acct.Sqid + "@example.com")
signUp(t, f.consoleFixture, c, "buy-csrf")
for _, door := range []string{"check", "buy"} {
- status, _, body := postForm(t, c, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/"+door, url.Values{"csrf": {"bad"}, "name": {"shop.com"}})
+ status, _, body := f.browserBuyDoor(t, c, door, url.Values{"csrf": {"bad"}, "name": {"shop.com"}})
if status != 403 {
t.Fatalf("%s: %d %s", door, status, body)
}
@@ -280,6 +277,14 @@ func TestBuyDoorsAbsentOnHostClaimConsole(t *testing.T) {
"route POST /a/{sqid}/apps/{app}/domains/buy",
"route GET /a/{sqid}/apps/{app}/domains/purchases/{id}",
"route GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status",
+ "route GET /a/{sqid}/domains/buy",
+ "route POST /a/{sqid}/domains/buy/check",
+ "route POST /a/{sqid}/domains/buy",
+ "route GET /a/{sqid}/domains/purchases/{id}",
+ "route GET /a/{sqid}/domains/purchases/{id}/status",
+ "route POST /a/{sqid}/domains/contacts",
+ "route POST /a/{sqid}/domains/contacts/{id}",
+ "route POST /a/{sqid}/domains/contacts/{id}/remove",
} {
if _, ok := claimFixtures[path]; ok {
t.Errorf("%s is in the host-claim census", path)
@@ -314,7 +319,7 @@ func TestBrowserBuyOwnerOnlyAndPurchaseIsolation(t *testing.T) {
if err := f.st.AddMember(f.acct.ID, "member@example.com", RoleMember, time.Now()); err != nil {
t.Fatal(err)
}
- base := f.ts.URL + "/a/" + f.acct.Sqid + "/apps/kass/domains"
+ base := f.ts.URL + "/a/" + f.acct.Sqid + "/domains"
for _, addr := range []string{"member@example.com", "stranger@example.com"} {
c := newBrowser(t)
f.setUser(addr)
@@ -325,7 +330,7 @@ func TestBrowserBuyOwnerOnlyAndPurchaseIsolation(t *testing.T) {
t.Fatalf("%s %s: %d %q", addr, path, status, body)
}
}
- for _, path := range []string{"/check", "/buy"} {
+ for _, path := range []string{"/buy/check", "/buy"} {
status, _, body := postForm(t, c, base+path, url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}})
if status != 404 || body != "404 page not found\n" {
t.Fatalf("%s POST %s: %d %q", addr, path, status, body)
@@ -340,7 +345,7 @@ func TestBrowserBuyOwnerOnlyAndPurchaseIsolation(t *testing.T) {
f.setUser("owner" + other.Sqid + "@example.com")
signUp(t, f.consoleFixture, c, "browser-other")
for _, suffix := range []string{"", "/status"} {
- prefix := f.ts.URL + "/a/" + other.Sqid + "/apps/kass/domains/purchases/"
+ prefix := f.ts.URL + "/a/" + other.Sqid + "/domains/purchases/"
s1, _, b1 := get(t, c, prefix+p.ID+suffix)
s2, _, b2 := get(t, c, prefix+"unknown"+suffix)
if s1 != 404 || s2 != 404 || b1 != b2 {
@@ -395,9 +400,16 @@ func TestBrowserBuyPrefillsContactAndHidesUnconfigured(t *testing.T) {
if err := f.addContact(contact); err != nil {
t.Fatal(err)
}
+ saved, err := f.st.SavedContacts(context.Background(), f.acct.ID)
+ if err != nil || len(saved) != 1 {
+ t.Fatal(saved, err)
+ }
base := f.ts.URL + "/a/" + f.acct.Sqid + "/apps/kass"
- status, _, body := postForm(t, c, base+"/domains/check", url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}})
- if status != 200 || !strings.Contains(body, `name="HouseNumber" value="42"`) || !strings.Contains(body, `name="PhoneCountryCode" value="353"`) {
+ // Step 3 starts from the most recently used saved contact, chosen; a
+ // new contact's fields start empty.
+ status, body := f.browserQuote(t, c, url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}})
+ if status != 200 || !strings.Contains(body, `name="contact" value="`+saved[0].ID+`" checked`) || !strings.Contains(body, "buyer@example.test · IE") ||
+ strings.Contains(body, `value="42"`) || !strings.Contains(body, `name="HouseNumber" value=""`) {
t.Fatalf("prefill %d %s", status, body)
}
status, _, body = get(t, c, base+"/settings/domains")
@@ -409,7 +421,7 @@ func TestBrowserBuyPrefillsContactAndHidesUnconfigured(t *testing.T) {
if status != 200 || strings.Contains(body, "/domains/buy") {
t.Fatalf("unconfigured link %d %s", status, body)
}
- status, _, body = get(t, c, base+"/domains/buy")
+ status, _, body = get(t, c, f.acctURL("/domains/buy"))
if status != 404 {
t.Fatalf("unconfigured browser %d %s", status, body)
}
diff --git a/internal/console/apilinks_test.go b/internal/console/apilinks_test.go
index 325b4194e..3e9092897 100644
--- a/internal/console/apilinks_test.go
+++ b/internal/console/apilinks_test.go
@@ -487,7 +487,13 @@ func TestLinkedPolicyCoversEveryAppRoute(t *testing.T) {
var linkedBodyAppDoors = map[string]string{
// Guarded with linkedRefusalFor.
"POST /api/cli/accounts/{account}/domains/purchases": "startDomainPurchase refuses a linked app with LD-C12 before any billing; the completion's attachDomain refuses it too",
- "POST /a/{sqid}/fleets/{fleet}/place": "placeAppTarget refuses a linked app with LD-C11",
+ "POST /a/{sqid}/domains/buy": "startDomainPurchase refuses a linked app with LD-C12 before any billing; the completion's attachDomain refuses it too",
+ // Cannot act on a linked app: the app only preselects step 2, whose
+ // choices are domainActionApps (no linked app); the purchase door
+ // above guards whatever is posted.
+ "GET /a/{sqid}/domains/buy": "the app only preselects step 2, which never offers a linked app; nothing is written",
+ "POST /a/{sqid}/domains/buy/check": "the app only travels on to step 2's preselection; the search writes nothing",
+ "POST /a/{sqid}/fleets/{fleet}/place": "placeAppTarget refuses a linked app with LD-C11",
// Cannot act on a linked app.
"POST /a/{sqid}/trash/restore": "acts only on a trashed row; linked rows are never trashed",
"POST /a/{sqid}/trash/delete": "acts only on a trashed row; linked rows are never trashed",
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go
index 69e2d49c1..8f904fa7d 100644
--- a/internal/console/appdomainbuy.go
+++ b/internal/console/appdomainbuy.go
@@ -1,33 +1,45 @@
package console
+// The purchase card (Plan 1, account-scoped since Plan 2a Task 9) and the
+// old app-scoped buy routes, which now only redirect to the account's.
+
import (
- "context"
+ "log"
"net/http"
"net/url"
- "strconv"
"strings"
- "time"
- "github.com/carlosframework/platform/internal/domainreg"
- "github.com/carlosframework/platform/internal/plans"
"github.com/carlosframework/platform/internal/registrar"
)
type domainBuyField struct {
- Name, Label, Value string
- Required bool
+ ID, Name, Label, Value string
+ Type, Autocomplete string
+ Required bool
+ Options []countryOption // the country select; nil for a text input
+ Choose string // the select's empty option
+}
+
+// countryOption is one country in a select.
+type countryOption struct {
+ Code, Name string
+ Selected bool
}
+
+// domainBuyView is the purchase card's page.
type domainBuyView struct {
- Base, Back, PollURL string
- CheckoutURL string
- Price string
- PriceChanged bool
- Quote *domainreg.Quote
- Fields []domainBuyField
- Purchase *DomainPurchase
- DomainState string
- Card domainPurchaseCard
- Stages map[PurchaseState]domainPurchaseStage
+ PollURL string
+ CheckoutURL string
+ Back string // the account's domains
+ Point string // the domain's page, to point it at an app
+ Purchase *DomainPurchase
+ DomainState string
+ Card domainPurchaseCard
+ // Stages and StagesNoApp are the card's script's maps; NoApp starts it
+ // on the second, which it also moves to once the purchase reads no app.
+ Stages, StagesNoApp map[PurchaseState]domainPurchaseStage
+ NoApp bool
+ CardCopy map[string]string
}
type domainPurchaseStage struct {
@@ -49,193 +61,200 @@ var domainPurchaseStages = map[PurchaseState]domainPurchaseStage{
"live": {Kind: "live", Steps: [4]string{"done", "done", "done", "done"}},
}
+// domainPurchaseStagesNoApp is the card for a purchase pointed at no app:
+// "Not yet", or an app that went away before it was pointed (Unpointing).
+// Two steps, then "ready to point at an app"; it never says it is
+// connecting the domain to an app.
+var domainPurchaseStagesNoApp = map[PurchaseState]domainPurchaseStage{
+ PurchaseAwaitingPayment: {Kind: "awaiting"},
+ PurchaseAuthorised: {Kind: "progressNoApp", Steps: [4]string{"done", "active"}},
+ PurchaseZoneReady: {Kind: "progressNoApp", Steps: [4]string{"done", "active"}},
+ PurchaseRegistering: {Kind: "progressNoApp", Steps: [4]string{"done", "active"}},
+ PurchaseRegistered: {Kind: "readying", Steps: [4]string{"done", "done"}},
+ PurchaseCaptured: {Kind: "readying", Steps: [4]string{"done", "done"}},
+ PurchaseDone: {Kind: "ready"},
+ PurchaseFailed: {Kind: "failed"},
+ PurchaseExpired: {Kind: "expired"},
+ PurchaseUnpaid: {Kind: "unpaid"},
+ "live": {Kind: "ready"},
+}
+
+// purchaseCardCopy is the card's words by kind: Plan 1's approved card
+// copy and the no-app kinds' drafts (accountBuyCopy).
+var purchaseCardCopy = func() map[string]string {
+ m := make(map[string]string, len(domainBuyCopy)+6)
+ for k, v := range domainBuyCopy {
+ m[k] = v
+ }
+ m["progressNoAppTitle"] = domainBuyCopy["progressTitle"]
+ m["progressNoAppLede"] = accountBuyCopy.NoAppProgressLede
+ m["readyingTitle"] = domainBuyCopy["progressTitle"]
+ m["readyingLede"] = accountBuyCopy.ReadyLede
+ m["readyTitle"] = accountBuyCopy.ReadyTitle
+ m["readyLede"] = accountBuyCopy.ReadyLede
+ return m
+}()
+
type domainPurchaseCard struct {
Stage domainPurchaseStage
Title, Lede string
Visit string
Status string
- StepLabels [4]string
+ StepLabels []string
+}
+
+// Stepped is a card that shows its steps: a purchase under way.
+func (c domainPurchaseCard) Stepped() bool {
+ return c.Stage.Kind == "progress" || c.Stage.Kind == "progressNoApp" || c.Stage.Kind == "readying"
}
+// purchaseNoApp is a purchase the card draws without an app.
+func purchaseNoApp(p *DomainPurchase) bool { return p.App == "" || p.Unpointing }
+
func purchaseCard(p *DomainPurchase, domainState string) domainPurchaseCard {
state := p.State
if state == PurchaseDone && domainState == StateLive {
state = "live"
}
- stage := domainPurchaseStages[state]
+ stages := domainPurchaseStages
+ labels := []string{domainBuyCopy["stepPaid"], domainBuyCopy["stepRegister"], domainBuyCopy["stepDNS"], domainBuyCopy["stepHTTPS"]}
+ if purchaseNoApp(p) {
+ stages, labels = domainPurchaseStagesNoApp, labels[:2]
+ }
+ stage := stages[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"]},
+ Stage: stage, Title: fill.Replace(purchaseCardCopy[stage.Kind+"Title"]),
+ Lede: fill.Replace(purchaseCardCopy[stage.Kind+"Lede"]), Visit: fill.Replace(domainBuyCopy["visit"]),
+ StepLabels: labels,
}
card.Status = card.Title
- if stage.Kind == "progress" {
- for i, step := range stage.Steps {
- if step == "active" {
- card.Status = card.StepLabels[i]
- }
+ for i, step := range stage.Steps {
+ if step == "active" {
+ card.Status = card.StepLabels[i]
}
}
return card
}
-func domainPurchaseURL(account, app, id string) string {
- return "/a/" + url.PathEscape(account) + "/apps/" + url.PathEscape(app) + "/domains/purchases/" + url.PathEscape(id)
-}
-func (s *Server) domainBuyBrowserGate(w http.ResponseWriter, r *http.Request) (string, string, *Account, string, bool) {
- addr, raw, acct, role, app, ok := s.accountApp(w, r)
- if !ok {
- return "", "", nil, "", false
- }
- if r.Method == http.MethodPost && !csrfFormOK(r, raw) {
- s.renderMessage(w, r, 403, domainBuyCopy["refused"], domainBuyCopy["csrf"])
- return "", "", nil, "", false
- }
- if role != RoleOwner || !s.domainBuyReady() {
- http.NotFound(w, r)
- return "", "", nil, "", false
- }
- if !s.allowDomains(Principal{Kind: PrincipalUser, Address: addr}, time.Now()) {
- s.renderDoorRefusal(w, r, &doorRefusal{Status: 429, Msg: domainBuyCopy["rate"]})
- return "", "", nil, "", false
- }
- w.Header().Set("Cache-Control", "no-store")
- return addr, raw, acct, app, true
+// domainPurchaseURL is a purchase's card, the page Checkout returns to.
+// Checkouts prepared before Plan 2a return to the old app-scoped path,
+// which redirects here (handleAppDomainPurchaseRedirect).
+func domainPurchaseURL(account, id string) string {
+ return "/a/" + url.PathEscape(account) + "/domains/purchases/" + url.PathEscape(id)
}
+
+// buyContactFields is a contact's form fields. Required marks the fields
+// the registrar needs; callers clear it where the fields may be hidden.
func buyContactFields(c registrar.Contact) []domainBuyField {
fields := []domainBuyField{
- {Name: "FirstName", Value: c.FirstName}, {Name: "LastName", Value: c.LastName}, {Name: "Company", Value: c.Company},
- {Name: "Email", Value: c.Email}, {Name: "PhoneCountryCode", Value: c.PhoneCountryCode}, {Name: "Phone", Value: c.Phone},
- {Name: "Street", Value: c.Street}, {Name: "HouseNumber", Value: c.HouseNumber}, {Name: "City", Value: c.City},
- {Name: "State", Value: c.State}, {Name: "PostalCode", Value: c.PostalCode}, {Name: "Country", Value: c.Country},
+ {Name: "FirstName", Value: c.FirstName, Autocomplete: "given-name"},
+ {Name: "LastName", Value: c.LastName, Autocomplete: "family-name"},
+ {Name: "Company", Value: c.Company, Autocomplete: "organization"},
+ {Name: "Email", Value: c.Email, Type: "email", Autocomplete: "email"},
+ {Name: "PhoneCountryCode", Value: c.PhoneCountryCode, Type: "tel", Autocomplete: "tel-country-code"},
+ {Name: "Phone", Value: c.Phone, Type: "tel", Autocomplete: "tel-national"},
+ {Name: "Street", Value: c.Street, Autocomplete: "address-line1"},
+ {Name: "HouseNumber", Value: c.HouseNumber, Autocomplete: "address-line2"},
+ {Name: "City", Value: c.City, Autocomplete: "address-level2"},
+ {Name: "State", Value: c.State, Autocomplete: "address-level1"},
+ {Name: "PostalCode", Value: c.PostalCode, Autocomplete: "postal-code"},
+ {Name: "Country", Value: c.Country, Autocomplete: "country", Options: countryOptions(c.Country)},
}
for i := range fields {
fields[i].Label = domainBuyCopy[fields[i].Name]
+ if fields[i].Type == "" {
+ fields[i].Type = "text"
+ }
fields[i].Required = fields[i].Name != "Company" && fields[i].Name != "HouseNumber" && fields[i].Name != "State"
}
+ fields[len(fields)-1].Label, fields[len(fields)-1].Choose = accountBuyCopy.Country, accountBuyCopy.Choose
return fields
}
-func (s *Server) renderDomainBuy(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, app string, v *domainBuyView) {
+
+// contactFromForm is the contact a form posted, in buyContactFields' names.
+func contactFromForm(r *http.Request) registrar.Contact {
+ return registrar.Contact{FirstName: r.FormValue("FirstName"), LastName: r.FormValue("LastName"), Company: r.FormValue("Company"),
+ Email: r.FormValue("Email"), PhoneCountryCode: r.FormValue("PhoneCountryCode"), Phone: r.FormValue("Phone"), Street: r.FormValue("Street"), HouseNumber: r.FormValue("HouseNumber"),
+ City: r.FormValue("City"), State: r.FormValue("State"), PostalCode: r.FormValue("PostalCode"), Country: r.FormValue("Country")}
+}
+
+// renderPurchaseCard draws a purchase's card on the account's buy page.
+func (s *Server) renderPurchaseCard(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, v *domainBuyView) {
p := s.accountPage(w, r, addr, raw, acct, RoleOwner)
p.Title = domainBuyCopy["title"]
- v.Base = "/a/" + url.PathEscape(acct.Sqid) + "/apps/" + url.PathEscape(app) + "/domains"
- v.Back = appSettingsURL(acct.Sqid, app, "domains")
- 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.ActiveNav = "domains"
+ v.Back = domainsBase(acct) + "/domains"
+ v.Point = domainPageURL(acct, v.Purchase.Domain) + "#point"
+ v.Card = purchaseCard(v.Purchase, v.DomainState)
+ v.Stages, v.StagesNoApp = domainPurchaseStages, domainPurchaseStagesNoApp
+ v.NoApp = purchaseNoApp(v.Purchase)
+ v.CardCopy = purchaseCardCopy
p.DomainBuy = v
- status := http.StatusOK
- if v.PriceChanged {
- status = http.StatusConflict
- }
- s.render(w, status, "domain_buy", p)
-}
-func (s *Server) handleAppDomainBuyForm(w http.ResponseWriter, r *http.Request) {
- addr, raw, acct, app, ok := s.domainBuyBrowserGate(w, r)
- if !ok {
- return
- }
- s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{})
+ s.render(w, http.StatusOK, "domain_buy", p)
}
-func (s *Server) handleAppDomainBuyCheck(w http.ResponseWriter, r *http.Request) {
- addr, raw, acct, app, ok := s.domainBuyBrowserGate(w, r)
+
+// ---- the old app-scoped routes ----------------------------------------------
+//
+// Plan 1 bought from an app's Settings at /a/{sqid}/apps/{app}/domains/...;
+// buying is the account's now. The old routes stay for open pages, stale
+// forms and Checkouts prepared before the move, and only redirect. They
+// check account membership (and a purchase's account), never that {app}
+// still exists, so a Checkout return lands after its app was purged. A
+// linked app still gets the domains refusal its policy names.
+
+// appBuyRedirectGate is the redirects' gate: membership, CSRF on a POST,
+// and the linked-app policy.
+func (s *Server) appBuyRedirectGate(w http.ResponseWriter, r *http.Request) (*Account, string, bool) {
+ _, raw, acct, _, ok := s.account(w, r)
if !ok {
- return
- }
- ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
- defer cancel()
- q, ref := s.checkDomainBuy(ctx, acct, r.FormValue("name"), r.FormValue("country"))
- if ref != nil {
- s.renderDoorRefusal(w, r, ref)
- return
- }
- // The form starts from the most recently used saved contact, whose
- // country checkDomainBuy's quote assumed when the request named none.
- contacts, err := s.store.SavedContacts(ctx, acct.ID)
- if err != nil {
- s.renderDoorRefusal(w, r, domainBuyUnavailable())
- return
+ return nil, "", false
}
- var c registrar.Contact
- if len(contacts) > 0 {
- c = contacts[0].Contact
+ if r.Method == http.MethodPost && !csrfFormOK(r, raw) {
+ s.renderMessage(w, r, http.StatusForbidden, domainBuyCopy["refused"], domainBuyCopy["csrf"])
+ return nil, "", false
}
- if country := r.FormValue("country"); country != "" {
- c.Country = country
+ app := r.PathValue("app")
+ if ref := s.linkedAppRefusal(r, acct, app); ref != nil {
+ s.renderMessage(w, r, ref.Status, "Refused", ref.Msg)
+ return nil, "", false
}
- s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Quote: &q, Fields: buyContactFields(c)})
+ return acct, app, true
}
-func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) {
- addr, raw, acct, app, ok := s.domainBuyBrowserGate(w, r)
+
+// handleAppDomainBuyRedirect answers the old buy page and its two stale
+// form posts (check, buy) with the account's buy page, the app chosen.
+// A post starts nothing.
+func (s *Server) handleAppDomainBuyRedirect(w http.ResponseWriter, r *http.Request) {
+ acct, app, ok := s.appBuyRedirectGate(w, r)
if !ok {
return
}
- if ref := s.customDomainRefusal(acct, r.FormValue("name")); ref != nil {
- s.renderDoorRefusal(w, r, ref)
- return
- }
- c := registrar.Contact{FirstName: r.FormValue("FirstName"), LastName: r.FormValue("LastName"), Company: r.FormValue("Company"),
- Email: r.FormValue("Email"), PhoneCountryCode: r.FormValue("PhoneCountryCode"), Phone: r.FormValue("Phone"), Street: r.FormValue("Street"), HouseNumber: r.FormValue("HouseNumber"),
- City: r.FormValue("City"), State: r.FormValue("State"), PostalCode: r.FormValue("PostalCode"), Country: r.FormValue("Country")}
- ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
- defer cancel()
- price, err := strconv.ParseInt(r.FormValue("price"), 10, 64)
- if err != nil {
- price = 0
- }
- p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), purchaseContactSelection{New: &c}, addr, domainreg.Quote{Currency: r.FormValue("currency"), Price: price})
- if changed != nil {
- s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Quote: changed, Fields: buyContactFields(c), PriceChanged: true})
- return
- }
- if ref != nil {
- s.renderDoorRefusal(w, r, ref)
- return
- }
- if checkout == "" {
- checkout = domainPurchaseURL(acct.Sqid, p.App, p.ID)
- }
- http.Redirect(w, r, checkout, http.StatusSeeOther)
+ http.Redirect(w, r, domainBuyURL(acct.Sqid, app), http.StatusSeeOther)
}
-func (s *Server) handleAppDomainPurchase(w http.ResponseWriter, r *http.Request) {
- addr, raw, acct, app, ok := s.domainBuyBrowserGate(w, r)
+
+// handleAppDomainPurchaseRedirect answers an old purchase card or status
+// URL with the account's. A purchase that is not the account's is the
+// same 404 as an unknown one.
+func (s *Server) handleAppDomainPurchaseRedirect(w http.ResponseWriter, r *http.Request) {
+ acct, _, ok := s.appBuyRedirectGate(w, r)
if !ok {
return
}
- p := s.purchaseForAccount(w, r, acct, app)
- if p == nil {
+ p, err := s.store.DomainPurchase(r.PathValue("id"))
+ if err != nil {
+ log.Printf("console: purchase redirect %s: %v", acct.Sqid, err)
+ s.renderDoorRefusal(w, r, domainBuyUnavailable())
return
}
- var checkout string
- if p.State == PurchaseAwaitingPayment && p.CheckoutSession != "" && time.Now().Before(p.CheckoutExpires) {
- ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout)
- defer cancel()
- info, err := s.billing.cfg.Provider.PaymentCheckout(ctx, p.CheckoutSession)
- if err == nil && info.Status == "open" {
- checkout = info.URL
- }
- }
- 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)
- if !ok {
+ if p == nil || p.AccountID != acct.ID {
+ http.NotFound(w, r)
return
}
- p := s.purchaseForAccount(w, r, acct, app)
- if p == nil {
- return
+ to := domainPurchaseURL(acct.Sqid, p.ID)
+ if strings.HasSuffix(r.Pattern, "/status") {
+ to += "/status"
}
- s.writeDomainPurchaseStatus(w, r, acct, p)
+ w.Header().Set("Cache-Control", "no-store")
+ http.Redirect(w, r, to, http.StatusSeeOther)
}
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go
index 4f3489e62..8d25d6780 100644
--- a/internal/console/domainbuy.go
+++ b/internal/console/domainbuy.go
@@ -497,7 +497,7 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s
if b == nil {
return "", sql.ErrNoRows
}
- back := s.cfg.Origin + domainPurchaseURL(acct.Sqid, p.App, p.ID)
+ back := s.cfg.Origin + domainPurchaseURL(acct.Sqid, p.ID)
prepared, err := provider.PreparePaymentCheckout(billing.PaymentCheckoutRequest{AccountSqid: acct.Sqid, Customer: b.Customer, Currency: p.Currency, Amount: p.Amount,
Description: p.Domain, Reference: p.ID, SuccessURL: back, CancelURL: back, ExpiresAt: p.CheckoutExpires, Key: p.ID})
if err != nil {
diff --git a/internal/console/domainbuy_admission_test.go b/internal/console/domainbuy_admission_test.go
index 3b920b7e4..8c573e922 100644
--- a/internal/console/domainbuy_admission_test.go
+++ b/internal/console/domainbuy_admission_test.go
@@ -117,7 +117,7 @@ func TestBuyAdmissionNeutralityGuard(t *testing.T) {
for _, field := range buyContactFields(purchaseContact()) {
values.Set(field.Name, field.Value)
}
- status, _, body = postForm(t, browser, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/"+path, values)
+ status, _, body = f.browserBuyDoor(t, browser, path, values)
}
if status != tc.status || !strings.Contains(body, wantMessage) {
t.Errorf("%s/%s/%s: status %d, want %d and message %q", transport, door, name, status, tc.status, wantMessage)
@@ -182,7 +182,7 @@ func TestBuyAdmissionSharesCheckBudget(t *testing.T) {
for _, field := range buyContactFields(purchaseContact()) {
values.Set(field.Name, field.Value)
}
- status, _, _ = postForm(t, browser, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/"+door, values)
+ status, _, _ = f.browserBuyDoor(t, browser, door, values)
}
want := 409
if i >= domainCheckAccountBudget {
@@ -234,7 +234,7 @@ func TestBuyAdmissionCatalogRefusals(t *testing.T) {
if path == "purchases" {
path = "buy"
}
- status, _, body = postForm(t, browser, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/"+path, values)
+ status, _, body = f.browserBuyDoor(t, browser, path, values)
}
if status != tc.status || !strings.Contains(body, domainBuyCopy[tc.key]) {
t.Errorf("%s/%s: status %d, want %d and %q", transport, door, status, tc.status, domainBuyCopy[tc.key])
diff --git a/internal/console/domainbuy_card_test.go b/internal/console/domainbuy_card_test.go
index 5803efbb9..de6bdae4a 100644
--- a/internal/console/domainbuy_card_test.go
+++ b/internal/console/domainbuy_card_test.go
@@ -36,7 +36,7 @@ func TestDomainPurchaseCardSteps(t *testing.T) {
{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
+ got := purchaseCard(&DomainPurchase{App: "kass", 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)
}
@@ -48,9 +48,9 @@ func purchaseCardHTML(t *testing.T, f *purchaseFixture, p *DomainPurchase, domai
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{
+ f.srv.renderPurchaseCard(w, r, "buyer@example.test", "csrf-test", f.acct, &domainBuyView{
Purchase: p, DomainState: domainState, CheckoutURL: checkout,
- PollURL: domainPurchaseURL(f.acct.Sqid, p.App, p.ID) + "/status",
+ PollURL: domainPurchaseURL(f.acct.Sqid, p.ID) + "/status",
})
if w.Code != http.StatusOK {
t.Fatalf("render: %d %s", w.Code, w.Body.String())
@@ -246,7 +246,7 @@ func TestDomainPurchasePageRendersLiveBeforePolling(t *testing.T) {
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)
+ path := f.ts.URL + domainPurchaseURL(f.acct.Sqid, 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")
diff --git a/internal/console/domainbuy_final_fix_test.go b/internal/console/domainbuy_final_fix_test.go
index d35b437c8..ff68dcfb3 100644
--- a/internal/console/domainbuy_final_fix_test.go
+++ b/internal/console/domainbuy_final_fix_test.go
@@ -117,26 +117,26 @@ func TestCheckoutCancelPageOffersContinue(t *testing.T) {
if err := json.Unmarshal(p.CheckoutPrepared.Body, &request); err != nil {
t.Fatal(err)
}
- back := f.srv.cfg.Origin + domainPurchaseURL(f.acct.Sqid, p.App, p.ID)
+ back := f.srv.cfg.Origin + domainPurchaseURL(f.acct.Sqid, p.ID)
if request.Request.CancelURL != back {
t.Fatalf("cancel URL: %v", request)
}
- status, _, body := get(t, c, f.ts.URL+domainPurchaseURL(f.acct.Sqid, p.App, p.ID))
+ status, _, body := get(t, c, f.ts.URL+domainPurchaseURL(f.acct.Sqid, p.ID))
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"}}
- status, loc, _ := postForm(t, c, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/buy", values)
+ status, loc, _ := f.browserBuyDoor(t, c, "buy", values)
if status != 303 || loc != info.URL {
t.Fatalf("browser resume: %d %s", status, loc)
}
f.authorise(t, p)
- status, _, body = get(t, c, f.ts.URL+domainPurchaseURL(f.acct.Sqid, p.App, p.ID))
+ status, _, body = get(t, c, f.ts.URL+domainPurchaseURL(f.acct.Sqid, p.ID))
if status != 200 || strings.Contains(body, `href="`+info.URL+`"`) {
t.Fatal("closed checkout still offered")
}
- status, loc, _ = postForm(t, c, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/buy", values)
- if status != 303 || loc != domainPurchaseURL(f.acct.Sqid, p.App, p.ID) {
+ status, loc, _ = f.browserBuyDoor(t, c, "buy", values)
+ if status != 303 || loc != domainPurchaseURL(f.acct.Sqid, p.ID) {
t.Fatalf("active purchase resume: %d %s", status, loc)
}
}
diff --git a/internal/console/domainbuy_fix_test.go b/internal/console/domainbuy_fix_test.go
index dfa2b0633..798a47c5f 100644
--- a/internal/console/domainbuy_fix_test.go
+++ b/internal/console/domainbuy_fix_test.go
@@ -215,7 +215,7 @@ func TestCheckLimiterPerAccountAndDeployment(t *testing.T) {
browser := newBrowser(t)
f.setUser("owner" + f.acct.Sqid + "@example.com")
signUp(t, f.consoleFixture, browser, "limited")
- status, _, body = postForm(t, browser, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/check", map[string][]string{"csrf": {sessionToken(t, f.consoleFixture, browser)}, "name": {"shop.com"}})
+ status, _, body = f.browserBuyDoor(t, browser, "check", map[string][]string{"csrf": {sessionToken(t, f.consoleFixture, browser)}, "name": {"shop.com"}})
if status != 429 || !strings.Contains(body, domainBuyCopy["rate"]) {
t.Errorf("browser budget: %d %s", status, body)
}
diff --git a/internal/console/domainbuy_round1_test.go b/internal/console/domainbuy_round1_test.go
index 6329e70bb..4c5380acd 100644
--- a/internal/console/domainbuy_round1_test.go
+++ b/internal/console/domainbuy_round1_test.go
@@ -108,9 +108,8 @@ func TestBrowserBuyConfirmedPrice(t *testing.T) {
c := newBrowser(t)
f.setUser("owner" + f.acct.Sqid + "@example.com")
signUp(t, f.consoleFixture, c, "price-browser")
- base := f.ts.URL + "/a/" + f.acct.Sqid + "/apps/kass/domains"
values := url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}}
- status, _, body := postForm(t, c, base+"/check", values)
+ status, body := f.browserQuote(t, c, values)
if status != 200 || !strings.Contains(body, `name="currency" value="eur"`) || !strings.Contains(body, `name="price" value="1600"`) {
t.Fatalf("confirm: %d %s", status, body)
}
@@ -121,14 +120,14 @@ func TestBrowserBuyConfirmedPrice(t *testing.T) {
}
values.Set("currency", "eur")
values.Set("price", "1600")
- status, _, body = postForm(t, c, base+"/buy", values)
- if status != 409 || !strings.Contains(body, `name="currency" value="gbp"`) || !strings.Contains(body, `name="price" value="1700"`) || !strings.Contains(body, `name="Country" value="GB"`) {
+ status, _, body = f.browserBuyDoor(t, c, "buy", values)
+ if status != 409 || !strings.Contains(body, `name="currency" value="gbp"`) || !strings.Contains(body, `name="price" value="1700"`) || !strings.Contains(body, `<option value="GB" selected>`) {
t.Fatalf("new confirmation: %d %s", status, body)
}
assertNoPurchaseEffects(t, f)
values.Set("currency", "gbp")
values.Set("price", "1700")
- status, loc, _ := postForm(t, c, base+"/buy", values)
+ status, loc, _ := f.browserBuyDoor(t, c, "buy", values)
if status != 303 || !strings.HasPrefix(loc, "https://checkout.example.test/") {
t.Fatalf("confirmed: %d %s", status, loc)
}
diff --git a/internal/console/domainbuy_round2_test.go b/internal/console/domainbuy_round2_test.go
index 3d6fbfb05..88d93b2e5 100644
--- a/internal/console/domainbuy_round2_test.go
+++ b/internal/console/domainbuy_round2_test.go
@@ -45,11 +45,11 @@ func TestPurchaseCheckCountry(t *testing.T) {
c := newBrowser(t)
f.setUser("owner" + f.acct.Sqid + "@example.com")
signUp(t, f.consoleFixture, c, "country-browser")
- status, _, body := postForm(t, c, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/check", url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}, "country": {tc.country}})
+ status, body := f.browserQuote(t, c, url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}, "country": {tc.country}})
if status != 200 || !strings.Contains(body, `name="currency" value="`+tc.currency+`"`) || !strings.Contains(body, fmt.Sprintf(`name="price" value="%d"`, tc.price)) {
t.Fatalf("check: %d %s", status, body)
}
- if tc.country != "" && !strings.Contains(body, `name="Country" value="`+tc.country+`"`) {
+ if tc.country != "" && !strings.Contains(body, `<option value="`+tc.country+`" selected>`) {
t.Fatal("confirmation contact lost requested country")
}
} else {
@@ -85,7 +85,7 @@ func TestPurchaseCheckCountryValidation(t *testing.T) {
c := newBrowser(t)
f.setUser("owner" + f.acct.Sqid + "@example.com")
signUp(t, f.consoleFixture, c, "invalid-country")
- status, _, body = postForm(t, c, f.ts.URL+"/a/"+f.acct.Sqid+"/apps/kass/domains/check", url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}, "country": {country}})
+ status, _, body = f.browserBuyDoor(t, c, "check", url.Values{"csrf": {sessionToken(t, f.consoleFixture, c)}, "name": {"shop.com"}, "country": {country}})
if status != 422 || !strings.Contains(body, domainBuyCopy["contactError"]) {
t.Fatalf("browser: %d %s", status, body)
}
diff --git a/internal/console/domainbuy_test.go b/internal/console/domainbuy_test.go
index 9bc01868b..ab25543e8 100644
--- a/internal/console/domainbuy_test.go
+++ b/internal/console/domainbuy_test.go
@@ -626,7 +626,7 @@ func TestPurchaseCheckoutUsesQuoteAndPurchaseReturnPage(t *testing.T) {
t.Fatal(err)
}
r := body.Request
- back := f.srv.cfg.Origin + domainPurchaseURL(f.acct.Sqid, "kass", p.ID)
+ back := f.srv.cfg.Origin + domainPurchaseURL(f.acct.Sqid, p.ID)
if r.Reference != p.ID || r.Amount != 1500 || r.Currency != "usd" || r.Customer != "cus_1" || r.SuccessURL != back || r.CancelURL != back || r.Description != p.Domain || f.fake.Sent[0].Key != p.ID || r.ExpiresAt.Sub(p.CreatedAt) != time.Hour {
t.Fatal("checkout did not preserve the quote, expiry, purchase identity and return page")
}
diff --git a/internal/console/nobucket_posts_test.go b/internal/console/nobucket_posts_test.go
index 6ae998eac..eb1c791e2 100644
--- a/internal/console/nobucket_posts_test.go
+++ b/internal/console/nobucket_posts_test.go
@@ -26,8 +26,8 @@ var noBucketPostAllowed = map[string]string{
"POST /a/{sqid}/apps/{app}/place": "placeAppTarget refuses without a bucket",
"POST /a/{sqid}/apps/{app}/domains/attach": "attachDomain opens with bucketRefusal (503)",
"POST /a/{sqid}/apps/{app}/domains/detach": "detachDomain and detachInstanceCatchall refuse without a bucket",
- "POST /a/{sqid}/apps/{app}/domains/buy": "domainPurchaseReady needs Releases, so the door is 404",
- "POST /a/{sqid}/apps/{app}/domains/check": "domainPurchaseReady needs Releases, so the door is 404",
+ "POST /a/{sqid}/apps/{app}/domains/buy": "console database only: a stale form, redirected to the account's buy page; starts nothing",
+ "POST /a/{sqid}/apps/{app}/domains/check": "console database only: a stale form, redirected to the account's buy page; starts nothing",
"POST /a/{sqid}/apps/{app}/domains/point": "domainPurchaseReady needs Releases, so the door is 404",
"POST /a/{sqid}/apps/{app}/restart": "handleBrowserRestart refuses before any restart without a bucket",
"POST /a/{sqid}/apps/{app}/instances/{host}/restart": "handleBrowserRestart refuses before any restart without a bucket",
diff --git a/internal/console/perfwalk_test.go b/internal/console/perfwalk_test.go
index 346506fb3..4e9712dd2 100644
--- a/internal/console/perfwalk_test.go
+++ b/internal/console/perfwalk_test.go
@@ -524,11 +524,19 @@ func perfTargets(fx *consoleFixture) map[string][]perfTarget {
for _, p := range []string{"/fleet/billing", "/fleet/billing/accounts", "/fleet/billing/payments"} {
m[p] = []perfTarget{{Path: p, Expect: http.StatusNotFound}}
}
- // The walk also leaves domain buying unconfigured. All three pages
- // answer domainBuyBrowserGate's 404 before any purchase or provider read.
+ // The walk also leaves domain buying unconfigured. The account's three
+ // pages answer domainBuyAccountGate's 404 before any purchase or
+ // provider read. The old app-scoped pages only redirect: the buy page
+ // at once, a purchase after reading it (an unknown one is the 404).
for _, p := range []string{"buy", "purchases/{id}", "purchases/{id}/status"} {
+ m["GET /a/{sqid}/domains/"+p] = []perfTarget{{
+ Path: fx.path("/domains/" + strings.ReplaceAll(p, "{id}", "dp_0000000000000001")), Expect: http.StatusNotFound}}
+ want := http.StatusNotFound
+ if p == "buy" {
+ want = http.StatusSeeOther
+ }
m["GET /a/{sqid}/apps/{app}/domains/"+p] = []perfTarget{{
- Path: app + "/domains/" + strings.ReplaceAll(p, "{id}", "dp_0000000000000001"), Expect: http.StatusNotFound}}
+ Path: app + "/domains/" + strings.ReplaceAll(p, "{id}", "dp_0000000000000001"), Expect: want}}
}
for _, tab := range []string{"account-review", "activity", "analytics", "availability", "errors",
"instances", "logs", "logs/data", "protection", "protection/data", "settings"} {
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index 03a40d206..f5ccd7ade 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -194,6 +194,21 @@ var routeDecls = []routeDecl{
// configured.
{Pattern: "GET /a/{sqid}/domains", Handler: (*Server).handleAccountDomains},
{Pattern: "GET /a/{sqid}/domains/{domain}", Handler: (*Server).handleAccountDomain},
+ // Buying at the account (accountdomainbuy.go, Plan 2a Task 9): the
+ // three-step page, its search and its purchase, the purchase card
+ // Checkout returns to and its poll, and the saved contacts' forms.
+ // Owner sessions, CSRF on every post; a member, a stranger and another
+ // account's purchase or contact get the same 404. Go's mux prefers
+ // these literals over {domain} above. Not registered on a host-claim
+ // console, where buying is off.
+ {Pattern: "GET /a/{sqid}/domains/buy", Gate: gateNoHostClaim, Handler: (*Server).handleAccountDomainBuy},
+ {Pattern: "POST /a/{sqid}/domains/buy/check", Gate: gateNoHostClaim, Handler: (*Server).handleAccountDomainBuyCheck},
+ {Pattern: "POST /a/{sqid}/domains/buy", Gate: gateNoHostClaim, Handler: (*Server).handleAccountDomainBuyPay},
+ {Pattern: "GET /a/{sqid}/domains/purchases/{id}", Gate: gateNoHostClaim, Handler: (*Server).handleAccountDomainPurchase},
+ {Pattern: "GET /a/{sqid}/domains/purchases/{id}/status", Gate: gateNoHostClaim, Handler: (*Server).handleAccountDomainPurchaseStatus},
+ {Pattern: "POST /a/{sqid}/domains/contacts", Gate: gateNoHostClaim, Handler: (*Server).handleDomainContactAdd},
+ {Pattern: "POST /a/{sqid}/domains/contacts/{id}", Gate: gateNoHostClaim, Handler: (*Server).handleDomainContactEdit},
+ {Pattern: "POST /a/{sqid}/domains/contacts/{id}/remove", Gate: gateNoHostClaim, Handler: (*Server).handleDomainContactRemove},
{Pattern: "GET /a/{sqid}/fleet", Handler: (*Server).handleAccountFleetTab},
{Pattern: "GET /a/{sqid}/fleet/byo", Handler: (*Server).handleFleetBYO},
{Pattern: "GET /a/{sqid}/team", Handler: (*Server).handleTeam},
@@ -327,13 +342,17 @@ var routeDecls = []routeDecl{
// (controlplane.go).
{Pattern: "POST /a/{sqid}/apps/{app}/control-plane/clear", Handler: (*Server).handleAppControlPlaneClear},
{Pattern: "POST /a/{sqid}/apps/{app}/control-plane/set", Handler: (*Server).handleAppControlPlaneSet},
- // Domain purchases: owner sessions, with CSRF on both form posts. Not
- // registered on a host-claim console, where buying is off.
- {Pattern: "GET /a/{sqid}/apps/{app}/domains/buy", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuyForm},
- {Pattern: "POST /a/{sqid}/apps/{app}/domains/check", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuyCheck},
- {Pattern: "POST /a/{sqid}/apps/{app}/domains/buy", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuy},
- {Pattern: "GET /a/{sqid}/apps/{app}/domains/purchases/{id}", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainPurchase},
- {Pattern: "GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainPurchaseStatus},
+ // Plan 1's app-scoped buy routes, kept for open pages, stale forms and
+ // Checkouts prepared before buying moved to the account: they only
+ // redirect there (appdomainbuy.go), checking membership and a
+ // purchase's account, never that the app still exists. The two posts
+ // (CSRF checked) start nothing. Not registered on a host-claim console,
+ // where buying is off.
+ {Pattern: "GET /a/{sqid}/apps/{app}/domains/buy", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuyRedirect},
+ {Pattern: "POST /a/{sqid}/apps/{app}/domains/check", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuyRedirect},
+ {Pattern: "POST /a/{sqid}/apps/{app}/domains/buy", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainBuyRedirect},
+ {Pattern: "GET /a/{sqid}/apps/{app}/domains/purchases/{id}", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainPurchaseRedirect},
+ {Pattern: "GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status", Gate: gateNoHostClaim, Handler: (*Server).handleAppDomainPurchaseRedirect},
// Custom domain attach/detach (appdomains.go, #82): owner-only, no
// passkey step-up (spec §6) — detach's guard is the typed-host confirm.
{Pattern: "POST /a/{sqid}/apps/{app}/domains/attach", Handler: (*Server).handleAppDomainAttach},
diff --git a/internal/console/templates/account_domain_buy.html b/internal/console/templates/account_domain_buy.html
new file mode 100644
index 000000000..66dcd704f
--- /dev/null
+++ b/internal/console/templates/account_domain_buy.html
@@ -0,0 +1,104 @@
+{{define "contact_fields"}}<div class="fields">
+ {{range .}}{{$f := .}}<p><label for="{{.ID}}">{{.Label}}</label>{{if .Options}}<select id="{{.ID}}" name="{{.Name}}" autocomplete="{{.Autocomplete}}" {{if .Required}}required{{end}}>
+ <option value="">{{$f.Choose}}</option>{{range .Options}}<option value="{{.Code}}"{{if .Selected}} selected{{end}}>{{.Name}}</option>{{end}}
+ </select>{{else}}<input type="{{.Type}}" id="{{.ID}}" name="{{.Name}}" value="{{.Value}}" autocomplete="{{.Autocomplete}}" {{if eq .Type "tel"}}inputmode="tel" {{end}}{{if .Required}}required{{end}}>{{end}}</p>
+ {{end}}
+</div>{{end}}
+
+{{define "account_domain_buy"}}{{template "top" .}}
+{{$c := .AccountBuyCopy}}{{$v := .AccountBuy}}
+<div class="pagehead">
+ <p class="eyebrow">{{$v.Eyebrow}}</p>
+ <h1>{{.DomainBuyCopy.title}}</h1>
+</div>
+<p class="chips" aria-label="{{$c.Steps}}">{{range $v.Chips}}<span class="chip {{if .Current}}chip-canary{{else}}chip-env{{end}}"{{if .Current}} aria-current="step"{{end}}>{{if .Done}}{{icon "check"}}{{else}}{{.N}} {{end}}{{.Label}}</span>{{end}}</p>
+{{with $v.Alert}}<p class="banner error" role="alert">{{.}}</p>{{end}}
+
+{{if eq $v.Step "name"}}
+<form class="signin" method="post" action="{{$v.Base}}/check">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ {{with $v.App}}<input type="hidden" name="app" value="{{.}}">{{end}}
+ <label for="buy-name">{{.DomainBuyCopy.name}}</label>
+ <input id="buy-name" type="text" name="name" value="{{$v.Name}}" placeholder="example.com" autocomplete="off" autocapitalize="none" spellcheck="false" required autofocus>
+ {{if $v.AskCountry}}
+ <label for="buy-country">{{$c.Country}}</label>
+ <select id="buy-country" name="country" autocomplete="country" required>
+ <option value="">{{$c.Choose}}</option>{{range $v.Countries}}<option value="{{.Code}}"{{if .Selected}} selected{{end}}>{{.Name}}</option>{{end}}
+ </select>
+ {{else if $v.Country}}<input type="hidden" name="country" value="{{$v.Country}}">{{end}}
+ <button type="submit" class="btn-secondary" data-busy>{{.DomainBuyCopy.check}}</button>
+</form>
+
+{{else if eq $v.Step "app"}}
+<p><code>{{$v.Name}}</code> · {{$v.PerYear}}</p>
+<form method="get" action="{{$v.Base}}">
+ <input type="hidden" name="step" value="pay">
+ <input type="hidden" name="name" value="{{$v.Name}}">
+ {{with $v.Country}}<input type="hidden" name="country" value="{{.}}">{{end}}
+ <div class="plan-cards" role="radiogroup" aria-label="{{$c.PointAt}}">
+ {{range $v.Apps}}<div class="plan-card"><label><input type="radio" name="choice" value="app:{{.App}}"{{if .Checked}} checked{{end}} required><span class="plan-name">{{.App}}</span></label></div>
+ {{end}}<div class="plan-card"><label><input type="radio" name="choice" value="notyet"{{if $v.NotYetPicked}} checked{{end}} required><span class="plan-name">{{$c.NotYet}}</span></label><p class="small">{{$c.NotYetNote}}</p></div>
+ </div>
+ <p class="small">{{$v.PointNote}}</p>
+ <div class="settings-row">
+ <a class="btn btn-secondary" href="{{$v.Back}}">{{$c.Back}}</a>
+ <button type="submit">{{$c.Next}}</button>
+ </div>
+</form>
+
+{{else}}
+<section class="tiles" aria-label="{{if $v.NotYet}}{{$c.OrderNotYet}}{{else}}{{$c.Order}}{{end}}">
+ {{range $v.Tiles}}<div class="tile">
+ <h2>{{.Label}}</h2>
+ <p class="tile-value">{{.Value}}</p>
+ <p class="tile-detail">{{.Detail}}</p>
+ </div>{{end}}
+</section>
+
+<form method="post" action="{{$v.Base}}">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ <input type="hidden" name="name" value="{{$v.Name}}">
+ {{if $v.NotYet}}<input type="hidden" name="notyet" value="1">{{else}}<input type="hidden" name="app" value="{{$v.App}}">{{end}}
+ {{with $v.Country}}<input type="hidden" name="country" value="{{.}}">{{end}}
+ <input type="hidden" name="currency" value="{{$v.Quote.Currency}}">
+ <input type="hidden" name="price" value="{{$v.Quote.Price}}">
+ <h2>{{.DomainsCopy.RegisteredTo}}</h2>
+ <p class="small">{{$c.RegisteredNote}}</p>
+ {{if $v.Contacts}}
+ {{if $v.Filter}}<label class="visually-hidden" for="contact-find">{{$c.FindContact}}</label>
+ <input type="search" id="contact-find" class="contact-find" placeholder="{{$c.FindContact}}" autocomplete="off">{{end}}
+ <div class="tablewrap">
+ <ul class="envvars contact-pick" id="contact-pick">
+ {{range $v.Contacts}}<li><label class="envvar-row"><input type="radio" name="contact" value="{{.ID}}"{{if .Checked}} checked{{end}}><span class="envvar-name">{{.Name}}</span><span class="envvar-value small">{{.Detail}}</span></label></li>
+ {{end}}<li><label class="envvar-row"><input type="radio" name="contact" value="new" id="contact-new"{{if $v.NewPicked}} checked{{end}}><span class="envvar-name">{{$c.AddContact}}</span></label></li>
+ </ul>
+ </div>
+ <div class="newcontact">
+ {{template "contact_fields" $v.NewFields}}
+ <p class="small">{{$c.SavedForNext}}</p>
+ </div>
+ {{else}}
+ <input type="hidden" name="contact" value="new">
+ {{template "contact_fields" $v.NewFields}}
+ <p class="small">{{$c.SavedForNext}}</p>
+ {{end}}
+ <div class="settings-row">
+ <a class="btn btn-secondary" href="{{$v.Back}}">{{$c.Back}}</a>
+ <button type="submit" data-busy>{{$c.Pay}}</button>
+ </div>
+</form>
+{{if $v.Filter}}<script>
+(function () {
+ const find = document.getElementById('contact-find');
+ const rows = document.querySelectorAll('#contact-pick li');
+ find.addEventListener('input', () => {
+ const q = find.value.trim().toLowerCase();
+ rows.forEach(row => {
+ const isNew = row.querySelector('#contact-new');
+ row.hidden = !isNew && q !== '' && !row.textContent.toLowerCase().includes(q);
+ });
+ });
+})();
+</script>{{end}}
+{{end}}
+{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/account_domains.html b/internal/console/templates/account_domains.html
index 1d764677a..6aba36dca 100644
--- a/internal/console/templates/account_domains.html
+++ b/internal/console/templates/account_domains.html
@@ -73,13 +73,30 @@
<div class="sectionhead" id="contacts">
<h2>{{$c.Contacts}}</h2>
</div>
-{{if $v.Contacts}}
-<p class="small">{{$c.ContactsNote}}</p>
+{{$b := $.AccountBuyCopy}}
+{{if $v.Contacts}}<p class="small">{{$c.ContactsNote}}</p>{{else}}<p class="small">{{$c.ContactsEmpty}}</p>{{end}}
+{{if or $v.Contacts $v.ContactsAction}}
<div class="tablewrap">
<ul class="envvars">
- {{range $v.Contacts}}<li><div class="envvar-row"><span class="envvar-name">{{.Name}}</span><span class="envvar-value small">{{.Detail}}</span></div></li>{{end}}
+ {{range $v.Contacts}}{{if .Action}}<li><details class="envvar"><summary><span class="envvar-name">{{.Name}}</span><span class="envvar-value small">{{.Detail}}</span><span class="envvar-edit"><span class="envvar-when-closed">{{$b.Edit}}</span><span class="envvar-when-open">{{$c.Close}}</span></span></summary>
+ <form class="envvar-panel" method="post" action="{{.Action}}">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ {{template "contact_fields" .Fields}}
+ <div class="settings-row">
+ <button type="submit" class="btn-sm" data-busy>{{$b.Save}}</button>
+ <button type="submit" class="linkish danger" formaction="{{.RemoveAction}}" formnovalidate>{{$b.Remove}}</button>
+ </div>
+ </form>
+ </details></li>{{else}}<li><div class="envvar-row"><span class="envvar-name">{{.Name}}</span><span class="envvar-value small">{{.Detail}}</span></div></li>{{end}}
+ {{end}}{{with $v.ContactsAction}}<li><details class="envvar"><summary><span class="envvar-name">{{$b.AddContact}}</span><span class="envvar-value"></span><span class="envvar-edit"><span class="envvar-when-closed">{{$c.Add}}</span><span class="envvar-when-open">{{$c.Close}}</span></span></summary>
+ <form class="envvar-panel" method="post" action="{{.}}">
+ <input type="hidden" name="csrf" value="{{$.CSRF}}">
+ {{template "contact_fields" $v.AddFields}}
+ <div class="settings-row"><button type="submit" class="btn-sm" data-busy>{{$b.SaveContact}}</button></div>
+ </form>
+ </details></li>{{end}}
</ul>
</div>
-{{else}}<p class="small">{{$c.ContactsEmpty}}</p>{{end}}
+{{end}}
{{end}}
{{template "bottom" .}}{{end}}
diff --git a/internal/console/templates/console_chrome.html b/internal/console/templates/console_chrome.html
index 92656daa3..c5cae698e 100644
--- a/internal/console/templates/console_chrome.html
+++ b/internal/console/templates/console_chrome.html
@@ -280,6 +280,20 @@
.domain-head .envvar-name { font-weight: 600; }
.domain-head .envvar-value { flex: 1 1 14rem; white-space: normal; }
.domain-head .chip { margin: 0; }
+ /* Buying a domain and saved contacts (account_domain_buy.html,
+ account_domains.html): radio rows on the variable-row list, the filter
+ above a long one, a contact's fields as a wrapping grid of labelled
+ inputs, and the new contact's fields, shown only once "Add a new
+ contact" is chosen (no script needed). */
+ .contact-pick .envvar-row { align-items: center; cursor: pointer; }
+ .contact-pick input { margin: 0; accent-color: var(--accent); }
+ .contact-find { margin: 0 0 0.6rem; width: 100%; max-width: 24rem; box-sizing: border-box; }
+ .newcontact { display: none; }
+ form:has(#contact-new:checked) .newcontact { display: block; }
+ .fields { display: grid; grid-template-columns: repeat(auto-fit, minmax(13rem, 1fr)); gap: 0.75rem 1rem; margin: 0.25rem 0 1rem; }
+ .fields p { margin: 0; }
+ .fields label { display: block; font-size: 0.9rem; font-weight: 600; margin: 0 0 0.25rem; }
+ .fields :is(input, select) { width: 100%; box-sizing: border-box; }
/* Address rows wrap on a phone, so the app and its state chip are never
cut off. */
.addr-rows .envvar > summary, .addr-rows .envvar-row { flex-wrap: wrap; row-gap: 0.3rem; }
diff --git a/internal/console/templates/domain_buy.html b/internal/console/templates/domain_buy.html
index f61b62098..18eb250ec 100644
--- a/internal/console/templates/domain_buy.html
+++ b/internal/console/templates/domain_buy.html
@@ -25,13 +25,14 @@
}
@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">
+{{$done := or (eq .Card.Stage.Kind "live") (eq .Card.Stage.Kind "ready")}}
+<section id="purchase-card" class="purchase-card{{if $done}} 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>
+ <span id="purchase-mark" class="done-mark" aria-hidden="true" {{if not $done}}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}}>
+ <ol id="purchase-steps" class="purchase-steps" {{if not .Card.Stepped}}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>
@@ -39,36 +40,41 @@
<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>
+ <a id="purchase-point" class="btn" href="{{.Point}}" {{if ne .Card.Stage.Kind "ready"}}hidden{{end}}>{{$.DomainsCopy.PointAtApp}}</a>
+ <a id="purchase-back" 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}}, stages = {{.Stages}};
+ const endpoint = {{.PollURL}}, copy = {{.CardCopy}}, stagesApp = {{.Stages}}, stagesNoApp = {{.StagesNoApp}};
+ let noApp = {{.NoApp}};
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 point = document.getElementById('purchase-point');
const status = document.getElementById('purchase-status'), labels = {{.Card.StepLabels}};
const started = Date.now();
let state = {{.Purchase.State}}, domainState = {{.DomainState}};
- let rendered = state + ':' + domainState + ':false';
+ let rendered = state + ':' + domainState + ':false:' + noApp;
const fill = text => text.replace(/\{(domain|app)\}/g, (_, key) => key === 'domain' ? domain : app);
- const terminal = () => ['failed', 'expired', 'unpaid'].includes(state) || (state === 'done' && domainState === 'live');
+ const stageNow = () => (noApp ? stagesNoApp : stagesApp)[state === 'done' && domainState === 'live' ? 'live' : state];
+ const terminal = () => ['failed', 'expired', 'unpaid', 'live', 'ready'].includes(stageNow().Kind);
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;
+ const stage = stageNow(), stepped = ['progress', 'progressNoApp', 'readying'].includes(stage.Kind);
+ const slow = stage.Steps.includes('active') && Date.now() - started >= 600000;
+ const key = state + ':' + domainState + ':' + slow + ':' + noApp;
if (key === rendered) return;
rendered = key;
- card.classList.toggle('done', stage.Kind === 'live');
- mark.hidden = stage.Kind !== 'live';
+ const done = stage.Kind === 'live' || stage.Kind === 'ready';
+ card.classList.toggle('done', done);
+ mark.hidden = !done;
title.textContent = fill(copy[stage.Kind + 'Title']);
lede.textContent = fill(copy[slow ? 'slowLede' : stage.Kind + 'Lede']);
- steps.hidden = stage.Kind !== 'progress';
+ steps.hidden = !stepped;
rows.forEach((row, i) => {
row.dataset.state = stage.Steps[i];
if (stage.Steps[i] === 'active') row.setAttribute('aria-current', 'step');
@@ -77,7 +83,9 @@
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 (point) point.hidden = stage.Kind !== 'ready';
+ const active = stage.Steps.indexOf('active');
+ const announcement = active >= 0 ? labels[active] : title.textContent;
if (status.textContent !== announcement) status.textContent = announcement;
}
async function poll() {
@@ -86,9 +94,10 @@
const response = await fetch(endpoint, {credentials: 'same-origin', cache: 'no-store'});
if (!response.ok) throw new Error();
const purchase = await response.json();
- if (!Object.prototype.hasOwnProperty.call(stages, purchase.state)) throw new Error();
+ if (!Object.prototype.hasOwnProperty.call(stagesApp, purchase.state)) throw new Error();
state = purchase.state;
domainState = purchase.domain_state || '';
+ if (purchase.app === '') noApp = true;
error.hidden = true;
update();
if (terminal()) return;
@@ -106,35 +115,6 @@
if (!terminal()) poll();
})();
</script>
-{{else if .Quote}}
-{{if .PriceChanged}}<p role="alert">{{$.DomainBuyCopy.priceChanged}}</p>{{end}}
-<p>{{$.DomainBuyCopy.name}}: <strong>{{.Quote.Domain}}</strong></p>
-<p>{{$.DomainBuyCopy.quote}}: {{.Price}}</p>
-<p class="small">{{$.DomainBuyCopy.paymentDetails}}</p>
-<h2>{{$.DomainBuyCopy.contact}}</h2>
-<p>{{$.DomainBuyCopy.ownership}}</p>
-<p>{{$.DomainBuyCopy.timing}}</p>
-<form method="post" action="{{.Base}}/buy">
- <input type="hidden" name="csrf" value="{{$.CSRF}}">
- <input type="hidden" name="name" value="{{.Quote.Domain}}">
- <input type="hidden" name="currency" value="{{.Quote.Currency}}">
- <input type="hidden" name="price" value="{{.Quote.Price}}">
- {{range .Fields}}
- <p><label for="buy-{{.Name}}">{{.Label}}</label>
- <input id="buy-{{.Name}}" name="{{.Name}}" value="{{.Value}}" {{if .Required}}required{{end}}></p>
- {{end}}
- <button type="submit">{{$.DomainBuyCopy.pay}}</button>
-</form>
-{{else}}
-<form method="post" action="{{.Base}}/check" class="settings-row">
- <input type="hidden" name="csrf" value="{{$.CSRF}}">
- <label for="buy-name">{{$.DomainBuyCopy.name}}</label>
- <input id="buy-name" name="name" required>
- <label for="buy-country">{{$.DomainBuyCopy.Country}}</label>
- <input id="buy-country" name="country" maxlength="2" pattern="[A-Z]{2}">
- <button type="submit">{{$.DomainBuyCopy.check}}</button>
-</form>
{{end}}
-{{if not .Purchase}}<p><a href="{{.Back}}">{{$.DomainBuyCopy.back}}</a></p>{{end}}
{{end}}
{{template "bottom" .}}{{end}}
diff --git a/parity/parity.tsv b/parity/parity.tsv
index 5f71afd28..9ff3ff8e1 100644
--- a/parity/parity.tsv
+++ b/parity/parity.tsv
@@ -86,7 +86,8 @@ domains-account domains console-only GET /a/{sqid}/domains The account's doma
domains-account-page domains console-only GET /a/{sqid}/domains/{domain} One domain's addresses, expiry and the records to set; the CLI list comes later.
domains-attach domains both domains attach ; domains detach POST /a/{sqid}/apps/{app}/domains/attach ; POST /a/{sqid}/apps/{app}/domains/detach
domains-verify domains partial domains verify POST /a/{sqid}/apps/{app}/domains/attach There is no Verify button; attaching again verifies.
-domains-buy domains both domains check ; domains buy GET /a/{sqid}/apps/{app}/domains/buy ; POST /a/{sqid}/apps/{app}/domains/check ; POST /a/{sqid}/apps/{app}/domains/buy ; GET /a/{sqid}/apps/{app}/domains/purchases/{id} ; GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status
+domains-buy domains both domains check ; domains buy GET /a/{sqid}/domains/buy ; POST /a/{sqid}/domains/buy/check ; POST /a/{sqid}/domains/buy ; GET /a/{sqid}/domains/purchases/{id} ; GET /a/{sqid}/domains/purchases/{id}/status ; GET /a/{sqid}/apps/{app}/domains/buy ; POST /a/{sqid}/apps/{app}/domains/check ; POST /a/{sqid}/apps/{app}/domains/buy ; GET /a/{sqid}/apps/{app}/domains/purchases/{id} ; GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status The app-scoped routes only redirect to the account's.
+domains-contacts domains console-only POST /a/{sqid}/domains/contacts ; POST /a/{sqid}/domains/contacts/{id} ; POST /a/{sqid}/domains/contacts/{id}/remove Saved contacts are added, edited and removed on the Domains page; the CLI buys with the most recently used one.
domains-point domains console-only POST /a/{sqid}/apps/{app}/domains/point Pointing a bought domain at an app; the CLI verb comes later.
domains-paths domains gap domains paths wp-settings
domains-placements domains gap domains placements wp-settings