console: domain check and buy doors, purchase status, browser flow
Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
16 files changed,
+946
−19
internal/console/apidomainbuy.go+192 −0internal/console/apidomainbuy_test.go+432 −0internal/console/appdomainbuy.go+142 −0internal/console/appsettings.go+3 −2internal/console/authcli.go+3 −0internal/console/claim_invariant_fixtures_test.go+14 −0internal/console/claim_invariant_probes_read_test.go+9 −0internal/console/domainbuy.go+7 −12internal/console/domainbuy_copy.go+58 −0internal/console/domainbuy_test.go+2 −2internal/console/domainstate.go+10 −0internal/console/server.go+10 −1internal/console/svcroutes_test.go+5 −2internal/console/templates/app_settings.html+1 −0internal/console/templates/domain_buy.html+50 −0internal/console/testdata/claim-routes.txt+8 −0
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go| new file mode 100644 |
| index 000000000..3073a27ad |
| --- /dev/null |
| +++ b/internal/console/apidomainbuy.go |
| @@ -0,0 +1,192 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "net/http" |
| + "os" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domainreg" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| +) |
| + |
| +// Account-scoped doors share the domains ceiling without requiring an app URL. |
| +func (s *Server) domainBuyAPIGate(w http.ResponseWriter, r *http.Request) (string, *Account, bool) { |
| + if !s.apiPerson(w, r) { |
| + return "", nil, false |
| + } |
| + addr, acct, ok := s.apiAccount(w, r) |
| + if !ok { |
| + return "", nil, false |
| + } |
| + role, err := s.store.Role(acct.ID, addr) |
| + if err != nil || role != RoleOwner || !s.domainBuyReady() { |
| + http.NotFound(w, r) |
| + return "", nil, false |
| + } |
| + p, _ := principalFrom(r.Context()) |
| + if !s.allowDomains(p, time.Now()) { |
| + jsonError(w, 429, domainBuyCopy["rate"]) |
| + return "", nil, false |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + return addr, acct, true |
| +} |
| + |
| +// Check cannot name an app, so any existing claim is unavailable here. The |
| +// engine repeats its own checks before creating a purchase; this read reserves nothing. |
| +func (s *Server) checkDomainBuy(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) { |
| + name, err := domainreg.Normalize(name) |
| + if err != nil { |
| + return domainreg.Quote{}, &doorRefusal{422, domainBuyCopy["nameError"]} |
| + } |
| + for _, host := range []string{name, "www." + name} { |
| + if s.domainHostDenied(host, acct.Sqid) { |
| + return domainreg.Quote{}, claimRefusal(host, domains.ErrHostUnavailable) |
| + } |
| + if ref := s.heldElsewhere(ctx, host, acct.Sqid, ""); ref != nil { |
| + return domainreg.Quote{}, ref |
| + } |
| + _, err := domains.GetClaim(ctx, s.cfg.Releases, host) |
| + if err == nil { |
| + return domainreg.Quote{}, claimRefusal(host, domains.ErrHostUnavailable) |
| + } |
| + if !errors.Is(err, os.ErrNotExist) { |
| + return domainreg.Quote{}, domainBuyUnavailable() |
| + } |
| + } |
| + if ref := s.liveDomainPurchaseRefusal(ctx, name); ref != nil { |
| + return domainreg.Quote{}, ref |
| + } |
| + q, ref := s.quoteDomain(ctx, acct, name) |
| + return q, domainBuyDoorRefusal(ref) |
| +} |
| + |
| +func (s *Server) liveDomainPurchaseRefusal(ctx context.Context, name string) *doorRefusal { |
| + var live bool |
| + if err := s.store.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM domain_purchases WHERE domain=? AND `+liveDomainPurchaseSQL+`)`, name).Scan(&live); err != nil { |
| + return domainBuyUnavailable() |
| + } |
| + if live { |
| + return claimRefusal(name, domains.ErrHostUnavailable) |
| + } |
| + return nil |
| +} |
| + |
| +func (s *Server) handleAPIDomainCheck(w http.ResponseWriter, r *http.Request) { |
| + _, acct, ok := s.domainBuyAPIGate(w, r) |
| + if !ok { |
| + return |
| + } |
| + var in struct { |
| + Name string `json:"name"` |
| + } |
| + if !readJSONStrictLimit(w, r, &in, 8<<10) { |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) |
| + defer cancel() |
| + q, ref := s.checkDomainBuy(ctx, acct, in.Name) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, ref) |
| + return |
| + } |
| + writeJSON(w, 200, map[string]any{"domain": q.Domain, "price": q.Price, "currency": q.Currency, "available": true}) |
| +} |
| + |
| +func (s *Server) domainBuyContact(acct *Account, supplied *registrar.Contact) (registrar.Contact, *doorRefusal) { |
| + var c registrar.Contact |
| + if supplied != nil { |
| + c = *supplied |
| + } else { |
| + var err error |
| + c, _, err = s.store.DomainContact(acct.ID) |
| + if err != nil { |
| + return c, domainBuyUnavailable() |
| + } |
| + } |
| + if err := c.Validate(); err != nil { |
| + return c, &doorRefusal{422, domainBuyCopy["contactError"]} |
| + } |
| + return c, nil |
| +} |
| +func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request) { |
| + addr, acct, ok := s.domainBuyAPIGate(w, r) |
| + if !ok { |
| + return |
| + } |
| + var in struct { |
| + Name string `json:"name"` |
| + App string `json:"app"` |
| + Contact *registrar.Contact `json:"contact"` |
| + } |
| + if !readJSONStrictLimit(w, r, &in, 16<<10) { |
| + return |
| + } |
| + c, ref := s.domainBuyContact(acct, in.Contact) |
| + if ref != nil { |
| + if ref.Status == 422 { |
| + writeJSON(w, 422, map[string]string{"error": ref.Msg, "code": "contact"}) |
| + } else { |
| + writeDoorRefusalJSON(w, r, ref) |
| + } |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) |
| + defer cancel() |
| + p, checkout, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, c, addr) |
| + if ref != nil { |
| + writeDoorRefusalJSON(w, r, domainBuyDoorRefusal(ref)) |
| + return |
| + } |
| + writeJSON(w, 200, map[string]any{"id": p.ID, "checkout_url": checkout, "state": p.State}) |
| +} |
| + |
| +type domainPurchaseReply struct { |
| + ID string `json:"id"` |
| + Domain string `json:"domain"` |
| + App string `json:"app"` |
| + State PurchaseState `json:"state"` |
| + Reason string `json:"reason"` |
| + DomainState string `json:"domain_state"` |
| +} |
| + |
| +func (s *Server) purchaseForAccount(w http.ResponseWriter, r *http.Request, acct *Account, app string) *DomainPurchase { |
| + p, err := s.store.DomainPurchase(r.PathValue("id")) |
| + if err != nil { |
| + writeDoorRefusalJSON(w, r, domainBuyUnavailable()) |
| + return nil |
| + } |
| + if p == nil || p.AccountID != acct.ID || (app != "" && p.App != app) { |
| + http.NotFound(w, r) |
| + return nil |
| + } |
| + return p |
| +} |
| +func (s *Server) writeDomainPurchaseStatus(w http.ResponseWriter, r *http.Request, acct *Account, p *DomainPurchase) { |
| + s.nudgePurchase(p.ID) |
| + out := domainPurchaseReply{ID: p.ID, Domain: p.Domain, App: p.App, State: p.State, Reason: p.Reason} |
| + ctx, cancel := context.WithTimeout(r.Context(), instanceStoreTimeout) |
| + defer cancel() |
| + c, err := domains.GetClaim(ctx, s.cfg.Releases, p.Domain) |
| + if err == nil && c.Account == acct.Sqid && c.App == p.App { |
| + now := time.Now() |
| + out.DomainState = s.domainItem(ctx, *c, aliasReadings(ctx, s.cfg.Releases, now), warmRecord(ctx, s.cfg.Releases, c.Host), s.dnsTargets(ctx), now, c.Wildcard && s.delegationZone != "").State |
| + } else if err != nil && !errors.Is(err, os.ErrNotExist) { |
| + out.DomainState = StateUnknown |
| + } |
| + writeJSON(w, 200, out) |
| +} |
| +func (s *Server) handleAPIDomainPurchaseStatus(w http.ResponseWriter, r *http.Request) { |
| + _, acct, ok := s.domainBuyAPIGate(w, r) |
| + if !ok { |
| + return |
| + } |
| + p := s.purchaseForAccount(w, r, acct, "") |
| + if p == nil { |
| + return |
| + } |
| + s.writeDomainPurchaseStatus(w, r, acct, p) |
| +} |
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go| new file mode 100644 |
| index 000000000..6576c4839 |
| --- /dev/null |
| +++ b/internal/console/apidomainbuy_test.go |
| @@ -0,0 +1,432 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/domainreg" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| + "github.com/carlosframework/platform/internal/registrar/registrartest" |
| + "github.com/carlosframework/platform/internal/svcrole" |
| + "github.com/carlosframework/platform/internal/zonehost/zonehosttest" |
| +) |
| + |
| +func buyToken(t *testing.T, f *purchaseFixture) string { |
| + t.Helper() |
| + return cliToken(t, f.consoleFixture, "owner"+f.acct.Sqid+"@example.com", "buy-owner") |
| +} |
| +func buyAPIPath(f *purchaseFixture) string { return "/api/cli/accounts/" + f.acct.Sqid + "/domains" } |
| +func buyRequest(t *testing.T, f *purchaseFixture, method, path, token, body string) (int, string) { |
| + t.Helper() |
| + req, err := http.NewRequest(method, f.ts.URL+path, strings.NewReader(body)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + req.Header.Set("Authorization", "Bearer "+token) |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := http.DefaultClient.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + b, err := io.ReadAll(resp.Body) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return resp.StatusCode, string(b) |
| +} |
| +func buyBody() string { |
| + b, _ := json.Marshal(map[string]any{"name": "shop.com", "app": "kass", "contact": purchaseContact()}) |
| + return string(b) |
| +} |
| +func TestBuyDoorAbsentWhenNotConfigured(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + tok := buyToken(t, f) |
| + original, billingRuntime := f.srv.cfg, f.srv.billing |
| + for _, missing := range []string{"registrar", "zone", "catalog", "billing", "billing-not-ready", "bucket"} { |
| + f.srv.cfg, f.srv.billing = original, billingRuntime |
| + f.srv.billing.ready.Store(true) |
| + switch missing { |
| + case "registrar": |
| + f.srv.cfg.Registrar = nil |
| + case "zone": |
| + f.srv.cfg.ZoneHost = nil |
| + case "catalog": |
| + f.srv.cfg.DomainCatalog = nil |
| + case "billing": |
| + f.srv.billing = nil |
| + case "billing-not-ready": |
| + f.srv.billing.ready.Store(false) |
| + case "bucket": |
| + f.srv.cfg.Releases = nil |
| + } |
| + for _, r := range []struct{ method, path, body string }{{"POST", "/check", `{"name":"shop.com"}`}, {"POST", "/purchases", buyBody()}, {"GET", "/purchases/unknown", ""}} { |
| + status, b := buyRequest(t, f, r.method, buyAPIPath(f)+r.path, tok, r.body) |
| + if status != 404 { |
| + t.Fatalf("%s %s: %d %s", missing, r.path, status, b) |
| + } |
| + } |
| + if _, ok := f.srv.domainCapability(context.Background(), f.acct.Sqid, "kass").Features["buy"]; ok { |
| + t.Fatalf("buy advertised without %s", missing) |
| + } |
| + } |
| + f.srv.cfg, f.srv.billing = original, billingRuntime |
| + f.srv.billing.ready.Store(true) |
| + if f.srv.domainCapability(context.Background(), f.acct.Sqid, "kass").Features["buy"] != "true" { |
| + t.Fatal("buy not advertised when ready") |
| + } |
| +} |
| +func TestBuyDoorOwnerOnly(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + if err := f.st.AddMember(f.acct.ID, "member@example.com", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, tok := range []string{cliToken(t, f.consoleFixture, "member@example.com", "buy-member"), serviceToken(t, f.st, f.acct.ID, "buy-service", "kass", svcrole.Publish)} { |
| + for _, r := range []struct{ method, path, body string }{{"POST", "/check", `{"name":"shop.com"}`}, {"POST", "/purchases", buyBody()}, {"GET", "/purchases/unknown", ""}} { |
| + status, b := buyRequest(t, f, r.method, buyAPIPath(f)+r.path, tok, r.body) |
| + if status != 404 && status != 403 && status != 401 { |
| + t.Fatalf("%s: %d %s", r.path, status, b) |
| + } |
| + } |
| + } |
| + if len(f.reg.Calls) != 0 { |
| + t.Fatalf("unauthorized provider calls: %v", f.reg.Calls) |
| + } |
| +} |
| +func TestBuyDoorSecondConcurrentBuyRefused(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + tok := buyToken(t, f) |
| + var wg sync.WaitGroup |
| + statuses := make([]int, 2) |
| + bodies := make([]string, 2) |
| + for i := range statuses { |
| + wg.Add(1) |
| + go func(i int) { |
| + defer wg.Done() |
| + statuses[i], bodies[i] = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, buyBody()) |
| + }(i) |
| + } |
| + wg.Wait() |
| + successes, conflicts := 0, 0 |
| + for i, s := range statuses { |
| + if s == 200 || s == 201 { |
| + successes++ |
| + } else if s == 409 { |
| + conflicts++ |
| + } else { |
| + t.Fatalf("unexpected %d %s", s, bodies[i]) |
| + } |
| + } |
| + if successes != 1 || conflicts != 1 { |
| + t.Fatalf("statuses %v", statuses) |
| + } |
| + if purchaseCalls(f.reg.Calls, "contact:") > 1 { |
| + t.Fatal("duplicate contact") |
| + } |
| +} |
| +func TestPurchaseStatusOtherAccount404(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(t) |
| + tok := buyToken(t, f) |
| + other := planAccount(t, f.consoleFixture, 502) |
| + otherTok := cliToken(t, f.consoleFixture, "owner"+other.Sqid+"@example.com", "buy-other") |
| + path := "/api/cli/accounts/" + other.Sqid + "/domains/purchases/" |
| + s1, b1 := buyRequest(t, f, "GET", path+p.ID, otherTok, "") |
| + s2, b2 := buyRequest(t, f, "GET", path+"unknown", otherTok, "") |
| + if s1 != 404 || s2 != 404 || b1 != b2 { |
| + t.Fatalf("foreign %d %q unknown %d %q", s1, b1, s2, b2) |
| + } |
| + before := f.read(t, p.ID).Revision |
| + status, b := buyRequest(t, f, "GET", buyAPIPath(f)+"/purchases/"+p.ID, tok, "") |
| + if status != 200 || !strings.Contains(b, `"state":"awaiting_payment"`) { |
| + t.Fatalf("status %d %s", status, b) |
| + } |
| + if f.read(t, p.ID).Revision != before { |
| + t.Fatal("poll mutated purchase") |
| + } |
| +} |
| +func TestCheckDoorRefusalsAreNeutral(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + tok := buyToken(t, f) |
| + if _, _, err := domains.AttachClaim(context.Background(), f.rel, domains.Claim{Schema: 1, Host: "held.com", Account: "foreign", App: "other", Route: "other.example.com"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.start(t) |
| + s1, b1 := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"held.com"}`) |
| + s2, b2 := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"shop.com"}`) |
| + if s1 != 409 || s2 != 409 || b1 != b2 { |
| + t.Fatalf("held %d %q live %d %q", s1, b1, s2, b2) |
| + } |
| +} |
| +func TestBrowserBuyRedirectsToCheckout(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + c := newBrowser(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"}}) |
| + if status != 200 || !strings.Contains(body, "$15") || !strings.Contains(body, "PhoneCountryCode") { |
| + t.Fatalf("quote %d %s", status, body) |
| + } |
| + values := url.Values{"csrf": {csrf}, "name": {"shop.com"}} |
| + raw, _ := json.Marshal(purchaseContact()) |
| + var fields map[string]string |
| + _ = json.Unmarshal(raw, &fields) |
| + for k, v := range fields { |
| + values.Set(k, v) |
| + } |
| + status, loc, body := postForm(t, c, base+"/buy", values) |
| + if status != 303 || !strings.HasPrefix(loc, "https://") { |
| + t.Fatalf("checkout %d %q %s", status, loc, body) |
| + } |
| + ps, err := f.st.LiveDomainPurchases() |
| + if err != nil || len(ps) != 1 { |
| + t.Fatalf("purchases %v %v", ps, err) |
| + } |
| + status, _, body = get(t, c, base+"/purchases/"+ps[0].ID) |
| + if status != 200 || !strings.Contains(body, "fetch(") { |
| + t.Fatalf("purchase page %d %s", status, body) |
| + } |
| +} |
| +func TestBrowserBuyCSRF(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + c := newBrowser(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"}}) |
| + if status != 403 { |
| + t.Fatalf("%s: %d %s", door, status, body) |
| + } |
| + } |
| + if len(f.reg.Calls) != 0 { |
| + t.Fatal("CSRF refusal reached registrar") |
| + } |
| +} |
| +func TestBuyDoorStoredContact(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + tok := buyToken(t, f) |
| + status, b := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass"}`) |
| + if status != 422 || !strings.Contains(b, `"code":"contact"`) { |
| + t.Fatalf("missing contact %d %s", status, b) |
| + } |
| + if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, b = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass"}`) |
| + if status != 200 && status != 201 { |
| + t.Fatalf("stored contact %d %s", status, b) |
| + } |
| +} |
| + |
| +func setupClaimBuyDoors(t *testing.T, cx *claimCase) { |
| + claimBillingWorld(t, cx) |
| + if err := cx.srv.syncSubscription(context.Background(), "sub_claim", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + reg := registrartest.New() |
| + reg.BalanceMoney = registrar.Money{Currency: "usd", Minor: 100000} |
| + reg.Available["shop.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + cx.srv.cfg.Registrar = reg |
| + cx.srv.cfg.ZoneHost = zonehosttest.New("ns1.carloku.test") |
| + cx.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": {Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}} |
| +} |
| +func claimBuyForm(t *testing.T, cx *claimCase) int { |
| + raw, _ := json.Marshal(purchaseContact()) |
| + var fields map[string]string |
| + _ = json.Unmarshal(raw, &fields) |
| + kv := []string{"name", "shop.com"} |
| + for k, v := range fields { |
| + kv = append(kv, k, v) |
| + } |
| + return cx.formReply(t, "/a/bab/apps/kass/domains/buy", kv...).Status |
| +} |
| +func claimBuyCheck(t *testing.T, cx *claimCase, open bool) string { |
| + ps, err := cx.st.LiveDomainPurchases() |
| + if err != nil { |
| + return err.Error() |
| + } |
| + if open { |
| + if len(ps) != 1 || ps[0].CheckoutSession == "" { |
| + return "purchase did not reach checkout" |
| + } |
| + } else if len(ps) != 0 { |
| + return "blocked purchase wrote a journal row" |
| + } |
| + return "" |
| +} |
| +func TestBuyDoorClaimBoundaries(t *testing.T) { |
| + keys := []string{ |
| + "route POST /api/cli/accounts/{account}/domains/check", |
| + "route POST /api/cli/accounts/{account}/domains/purchases", |
| + "route GET /api/cli/accounts/{account}/domains/purchases/{id}", |
| + "route GET /a/{sqid}/apps/{app}/domains/buy", |
| + "route POST /a/{sqid}/apps/{app}/domains/check", |
| + "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", |
| + } |
| + cx := newClaimCase(t) |
| + for _, p := range claimFixtureCensus(cx.srv.claimEntries.snapshot(), claimFixtures) { |
| + t.Error(p) |
| + } |
| + for _, p := range claimProbeCensus(claimFixtures, claimProbes) { |
| + t.Error(p) |
| + } |
| + for _, key := range keys { |
| + t.Run(key, func(t *testing.T) { |
| + f := claimFixtures[key] |
| + if f.door != nil { |
| + problems, writers := runClaimDoor(t, f.door) |
| + for _, p := range problems { |
| + t.Error(p) |
| + } |
| + found := false |
| + for _, w := range writers { |
| + if w == "sql/domain_purchases" { |
| + found = true |
| + } |
| + } |
| + if !found { |
| + t.Error("purchase writer not covered") |
| + } |
| + } else { |
| + for _, p := range runClaimProbe(t, newClaimCase(t), key, claimProbes[key]) { |
| + t.Error(p) |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestBrowserBuyOwnerOnlyAndPurchaseIsolation(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + p := f.start(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" |
| + for _, addr := range []string{"member@example.com", "stranger@example.com"} { |
| + c := newBrowser(t) |
| + f.setUser(addr) |
| + signUp(t, f.consoleFixture, c, "browser-"+addr) |
| + for _, path := range []string{"/buy", "/purchases/" + p.ID, "/purchases/" + p.ID + "/status"} { |
| + status, _, body := get(t, c, base+path) |
| + if status != 404 || body != "404 page not found\n" { |
| + t.Fatalf("%s %s: %d %q", addr, path, status, body) |
| + } |
| + } |
| + for _, path := range []string{"/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) |
| + } |
| + } |
| + } |
| + 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, "browser-other") |
| + for _, suffix := range []string{"", "/status"} { |
| + prefix := f.ts.URL + "/a/" + other.Sqid + "/apps/kass/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 { |
| + t.Fatalf("foreign purchase %d %q unknown %d %q", s1, b1, s2, b2) |
| + } |
| + } |
| +} |
| +func TestBuyDoorRateCeiling(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + tok := buyToken(t, f) |
| + p := Principal{Kind: PrincipalUser, Address: "owner" + f.acct.Sqid + "@example.com"} |
| + for i := 0; i < 1000 && f.srv.allowDomains(p, time.Now()); i++ { |
| + } |
| + status, b := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"shop.com"}`) |
| + if status != 429 { |
| + t.Fatalf("rate %d %s", status, b) |
| + } |
| + if len(f.reg.Calls) != 0 { |
| + t.Fatal("rate refusal called registrar") |
| + } |
| +} |
| +func TestCheckDoorQuoteAndPurchaseStatusShape(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + tok := buyToken(t, f) |
| + status, b := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"SHOP.com"}`) |
| + var quote map[string]any |
| + if err := json.Unmarshal([]byte(b), "e); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status != 200 || len(quote) != 4 || quote["domain"] != "shop.com" || quote["price"] != float64(1500) || quote["currency"] != "usd" || quote["available"] != true { |
| + t.Fatalf("quote %d %s", status, b) |
| + } |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseDone) |
| + status, b = buyRequest(t, f, "GET", buyAPIPath(f)+"/purchases/"+p.ID, tok, "") |
| + var result map[string]any |
| + if err := json.Unmarshal([]byte(b), &result); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status != 200 || len(result) != 6 || result["state"] != "done" || result["domain_state"] != StateChecking { |
| + t.Fatalf("status %d %s", status, b) |
| + } |
| +} |
| +func TestBrowserBuyPrefillsContactAndHidesUnconfigured(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + c := newBrowser(t) |
| + f.setUser("owner" + f.acct.Sqid + "@example.com") |
| + signUp(t, f.consoleFixture, c, "prefill") |
| + contact := purchaseContact() |
| + contact.HouseNumber = "42" |
| + if err := f.st.SetDomainContact(f.acct.ID, contact, ""); err != nil { |
| + t.Fatal(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"`) { |
| + t.Fatalf("prefill %d %s", status, body) |
| + } |
| + status, _, body = get(t, c, base+"/settings/domains") |
| + if status != 200 || !strings.Contains(body, base[len(f.ts.URL):]+"/domains/buy") { |
| + t.Fatalf("buy link %d %s", status, body) |
| + } |
| + f.srv.cfg.DomainCatalog = nil |
| + status, _, body = get(t, c, base+"/settings/domains") |
| + if status != 200 || strings.Contains(body, "/domains/buy") { |
| + t.Fatalf("unconfigured link %d %s", status, body) |
| + } |
| + status, _, body = get(t, c, base+"/domains/buy") |
| + if status != 404 { |
| + t.Fatalf("unconfigured browser %d %s", status, body) |
| + } |
| +} |
| + |
| +func TestBuyDoorLiveAndHeldRefusalsAreNeutral(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + tok := buyToken(t, f) |
| + f.start(t) |
| + // A pending journal may already have registered the name at the provider. |
| + f.reg.Available["shop.com"] = registrar.Availability{Available: false} |
| + if _, _, err := domains.AttachClaim(context.Background(), f.rel, domains.Claim{Schema: 1, Host: "www.held.com", Account: "foreign", App: "other"}); err != nil { |
| + t.Fatal(err) |
| + } |
| + s1, b1 := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, buyBody()) |
| + s2, b2 := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, strings.ReplaceAll(buyBody(), "shop.com", "held.com")) |
| + if s1 != 409 || s2 != 409 || b1 != b2 { |
| + t.Fatalf("live %d %q held %d %q", s1, b1, s2, b2) |
| + } |
| +} |
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go| new file mode 100644 |
| index 000000000..a74f6ed11 |
| --- /dev/null |
| +++ b/internal/console/appdomainbuy.go |
| @@ -0,0 +1,142 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/subtle" |
| + "net/http" |
| + "net/url" |
| + "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 |
| +} |
| +type domainBuyView struct { |
| + Base, Back, PollURL string |
| + Price string |
| + Quote *domainreg.Quote |
| + Fields []domainBuyField |
| + Purchase *DomainPurchase |
| +} |
| + |
| +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 && subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 { |
| + 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{429, domainBuyCopy["rate"]}) |
| + return "", "", nil, "", false |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + return addr, raw, acct, app, true |
| +} |
| +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}, |
| + } |
| + for i := range fields { |
| + fields[i].Label = domainBuyCopy[fields[i].Name] |
| + fields[i].Required = fields[i].Name != "Company" && fields[i].Name != "HouseNumber" && fields[i].Name != "State" |
| + } |
| + return fields |
| +} |
| +func (s *Server) renderDomainBuy(w http.ResponseWriter, r *http.Request, addr, raw string, acct *Account, app string, 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) |
| + } |
| + p.DomainBuy = v |
| + s.render(w, 200, "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{}) |
| +} |
| +func (s *Server) handleAppDomainBuyCheck(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, acct, app, ok := s.domainBuyBrowserGate(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")) |
| + if ref != nil { |
| + s.renderDoorRefusal(w, r, ref) |
| + return |
| + } |
| + c, _, err := s.store.DomainContact(acct.ID) |
| + if err != nil { |
| + s.renderDoorRefusal(w, r, domainBuyUnavailable()) |
| + return |
| + } |
| + s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Quote: &q, Fields: buyContactFields(c)}) |
| +} |
| +func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) { |
| + addr, _, acct, app, ok := s.domainBuyBrowserGate(w, r) |
| + if !ok { |
| + 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")} |
| + if _, ref := s.domainBuyContact(acct, &c); ref != nil { |
| + s.renderDoorRefusal(w, r, ref) |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) |
| + defer cancel() |
| + _, checkout, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), c, addr) |
| + if ref != nil { |
| + s.renderDoorRefusal(w, r, domainBuyDoorRefusal(ref)) |
| + return |
| + } |
| + http.Redirect(w, r, checkout, http.StatusSeeOther) |
| +} |
| +func (s *Server) handleAppDomainPurchase(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, acct, app, ok := s.domainBuyBrowserGate(w, r) |
| + if !ok { |
| + return |
| + } |
| + p := s.purchaseForAccount(w, r, acct, app) |
| + if p == nil { |
| + return |
| + } |
| + s.renderDomainBuy(w, r, addr, raw, acct, app, &domainBuyView{Purchase: p, 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 { |
| + return |
| + } |
| + p := s.purchaseForAccount(w, r, acct, app) |
| + if p == nil { |
| + return |
| + } |
| + s.writeDomainPurchaseStatus(w, r, acct, p) |
| +} |
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go| index cf2dc70ae..87ec306be 100644 |
| --- a/internal/console/appsettings.go |
| +++ b/internal/console/appsettings.go |
| @@ -153,7 +153,8 @@ type SettingsView struct { |
| // written back onto AppView.Domains itself — that slice stays |
| // index-parallel with AppView.Routes for assembleOverview's account |
| // filter (view.go), and a claim-only row has no route to pair with. |
| - Domains []DomainView |
| + Domains []DomainView |
| + BuyReady bool |
| // OnlyPlatformDomain is true when Domains holds rows but none of them |
| // is a custom one — the state the attach form's empty-state line |
| // ("this app already answers at its platform domain…") is written for. |
| @@ -333,7 +334,7 @@ type MailStandaloneView struct { |
| // The control-plane flag, the route-based channel question and the account |
| // mismatch are local and always filled. |
| func (s *Server) assembleSettings(ctx context.Context, p *page, acct *Account, reads settingsSectionReads) *SettingsView { |
| - sv := &SettingsView{} |
| + sv := &SettingsView{BuyReady: s.domainBuyReady()} |
| // Domains, its derived OnlyPlatformDomain, and NeedsChannel are all |
| // read-only against the registry/claims and owe nothing to the |
| // deployment-bucket check below — they must be set even on a console |
diff --git a/internal/console/authcli.go b/internal/console/authcli.go| index c1376804f..0309f77a5 100644 |
| --- a/internal/console/authcli.go |
| +++ b/internal/console/authcli.go |
| @@ -910,6 +910,9 @@ func (s *Server) registerCLIRoutes() { |
| // a team credential (no team set here) cannot reach it either. |
| s.cliRoute("PUT /api/cli/apps/{account}/{app}/domains/{host}/placements", svcrole.Set{}, s.handleAPIDomainPlacementsPut) |
| s.cliScopedRoute("POST /api/cli/apps/{account}/{app}/domains", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainBody, s.handleAPIDomainAttach) |
| + s.cliRoute("POST /api/cli/accounts/{account}/domains/check", svcrole.Set{}, s.handleAPIDomainCheck) |
| + s.cliRoute("POST /api/cli/accounts/{account}/domains/purchases", svcrole.Set{}, s.handleAPIDomainPurchase) |
| + s.cliRoute("GET /api/cli/accounts/{account}/domains/purchases/{id}", svcrole.Set{}, s.handleAPIDomainPurchaseStatus) |
| s.cliScopedRoute("DELETE /api/cli/apps/{account}/{app}/domains/{host}", svcrole.Allow(svcrole.Publish, svcrole.Instance), scopeDomainHost, s.handleAPIDomainDetach) |
| // The prefix-map publish (path-based routing): replace the WHOLE map of |
| // leading path segments a claimed hostname splits its traffic by. The |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 0fe393a0c..8374e4a5e 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -2294,6 +2294,20 @@ var claimFixtures = map[string]claimFixture{ |
| }, |
| do: claimWorker("StartDoorKeyResign"), |
| }}, |
| + "route POST /api/cli/accounts/{account}/domains/check": claimRead("checks availability and price without reserving or buying"), |
| + "route GET /api/cli/accounts/{account}/domains/purchases/{id}": claimRead("reads an owned purchase and wakes the worker without taking an app operation"), |
| + "route GET /a/{sqid}/apps/{app}/domains/buy": claimRead("renders the owner's domain search form"), |
| + "route POST /a/{sqid}/apps/{app}/domains/check": claimRead("quotes a domain and reads the account's stored contact"), |
| + "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}": claimRead("renders an owned purchase's progress page"), |
| + "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status": claimRead("reads purchase progress through the session gate"), |
| + "route POST /api/cli/accounts/{account}/domains/purchases": {door: &claimDoor{ |
| + apps: claimRefs("bab/kass"), setup: setupClaimBuyDoors, |
| + do: claimAPI(http.MethodPost, "/api/cli/accounts/bab/domains/purchases", buyBody()), check: claimBuyCheck, |
| + }}, |
| + "route POST /a/{sqid}/apps/{app}/domains/buy": {door: &claimDoor{ |
| + apps: claimRefs("bab/kass"), setup: setupClaimBuyDoors, do: claimBuyForm, check: claimBuyCheck, |
| + }}, |
| + |
| "worker StartDomainPurchasePass": {door: &claimDoor{ |
| apps: claimRefs("bab/kass"), |
| setup: setupClaimPurchase, |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index cce847130..f0adf4e6c 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -248,6 +248,15 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /upgrade": {setup: claimBillingWorld, do: claimPageReply("/upgrade?plan=personal"), status: http.StatusSeeOther, |
| loc: "/a/bab/billing?plan=personal"}, |
| + "route POST /api/cli/accounts/{account}/domains/check": {setup: setupClaimBuyDoors, |
| + do: claimAPIReply(http.MethodPost, "/api/cli/accounts/bab/domains/check", `{"name":"shop.com"}`), body: []string{`"domain":"shop.com"`, `"price":1500`}}, |
| + "route GET /api/cli/accounts/{account}/domains/purchases/{id}": claimAPIRead(setupClaimPurchase, "/api/cli/accounts/bab/domains/purchases/dp_claim_purchase", `"id":"dp_claim_purchase"`), |
| + "route GET /a/{sqid}/apps/{app}/domains/buy": claimPageRead(setupClaimBuyDoors, "/a/bab/apps/kass/domains/buy", "Check availability"), |
| + "route POST /a/{sqid}/apps/{app}/domains/check": {setup: setupClaimBuyDoors, |
| + do: claimFormReply("/a/bab/apps/kass/domains/check", "name", "shop.com"), body: []string{"shop.com", "PhoneCountryCode"}}, |
| + "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}": claimPageRead(setupClaimPurchase, "/a/bab/apps/kass/domains/purchases/dp_claim_purchase", "shop.com"), |
| + "route GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status": claimPageRead(setupClaimPurchase, "/a/bab/apps/kass/domains/purchases/dp_claim_purchase/status", `"id":"dp_claim_purchase"`), |
| + |
| // ---- the CLI's reads ---- |
| "route GET /api/cli/apps": claimAPIRead(nil, "/api/cli/apps", `"sqid":"bab"`, `"kass"`), |
| "route GET /api/cli/apps/{account}/list": claimAPIRead(nil, "/api/cli/apps/bab/list", `"kass"`), |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| index 39eaff23b..a638407ed 100644 |
| --- a/internal/console/domainbuy.go |
| +++ b/internal/console/domainbuy.go |
| @@ -28,7 +28,7 @@ func (s *Server) domainPurchaseReady() bool { |
| } |
| func domainBuyUnavailable() *doorRefusal { |
| - return &doorRefusal{http.StatusServiceUnavailable, "buying domains is unavailable right now"} |
| + return &doorRefusal{http.StatusServiceUnavailable, domainBuyCopy["unavailable"]} |
| } |
| func (s *Server) quoteDomain(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) { |
| @@ -106,6 +106,11 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| return nil, "", claimRefusal(host, domains.ErrHostUnavailable) |
| } |
| } |
| + // A live journal stays a neutral refusal even after registration makes the |
| + // registrar report the name unavailable. The unique index still closes races. |
| + if ref := s.liveDomainPurchaseRefusal(ctx, name); ref != nil { |
| + return nil, "", ref |
| + } |
| q, ref := s.quoteDomain(ctx, acct, name) |
| if ref != nil { |
| return nil, "", ref |
| @@ -241,7 +246,7 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| if b == nil { |
| return "", sql.ErrNoRows |
| } |
| - back := s.cfg.Origin + appSettingsURL(acct.Sqid, p.App, "domains") |
| + back := s.cfg.Origin + domainPurchaseURL(acct.Sqid, p.App, 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 { |
| @@ -631,16 +636,6 @@ func (s *Server) domainPurchasePass(ctx context.Context) error { |
| return errors.Join(errs...) |
| } |
| -var domainPurchaseCopy = struct { |
| - DailyCap, UnpaidSubject, UnpaidBody, OperatorSubject, OperatorBody string |
| -}{ |
| - DailyCap: "You have reached today's domain purchase limit. Try again tomorrow.", |
| - UnpaidSubject: "Payment for %s needs attention", |
| - UnpaidBody: "We registered %s for you, but could not collect the payment. Your domain is still yours. Auto-renew is off while payment is outstanding.\n\nReview your billing details:\n%s\n", |
| - OperatorSubject: "Domain purchase needs attention", |
| - OperatorBody: "Domain: %s\nPurchase: %s\nAccount: %s\nReason: %s\n", |
| -} |
| - |
| var pageDomainPurchase = alerting.Page |
| func (s *Server) purchaseAlert(ctx context.Context, acct *Account, domain, id, reason string) { |
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go| new file mode 100644 |
| index 000000000..cc33046fc |
| --- /dev/null |
| +++ b/internal/console/domainbuy_copy.go |
| @@ -0,0 +1,58 @@ |
| +package console |
| + |
| +import "github.com/carlosframework/platform/internal/domainreg" |
| + |
| +// Plan 1 drafts, replaced by the Luna pass (Task 11). |
| +var domainBuyCopy = map[string]string{ |
| + "title": "Buy a domain", "name": "Domain", "check": "Check availability", |
| + "quote": "Price for one year", "paymentDetails": "Final payment details appear at checkout.", |
| + "background": "Your purchase will continue in the background. Reload this page to check progress.", |
| + "contact": "Registrant contact details", "pay": "Continue to checkout", "back": "Back to domains", |
| + "contactError": "Enter your name, email, address, country code and phone number. Use digits for the phone and calling code, and two uppercase letters for the country.", |
| + "nameError": "Enter a registrable domain name.", "unavailable": "buying domains is unavailable right now", |
| + "rate": "Too many requests. Wait a minute and try again.", "refused": "Refused", "csrf": "Cross-site request blocked.", |
| + "notOffered": "This domain ending is not offered.", "premium": "Premium domains are not offered.", "taken": "This domain is not available.", |
| + "progress": "Your domain purchase", "pollError": "Could not check progress. Retrying shortly.", |
| + "awaiting_payment": "Waiting for payment approval.", "authorised": "Payment approved. Preparing your domain.", |
| + "zone_ready": "Domain settings are ready.", "registering": "Registering your domain.", "registered": "Domain registered. Collecting payment.", |
| + "captured": "Payment collected. Connecting your app.", "done": "Domain connected. Waiting for HTTPS to be ready.", |
| + "live": "Your domain is live.", "failed": "The purchase could not be completed.", "expired": "The checkout expired. Start a new purchase to try again.", |
| + "unpaid": "Your domain is registered, but payment needs attention. Check your billing details.", |
| + "FirstName": "First name", "LastName": "Last name", "Company": "Company (optional)", "Email": "Email", |
| + "PhoneCountryCode": "Phone calling code", "Phone": "National phone number", "Street": "Street", "HouseNumber": "House number (optional)", |
| + "City": "City", "State": "State or region (optional)", "PostalCode": "Postal code", "Country": "Country (two uppercase letters)", |
| +} |
| + |
| +// Keep provider validation vocabulary out of the doors' customer copy. |
| +func domainBuyDoorRefusal(ref *doorRefusal) *doorRefusal { |
| + if ref == nil { |
| + return nil |
| + } |
| + key := "" |
| + switch ref.Msg { |
| + case domainreg.ErrNotRegistrable.Error(): |
| + key = "nameError" |
| + case domainreg.ErrTLDNotOffered.Error(): |
| + key = "notOffered" |
| + case domainreg.ErrPremium.Error(): |
| + key = "premium" |
| + case domainreg.ErrNotAvailable.Error(): |
| + key = "taken" |
| + case domainreg.ErrCostAboveCeiling.Error(): |
| + key = "unavailable" |
| + } |
| + if key != "" { |
| + return &doorRefusal{ref.Status, domainBuyCopy[key]} |
| + } |
| + return ref |
| +} |
| + |
| +var domainPurchaseCopy = struct { |
| + DailyCap, UnpaidSubject, UnpaidBody, OperatorSubject, OperatorBody string |
| +}{ |
| + DailyCap: "You have reached today's domain purchase limit. Try again tomorrow.", |
| + UnpaidSubject: "Payment for %s needs attention", |
| + UnpaidBody: "We registered %s for you, but could not collect the payment. Your domain is still yours. Auto-renew is off while payment is outstanding.\n\nReview your billing details:\n%s\n", |
| + OperatorSubject: "Domain purchase needs attention", |
| + OperatorBody: "Domain: %s\nPurchase: %s\nAccount: %s\nReason: %s\n", |
| +} |
diff --git a/internal/console/domainbuy_test.go b/internal/console/domainbuy_test.go| index 7d1e5273f..bae7931dc 100644 |
| --- a/internal/console/domainbuy_test.go |
| +++ b/internal/console/domainbuy_test.go |
| @@ -690,7 +690,7 @@ func TestPurchaseHappyPathWithClaimSQLGate(t *testing.T) { |
| } |
| } |
| -func TestPurchaseCheckoutUsesQuoteAndExistingReturnPage(t *testing.T) { |
| +func TestPurchaseCheckoutUsesQuoteAndPurchaseReturnPage(t *testing.T) { |
| f := newPurchaseFixture(t) |
| p := f.start(t) |
| if len(f.fake.Sent) != 1 { |
| @@ -703,7 +703,7 @@ func TestPurchaseCheckoutUsesQuoteAndExistingReturnPage(t *testing.T) { |
| t.Fatal(err) |
| } |
| r := body.Request |
| - back := f.srv.cfg.Origin + appSettingsURL(f.acct.Sqid, "kass", "domains") |
| + back := f.srv.cfg.Origin + domainPurchaseURL(f.acct.Sqid, "kass", 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/domainstate.go b/internal/console/domainstate.go| index d49b3c72d..d21e612e3 100644 |
| --- a/internal/console/domainstate.go |
| +++ b/internal/console/domainstate.go |
| @@ -293,6 +293,16 @@ type deploymentCapability struct { |
| func (s *Server) domainCapability(ctx context.Context, acct, app string) deploymentCapability { |
| t := s.dnsTargets(ctx) |
| features, setAt := s.appFeatures(ctx, acct, app) |
| + // The buy capability is deployment-owned, never an app-supplied flag. |
| + if features != nil { |
| + delete(features, "buy") |
| + } |
| + if s.domainBuyReady() { |
| + if features == nil { |
| + features = make(map[string]string) |
| + } |
| + features["buy"] = "true" |
| + } |
| return deploymentCapability{ |
| ManagedDomains: true, |
| AppsDomain: strings.TrimSpace(s.cfg.AppsDomain), |
diff --git a/internal/console/server.go b/internal/console/server.go| index 6e5c61b1a..f37963fd5 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -2020,6 +2020,12 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // (controlplane.go). |
| s.registerRoute("POST /a/{sqid}/apps/{app}/control-plane/clear", s.handleAppControlPlaneClear) |
| s.registerRoute("POST /a/{sqid}/apps/{app}/control-plane/set", s.handleAppControlPlaneSet) |
| + // Domain purchases: owner sessions, with CSRF on both form posts. |
| + s.registerRoute("GET /a/{sqid}/apps/{app}/domains/buy", s.handleAppDomainBuyForm) |
| + s.registerRoute("POST /a/{sqid}/apps/{app}/domains/check", s.handleAppDomainBuyCheck) |
| + s.registerRoute("POST /a/{sqid}/apps/{app}/domains/buy", s.handleAppDomainBuy) |
| + s.registerRoute("GET /a/{sqid}/apps/{app}/domains/purchases/{id}", s.handleAppDomainPurchase) |
| + s.registerRoute("GET /a/{sqid}/apps/{app}/domains/purchases/{id}/status", s.handleAppDomainPurchaseStatus) |
| // Custom domain attach/detach (appdomains.go, #82): owner-only, no |
| // passkey step-up (spec §6) — detach's guard is the typed-host confirm. |
| s.registerRoute("POST /a/{sqid}/apps/{app}/domains/attach", s.handleAppDomainAttach) |
| @@ -2721,7 +2727,9 @@ type page struct { |
| Confirm *ConfirmView |
| // App Settings (appsettings.go): what the tab knows beyond the AppView. |
| - Settings *SettingsView |
| + Settings *SettingsView |
| + DomainBuy *domainBuyView |
| + DomainBuyCopy map[string]string |
| // /a/{sqid}/fleets/{fleet} (Task 9): the owner's own remote boxes, |
| // joined to their heartbeats, and the account's apps placed on this |
| @@ -2824,6 +2832,7 @@ type appRow struct { |
| } |
| func (s *Server) render(w http.ResponseWriter, status int, name string, p page) { |
| + p.DomainBuyCopy = domainBuyCopy |
| p.StatusCopy = approvedStatusCopy |
| p.BrowserRestartCopy = approvedBrowserRestartCopy |
| p.MismatchCopy = approvedMismatchCopy |
diff --git a/internal/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 0b5375ff3..6816dc5f8 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -207,6 +207,9 @@ var closedDoors = []string{ |
| // An account's plan, packs and sponsored limits are a fleet operator's |
| // decision (plans-caps-packs spec §4, §8.7); no machine credential reads |
| // or sets them. |
| + "GET /api/cli/accounts/{account}/domains/purchases/{id}", |
| + "POST /api/cli/accounts/{account}/domains/check", |
| + "POST /api/cli/accounts/{account}/domains/purchases", |
| "GET /api/cli/accounts/{account}/plan", |
| "POST /api/cli/accounts/{account}/plan", |
| // Billing problems are settled by a fleet operator in the provider's |
| @@ -1150,8 +1153,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) { |
| } |
| seen++ |
| } |
| - if seen != len(closedDoors) || seen != 76 { |
| - t.Errorf("walked %d closed doors, want all %d (and 76 today: three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)", |
| + if seen != len(closedDoors) || seen != 79 { |
| + t.Errorf("walked %d closed doors, want all %d (and 79 today: three domain purchase doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the fleet secrets key door, four services, two email credentials, email pause, the build probe, the swap policy, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, ten system doors, three deployment-wide antivirus, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, and the billing house door)", |
| seen, len(closedDoors)) |
| } |
| } |
diff --git a/internal/console/templates/app_settings.html b/internal/console/templates/app_settings.html| index 09be4156e..842d2afdf 100644 |
| --- a/internal/console/templates/app_settings.html |
| +++ b/internal/console/templates/app_settings.html |
| @@ -91,6 +91,7 @@ bucket keys and stays.</p> |
| </div> |
| {{else}}<p class="small">No domains yet — the first shipped route brings one.</p>{{end}} |
| {{if .IsOwner}} |
| +{{if .Settings.BuyReady}}<p><a href="{{.Base}}/apps/{{.Detail.App}}/domains/buy">{{.DomainBuyCopy.title}}</a></p>{{end}} |
| <h3>Attach a custom domain</h3> |
| {{if .Settings.OnlyPlatformDomain}}<p class="small">This app already answers |
| at its platform domain; attaching adds addresses, it never removes one.</p>{{end}} |
diff --git a/internal/console/templates/domain_buy.html b/internal/console/templates/domain_buy.html| new file mode 100644 |
| index 000000000..8bd9534c0 |
| --- /dev/null |
| +++ b/internal/console/templates/domain_buy.html |
| @@ -0,0 +1,50 @@ |
| +{{define "domain_buy"}}{{template "top" .}} |
| +<h1>{{.DomainBuyCopy.title}}</h1> |
| +{{with .DomainBuy}} |
| +{{if .Purchase}} |
| +<h2>{{$.DomainBuyCopy.progress}}: {{.Purchase.Domain}}</h2> |
| +<p id="purchase-progress" role="status">{{index $.DomainBuyCopy (printf "%s" .Purchase.State)}}</p> |
| +<script> |
| +(function () { |
| + const endpoint = {{.PollURL}}, copy = {{$.DomainBuyCopy}}; |
| + const progress = document.getElementById('purchase-progress'); |
| + const started = Date.now(); |
| + async function poll() { |
| + try { |
| + const response = await fetch(endpoint, {credentials: 'same-origin', cache: 'no-store'}); |
| + if (!response.ok) throw new Error(); |
| + const purchase = await response.json(); |
| + progress.textContent = purchase.state === 'done' && purchase.domain_state === 'live' ? copy.live : (copy[purchase.state] || copy.pollError); |
| + if (['failed', 'expired', 'unpaid'].includes(purchase.state) || (purchase.state === 'done' && purchase.domain_state === 'live')) return; |
| + } catch (_) { progress.textContent = copy.pollError; } |
| + if (Date.now() - started < 600000) setTimeout(poll, 3000); |
| + else progress.textContent = copy.background; |
| + } |
| + poll(); |
| +})(); |
| +</script> |
| +{{else if .Quote}} |
| +<p>{{$.DomainBuyCopy.name}}: <strong>{{.Quote.Domain}}</strong></p> |
| +<p>{{$.DomainBuyCopy.quote}}: {{.Price}} {{.Quote.Currency}}</p> |
| +<p class="small">{{$.DomainBuyCopy.paymentDetails}}</p> |
| +<h2>{{$.DomainBuyCopy.contact}}</h2> |
| +<form method="post" action="{{.Base}}/buy"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + <input type="hidden" name="name" value="{{.Quote.Domain}}"> |
| + {{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> |
| + <button type="submit">{{$.DomainBuyCopy.check}}</button> |
| +</form> |
| +{{end}} |
| +<p><a href="{{.Back}}">{{$.DomainBuyCopy.back}}</a></p> |
| +{{end}} |
| +{{template "bottom" .}}{{end}} |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index fcd51fd2d..d2d0fec7a 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -26,6 +26,9 @@ route GET /a/{sqid}/apps/{app}/analytics |
| route GET /a/{sqid}/apps/{app}/analytics/live |
| route GET /a/{sqid}/apps/{app}/availability |
| route GET /a/{sqid}/apps/{app}/deployments |
| +route GET /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}/apps/{app}/errors |
| route GET /a/{sqid}/apps/{app}/index |
| route GET /a/{sqid}/apps/{app}/instances |
| @@ -59,6 +62,7 @@ route GET /alerts/snooze/{token} |
| route GET /alerts/unsubscribe/{token} |
| route GET /api/box/interactive/{id} |
| route GET /api/box/runs/{id} |
| +route GET /api/cli/accounts/{account}/domains/purchases/{id} |
| route GET /api/cli/accounts/{account}/plan |
| route GET /api/cli/apps |
| route GET /api/cli/apps/{account}/list |
| @@ -166,6 +170,8 @@ route POST /a/{sqid}/apps/{app}/control-plane/clear |
| route POST /a/{sqid}/apps/{app}/control-plane/set |
| route POST /a/{sqid}/apps/{app}/delete |
| route POST /a/{sqid}/apps/{app}/domains/attach |
| +route POST /a/{sqid}/apps/{app}/domains/buy |
| +route POST /a/{sqid}/apps/{app}/domains/check |
| route POST /a/{sqid}/apps/{app}/domains/detach |
| route POST /a/{sqid}/apps/{app}/errors/level |
| route POST /a/{sqid}/apps/{app}/fasttrack |
| @@ -217,6 +223,8 @@ route POST /accounts/new |
| route POST /alerts/confirm/{token} |
| route POST /alerts/snooze/{token} |
| route POST /alerts/unsubscribe/{token} |
| +route POST /api/cli/accounts/{account}/domains/check |
| +route POST /api/cli/accounts/{account}/domains/purchases |
| route POST /api/cli/accounts/{account}/plan |
| route POST /api/cli/accounts/{account}/store/apply |
| route POST /api/cli/accounts/{account}/store/approve |