domains: buy without a subscription; sponsored accounts; Add a card
The first domain purchase creates the account's Stripe customer (shared subscription path, tax country from the contact) and fixes its currency; the confirmed price is the charged price. Real refusal reasons for the account's own state (name refusals stay neutral), registry message logged, CLI prints the purchase ID, unsigned-contract alerts, card saved for renewals, and Add a card on the billing page. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Squashed from domains-buy-without-subscription into main.
46 files changed,
+1,914
−155
apimode.go+22 −8approved_domains_buy_copy_test.go+9 −0docs/superpowers/notes/census-proposal-domains-buy-nosub.md+11 −0domains_buy_cli.go+51 −14domains_buy_cli_test.go+184 −6domains_buy_copy.go+4 −0internal/billing/billing.go+14 −1internal/billing/billingtest/fake.go+30 −6internal/billingstripe/card_test.go+94 −0internal/billingstripe/payment.go+33 −20internal/billingstripe/payment_test.go+3 −1internal/billingstripe/prepared.go+34 −4internal/console/apidomainbuy.go+25 −8internal/console/apidomainbuy_test.go+5 −5internal/console/appdomainbuy.go+21 −4internal/console/billingcard.go+79 −0internal/console/billingcard_test.go+122 −0internal/console/billingcheckout.go+25 −9internal/console/billingcustomer.go+62 −0internal/console/billingpage.go+14 −2internal/console/billingpage_copy.go+5 −0internal/console/billingpage_test.go+8 −6internal/console/billingstore.go+20 −8internal/console/claim_invariant_fixtures_test.go+1 −0internal/console/claim_invariant_probes_nonapp_test.go+28 −0internal/console/domainbuy.go+105 −25internal/console/domainbuy_admission_test.go+1 −1internal/console/domainbuy_copy.go+19 −0internal/console/domainbuy_final_fix_test.go+5 −5internal/console/domainbuy_fix_test.go+3 −3internal/console/domainbuy_nosub_test.go+269 −0internal/console/domainbuy_registry_test.go+54 −0internal/console/domainbuy_round1_test.go+278 −0internal/console/domainbuy_round2_test.go+173 −0internal/console/domainbuy_test.go+25 −12internal/console/server.go+1 −0internal/console/templates/billing.html+4 −0internal/console/templates/domain_buy.html+5 −0internal/console/testdata/claim-routes.txt+1 −0internal/provision/domains_buy_nosub_census_test.go+22 −0internal/provision/plan9_b8_census_test.go+1 −1internal/provision/testdata/plan14-root-reads-chain.tsv+1 −0internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv+4 −0internal/registrar/openprovider/client.go+9 −6internal/registrar/openprovider/client_test.go+27 −0internal/registrar/registrar.go+3 −0
CI failed — run details
diff --git a/apimode.go b/apimode.go| index 20e3bf86a..070250a99 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -4692,6 +4692,13 @@ type domainPurchaseResp struct { |
| type domainContactError struct{ error } |
| +type domainPriceChangedError struct { |
| + error |
| + Quote domainQuoteResp |
| +} |
| + |
| +func (e *domainPriceChangedError) Unwrap() error { return e.error } |
| + |
| func (e *domainContactError) Unwrap() error { return e.error } |
| func domainBuyAPIPath(acct apiAcct, tail string) string { |
| @@ -4702,11 +4709,12 @@ func domainBuyAPIPath(acct apiAcct, tail string) string { |
| return path |
| } |
| -func (s *apiSession) postDomainCheck(ctx context.Context, acct apiAcct, name string) (domainQuoteResp, error) { |
| +func (s *apiSession) postDomainCheck(ctx context.Context, acct apiAcct, name, country string) (domainQuoteResp, error) { |
| var out domainQuoteResp |
| status, body, err := s.postJSON(ctx, domainBuyAPIPath(acct, "/check"), struct { |
| - Name string `json:"name"` |
| - }{name}) |
| + Name string `json:"name"` |
| + Country string `json:"country,omitempty"` |
| + }{name, country}) |
| if err != nil { |
| return out, err |
| } |
| @@ -4719,13 +4727,15 @@ func (s *apiSession) postDomainCheck(ctx context.Context, acct apiAcct, name str |
| return out, nil |
| } |
| -func (s *apiSession) postDomainPurchase(ctx context.Context, acct apiAcct, name, app string, contact *registrar.Contact) (domainPurchaseResp, error) { |
| +func (s *apiSession) postDomainPurchase(ctx context.Context, acct apiAcct, name, app string, contact *registrar.Contact, confirmed domainQuoteResp) (domainPurchaseResp, error) { |
| var out domainPurchaseResp |
| status, body, err := s.postJSON(ctx, domainBuyAPIPath(acct, "/purchases"), struct { |
| - Name string `json:"name"` |
| - App string `json:"app"` |
| - Contact *registrar.Contact `json:"contact,omitempty"` |
| - }{name, app, contact}) |
| + Name string `json:"name"` |
| + App string `json:"app"` |
| + Contact *registrar.Contact `json:"contact,omitempty"` |
| + Currency string `json:"currency"` |
| + Price int64 `json:"price"` |
| + }{name, app, contact, confirmed.Currency, confirmed.Price}) |
| if err != nil { |
| return out, err |
| } |
| @@ -4733,6 +4743,10 @@ func (s *apiSession) postDomainPurchase(ctx context.Context, acct apiAcct, name, |
| err := apiErrorFromBody(status, body) |
| var refusal struct { |
| Code string `json:"code"` |
| + domainQuoteResp |
| + } |
| + if status == http.StatusConflict && json.Unmarshal(body, &refusal) == nil && refusal.Code == "price_changed" && refusal.Currency != "" && refusal.Price > 0 { |
| + return out, &domainPriceChangedError{err, refusal.domainQuoteResp} |
| } |
| if status == http.StatusUnprocessableEntity && json.Unmarshal(body, &refusal) == nil && refusal.Code == "contact" { |
| return out, &domainContactError{err} |
diff --git a/approved_domains_buy_copy_test.go b/approved_domains_buy_copy_test.go| index 770fd6f58..7905454a7 100644 |
| --- a/approved_domains_buy_copy_test.go |
| +++ b/approved_domains_buy_copy_test.go |
| @@ -9,6 +9,15 @@ import ( |
| // Like approved_copy_test.go, compare decoded Go literals byte for byte. |
| func TestApprovedDomainsBuyCopy(t *testing.T) { |
| rows := []struct{ key, path, want string }{ |
| + // Approved by delegation (reviewer), 2026-11-03. |
| + {"browser.priceChanged", "internal/console/domainbuy_copy.go", "the price is different from the one you confirmed. confirm the new price to continue"}, |
| + {"cli.confirmChanged", "domains_buy_copy.go", "buy this domain at the new price? [y/N] "}, |
| + // Approved by delegation (Luna), 2026-11-03, including the controller's hint. |
| + {"browser.billingSetup", "internal/console/domainbuy_copy.go", "we could not set up billing for your account. try again later"}, |
| + {"browser.currency", "internal/console/domainbuy_copy.go", "we could not find a price for this domain in your account currency"}, |
| + {"billing.button.card", "internal/console/billingpage_copy.go", "Add a card"}, |
| + {"billing.card.failed", "internal/console/billingpage_copy.go", "We could not open the card setup page. Try again later."}, |
| + {"billing.card.hint", "internal/console/billingpage_copy.go", "Save a card for buying domains. Nothing is charged until you buy one."}, |
| {"browser.title", "internal/console/domainbuy_copy.go", "Buy a domain"}, |
| {"browser.name", "internal/console/domainbuy_copy.go", "Domain"}, |
| {"browser.check", "internal/console/domainbuy_copy.go", "Check availability"}, |
diff --git a/docs/superpowers/notes/census-proposal-domains-buy-nosub.md b/docs/superpowers/notes/census-proposal-domains-buy-nosub.md| new file mode 100644 |
| index 000000000..96d7338ef |
| --- /dev/null |
| +++ b/docs/superpowers/notes/census-proposal-domains-buy-nosub.md |
| @@ -0,0 +1,11 @@ |
| +# Census approval: domains-buy-nosub |
| + |
| +Ruling `census-ruling-domains-buy-nosub`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26). |
| + |
| +Envelopes re-pinned: `.`, `internal/registrar`. |
| + |
| +Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner. |
| + |
| +Seal: `09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6` → `09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6`. |
| + |
| +Overlay: `internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`. |
diff --git a/domains_buy_cli.go b/domains_buy_cli.go| index df6a862f1..1b899a0f0 100644 |
| --- a/domains_buy_cli.go |
| +++ b/domains_buy_cli.go |
| @@ -76,7 +76,7 @@ func printDomainQuote(out io.Writer, q domainQuoteResp) { |
| } |
| func domainsCheck(ctx context.Context, s *apiSession, acct apiAcct, name string, out io.Writer) error { |
| - q, err := s.postDomainCheck(ctx, acct, name) |
| + q, err := s.postDomainCheck(ctx, acct, name, "") |
| if err != nil { |
| return err |
| } |
| @@ -102,7 +102,11 @@ func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app stri |
| return err |
| } |
| } |
| - q, err := s.postDomainCheck(ctx, acct, name) |
| + country := "" |
| + if contact != nil { |
| + country = contact.Country |
| + } |
| + q, err := s.postDomainCheck(ctx, acct, name, country) |
| if err != nil { |
| return err |
| } |
| @@ -124,23 +128,56 @@ func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app stri |
| return nil |
| } |
| } |
| - p, err := s.postDomainPurchase(ctx, acct, name, app, contact) |
| - var contactErr *domainContactError |
| - if errors.As(err, &contactErr) { |
| - if !o.terminal { |
| - return fmt.Errorf(domainsBuyCopy["contactNonTTY"], err) |
| + var p domainPurchaseResp |
| + contactRetried, priceRetried := false, false |
| + for { |
| + p, err = s.postDomainPurchase(ctx, acct, name, app, contact, q) |
| + var contactErr *domainContactError |
| + var priceErr *domainPriceChangedError |
| + if errors.As(err, &contactErr) && !contactRetried { |
| + if !o.terminal { |
| + return fmt.Errorf(domainsBuyCopy["contactNonTTY"], err) |
| + } |
| + contactRetried = true |
| + fmt.Fprintln(o.out, err) |
| + contact, err = promptDomainContact(input, o.out) |
| + if err != nil { |
| + return err |
| + } |
| + continue |
| + } |
| + if errors.As(err, &priceErr) { |
| + printDomainQuote(o.out, priceErr.Quote) |
| + if priceRetried { |
| + return err |
| + } |
| + priceRetried = true |
| + if o.yes { |
| + if q.Currency != priceErr.Quote.Currency || q.Price != priceErr.Quote.Price { |
| + return err |
| + } |
| + } else { |
| + if !o.terminal { |
| + return err |
| + } |
| + answer, askErr := domainBuyAnswer(input, o.out, domainsBuyCopy["confirmChanged"]) |
| + if askErr != nil { |
| + return askErr |
| + } |
| + if !strings.EqualFold(answer, "y") && !strings.EqualFold(answer, "yes") { |
| + fmt.Fprintln(o.out, domainsBuyCopy["cancelled"]) |
| + return nil |
| + } |
| + } |
| + q = priceErr.Quote |
| + continue |
| } |
| - // One retry, after collecting all fields. Validation remains at the door. |
| - fmt.Fprintln(o.out, err) |
| - contact, err = promptDomainContact(input, o.out) |
| if err != nil { |
| return err |
| } |
| - p, err = s.postDomainPurchase(ctx, acct, name, app, contact) |
| - } |
| - if err != nil { |
| - return err |
| + break |
| } |
| + fmt.Fprintf(o.out, domainsBuyCopy["purchaseID"], p.ID) |
| if p.CheckoutURL != "" { |
| fmt.Fprintf(o.out, domainsBuyCopy["checkout"], p.CheckoutURL) |
| } |
diff --git a/domains_buy_cli_test.go b/domains_buy_cli_test.go| index dc781d1a1..bd3ea55e2 100644 |
| --- a/domains_buy_cli_test.go |
| +++ b/domains_buy_cli_test.go |
| @@ -94,7 +94,7 @@ func TestDomainsBuyPrintsCheckoutAndWaitsToLive(t *testing.T) { |
| if err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil { |
| t.Fatal(err) |
| } |
| - for _, want := range []string{"https://checkout.example/p1", "awaiting_payment", "authorised", "registered", "captured", "done", "issuing-cert", "live"} { |
| + for _, want := range []string{"purchase: p1", "https://checkout.example/p1", "awaiting_payment", "authorised", "registered", "captured", "done", "issuing-cert", "live"} { |
| if strings.Count(out.String(), want) != 1 { |
| t.Fatalf("expected %q once: %s", want, &out) |
| } |
| @@ -234,7 +234,7 @@ func TestDomainsBuyContactInputs(t *testing.T) { |
| if calls != wantCalls { |
| t.Fatalf("purchase calls=%d want=%d", calls, wantCalls) |
| } |
| - if !strings.Contains(out.String(), "https://checkout.example/p1") { |
| + if !strings.Contains(out.String(), "https://checkout.example/p1") || !strings.Contains(out.String(), "purchase: p1") { |
| t.Fatalf("missing checkout: %s", &out) |
| } |
| }) |
| @@ -317,9 +317,9 @@ func TestDomainsBuyDoorErrors(t *testing.T) { |
| var err error |
| switch door { |
| case "check": |
| - _, err = s.postDomainCheck(context.Background(), apiAcct{Seg: "bab"}, "shop.com") |
| + _, err = s.postDomainCheck(context.Background(), apiAcct{Seg: "bab"}, "shop.com", "") |
| case "purchase": |
| - _, err = s.postDomainPurchase(context.Background(), apiAcct{Seg: "bab"}, "shop.com", "shop", nil) |
| + _, err = s.postDomainPurchase(context.Background(), apiAcct{Seg: "bab"}, "shop.com", "shop", nil, domainQuoteResp{Currency: "eur", Price: 1299}) |
| case "status": |
| _, err = s.getDomainPurchase(context.Background(), apiAcct{Seg: "bab"}, "p1") |
| } |
| @@ -359,9 +359,9 @@ func TestDomainsBuyAPIExactAccountAndEscapedID(t *testing.T) { |
| var err error |
| switch door { |
| case "check": |
| - _, err = s.postDomainCheck(context.Background(), a, "shop.com") |
| + _, err = s.postDomainCheck(context.Background(), a, "shop.com", "") |
| case "purchase": |
| - _, err = s.postDomainPurchase(context.Background(), a, "shop.com", "shop", nil) |
| + _, err = s.postDomainPurchase(context.Background(), a, "shop.com", "shop", nil, domainQuoteResp{Currency: "eur", Price: 1299}) |
| case "status": |
| _, err = s.getDomainPurchase(context.Background(), a, "p/1") |
| } |
| @@ -420,3 +420,181 @@ func TestDomainsBuyLivePollHasRemainingDeadline(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| + |
| +func TestDomainsBuyConfirmedPriceRetry(t *testing.T) { |
| + for _, mode := range []string{"accept", "decline", "yes", "twice", "unchanged"} { |
| + t.Run(mode, func(t *testing.T) { |
| + calls := 0 |
| + ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + var in struct { |
| + Currency string |
| + Price int64 |
| + } |
| + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { |
| + t.Error(err) |
| + } |
| + expected := int64(1299) |
| + if calls > 1 && mode != "unchanged" { |
| + expected = 1699 |
| + } |
| + if in.Currency != "eur" || in.Price != expected { |
| + t.Errorf("confirmed price missing/wrong: %+v", in) |
| + } |
| + if calls == 1 || mode == "twice" { |
| + price := 1699 |
| + if mode == "unchanged" { |
| + price = 1299 |
| + } |
| + if calls > 1 { |
| + price = 1799 |
| + } |
| + w.WriteHeader(409) |
| + fmt.Fprintf(w, `{"code":"price_changed","error":"price changed","domain":"shop.com","available":true,"currency":"eur","price":%d}`, price) |
| + return |
| + } |
| + fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`) |
| + }, nil) |
| + var out bytes.Buffer |
| + o := buyTestOptions(&out) |
| + o.noWait = true |
| + o.terminal = true |
| + o.yes = mode == "yes" || mode == "unchanged" |
| + o.in = strings.NewReader("y\ny\n") |
| + if mode == "decline" { |
| + o.in = strings.NewReader("y\nn\n") |
| + } |
| + err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o) |
| + wantErr := mode == "yes" || mode == "twice" |
| + wantCalls := 2 |
| + if mode == "yes" || mode == "decline" { |
| + wantCalls = 1 |
| + } |
| + if (err != nil) != wantErr || calls != wantCalls { |
| + t.Fatalf("calls=%d err=%v output=%s", calls, err, &out) |
| + } |
| + if mode != "unchanged" && !strings.Contains(out.String(), "16.99") { |
| + t.Fatalf("new price missing: %s", &out) |
| + } |
| + if mode == "twice" && !strings.Contains(out.String(), "17.99") { |
| + t.Fatalf("second change missing: %s", &out) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestDomainsBuyChangedPriceExitsNonZero(t *testing.T) { |
| + calls := 0 |
| + ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + w.WriteHeader(409) |
| + fmt.Fprint(w, `{"code":"price_changed","error":"price changed","domain":"shop.com","available":true,"currency":"gbp","price":1700}`) |
| + }, nil) |
| + out, err := runBuyTestCommand(t, ts.URL, "--no-wait") |
| + if err == nil || calls != 1 || !strings.Contains(out, "£17 GBP") { |
| + t.Fatalf("calls=%d err=%v output=%s", calls, err, out) |
| + } |
| +} |
| + |
| +func TestDomainsBuyChangedPriceAfterContact(t *testing.T) { |
| + calls := 0 |
| + ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) { |
| + calls++ |
| + var in struct { |
| + Price int64 |
| + Currency string |
| + Contact json.RawMessage |
| + } |
| + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { |
| + t.Error(err) |
| + } |
| + want := int64(1299) |
| + if calls == 3 { |
| + want = 1699 |
| + } |
| + if in.Price != want || in.Currency != "eur" { |
| + t.Errorf("request %d: %+v", calls, in) |
| + } |
| + if calls == 1 { |
| + w.WriteHeader(422) |
| + fmt.Fprint(w, `{"code":"contact","error":"contact required"}`) |
| + return |
| + } |
| + if len(in.Contact) == 0 { |
| + t.Error("lost collected contact") |
| + } |
| + if calls == 2 { |
| + w.WriteHeader(409) |
| + fmt.Fprint(w, `{"code":"price_changed","error":"price changed","domain":"shop.com","available":true,"currency":"eur","price":1699}`) |
| + return |
| + } |
| + fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`) |
| + }, nil) |
| + var out bytes.Buffer |
| + o := buyTestOptions(&out) |
| + o.yes = false |
| + o.noWait = true |
| + o.terminal = true |
| + o.in = strings.NewReader("y\nJane\nBuyer\n\nbuyer@example.test\n353\n871234567\nMain Street\n\nDublin\n\nD01 A123\nIE\ny\n") |
| + if err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil || calls != 3 { |
| + t.Fatalf("calls=%d err=%v output=%s", calls, err, &out) |
| + } |
| +} |
| + |
| +func TestDomainsBuyContactFileCountryWithYes(t *testing.T) { |
| + for _, country := range []string{"IE", "GB"} { |
| + t.Run(country, func(t *testing.T) { |
| + currency := "eur" |
| + if country == "GB" { |
| + currency = "gbp" |
| + } |
| + checks, purchases := 0, 0 |
| + mux := http.NewServeMux() |
| + mux.HandleFunc("POST "+buyTestPath+"/check", func(w http.ResponseWriter, r *http.Request) { |
| + checks++ |
| + var in struct{ Name, Country string } |
| + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { |
| + t.Error(err) |
| + } |
| + quoted := "usd" |
| + if in.Country == country { |
| + quoted = currency |
| + } |
| + json.NewEncoder(w).Encode(map[string]any{"domain": "shop.com", "available": true, "currency": quoted, "price": 1600}) |
| + }) |
| + mux.HandleFunc("POST "+buyTestPath+"/purchases", func(w http.ResponseWriter, r *http.Request) { |
| + purchases++ |
| + var in struct { |
| + Currency string |
| + Price int64 |
| + Contact struct{ Country string } |
| + } |
| + if err := json.NewDecoder(r.Body).Decode(&in); err != nil { |
| + t.Error(err) |
| + } |
| + if in.Currency != currency || in.Price != 1600 || in.Contact.Country != country { |
| + w.WriteHeader(http.StatusConflict) |
| + json.NewEncoder(w).Encode(map[string]any{"error": "price differs", "code": "price_changed", "domain": "shop.com", "available": true, "currency": currency, "price": 1600}) |
| + return |
| + } |
| + fmt.Fprint(w, `{"id":"p1","checkout_url":"https://checkout.example/p1","state":"awaiting_payment"}`) |
| + }) |
| + mux.HandleFunc("GET "+buyTestPath+"/purchases/p1", func(w http.ResponseWriter, r *http.Request) { |
| + fmt.Fprint(w, `{"id":"p1","state":"done","domain_state":"live"}`) |
| + }) |
| + ts := httptest.NewServer(mux) |
| + defer ts.Close() |
| + contactFile := filepath.Join(t.TempDir(), "contact.json") |
| + if err := os.WriteFile(contactFile, []byte(fmt.Sprintf(`{"first_name":"Jane","last_name":"Buyer","email":"buyer@example.test","phone_country_code":"353","phone":"871234567","street":"Main Street","city":"Dublin","postal_code":"D01 A123","country":%q}`, country)), 0600); err != nil { |
| + t.Fatal(err) |
| + } |
| + out, err := runBuyTestCommand(t, ts.URL, "--contact-file", contactFile) |
| + if err != nil { |
| + t.Fatalf("first purchase --yes: %v\n%s", err, out) |
| + } |
| + if checks != 1 || purchases != 1 || !strings.Contains(out, strings.ToUpper(currency)) || !strings.Contains(out, "live") { |
| + t.Fatalf("checks=%d purchases=%d output=%s", checks, purchases, out) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/domains_buy_copy.go b/domains_buy_copy.go| index bfe00c1e5..a1b310ddd 100644 |
| --- a/domains_buy_copy.go |
| +++ b/domains_buy_copy.go |
| @@ -9,6 +9,10 @@ const domainsCheckUsage = "usage: carlos domains check <name> [--account <a>] [- |
| const domainsBuyUsage = "usage: carlos domains buy <name> --app <a> [--contact-file contact.json] [--yes] [--no-wait] [--account <a>] [--account-id <id>] [--console <origin>]\n" |
| var domainsBuyCopy = map[string]string{ |
| + // Approved by delegation (reviewer), 2026-11-03. |
| + "confirmChanged": "buy this domain at the new price? [y/N] ", |
| + // Draft for the Luna pass: domain registration Plan 2, slice 1. |
| + "purchaseID": "purchase: %s\n", |
| "appFlag": "app the domain will serve", |
| "accountFlag": "account (sqid or name)", |
| "accountIDFlag": "account sqid, matched as a sqid only", |
diff --git a/internal/billing/billing.go b/internal/billing/billing.go| index a0bb61f0c..a154e6a60 100644 |
| --- a/internal/billing/billing.go |
| +++ b/internal/billing/billing.go |
| @@ -143,6 +143,17 @@ type CheckoutRequest struct { |
| IdempotencyKey string |
| } |
| +// CustomerDetails supplies an owner's email and optional tax location at creation. |
| +type CustomerDetails struct{ Email, Country, PostalCode string } |
| + |
| +func (CustomerDetails) String() string { return "billing.CustomerDetails{redacted}" } |
| +func (d CustomerDetails) GoString() string { return d.String() } |
| + |
| +// SetupCheckoutRequest saves a card on an existing customer without a charge. |
| +type SetupCheckoutRequest struct { |
| + AccountSqid, Customer, SuccessURL, CancelURL, Key string |
| +} |
| + |
| // PaymentCheckoutRequest creates a one-off Checkout payment for later capture. |
| type PaymentCheckoutRequest struct { |
| AccountSqid, Customer, Currency string |
| @@ -196,6 +207,7 @@ type CheckoutInfo struct { |
| // The kinds of Prepared. |
| const ( |
| + PreparedSetupCheckout = "setup_checkout" |
| PreparedCustomer = "customer" |
| PreparedCheckout = "checkout" |
| PreparedExpire = "expire" |
| @@ -297,7 +309,8 @@ type Provider interface { |
| // The Prepare methods encode a write exactly as Send will send it, with |
| // the given idempotency key. They make no request. |
| - PrepareCustomer(accountSqid, key string) (Prepared, error) |
| + PrepareCustomer(accountSqid, key string, details ...CustomerDetails) (Prepared, error) |
| + PrepareSetupCheckout(req SetupCheckoutRequest) (Prepared, error) |
| PrepareCheckout(req CheckoutRequest) (Prepared, error) |
| PrepareExpire(sessionID, key string) (Prepared, error) |
| PrepareChange(req ChangeRequest) (Prepared, error) |
diff --git a/internal/billing/billingtest/fake.go b/internal/billing/billingtest/fake.go| index 445fbebe5..ab4766e20 100644 |
| --- a/internal/billing/billingtest/fake.go |
| +++ b/internal/billing/billingtest/fake.go |
| @@ -76,7 +76,10 @@ const ( |
| const maxPage = 100 |
| // Customer is a customer at the provider. |
| -type Customer struct{ ID, Account string } |
| +type Customer struct { |
| + ID, Account string |
| + Details billing.CustomerDetails |
| +} |
| // Invoice is an invoice at the provider. Lines use PriceID and Quantity. |
| type Invoice struct { |
| @@ -784,7 +787,8 @@ func (f *Fake) Writes() int { |
| // ---- prepared requests ---- |
| type customerBody struct { |
| - Account string `json:"account"` |
| + Account string `json:"account"` |
| + Details billing.CustomerDetails `json:"details,omitempty"` |
| } |
| type checkoutBody struct { |
| @@ -832,7 +836,7 @@ func fromUnix(s int64) time.Time { |
| func pathFor(kind string, body any) string { |
| switch b := body.(type) { |
| - case *paymentCheckoutBody: |
| + case *billing.SetupCheckoutRequest, *paymentCheckoutBody: |
| return "/v1/checkout/sessions" |
| case *paymentActionBody: |
| action := "capture" |
| @@ -866,11 +870,18 @@ func prepare(kind, key string, body any) (billing.Prepared, error) { |
| } |
| // PrepareCustomer encodes a customer create for the account. |
| -func (f *Fake) PrepareCustomer(accountSqid, key string) (billing.Prepared, error) { |
| +func (f *Fake) PrepareCustomer(accountSqid, key string, details ...billing.CustomerDetails) (billing.Prepared, error) { |
| if accountSqid == "" { |
| return billing.Prepared{}, errors.New("billingtest: customer: no account") |
| } |
| - return prepare(billing.PreparedCustomer, key, &customerBody{Account: accountSqid}) |
| + body := &customerBody{Account: accountSqid} |
| + if len(details) > 1 { |
| + return billing.Prepared{}, billing.ErrRefused |
| + } |
| + if len(details) == 1 { |
| + body.Details = details[0] |
| + } |
| + return prepare(billing.PreparedCustomer, key, body) |
| } |
| // PrepareCheckout encodes a Checkout create. |
| @@ -920,6 +931,8 @@ func (f *Fake) PrepareRenewal(subscription string, renew bool, key string) (bill |
| func decode(p billing.Prepared) (any, error) { |
| var body any |
| switch p.Kind { |
| + case billing.PreparedSetupCheckout: |
| + body = &billing.SetupCheckoutRequest{} |
| case billing.PreparedPaymentCheckout: |
| body = &paymentCheckoutBody{} |
| case billing.PreparedCapture, billing.PreparedCancelPayment: |
| @@ -1121,9 +1134,13 @@ func (f *Fake) execute(body any) (billing.Result, error) { |
| return billing.Result{Payment: &info}, nil |
| } |
| return billing.Result{}, billing.ErrRefused |
| + case *billing.SetupCheckoutRequest: |
| + id := f.nextID("cs") |
| + info := billing.CheckoutInfo{ID: id, URL: "https://checkout.example.test/c/" + id, Customer: b.Customer, State: billing.CheckoutOpen} |
| + return billing.Result{Checkout: &info}, nil |
| case *customerBody: |
| id := f.nextID("cus") |
| - f.Customers[id] = &Customer{ID: id, Account: b.Account} |
| + f.Customers[id] = &Customer{ID: id, Account: b.Account, Details: b.Details} |
| return billing.Result{Customer: id}, nil |
| case *checkoutBody: |
| id := f.nextID("cs") |
| @@ -1532,3 +1549,10 @@ func (f *Fake) CompletePaymentCheckout(sessionID string) (string, error) { |
| s.Authorised = true |
| return s.PaymentIntent, nil |
| } |
| + |
| +func (f *Fake) PrepareSetupCheckout(req billing.SetupCheckoutRequest) (billing.Prepared, error) { |
| + if req.Customer == "" || req.AccountSqid == "" || req.SuccessURL == "" || req.CancelURL == "" { |
| + return billing.Prepared{}, billing.ErrRefused |
| + } |
| + return prepare(billing.PreparedSetupCheckout, req.Key, &req) |
| +} |
diff --git a/internal/billingstripe/card_test.go b/internal/billingstripe/card_test.go| new file mode 100644 |
| index 000000000..b64571506 |
| --- /dev/null |
| +++ b/internal/billingstripe/card_test.go |
| @@ -0,0 +1,94 @@ |
| +package billingstripe |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func TestCustomerDetailsForm(t *testing.T) { |
| + var cap capture |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + cap.add(r) |
| + fmt.Fprint(w, `{"id":"cus_1","livemode":false}`) |
| + })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + prep, err := p.PrepareCustomer("bab", "customer:bab:1", billing.CustomerDetails{Email: "owner@example.com", Country: "IE", PostalCode: "D01 A123"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + form, _ := url.ParseQuery(string(prep.Body)) |
| + for key, want := range map[string]string{"metadata[account_sqid]": "bab", "email": "owner@example.com", "address[country]": "IE", "address[postal_code]": "D01 A123"} { |
| + if form.Get(key) != want { |
| + t.Errorf("%s=%q, want %q", key, form.Get(key), want) |
| + } |
| + } |
| + if _, err := p.Send(context.Background(), prep); err != nil { |
| + t.Fatal(err) |
| + } |
| + if string(cap.last().body) != string(prep.Body) || cap.last().key != prep.Key { |
| + t.Fatal("prepared customer changed") |
| + } |
| +} |
| + |
| +func TestSetupCheckoutFormAndRefusals(t *testing.T) { |
| + for _, which := range []string{"ok", "wrong customer", "wrong mode", "untrusted url", "missing mode", "missing livemode"} { |
| + t.Run(which, func(t *testing.T) { |
| + var cap capture |
| + response := `{"id":"cs_setup","mode":"setup","status":"open","livemode":false,"customer":"cus_1","url":"https://checkout.stripe.com/c/pay/cs_setup"}` |
| + switch which { |
| + case "wrong customer": |
| + response = strings.ReplaceAll(response, "cus_1", "cus_other") |
| + case "wrong mode": |
| + response = strings.ReplaceAll(response, `"mode":"setup"`, `"mode":"payment"`) |
| + case "untrusted url": |
| + response = strings.ReplaceAll(response, "checkout.stripe.com", "attacker.example") |
| + case "missing mode": |
| + response = strings.ReplaceAll(response, `"mode":"setup",`, "") |
| + case "missing livemode": |
| + response = strings.ReplaceAll(response, `"livemode":false,`, "") |
| + } |
| + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { cap.add(r); fmt.Fprint(w, response) })) |
| + defer srv.Close() |
| + p := prepProvider(t, srv.URL, nil) |
| + req := billing.SetupCheckoutRequest{AccountSqid: "bab", Customer: "cus_1", SuccessURL: "https://console.example.com/billing", CancelURL: "https://console.example.com/billing", Key: "setup-key"} |
| + prep, err := p.PrepareSetupCheckout(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if cap.count() != 0 { |
| + t.Fatal("prepare sent request") |
| + } |
| + form, _ := url.ParseQuery(string(prep.Body)) |
| + for key, want := range map[string]string{"mode": "setup", "customer": "cus_1", "payment_method_types[0]": "card", "success_url": req.SuccessURL, "cancel_url": req.CancelURL, "metadata[account]": "bab"} { |
| + if form.Get(key) != want { |
| + t.Errorf("%s=%q", key, form.Get(key)) |
| + } |
| + } |
| + if form.Has("line_items[0][quantity]") || form.Has("payment_intent_data[capture_method]") { |
| + t.Fatal("setup must not charge") |
| + } |
| + result, err := p.Send(context.Background(), prep) |
| + if which != "ok" { |
| + if !errors.Is(err, billing.ErrIndeterminate) { |
| + t.Fatalf("untrusted response: %+v %v", result, err) |
| + } |
| + return |
| + } |
| + if err != nil || result.Checkout == nil || result.Checkout.Customer != req.Customer { |
| + t.Fatalf("setup result: %+v %v", result, err) |
| + } |
| + if cap.last().path != "/v1/checkout/sessions" || cap.last().key != req.Key || string(cap.last().body) != string(prep.Body) { |
| + t.Fatal("send changed setup") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/billingstripe/payment.go b/internal/billingstripe/payment.go| index 990381dac..cd3e34ce2 100644 |
| --- a/internal/billingstripe/payment.go |
| +++ b/internal/billingstripe/payment.go |
| @@ -21,26 +21,28 @@ func (p *Provider) PreparePaymentCheckout(req billing.PaymentCheckoutRequest) (b |
| return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| } |
| form := url.Values{ |
| - "mode": {"payment"}, |
| - "payment_intent_data[capture_method]": {"manual"}, |
| - "line_items[0][price_data][currency]": {req.Currency}, |
| - "line_items[0][price_data][unit_amount]": {strconv.FormatInt(req.Amount, 10)}, |
| - "line_items[0][price_data][product_data][name]": {req.Description}, |
| - "line_items[0][price_data][tax_behavior]": {"exclusive"}, |
| - "line_items[0][quantity]": {"1"}, |
| - "automatic_tax[enabled]": {"true"}, |
| - "adaptive_pricing[enabled]": {"false"}, |
| - "billing_address_collection": {"required"}, |
| - "customer_update[address]": {"auto"}, |
| - "customer_update[name]": {"auto"}, |
| - "tax_id_collection[enabled]": {"true"}, |
| - "customer": {req.Customer}, |
| - "expires_at": {strconv.FormatInt(req.ExpiresAt.Unix(), 10)}, |
| - "metadata[account]": {req.AccountSqid}, |
| - "metadata[purchase]": {req.Reference}, |
| - "success_url": {req.SuccessURL}, |
| - "cancel_url": {req.CancelURL}, |
| - "expand[]": {"payment_intent"}, |
| + "mode": {"payment"}, |
| + "payment_intent_data[setup_future_usage]": {"off_session"}, |
| + "saved_payment_method_options[payment_method_save]": {"enabled"}, |
| + "payment_intent_data[capture_method]": {"manual"}, |
| + "line_items[0][price_data][currency]": {req.Currency}, |
| + "line_items[0][price_data][unit_amount]": {strconv.FormatInt(req.Amount, 10)}, |
| + "line_items[0][price_data][product_data][name]": {req.Description}, |
| + "line_items[0][price_data][tax_behavior]": {"exclusive"}, |
| + "line_items[0][quantity]": {"1"}, |
| + "automatic_tax[enabled]": {"true"}, |
| + "adaptive_pricing[enabled]": {"false"}, |
| + "billing_address_collection": {"required"}, |
| + "customer_update[address]": {"auto"}, |
| + "customer_update[name]": {"auto"}, |
| + "tax_id_collection[enabled]": {"true"}, |
| + "customer": {req.Customer}, |
| + "expires_at": {strconv.FormatInt(req.ExpiresAt.Unix(), 10)}, |
| + "metadata[account]": {req.AccountSqid}, |
| + "metadata[purchase]": {req.Reference}, |
| + "success_url": {req.SuccessURL}, |
| + "cancel_url": {req.CancelURL}, |
| + "expand[]": {"payment_intent"}, |
| } |
| return prepared(billing.PreparedPaymentCheckout, "/v1/checkout/sessions", form, req.Key) |
| } |
| @@ -186,3 +188,14 @@ func paymentResult(prep billing.Prepared, raw json.RawMessage) (billing.PaymentI |
| } |
| return billing.PaymentInfo{PaymentIntent: pi.ID, IntentStatus: pi.Status, AmountTotal: *pi.Amount, Currency: pi.Currency}, nil |
| } |
| + |
| +func (p *Provider) PrepareSetupCheckout(req billing.SetupCheckoutRequest) (billing.Prepared, error) { |
| + if !validID(req.Customer) || req.AccountSqid == "" || req.SuccessURL == "" || req.CancelURL == "" { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + return prepared(billing.PreparedSetupCheckout, "/v1/checkout/sessions", url.Values{ |
| + "mode": {"setup"}, "customer": {req.Customer}, "payment_method_types[0]": {"card"}, |
| + "metadata[account]": {req.AccountSqid}, "setup_intent_data[metadata][account]": {req.AccountSqid}, |
| + "success_url": {req.SuccessURL}, "cancel_url": {req.CancelURL}, |
| + }, req.Key) |
| +} |
diff --git a/internal/billingstripe/payment_test.go b/internal/billingstripe/payment_test.go| index 7ad5629d4..8e00314f1 100644 |
| --- a/internal/billingstripe/payment_test.go |
| +++ b/internal/billingstripe/payment_test.go |
| @@ -51,7 +51,9 @@ func TestPaymentCheckoutForm(t *testing.T) { |
| } |
| want := url.Values{ |
| "mode": {"payment"}, "payment_intent_data[capture_method]": {"manual"}, |
| - "line_items[0][price_data][currency]": {"eur"}, "line_items[0][price_data][unit_amount]": {"1500"}, |
| + "payment_intent_data[setup_future_usage]": {"off_session"}, |
| + "saved_payment_method_options[payment_method_save]": {"enabled"}, |
| + "line_items[0][price_data][currency]": {"eur"}, "line_items[0][price_data][unit_amount]": {"1500"}, |
| "line_items[0][price_data][product_data][name]": {"example.com"}, "line_items[0][price_data][tax_behavior]": {"exclusive"}, |
| "line_items[0][quantity]": {"1"}, "automatic_tax[enabled]": {"true"}, "customer": {"cus_1"}, |
| "expires_at": {strconv.FormatInt(req.ExpiresAt.Unix(), 10)}, "metadata[account]": {"bab"}, "metadata[purchase]": {"purchase_1"}, |
diff --git a/internal/billingstripe/prepared.go b/internal/billingstripe/prepared.go| index c48942e5d..cf560c4d5 100644 |
| --- a/internal/billingstripe/prepared.go |
| +++ b/internal/billingstripe/prepared.go |
| @@ -29,13 +29,30 @@ func prepared(kind, path string, form url.Values, key string) (billing.Prepared, |
| } |
| // PrepareCustomer encodes a customer create for the account: its metadata |
| -// only. Checkout collects the billing address (billing_address_collection) |
| -// and saves it on the customer. |
| -func (p *Provider) PrepareCustomer(accountSqid, key string) (billing.Prepared, error) { |
| +// plus optional owner email and tax location. Checkout collects the full address. |
| +func (p *Provider) PrepareCustomer(accountSqid, key string, details ...billing.CustomerDetails) (billing.Prepared, error) { |
| form, err := customerMetadataForm(accountSqid) |
| if err != nil { |
| return billing.Prepared{}, err |
| } |
| + if len(details) > 1 { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + if len(details) == 1 { |
| + d := details[0] |
| + if !noControlChars(d.Email) || !validPostalCode(d.PostalCode) || (d.Country != "" && !validCountry(d.Country)) || (d.Country == "" && d.PostalCode != "") { |
| + return billing.Prepared{}, &Error{Code: CodeInvalidParams} |
| + } |
| + if d.Email != "" { |
| + form.Set("email", d.Email) |
| + } |
| + if d.Country != "" { |
| + form.Set("address[country]", d.Country) |
| + } |
| + if d.PostalCode != "" { |
| + form.Set("address[postal_code]", d.PostalCode) |
| + } |
| + } |
| return prepared(billing.PreparedCustomer, "/v1/customers", form, key) |
| } |
| @@ -171,7 +188,7 @@ var preparedPathRe = regexp.MustCompile(`^/v1(/[A-Za-z0-9_]+)+$`) |
| // Idempotent-Replayed and Date headers whenever a response arrived. |
| func (p *Provider) Send(ctx context.Context, prep billing.Prepared) (billing.Result, error) { |
| switch prep.Kind { |
| - case billing.PreparedCustomer, billing.PreparedCheckout, billing.PreparedExpire, billing.PreparedChange, billing.PreparedRenewal, |
| + case billing.PreparedSetupCheckout, billing.PreparedCustomer, billing.PreparedCheckout, billing.PreparedExpire, billing.PreparedChange, billing.PreparedRenewal, |
| billing.PreparedPaymentCheckout, billing.PreparedCapture, billing.PreparedCancelPayment: |
| default: |
| return billing.Result{}, fmt.Errorf("%w: unknown prepared kind %q, not sent", billing.ErrRefused, prep.Kind) |
| @@ -197,6 +214,19 @@ func (p *Provider) Send(ctx context.Context, prep billing.Prepared) (billing.Res |
| // decodeResult reads a 2xx answer to prep by its kind. |
| func decodeResult(prep billing.Prepared, raw json.RawMessage, date time.Time, res *billing.Result) error { |
| switch prep.Kind { |
| + case billing.PreparedSetupCheckout: |
| + var sess struct { |
| + ID, URL, Mode, Status, Customer string |
| + LiveMode *bool `json:"livemode"` |
| + } |
| + if err := json.Unmarshal(raw, &sess); err != nil { |
| + return errors.New("billingstripe: setup answer does not decode") |
| + } |
| + form, _ := url.ParseQuery(string(prep.Body)) |
| + if !validID(sess.ID) || sess.Mode != "setup" || sess.LiveMode == nil || sess.Customer != form.Get("customer") || sess.Status != "open" || validateRedirectURL(sess.URL, "checkout.stripe.com") != nil { |
| + return errors.New("billingstripe: invalid setup session") |
| + } |
| + res.Checkout = &billing.CheckoutInfo{ID: sess.ID, URL: sess.URL, Customer: sess.Customer, State: billing.CheckoutOpen} |
| case billing.PreparedPaymentCheckout, billing.PreparedCapture, billing.PreparedCancelPayment: |
| info, err := paymentResult(prep, raw) |
| if err != nil { |
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go| index cea2c370a..ecbaff283 100644 |
| --- a/internal/console/apidomainbuy.go |
| +++ b/internal/console/apidomainbuy.go |
| @@ -35,8 +35,18 @@ func (s *Server) domainBuyAPIGate(w http.ResponseWriter, r *http.Request) (strin |
| return addr, acct, true |
| } |
| -func (s *Server) checkDomainBuy(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) { |
| - return s.admitDomainBuy(ctx, acct, name) |
| +func (s *Server) checkDomainBuy(ctx context.Context, acct *Account, name, country string) (domainreg.Quote, *doorRefusal) { |
| + if country != "" && (len(country) != 2 || country[0] < 'A' || country[0] > 'Z' || country[1] < 'A' || country[1] > 'Z') { |
| + return domainreg.Quote{}, &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]} |
| + } |
| + if country == "" { |
| + c, _, err := s.store.DomainContact(acct.ID) |
| + if err != nil { |
| + return domainreg.Quote{}, domainBuyUnavailable() |
| + } |
| + country = c.Country |
| + } |
| + return s.admitDomainBuy(ctx, acct, name, country) |
| } |
| func (s *Server) liveDomainPurchaseRefusal(ctx context.Context, name string) *doorRefusal { |
| @@ -56,14 +66,15 @@ func (s *Server) handleAPIDomainCheck(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| var in struct { |
| - Name string `json:"name"` |
| + Name string `json:"name"` |
| + Country string `json:"country"` |
| } |
| 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) |
| + q, ref := s.checkDomainBuy(ctx, acct, in.Name, in.Country) |
| if ref != nil { |
| writeDoorRefusalJSON(w, r, ref) |
| return |
| @@ -77,9 +88,11 @@ func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| var in struct { |
| - Name string `json:"name"` |
| - App string `json:"app"` |
| - Contact *registrar.Contact `json:"contact"` |
| + Name string `json:"name"` |
| + App string `json:"app"` |
| + Contact *registrar.Contact `json:"contact"` |
| + Currency string `json:"currency"` |
| + Price int64 `json:"price"` |
| } |
| if !readJSONStrictLimit(w, r, &in, 16<<10) { |
| return |
| @@ -101,7 +114,11 @@ func (s *Server) handleAPIDomainPurchase(w http.ResponseWriter, r *http.Request) |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) |
| defer cancel() |
| - p, checkout, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, c, addr) |
| + p, checkout, changed, ref := s.startDomainPurchase(ctx, acct, in.App, in.Name, c, addr, domainreg.Quote{Currency: in.Currency, Price: in.Price}) |
| + if changed != nil { |
| + writeJSON(w, http.StatusConflict, map[string]any{"error": ref.Msg, "code": "price_changed", "domain": changed.Domain, "currency": changed.Currency, "price": changed.Price, "available": true}) |
| + return |
| + } |
| if ref != nil { |
| if ref.Status == 422 && ref.Msg == domainBuyCopy["contactError"] { |
| writeJSON(w, 422, map[string]string{"error": ref.Msg, "code": "contact"}) |
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go| index d510f1226..15598c346 100644 |
| --- a/internal/console/apidomainbuy_test.go |
| +++ b/internal/console/apidomainbuy_test.go |
| @@ -45,7 +45,7 @@ func buyRequest(t *testing.T, f *purchaseFixture, method, path, token, body stri |
| return resp.StatusCode, string(b) |
| } |
| func buyBody() string { |
| - b, _ := json.Marshal(map[string]any{"name": "shop.com", "app": "kass", "contact": purchaseContact()}) |
| + b, _ := json.Marshal(map[string]any{"name": "shop.com", "app": "kass", "contact": purchaseContact(), "currency": "usd", "price": 1500}) |
| return string(b) |
| } |
| func TestBuyDoorAbsentWhenNotConfigured(t *testing.T) { |
| @@ -188,7 +188,7 @@ func TestBrowserBuyRedirectsToCheckout(t *testing.T) { |
| t.Errorf("missing visible copy %q", want) |
| } |
| } |
| - values := url.Values{"csrf": {csrf}, "name": {"shop.com"}} |
| + values := url.Values{"csrf": {csrf}, "name": {"shop.com"}, "currency": {"usd"}, "price": {"1500"}} |
| for _, field := range buyContactFields(purchaseContact()) { |
| values.Set(field.Name, field.Value) |
| } |
| @@ -231,14 +231,14 @@ func TestBrowserBuyCSRF(t *testing.T) { |
| 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"}`) |
| + status, b := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass","currency":"usd","price":1500}`) |
| 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"}`) |
| + status, b = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass","currency":"usd","price":1500}`) |
| if status != 200 && status != 201 { |
| t.Fatalf("stored contact %d %s", status, b) |
| } |
| @@ -257,7 +257,7 @@ func setupClaimBuyDoors(t *testing.T, cx *claimCase) { |
| 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 { |
| - kv := []string{"name", "shop.com"} |
| + kv := []string{"name", "shop.com", "currency", "usd", "price", "1500"} |
| for _, field := range buyContactFields(purchaseContact()) { |
| kv = append(kv, field.Name, field.Value) |
| } |
diff --git a/internal/console/appdomainbuy.go b/internal/console/appdomainbuy.go| index abfee982e..1eb02dedb 100644 |
| --- a/internal/console/appdomainbuy.go |
| +++ b/internal/console/appdomainbuy.go |
| @@ -5,6 +5,7 @@ import ( |
| "crypto/subtle" |
| "net/http" |
| "net/url" |
| + "strconv" |
| "time" |
| "github.com/carlosframework/platform/internal/domainreg" |
| @@ -20,6 +21,7 @@ type domainBuyView struct { |
| Base, Back, PollURL string |
| CheckoutURL string |
| Price string |
| + PriceChanged bool |
| Quote *domainreg.Quote |
| Fields []domainBuyField |
| Purchase *DomainPurchase |
| @@ -70,7 +72,11 @@ func (s *Server) renderDomainBuy(w http.ResponseWriter, r *http.Request, addr, r |
| v.Price = plans.FormatMinor(v.Quote.Currency, v.Quote.Price) |
| } |
| p.DomainBuy = v |
| - s.render(w, 200, "domain_buy", p) |
| + 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) |
| @@ -86,7 +92,7 @@ func (s *Server) handleAppDomainBuyCheck(w http.ResponseWriter, r *http.Request) |
| } |
| ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) |
| defer cancel() |
| - q, ref := s.checkDomainBuy(ctx, acct, r.FormValue("name")) |
| + q, ref := s.checkDomainBuy(ctx, acct, r.FormValue("name"), r.FormValue("country")) |
| if ref != nil { |
| s.renderDoorRefusal(w, r, ref) |
| return |
| @@ -96,10 +102,13 @@ func (s *Server) handleAppDomainBuyCheck(w http.ResponseWriter, r *http.Request) |
| s.renderDoorRefusal(w, r, domainBuyUnavailable()) |
| return |
| } |
| + if country := r.FormValue("country"); country != "" { |
| + c.Country = country |
| + } |
| 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) |
| + addr, raw, acct, app, ok := s.domainBuyBrowserGate(w, r) |
| if !ok { |
| return |
| } |
| @@ -112,7 +121,15 @@ func (s *Server) handleAppDomainBuy(w http.ResponseWriter, r *http.Request) { |
| 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() |
| - p, checkout, ref := s.startDomainPurchase(ctx, acct, app, r.FormValue("name"), c, addr) |
| + 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"), 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 |
diff --git a/internal/console/billingcard.go b/internal/console/billingcard.go| new file mode 100644 |
| index 000000000..7c8ea9bf7 |
| --- /dev/null |
| +++ b/internal/console/billingcard.go |
| @@ -0,0 +1,79 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "crypto/subtle" |
| + "log" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func (s *Server) handleBillingCard(w http.ResponseWriter, r *http.Request) { |
| + addr, raw, acct, ok := s.billingOwner(w, r) |
| + if !ok { |
| + return |
| + } |
| + if subtle.ConstantTimeCompare([]byte(r.FormValue("csrf")), []byte(raw)) != 1 { |
| + s.billingCSRFRefused(w, r) |
| + return |
| + } |
| + back := billingPagePath(acct.Sqid) |
| + if !s.domainBuyReady() || s.checkCustomDomains(acct) != nil { |
| + s.setFlash(w, "err", billingCopy["card.failed"]) |
| + http.Redirect(w, r, back, http.StatusSeeOther) |
| + return |
| + } |
| + if !s.requireFreshAuth(w, r, addr, raw) { |
| + return |
| + } |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + s.holdRefused(w, r, acct, err) |
| + return |
| + } |
| + ctx, cancel := context.WithTimeout(s.billingClock(r.Context()), 30*time.Second) |
| + defer cancel() |
| + to, err := s.cardSetupLocked(h, ctx, acct) |
| + release() |
| + if err != nil { |
| + log.Printf("console: billing card %s: %v", acct.Sqid, err) |
| + s.setFlash(w, "err", billingCopy["card.failed"]) |
| + to = back |
| + } |
| + http.Redirect(w, r, to, http.StatusSeeOther) |
| +} |
| + |
| +func (s *Server) cardSetupLocked(h billingHold, ctx context.Context, acct *Account) (string, error) { |
| + b, err := s.paymentCustomerLocked(h, ctx, acct, "", "", false) |
| + if err != nil { |
| + return "", err |
| + } |
| + stamp, err := s.providerNow(ctx) |
| + if err != nil { |
| + return "", errNoProviderTimeRefusal |
| + } |
| + back := s.cfg.Origin + billingPagePath(acct.Sqid) |
| + // Like a portal open, each attempt gets a fresh session. It cannot charge |
| + // money or change a subscription, and an unknown response is never replayed. |
| + req, err := s.billing.cfg.Provider.PrepareSetupCheckout(billing.SetupCheckoutRequest{AccountSqid: acct.Sqid, Customer: b.Customer, SuccessURL: back, CancelURL: back, Key: "card:" + b.Customer + ":" + newPortalNonce()}) |
| + if err != nil { |
| + return "", err |
| + } |
| + now, err := s.providerNow(ctx) |
| + if err != nil { |
| + return "", errNoProviderTimeRefusal |
| + } |
| + if ok, _ := recoveryEligible(resendState{State: opSending, FirstSent: stamp, ContextCurrent: ctx.Err() == nil}, now); !ok { |
| + return "", errCheckoutFailed |
| + } |
| + result, err := s.sendPreparedLocked(h, ctx, req) |
| + if err != nil { |
| + return "", err |
| + } |
| + if result.Checkout == nil || result.Checkout.ID == "" || result.Checkout.URL == "" || result.Checkout.Customer != b.Customer { |
| + return "", billing.ErrIndeterminate |
| + } |
| + return result.Checkout.URL, nil |
| +} |
diff --git a/internal/console/billingcard_test.go b/internal/console/billingcard_test.go| new file mode 100644 |
| index 000000000..439044646 |
| --- /dev/null |
| +++ b/internal/console/billingcard_test.go |
| @@ -0,0 +1,122 @@ |
| +package console |
| + |
| +import ( |
| + "encoding/json" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/domainreg" |
| + "github.com/carlosframework/platform/internal/registrar/registrartest" |
| + "github.com/carlosframework/platform/internal/zonehost/zonehosttest" |
| +) |
| + |
| +func TestBillingAddCardWithoutCustomer(t *testing.T) { |
| + o := newCheckoutFixture(t, false) |
| + o.srv.cfg.Registrar = registrartest.New() |
| + o.srv.cfg.ZoneHost = zonehosttest.New("ns1.example.test") |
| + o.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3} |
| + sponsored := sponsorUnlimited() |
| + if _, err := o.st.SetAccountPlan(o.acct.ID, "free", nil, 0, PlanSourceSponsored, &sponsored, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + page := o.request(t, http.MethodGet, o.billingBase(), nil) |
| + if page.Status != 200 || !strings.Contains(page.Body, "Add a card") || strings.Contains(page.Body, "/billing/portal") { |
| + t.Fatal("missing add card action or unexpected portal") |
| + } |
| + if !strings.Contains(page.Body, billingCopy["card.hint"]) { |
| + t.Fatal("missing add card hint") |
| + } |
| + o.stepUp(t) |
| + for i := 0; i < 2; i++ { |
| + r := o.request(t, http.MethodPost, o.billingBase()+"/card", nil) |
| + if r.Status != 303 || !strings.HasPrefix(r.Loc, "https://checkout.example.test/") { |
| + t.Fatalf("setup: %+v", r) |
| + } |
| + } |
| + b, err := o.st.BillingAccount(o.acct.ID) |
| + if err != nil || b == nil || b.Customer == "" || b.Subscription != "" || b.Currency != "" { |
| + t.Fatalf("billing: %+v %v", b, err) |
| + } |
| + customers, setups := 0, 0 |
| + for _, p := range o.fake.Sent { |
| + if p.Kind == billing.PreparedCustomer { |
| + customers++ |
| + } |
| + if p.Kind == "setup_checkout" { |
| + setups++ |
| + var req struct{ Customer, SuccessURL, CancelURL string } |
| + if err := json.Unmarshal(p.Body, &req); err != nil { |
| + t.Fatal(err) |
| + } |
| + if req.Customer != b.Customer || req.SuccessURL != o.srv.cfg.Origin+o.billingBase() || req.CancelURL != req.SuccessURL { |
| + t.Fatalf("setup request: %+v", req) |
| + } |
| + } |
| + } |
| + if customers != 1 || setups != 2 { |
| + t.Fatalf("customers=%d setups=%d", customers, setups) |
| + } |
| + page = o.request(t, http.MethodGet, o.billingBase(), nil) |
| + if strings.Contains(page.Body, "/billing/card") || !strings.Contains(page.Body, "/billing/portal") { |
| + t.Fatal("bound customer needs portal only") |
| + } |
| + if strings.Contains(page.Body, billingCopy["card.hint"]) { |
| + t.Fatal("add card hint shown without the add card action") |
| + } |
| +} |
| + |
| +func TestBillingAddCardGates(t *testing.T) { |
| + o := newCheckoutFixture(t, false) |
| + enableCardBuying(t, o) |
| + if err := o.st.AddMember(o.acct.ID, "kim@keymail.dev", RoleMember, time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + kim := newBrowser(t) |
| + o.setUser("kim@keymail.dev") |
| + signUp(t, o.consoleFixture, kim, "card-member") |
| + if status, _, _ := postForm(t, kim, o.ts.URL+o.billingBase()+"/card", url.Values{"csrf": {sessionToken(t, o.consoleFixture, kim)}}); status != 404 { |
| + t.Fatalf("member status=%d", status) |
| + } |
| + if status := httpPostNoCSRF(t, o, o.billingBase()+"/card", url.Values{}); status != 403 { |
| + t.Fatalf("csrf status=%d", status) |
| + } |
| + if r := o.request(t, http.MethodPost, o.billingBase()+"/card", nil); r.Status != 303 || !strings.Contains(r.Loc, "/oauth/authorize") { |
| + t.Fatalf("stepup: %+v", r) |
| + } |
| + if b, err := o.st.BillingAccount(o.acct.ID); err != nil || b != nil { |
| + t.Fatalf("gate wrote billing: %+v %v", b, err) |
| + } |
| + if len(o.fake.Sent) != 0 { |
| + t.Fatal("gate sent provider writes") |
| + } |
| +} |
| + |
| +func TestBillingAddCardNoProviderTimeSendsNothing(t *testing.T) { |
| + o := newCheckoutFixture(t, true) |
| + enableCardBuying(t, o) |
| + o.stepUp(t) |
| + o.reset() |
| + o.fake.ProbeErr = billing.ErrNoResponse |
| + r := o.request(t, http.MethodPost, o.billingBase()+"/card", nil) |
| + if r.Status != 303 || r.Loc != o.billingBase() || r.FlashMsg != billingCopy["card.failed"] { |
| + t.Fatalf("clock refusal: %+v", r) |
| + } |
| + if len(o.fake.Sent) != 0 { |
| + t.Fatal("setup sent without provider time") |
| + } |
| +} |
| + |
| +func enableCardBuying(t *testing.T, o *opsFixture) { |
| + t.Helper() |
| + o.srv.cfg.Registrar = registrartest.New() |
| + o.srv.cfg.ZoneHost = zonehosttest.New("ns1.example.test") |
| + o.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3} |
| + sponsored := sponsorUnlimited() |
| + if _, err := o.st.SetAccountPlan(o.acct.ID, "free", nil, 0, PlanSourceSponsored, &sponsored, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/console/billingcheckout.go b/internal/console/billingcheckout.go| index 151070584..0f4b3e77b 100644 |
| --- a/internal/console/billingcheckout.go |
| +++ b/internal/console/billingcheckout.go |
| @@ -428,13 +428,24 @@ func customerKey(sqid string, attempt int) string { |
| return fmt.Sprintf("customer:%s:%d", sqid, attempt) |
| } |
| +type customerSetup struct { |
| + Details billing.CustomerDetails |
| + Currency string |
| +} |
| + |
| // ensureCustomerLocked is the account's provider customer, created if |
| // needed. An attempt already stored and not bound is finished first, by |
| // resending its bytes while recoveryEligible; one that is over is replaced by |
| // a new attempt with a new key. A new attempt is prepared and stored, with |
| // its provider-time stamp, before its first send; with no provider time |
| // nothing is stored or sent. Only a definite answer is bound. |
| -func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *Account, now time.Time) (string, error) { |
| +func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct *Account, now time.Time, setup ...customerSetup) (string, error) { |
| + var currency string |
| + var details []billing.CustomerDetails |
| + if len(setup) > 0 { |
| + currency = setup[0].Currency |
| + details = []billing.CustomerDetails{setup[0].Details} |
| + } |
| b, err := s.store.BillingAccount(acct.ID) |
| if err != nil { |
| return "", err |
| @@ -443,6 +454,11 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct * |
| b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}} |
| } |
| if b.Customer != "" { |
| + if currency != "" { |
| + if err := s.store.SetBillingCustomer(acct.ID, b.Customer, now, currency); err != nil { |
| + return "", err |
| + } |
| + } |
| return b.Customer, nil |
| } |
| started := 0 |
| @@ -453,11 +469,11 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct * |
| return "", errCheckoutFailed |
| } |
| started++ |
| - if err := s.startCustomerLocked(h, ctx, acct, b); err != nil { |
| + if err := s.startCustomerLocked(h, ctx, acct, b, details...); err != nil { |
| return "", err |
| } |
| } |
| - out, err := s.sendCustomerLocked(h, ctx, acct, b, recovering, handlerRetries, now) |
| + out, err := s.sendCustomerLocked(h, ctx, acct, b, recovering, handlerRetries, now, currency) |
| if err != nil { |
| return "", err |
| } |
| @@ -474,7 +490,7 @@ func (s *Server) ensureCustomerLocked(h billingHold, ctx context.Context, acct * |
| // startCustomerLocked prepares the next customer attempt and stores it on |
| // the billing row with its provider-time stamp, before anything is sent. |
| -func (s *Server) startCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount) error { |
| +func (s *Server) startCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, details ...billing.CustomerDetails) error { |
| _ = h |
| if err := s.requireBillingReady(); err != nil { |
| return err |
| @@ -484,7 +500,7 @@ func (s *Server) startCustomerLocked(h billingHold, ctx context.Context, acct *A |
| return errNoProviderTimeRefusal |
| } |
| attempt := b.CustomerAttempt + 1 |
| - p, err := s.billing.cfg.Provider.PrepareCustomer(acct.Sqid, customerKey(acct.Sqid, attempt)) |
| + p, err := s.billing.cfg.Provider.PrepareCustomer(acct.Sqid, customerKey(acct.Sqid, attempt), details...) |
| if err != nil { |
| return err |
| } |
| @@ -510,7 +526,7 @@ func customerResendState(b *billingAccount) resendState { |
| // the backoff and only while recoveryEligible; there is no read to make, so |
| // the resend is the check, and provider time comes from the request's |
| // recorder or one probe. |
| -func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, recovering bool, retries int, now time.Time) (customerOutcome, error) { |
| +func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Account, b *billingAccount, recovering bool, retries int, now time.Time, currency ...string) (customerOutcome, error) { |
| if recovering { |
| retries = 0 // a recovery is F: at most one resend, whoever calls |
| } |
| @@ -534,7 +550,7 @@ func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Ac |
| } |
| res, err := s.sendPreparedLocked(h, ctx, *b.CustomerPrepared) |
| if !retryableSend(err) || attempt == retries { |
| - return s.recordCustomerLocked(h, acct, b, res, err, now) |
| + return s.recordCustomerLocked(h, acct, b, res, err, now, currency...) |
| } |
| } |
| } |
| @@ -543,10 +559,10 @@ func (s *Server) sendCustomerLocked(h billingHold, ctx context.Context, acct *Ac |
| // bound; a refusal or a cached 5xx retires the attempt; an unknown delivery or |
| // a reused key leaves it to be resent. An error outside every class (a crash) |
| // is returned at once with nothing recorded. |
| -func (s *Server) recordCustomerLocked(h billingHold, acct *Account, b *billingAccount, res billing.Result, err error, now time.Time) (customerOutcome, error) { |
| +func (s *Server) recordCustomerLocked(h billingHold, acct *Account, b *billingAccount, res billing.Result, err error, now time.Time, currency ...string) (customerOutcome, error) { |
| switch { |
| case err == nil && res.Customer != "": |
| - if err := s.store.SetBillingCustomer(acct.ID, res.Customer, now); err != nil { |
| + if err := s.store.SetBillingCustomer(acct.ID, res.Customer, now, currency...); err != nil { |
| return customerUnknown, err |
| } |
| b.Customer = res.Customer |
diff --git a/internal/console/billingcustomer.go b/internal/console/billingcustomer.go| new file mode 100644 |
| index 000000000..462c01497 |
| --- /dev/null |
| +++ b/internal/console/billingcustomer.go |
| @@ -0,0 +1,62 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +// Payment customers use the subscription customer's lock, journal and keys. |
| +// Adding a card alone leaves currency unset; the first purchase fixes it. |
| +func (s *Server) paymentCustomerLocked(h billingHold, ctx context.Context, acct *Account, country, postal string, fixCurrency bool) (*billingAccount, error) { |
| + now := time.Now() |
| + if err := s.requireBillingReady(); err != nil { |
| + return nil, err |
| + } |
| + if retiring, err := s.store.BillingRetiring(acct.ID, now); err != nil { |
| + return nil, err |
| + } else if retiring { |
| + return nil, errBillingRetiring |
| + } |
| + b, err := s.store.BillingAccount(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if b == nil { |
| + b = &billingAccount{AccountID: acct.ID, PaidPacks: map[string]int{}} |
| + } |
| + currency := b.Currency |
| + if fixCurrency && currency == "" { |
| + currency, err = s.billing.cfg.Book.ChooseCurrency("", country) |
| + if err != nil { |
| + return nil, err |
| + } |
| + prior, err := s.store.CheckoutIntent(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if prior != nil && (!intentTerminal(prior) || prior.State == intentCompleted) && prior.Currency != currency { |
| + return nil, errCheckoutUncertain |
| + } |
| + } |
| + details := billing.CustomerDetails{Country: country, PostalCode: postal} |
| + members, err := s.store.Members(acct.ID) |
| + if err != nil { |
| + return nil, err |
| + } |
| + for _, member := range members { |
| + if member.Role == RoleOwner { |
| + details.Email = member.Name |
| + break |
| + } |
| + } |
| + if details.Email == "" { |
| + return nil, errors.New("billing: account has no owner") |
| + } |
| + if _, err := s.ensureCustomerLocked(h, ctx, acct, now, customerSetup{Details: details, Currency: currency}); err != nil { |
| + return nil, err |
| + } |
| + return s.store.BillingAccount(acct.ID) |
| +} |
diff --git a/internal/console/billingpage.go b/internal/console/billingpage.go| index 75967b567..cc41b5103 100644 |
| --- a/internal/console/billingpage.go |
| +++ b/internal/console/billingpage.go |
| @@ -35,6 +35,7 @@ const ( |
| offerStop = "stop" |
| offerResume = "resume" |
| offerPortal = "portal" |
| + offerCard = "card" |
| offerConfirm = "confirm" |
| offerContinue = "continue" |
| offerStartOver = "start_over" |
| @@ -49,6 +50,7 @@ type billingPageInput struct { |
| Op *billingOp // the outstanding operation, nil for none |
| Problems []string // open problem reasons |
| Retiring, Ready, Owner bool |
| + CanBuyDomains bool |
| // Exempt is the ops account, which has no plan (planExempt). |
| Exempt bool |
| Now time.Time |
| @@ -70,6 +72,9 @@ type billingPageState struct { |
| // owner's notice and, where an owner would act, notice.owners_only. |
| func decideBillingPage(in billingPageInput) billingPageState { |
| notice, offered := decideBillingOwner(in) |
| + if !in.CanBuyDomains { |
| + offered = slices.DeleteFunc(offered, func(key string) bool { return key == offerCard }) |
| + } |
| if in.Owner { |
| return billingPageState{Notice: notice, Offered: offered} |
| } |
| @@ -108,7 +113,10 @@ func decideBillingOwner(in billingPageInput) (string, []string) { |
| case len(in.Problems) > 0: |
| return "notice.problem", ifBound() |
| case in.Row != nil && (in.Row.Source == PlanSourceOperator || in.Row.Source == PlanSourceSponsored): |
| - return "notice.operator_plan", nil |
| + if bound { |
| + return "notice.operator_plan", []string{offerPortal} |
| + } |
| + return "notice.operator_plan", []string{offerCard} |
| // A sending row under no hold is one a crash left behind: Confirm now |
| // adopts it as unresolved and finishes it. |
| case op != nil && (op.State == opUnresolved || op.State == opSending): |
| @@ -120,7 +128,10 @@ func decideBillingOwner(in billingPageInput) (string, []string) { |
| case intent != nil && intent.State == intentCreating && !live: |
| return "notice.settling", []string{offerConfirm} |
| case !live: |
| - return "", []string{offerBuy} |
| + if bound { |
| + return "", []string{offerBuy, offerPortal} |
| + } |
| + return "", []string{offerBuy, offerCard} |
| case b.State == billing.StatePending: |
| return "notice.settling", nil |
| case b.Collecting: |
| @@ -309,6 +320,7 @@ func (s *Server) billingPageInputFor(acct *Account, role string, now time.Time) |
| if in.Exempt { |
| return in, nil // nothing else decides its page |
| } |
| + in.CanBuyDomains = s.domainBuyReady() && s.checkCustomDomains(acct) == nil |
| var err error |
| if in.Row, err = s.store.AccountPlan(acct.ID); err != nil { |
| return in, err |
diff --git a/internal/console/billingpage_copy.go b/internal/console/billingpage_copy.go| index bc0831c5a..454595b1d 100644 |
| --- a/internal/console/billingpage_copy.go |
| +++ b/internal/console/billingpage_copy.go |
| @@ -9,6 +9,11 @@ package console |
| // here. The change.* keys below are the plan's drafts for Task 10, declared |
| // here because Confirm now and the refusals of this task use them. |
| var billingCopy = map[string]string{ |
| + // Approved by delegation (Luna), 2026-11-03: domain registration Plan 2, slice 1. |
| + "button.card": "Add a card", |
| + "card.failed": "We could not open the card setup page. Try again later.", |
| + "card.hint": "Save a card for buying domains. Nothing is charged until you buy one.", |
| + |
| "change.done": "Your billing change is saved.", |
| "change.pending": "Your card didn't go through, so nothing changed. Pay from Payment and invoices to finish.", |
| "change.declined": "Your card was declined, so nothing changed.", |
diff --git a/internal/console/billingpage_test.go b/internal/console/billingpage_test.go| index cd4008699..92a894a62 100644 |
| --- a/internal/console/billingpage_test.go |
| +++ b/internal/console/billingpage_test.go |
| @@ -22,6 +22,7 @@ import ( |
| func TestDecideBillingPage(t *testing.T) { |
| now := billingNow |
| + sponsored := sponsorUnlimited() |
| paid := func(mod func(b *billingAccount)) *billingAccount { |
| b := &billingAccount{Customer: "cus_1", Subscription: "sub_1", State: billing.StatePaid, Live: true, Currency: "usd", PeriodEnd: periodEnd} |
| if mod != nil { |
| @@ -52,8 +53,9 @@ func TestDecideBillingPage(t *testing.T) { |
| "notice.problem", []string{"portal"}}, |
| {"another problem, unbound", billingPageInput{Ready: true, Problems: []string{problemUnknownCustomer}}, "notice.problem", nil}, |
| {"operator row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "business", Source: PlanSourceOperator}, Billing: free, |
| - Op: op(opUnresolved)}, "notice.operator_plan", nil}, |
| - {"sponsored row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored}}, "notice.operator_plan", nil}, |
| + Op: op(opUnresolved)}, "notice.operator_plan", []string{"portal"}}, |
| + {"sponsored row", billingPageInput{Ready: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored, Sponsored: &sponsored}}, "notice.operator_plan", nil}, |
| + {"sponsored with buying enabled", billingPageInput{Ready: true, CanBuyDomains: true, Row: &AccountPlanRow{Plan: "free", Source: PlanSourceSponsored, Sponsored: &sponsored}}, "notice.operator_plan", []string{"card"}}, |
| {"op unresolved", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opUnresolved)}, |
| "notice.confirming", []string{"confirm", "portal"}}, |
| {"op sending", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opSending)}, |
| @@ -68,7 +70,7 @@ func TestDecideBillingPage(t *testing.T) { |
| "notice.checkout_open", []string{"continue", "start_over"}}, |
| {"intent creating", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCreating)}, |
| "notice.settling", []string{"confirm"}}, |
| - {"not live", billingPageInput{Ready: true, Billing: free}, "", []string{"buy"}}, |
| + {"not live", billingPageInput{Ready: true, Billing: free}, "", []string{"buy", "portal"}}, |
| {"no billing row", billingPageInput{Ready: true}, "", []string{"buy"}}, |
| {"intent open but live", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Intent: intent(intentOpen)}, |
| "", []string{"change", "stop", "portal"}}, |
| @@ -82,9 +84,9 @@ func TestDecideBillingPage(t *testing.T) { |
| "notice.seat_drift", []string{"match_seats", "change", "stop", "portal"}}, |
| {"paid", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil)}, "", []string{"change", "stop", "portal"}}, |
| // Terminal intents are ignored, whatever their state. |
| - {"intent completed", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCompleted)}, "", []string{"buy"}}, |
| - {"intent expired", billingPageInput{Ready: true, Billing: free, Intent: intent(intentExpired)}, "", []string{"buy"}}, |
| - {"intent abandoned", billingPageInput{Ready: true, Billing: free, Intent: intent(intentAbandoned)}, "", []string{"buy"}}, |
| + {"intent completed", billingPageInput{Ready: true, Billing: free, Intent: intent(intentCompleted)}, "", []string{"buy", "portal"}}, |
| + {"intent expired", billingPageInput{Ready: true, Billing: free, Intent: intent(intentExpired)}, "", []string{"buy", "portal"}}, |
| + {"intent abandoned", billingPageInput{Ready: true, Billing: free, Intent: intent(intentAbandoned)}, "", []string{"buy", "portal"}}, |
| // A settled operation is not outstanding. |
| {"op applied", billingPageInput{Ready: true, Row: billingRow, Billing: paid(nil), Op: op(opApplied)}, "", []string{"change", "stop", "portal"}}, |
| } |
diff --git a/internal/console/billingstore.go b/internal/console/billingstore.go| index 1d14d8c65..178f88c00 100644 |
| --- a/internal/console/billingstore.go |
| +++ b/internal/console/billingstore.go |
| @@ -380,28 +380,40 @@ func (s *Store) BillingAccountByCustomer(customer string) (*billingAccount, erro |
| } |
| // SetBillingCustomer binds the account's provider customer. Binding the |
| -// same customer again is a no-op; a customer bound to another account, or |
| -// a second customer for this one, is an error. |
| -func (s *Store) SetBillingCustomer(accountID int64, customer string, now time.Time) error { |
| +// same customer preserves its binding time. An optional currency fixes an |
| +// unset currency in the same write, including for an existing card customer. |
| +// A different customer or fixed currency is refused. |
| +func (s *Store) SetBillingCustomer(accountID int64, customer string, now time.Time, currency ...string) error { |
| + fix := "" |
| + if len(currency) > 0 { |
| + fix = currency[0] |
| + } |
| if customer == "" { |
| return errors.New("billing: empty customer") |
| } |
| - res, err := s.db.Exec(`INSERT INTO billing_accounts (account_id, customer, synced_at, bound_at) VALUES (?, ?, ?, ?) |
| - ON CONFLICT(account_id) DO UPDATE SET customer = excluded.customer, bound_at = excluded.bound_at WHERE billing_accounts.customer = ''`, |
| - accountID, customer, now.Unix(), now.Unix()) |
| + res, err := s.db.Exec(`INSERT INTO billing_accounts (account_id, customer, synced_at, bound_at, currency) VALUES (?, ?, ?, ?, ?) |
| + ON CONFLICT(account_id) DO UPDATE SET customer = excluded.customer, |
| + bound_at = CASE WHEN billing_accounts.customer = '' THEN excluded.bound_at ELSE billing_accounts.bound_at END, |
| + currency = CASE WHEN billing_accounts.currency = '' THEN excluded.currency ELSE billing_accounts.currency END |
| + WHERE (billing_accounts.customer = '' OR billing_accounts.customer = excluded.customer) |
| + AND (excluded.currency = '' OR billing_accounts.currency = '' OR billing_accounts.currency = excluded.currency)`, |
| + accountID, customer, now.Unix(), now.Unix(), fix) |
| if err != nil { |
| return err |
| } |
| if n, err := res.RowsAffected(); err != nil || n == 1 { |
| return err |
| } |
| - var bound string |
| - if err := s.db.QueryRow(`SELECT customer FROM billing_accounts WHERE account_id = ?`, accountID).Scan(&bound); err != nil { |
| + var bound, fixed string |
| + if err := s.db.QueryRow(`SELECT customer, currency FROM billing_accounts WHERE account_id = ?`, accountID).Scan(&bound, &fixed); err != nil { |
| return err |
| } |
| if bound != customer { |
| return errors.New("billing: the account already has another customer") |
| } |
| + if fix != "" && fixed != fix { |
| + return currencyFixedRefusal{Currency: fixed} |
| + } |
| return nil |
| } |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 169eab9a9..a666128a5 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -1399,6 +1399,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route POST /billing/webhook": claimNonApp("re-reads a billing subscription and writes the account's plan row, billing state and billing problems; names no app"), |
| // Plans 6b: the locked portal opens a provider portal session for the |
| // account's customer and writes nothing locally. |
| + "route POST /a/{sqid}/billing/card": claimNonApp("creates or reuses the account billing customer and opens a card setup session; writes only account billing state and names no app"), |
| "route POST /a/{sqid}/billing/portal": claimNonApp("opens a provider portal session for the account's customer and redirects the owner to it, writing nothing locally; names no app"), |
| // Plans 6b: an owner's Confirm now finishes an outstanding billing |
| // operation under the account's billing hold and refreshes the |
diff --git a/internal/console/claim_invariant_probes_nonapp_test.go b/internal/console/claim_invariant_probes_nonapp_test.go| index 723a3d270..6c3830f57 100644 |
| --- a/internal/console/claim_invariant_probes_nonapp_test.go |
| +++ b/internal/console/claim_invariant_probes_nonapp_test.go |
| @@ -22,13 +22,16 @@ import ( |
| "github.com/carlosframework/platform/internal/appconfig" |
| "github.com/carlosframework/platform/internal/billing" |
| "github.com/carlosframework/platform/internal/billing/billingtest" |
| + "github.com/carlosframework/platform/internal/domainreg" |
| "github.com/carlosframework/platform/internal/economics" |
| "github.com/carlosframework/platform/internal/geoip" |
| "github.com/carlosframework/platform/internal/infraview" |
| "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/registrar/registrartest" |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/seeds" |
| "github.com/carlosframework/platform/internal/telemetry" |
| + "github.com/carlosframework/platform/internal/zonehost/zonehosttest" |
| ) |
| // claimProbes is every read, nonApp and worker probe, merged. A key in two |
| @@ -914,6 +917,31 @@ var claimNonAppProbes = map[string]claimProbe{ |
| return claimBillingPlanIs(t, cx, "personal") |
| }, |
| }, |
| + "route POST /a/{sqid}/billing/card": { |
| + setup: func(t *testing.T, cx *claimCase) { |
| + claimCheckoutWorld(t, cx) |
| + cx.srv.cfg.Registrar = registrartest.New() |
| + cx.srv.cfg.ZoneHost = zonehosttest.New("ns1.example.test") |
| + cx.srv.cfg.DomainCatalog = &domainreg.Catalog{DailyCap: 3} |
| + sponsored := sponsorUnlimited() |
| + if _, err := cx.st.SetAccountPlan(OpsAccountID, "free", nil, 0, PlanSourceSponsored, &sponsored, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + }, |
| + do: claimFormReply("/a/bab/billing/card"), |
| + status: http.StatusSeeOther, loc: "https://checkout.example.test/c/", |
| + effect: func(t *testing.T, cx *claimCase, r claimReply) string { |
| + fake := cx.srv.billing.cfg.Provider.(*billingtest.Fake) |
| + fake.Lock() |
| + defer fake.Unlock() |
| + for _, p := range fake.Sent { |
| + if p.Kind == billing.PreparedSetupCheckout { |
| + return "" |
| + } |
| + } |
| + return "no card setup session was created" |
| + }, |
| + }, |
| "route POST /a/{sqid}/billing/portal": { |
| setup: claimBillingWorld, |
| do: claimFormReply("/a/bab/billing/portal"), |
diff --git a/internal/console/domainbuy.go b/internal/console/domainbuy.go| index 971e829a5..cc0436649 100644 |
| --- a/internal/console/domainbuy.go |
| +++ b/internal/console/domainbuy.go |
| @@ -36,11 +36,14 @@ func domainBuyUnavailable() *doorRefusal { |
| // Other holders may only produce the neutral refusal: |
| // name-only refusals and the shared budget come first, then registrar availability, |
| // then the claim/live checks, and finally premium and price checks. |
| -func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) (domainreg.Quote, *doorRefusal) { |
| +func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string, country ...string) (domainreg.Quote, *doorRefusal) { |
| if !s.domainBuyReady() { |
| return domainreg.Quote{}, &doorRefusal{Status: http.StatusNotFound} |
| } |
| if ref := s.customDomainRefusal(acct, name); ref != nil { |
| + if ref.Status == http.StatusConflict { |
| + return domainreg.Quote{}, domainBuyStateRefusal("plan", http.StatusConflict) |
| + } |
| return domainreg.Quote{}, ref |
| } |
| name, err := domainreg.Normalize(name) |
| @@ -55,20 +58,37 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) |
| return domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount}, nil |
| } |
| b, err := s.store.BillingAccount(acct.ID) |
| - if err != nil || b == nil || b.Currency == "" || b.Customer == "" { |
| - return domainreg.Quote{}, domainBuyUnavailable() |
| + if err != nil { |
| + return domainreg.Quote{}, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| + } |
| + currency := "" |
| + if b != nil { |
| + currency = b.Currency |
| + } |
| + if currency == "" { |
| + location := "" |
| + if len(country) > 0 { |
| + location = country[0] |
| + } |
| + currency, err = s.billing.cfg.Book.ChooseCurrency("", location) |
| + if err != nil { |
| + return domainreg.Quote{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity) |
| + } |
| } |
| suffix, _ := publicsuffix.PublicSuffix(name) |
| tld, offered := s.cfg.DomainCatalog.TLDs[suffix] |
| - if !offered || tld.Register[b.Currency] <= 0 { |
| + if !offered { |
| return domainreg.Quote{}, domainBuyErrorRefusal(domainreg.ErrTLDNotOffered) |
| } |
| + if tld.Register[currency] <= 0 { |
| + return domainreg.Quote{}, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity) |
| + } |
| if !s.domainChecks.allow(acct.ID) { |
| return domainreg.Quote{}, &doorRefusal{http.StatusTooManyRequests, domainBuyCopy["rate"]} |
| } |
| a, err := s.cfg.Registrar.Check(ctx, name) |
| if err != nil { |
| - return domainreg.Quote{}, domainBuyErrorRefusal(err) |
| + return domainreg.Quote{}, s.domainBuyRegistrarRefusal(ctx, acct, name, err) |
| } |
| if !a.Available { |
| return domainreg.Quote{}, claimRefusal(name, domains.ErrHostUnavailable) |
| @@ -95,7 +115,7 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) |
| if ref := s.liveDomainPurchaseRefusal(ctx, name); ref != nil { |
| return domainreg.Quote{}, ref |
| } |
| - q, err := s.cfg.DomainCatalog.Quote(name, b.Currency, a) |
| + q, err := s.cfg.DomainCatalog.Quote(name, currency, a) |
| if errors.Is(err, domainreg.ErrCostAboveCeiling) { |
| s.purchaseRefusalAlert(ctx, acct, name, "cost:"+suffix, "registrar cost above ceiling") |
| } |
| @@ -105,46 +125,84 @@ func (s *Server) admitDomainBuy(ctx context.Context, acct *Account, name string) |
| return q, nil |
| } |
| -func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) { |
| +// A non-nil third result supplies the replacement quote for confirmation. |
| +func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string, confirmed domainreg.Quote) (*DomainPurchase, string, *domainreg.Quote, *doorRefusal) { |
| // Serialize starts so a concurrent buyer resumes the winning checkout. |
| defer s.planLock(acct)() |
| - q, ref := s.admitDomainBuy(ctx, acct, name) |
| + q, ref := s.admitDomainBuy(ctx, acct, name, c.Country) |
| if ref != nil { |
| - return nil, "", ref |
| + return nil, "", nil, ref |
| } |
| name = q.Domain |
| own, err := s.ownLiveDomainPurchase(ctx, acct.ID, name) |
| if err != nil { |
| - return nil, "", domainBuyUnavailable() |
| + return nil, "", nil, domainBuyUnavailable() |
| } |
| if own != nil { |
| - return s.resumeDomainPurchase(ctx, own) |
| + if confirmed.Currency != q.Currency || confirmed.Price != q.Price { |
| + return nil, "", &q, domainBuyStateRefusal("priceChanged", http.StatusConflict) |
| + } |
| + p, link, ref := s.resumeDomainPurchase(ctx, own) |
| + return p, link, nil, ref |
| } |
| exists, err := s.store.HasAppIn(acct.ID, app) |
| if err != nil { |
| - return nil, "", domainBuyUnavailable() |
| + return nil, "", nil, domainBuyUnavailable() |
| } |
| if !exists { |
| - return nil, "", &doorRefusal{Status: http.StatusNotFound} |
| + return nil, "", nil, &doorRefusal{Status: http.StatusNotFound} |
| } |
| if err := c.Validate(); err != nil { |
| - return nil, "", &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]} |
| + return nil, "", nil, &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]} |
| + } |
| + h, release, err := s.holdBilling(acct) |
| + if err != nil { |
| + return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| + } |
| + // Choose and confirm under the same hold that creates the customer. A |
| + // subscription may have fixed currency since admission read the account. |
| + b, err := s.store.BillingAccount(acct.ID) |
| + if err != nil { |
| + release() |
| + return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| + } |
| + if b != nil && b.Currency != "" { |
| + q.Currency = b.Currency |
| + } |
| + q.Price = s.cfg.DomainCatalog.TLDs[q.TLD].Register[q.Currency] |
| + if q.Price <= 0 { |
| + release() |
| + return nil, "", nil, domainBuyStateRefusal("currency", http.StatusUnprocessableEntity) |
| + } |
| + if confirmed.Currency != q.Currency || confirmed.Price != q.Price { |
| + release() |
| + return nil, "", &q, domainBuyStateRefusal("priceChanged", http.StatusConflict) |
| } |
| count, err := s.store.PurchasesToday(acct.ID, time.Now()) |
| if err != nil { |
| - return nil, "", domainBuyUnavailable() |
| + release() |
| + return nil, "", nil, domainBuyUnavailable() |
| } |
| if count >= s.cfg.DomainCatalog.DailyCap { |
| - return nil, "", &doorRefusal{http.StatusTooManyRequests, domainPurchaseCopy.DailyCap} |
| + release() |
| + return nil, "", nil, &doorRefusal{http.StatusTooManyRequests, domainPurchaseCopy.DailyCap} |
| } |
| balance, err := s.cfg.Registrar.Balance(ctx) |
| if err != nil { |
| - return nil, "", domainBuyErrorRefusal(err) |
| + release() |
| + return nil, "", nil, s.domainBuyRegistrarRefusal(ctx, acct, name, err) |
| } |
| if balance.Currency != q.Cost.Currency || balance.Minor < q.Cost.Minor { |
| s.purchaseRefusalAlert(ctx, acct, name, "balance", "registrar balance") |
| - return nil, "", domainBuyUnavailable() |
| + release() |
| + return nil, "", nil, domainBuyUnavailable() |
| + } |
| + _, err = s.paymentCustomerLocked(h, s.billingClock(ctx), acct, c.Country, c.PostalCode, true) |
| + release() |
| + if err != nil { |
| + log.Printf("console: domain buy billing %s: %v", acct.Sqid, err) |
| + return nil, "", nil, domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| } |
| now := time.Now().UTC() |
| p := DomainPurchase{ID: newDomainPurchaseID(), AccountID: acct.ID, Domain: q.Domain, App: app, Currency: q.Currency, Amount: q.Price, |
| @@ -154,17 +212,23 @@ func (s *Server) startDomainPurchase(ctx context.Context, acct *Account, app, na |
| if errors.Is(err, ErrDomainPurchaseLive) { |
| own, readErr := s.ownLiveDomainPurchase(ctx, acct.ID, name) |
| if readErr != nil { |
| - return nil, "", domainBuyUnavailable() |
| + return nil, "", nil, domainBuyUnavailable() |
| } |
| if own != nil { |
| - return s.resumeDomainPurchase(ctx, own) |
| + if confirmed.Currency != own.Currency || confirmed.Price != own.Amount { |
| + changed := domainreg.Quote{Domain: own.Domain, Currency: own.Currency, Price: own.Amount} |
| + return nil, "", &changed, domainBuyStateRefusal("priceChanged", http.StatusConflict) |
| + } |
| + p, link, ref := s.resumeDomainPurchase(ctx, own) |
| + return p, link, nil, ref |
| } |
| - return nil, "", claimRefusal(name, domains.ErrHostUnavailable) |
| + return nil, "", nil, claimRefusal(name, domains.ErrHostUnavailable) |
| } |
| if err != nil { |
| - return nil, "", domainBuyUnavailable() |
| + return nil, "", nil, domainBuyUnavailable() |
| } |
| - return s.resumeDomainPurchase(ctx, &p) |
| + purchase, link, ref := s.resumeDomainPurchase(ctx, &p) |
| + return purchase, link, nil, ref |
| } |
| func (s *Server) ownLiveDomainPurchase(ctx context.Context, account int64, name string) (*DomainPurchase, error) { |
| @@ -183,6 +247,16 @@ func (s *Server) resumeDomainPurchase(ctx context.Context, p *DomainPurchase) (* |
| } |
| if err != nil { |
| log.Printf("console: purchase %s: checkout: %v", p.ID, err) |
| + if errors.Is(err, registrar.ErrSetup) { |
| + acct, readErr := s.store.AccountByID(p.AccountID) |
| + if readErr == nil && acct != nil { |
| + s.domainBuyRegistrarRefusal(ctx, acct, p.Domain, err) |
| + } |
| + return p, "", domainBuyUnavailable() |
| + } |
| + if p.State == PurchaseFailed && p.Reason == "payment_setup" { |
| + return p, "", domainBuyStateRefusal("billingSetup", http.StatusServiceUnavailable) |
| + } |
| if p.State == PurchaseFailed && p.Reason == "contact" { |
| return p, "", &doorRefusal{http.StatusUnprocessableEntity, domainBuyCopy["contactError"]} |
| } |
| @@ -271,7 +345,7 @@ func (s *Server) purchaseCheckoutStep(ctx context.Context, p *DomainPurchase) (s |
| } |
| handle, err := s.cfg.Registrar.EnsureContact(ctx, existing, p.Contact) |
| if err != nil { |
| - if errors.Is(err, registrar.ErrRefused) { |
| + if errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrSetup) { |
| return "", errors.Join(err, s.movePurchase(ctx, p, PurchaseFailed, func(p *DomainPurchase) { p.Reason = "contact" })) |
| } |
| return "", err |
| @@ -613,6 +687,12 @@ func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error |
| if err == nil { |
| return s.registeredPurchase(ctx, p, r) |
| } |
| + if errors.Is(err, registrar.ErrSetup) { |
| + acct, readErr := s.store.AccountByID(p.AccountID) |
| + if readErr == nil && acct != nil { |
| + s.domainBuyRegistrarRefusal(ctx, acct, p.Domain, err) |
| + } |
| + } |
| if p.Attempts > 1 { |
| // Any earlier attempt may have registered it. Even a definite refusal of this request cannot disprove that. |
| r, found, readErr := s.cfg.Registrar.Lookup(ctx, p.Domain) |
| @@ -627,7 +707,7 @@ func (s *Server) registerPurchase(ctx context.Context, p *DomainPurchase) error |
| reason := "" |
| if errors.Is(err, registrar.ErrUnavailable) { |
| reason = "taken" |
| - } else if errors.Is(err, registrar.ErrRefused) { |
| + } else if errors.Is(err, registrar.ErrRefused) || errors.Is(err, registrar.ErrSetup) { |
| reason = "refused" |
| } |
| if reason == "" { |
diff --git a/internal/console/domainbuy_admission_test.go b/internal/console/domainbuy_admission_test.go| index 935ded5ee..9db74fc56 100644 |
| --- a/internal/console/domainbuy_admission_test.go |
| +++ b/internal/console/domainbuy_admission_test.go |
| @@ -22,7 +22,7 @@ func TestBuyAdmissionNeutralityGuard(t *testing.T) { |
| {name: "offered", suffix: "com", status: 409, checks: 8}, |
| {name: "outside-catalog", suffix: "io", key: "notOffered", status: 422}, |
| {name: "non-registrable", suffix: "shop.com", key: "nameError", status: 422}, |
| - {name: "missing-currency", suffix: "com", key: "notOffered", status: 422}, |
| + {name: "missing-currency", suffix: "com", key: "currency", status: 422}, |
| {name: "held-premium", suffix: "com", status: 409, checks: 8, premium: true}, |
| {name: "held-high-cost", suffix: "com", status: 409, checks: 8}, |
| {name: "registered-premium", suffix: "com", status: 409, checks: 8, premium: true}, |
diff --git a/internal/console/domainbuy_copy.go b/internal/console/domainbuy_copy.go| index 5e91517e2..446186a02 100644 |
| --- a/internal/console/domainbuy_copy.go |
| +++ b/internal/console/domainbuy_copy.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "errors" |
| "log" |
| "net/http" |
| @@ -14,6 +15,13 @@ import ( |
| // docs/superpowers/specs/LUNA-COPY-RESULT-DOMAINS-1.md, plus controller rulings |
| // on four flags. Apply later edits through a copy pass. |
| var domainBuyCopy = map[string]string{ |
| + // Approved by delegation (reviewer), 2026-11-03. |
| + "priceChanged": "the price is different from the one you confirmed. confirm the new price to continue", |
| + "plan": capMessage("cli.cap.custom_domain"), // Existing approved plan refusal. |
| + // Approved by delegation (Luna), 2026-11-03: domain registration Plan 2, slice 1. |
| + "billingSetup": "we could not set up billing for your account. try again later", |
| + "currency": "we could not find a price for this domain in your account currency", |
| + |
| "title": "Buy a domain", |
| "name": "Domain", |
| "check": "Check availability", |
| @@ -89,3 +97,14 @@ var domainPurchaseCopy = struct { |
| OperatorSubject: "Domain purchase needs attention", |
| OperatorBody: "Domain: %s\nPurchase: %s\nAccount: %s\nReason: %s\n", |
| } |
| + |
| +func domainBuyStateRefusal(key string, status int) *doorRefusal { |
| + return &doorRefusal{status, domainBuyCopy[key]} |
| +} |
| + |
| +func (s *Server) domainBuyRegistrarRefusal(ctx context.Context, acct *Account, name string, err error) *doorRefusal { |
| + if errors.Is(err, registrar.ErrSetup) { |
| + s.purchaseRefusalAlert(ctx, acct, name, "registrar-setup", err.Error()) |
| + } |
| + return domainBuyErrorRefusal(err) |
| +} |
diff --git a/internal/console/domainbuy_final_fix_test.go b/internal/console/domainbuy_final_fix_test.go| index c4f43d1f0..41e17d286 100644 |
| --- a/internal/console/domainbuy_final_fix_test.go |
| +++ b/internal/console/domainbuy_final_fix_test.go |
| @@ -66,7 +66,7 @@ func TestOwnLivePurchaseResumes(t *testing.T) { |
| } |
| f.srv.cfg.DomainCatalog.DailyCap = 1 |
| before := len(f.fake.Sent) |
| - status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"SHOP.COM.","app":"kass"}`) |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"SHOP.COM.","app":"kass","currency":"usd","price":1500}`) |
| var got struct { |
| ID string |
| State PurchaseState |
| @@ -88,11 +88,11 @@ func TestOwnLivePurchaseResumes(t *testing.T) { |
| func TestOwnLostCheckoutResumes(t *testing.T) { |
| f := newPurchaseFixture(t) |
| f.fake.LoseNextResponse = true |
| - p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + p, _, _ := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| if p == nil { |
| t.Fatal("missing journal") |
| } |
| - status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass"}`) |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass","currency":"usd","price":1500}`) |
| if status != 200 || !strings.Contains(body, p.ID) || !strings.Contains(body, `"checkout_url":"https://`) { |
| t.Fatalf("resume: %d %s", status, body) |
| } |
| @@ -125,7 +125,7 @@ func TestCheckoutCancelPageOffersContinue(t *testing.T) { |
| 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"}} |
| + 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) |
| if status != 303 || loc != info.URL { |
| t.Fatalf("browser resume: %d %s", status, loc) |
| @@ -291,7 +291,7 @@ func TestPurchaseRefusalAlertsRateLimited(t *testing.T) { |
| alerts := 0 |
| pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil } |
| for _, name := range []string{"shop.com", "other.com", "shop.net", "shop.com"} { |
| - _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", name, purchaseContact(), "buyer") |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", name, purchaseContact(), "buyer") |
| if ref == nil || ref.Status != 503 { |
| t.Fatalf("refusal: %+v", ref) |
| } |
diff --git a/internal/console/domainbuy_fix_test.go b/internal/console/domainbuy_fix_test.go| index 70c884cb4..c7001b533 100644 |
| --- a/internal/console/domainbuy_fix_test.go |
| +++ b/internal/console/domainbuy_fix_test.go |
| @@ -133,7 +133,7 @@ func TestCatalogErrorsNeverReachCustomers(t *testing.T) { |
| status int |
| err error |
| }{ |
| - {"missing-currency", "shop.com", "notOffered", 422, nil}, |
| + {"missing-currency", "shop.com", "currency", 422, nil}, |
| {"not-registrable", "www.shop.com", "nameError", 422, nil}, |
| {"wrapped-catalog", "shop.com", "notOffered", 422, fmt.Errorf("private: %w", domainreg.ErrTLDNotOffered)}, |
| {"wrapped-name", "shop.com", "nameError", 422, fmt.Errorf("private: %w", domainreg.ErrNotRegistrable)}, |
| @@ -232,7 +232,7 @@ func TestCheckLimiterPerAccountAndDeployment(t *testing.T) { |
| t.Fatal(err) |
| } |
| for j := 0; j < 20; j++ { |
| - _, ref := f.srv.checkDomainBuy(context.Background(), acct, "shop.com") |
| + _, ref := f.srv.checkDomainBuy(context.Background(), acct, "shop.com", "") |
| if i < 5 && ref != nil { |
| t.Fatalf("deployment %d/%d: %+v", i, j, ref) |
| } |
| @@ -255,7 +255,7 @@ func TestHeldElsewhereLogsNoAlert(t *testing.T) { |
| old := log.Writer() |
| log.SetOutput(&logs) |
| defer log.SetOutput(old) |
| - _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| if ref == nil || ref.Status != 409 { |
| t.Fatalf("refusal: %+v", ref) |
| } |
diff --git a/internal/console/domainbuy_nosub_test.go b/internal/console/domainbuy_nosub_test.go| new file mode 100644 |
| index 000000000..df84aca35 |
| --- /dev/null |
| +++ b/internal/console/domainbuy_nosub_test.go |
| @@ -0,0 +1,269 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/domains" |
| + "github.com/carlosframework/platform/internal/registrar" |
| + "github.com/carlosframework/platform/internal/registry" |
| +) |
| + |
| +func firstPurchaseAccount(t *testing.T, f *purchaseFixture) { |
| + t.Helper() |
| + f.acct = planAccount(t, f.consoleFixture, 503) |
| + sponsored := sponsorUnlimited() |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceSponsored, &sponsored, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := f.st.CreateAppIn(f.acct.ID, "kass", "buyer@example.test", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + tld := f.srv.cfg.DomainCatalog.TLDs["com"] |
| + tld.Register = map[string]int64{"usd": 1500, "eur": 1600, "gbp": 1700} |
| + f.srv.cfg.DomainCatalog.TLDs["com"] = tld |
| +} |
| + |
| +func TestPurchaseWithoutSubscription(t *testing.T) { |
| + for _, country := range []string{"IE", "GB", "US"} { |
| + t.Run(country, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + c := purchaseContact() |
| + c.Country = country |
| + p, link, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", c, "buyer@example.test") |
| + if ref != nil || p == nil || link == "" { |
| + t.Fatalf("start: %+v %q %+v", p, link, ref) |
| + } |
| + currency, _ := f.srv.billing.cfg.Book.ChooseCurrency("", country) |
| + b, err := f.st.BillingAccount(f.acct.ID) |
| + if err != nil || b == nil || b.Customer == "" || b.Currency != currency || p.Currency != currency || b.Subscription != "" { |
| + t.Fatalf("billing/purchase currency: %+v %+v %v", b, p, err) |
| + } |
| + if p.Amount != f.srv.cfg.DomainCatalog.TLDs["com"].Register[currency] { |
| + t.Fatalf("wrong quote: %+v", p) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatal("expected exactly one customer create") |
| + } |
| + for _, req := range f.fake.Sent { |
| + if req.Kind == billing.PreparedCustomer { |
| + var body map[string]any |
| + if err := json.Unmarshal(req.Body, &body); err != nil { |
| + t.Fatal(err) |
| + } |
| + details, _ := body["details"].(map[string]any) |
| + if details["Country"] != country || details["PostalCode"] != c.PostalCode || details["Email"] != "owner"+f.acct.Sqid+"@example.com" { |
| + t.Fatalf("customer details: %v", details) |
| + } |
| + } |
| + } |
| + if ref := f.srv.customDomainRefusal(f.acct, "shop.com"); ref != nil { |
| + t.Fatalf("sponsored attach refused: %+v", ref) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPurchaseConcurrentFirstCustomer(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + f.reg.Available["second.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + var wg sync.WaitGroup |
| + errs := make(chan *doorRefusal, 2) |
| + for _, name := range []string{"shop.com", "second.com"} { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", name, purchaseContact(), "buyer@example.test") |
| + errs <- ref |
| + }() |
| + } |
| + wg.Wait() |
| + close(errs) |
| + for ref := range errs { |
| + if ref != nil { |
| + t.Fatalf("start: %+v", ref) |
| + } |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatalf("customer creates: %d", f.sent(billing.PreparedCustomer)) |
| + } |
| +} |
| + |
| +func TestPurchaseOwnStateReasons(t *testing.T) { |
| + for _, reason := range []string{"billingSetup", "currency", "plan", "daily"} { |
| + t.Run(reason, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + switch reason { |
| + case "billingSetup": |
| + firstPurchaseAccount(t, f) |
| + f.fake.Err = billing.ErrRefused |
| + case "currency": |
| + tld := f.srv.cfg.DomainCatalog.TLDs["com"] |
| + tld.Register = map[string]int64{"eur": 1500} |
| + f.srv.cfg.DomainCatalog.TLDs["com"] = tld |
| + case "plan": |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "daily": |
| + f.srv.cfg.DomainCatalog.DailyCap = 1 |
| + f.start(t) |
| + f.reg.Available["second.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + } |
| + name := "shop.com" |
| + if reason == "daily" { |
| + name = "second.com" |
| + } |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", name, purchaseContact(), "buyer@example.test") |
| + if ref == nil || ref.Msg == domainBuyCopy["unavailable"] || strings.TrimSpace(ref.Msg) == "" { |
| + t.Fatalf("%s: %+v", reason, ref) |
| + } |
| + if reason == "currency" && !strings.Contains(ref.Msg, "currency") { |
| + t.Fatalf("missing currency reason: %+v", ref) |
| + } |
| + if reason != "daily" && f.sent(billing.PreparedPaymentCheckout) != 0 { |
| + t.Fatal("refusal created checkout") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPurchaseWithoutSubscriptionRefusalsHaveNoCustomer(t *testing.T) { |
| + for _, cause := range []string{"contact", "held", "currency", "balance"} { |
| + t.Run(cause, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + c := purchaseContact() |
| + switch cause { |
| + case "contact": |
| + c.FirstName = "" |
| + case "held": |
| + holdBuyName(t, f, "shop.com") |
| + case "currency": |
| + tld := f.srv.cfg.DomainCatalog.TLDs["com"] |
| + tld.Register = map[string]int64{"gbp": 1500} |
| + f.srv.cfg.DomainCatalog.TLDs["com"] = tld |
| + case "balance": |
| + f.reg.BalanceMoney.Minor = 0 |
| + } |
| + p, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", c, "buyer@example.test") |
| + if p != nil || ref == nil { |
| + t.Fatalf("expected refusal: %+v %+v", p, ref) |
| + } |
| + if b, err := f.st.BillingAccount(f.acct.ID); err != nil || b != nil { |
| + t.Fatalf("refusal wrote billing: %+v %v", b, err) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 0 || f.sent(billing.PreparedPaymentCheckout) != 0 || purchaseCalls(f.reg.Calls, "contact:") != 0 { |
| + t.Fatal("refusal made side effects") |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPurchaseKeepsFirstCurrency(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + first := f.start(t) |
| + f.reg.Available["second.com"] = registrar.Availability{Available: true, Cost: registrar.Money{Currency: "usd", Minor: 900}} |
| + c := purchaseContact() |
| + c.Country = "GB" |
| + p, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "second.com", c, "buyer@example.test") |
| + if ref != nil || p == nil || p.Currency != first.Currency || p.Amount != first.Amount { |
| + t.Fatalf("currency moved: %+v %+v %+v", first, p, ref) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatal("second customer created") |
| + } |
| +} |
| + |
| +func TestPurchaseAndCardShareCustomer(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + var wg sync.WaitGroup |
| + wg.Add(2) |
| + errs := make(chan error, 1) |
| + refs := make(chan *doorRefusal, 1) |
| + go func() { |
| + defer wg.Done() |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + refs <- ref |
| + }() |
| + go func() { |
| + defer wg.Done() |
| + h, release, err := f.srv.holdBilling(f.acct) |
| + if err != nil { |
| + errs <- err |
| + return |
| + } |
| + defer release() |
| + _, err = f.srv.cardSetupLocked(h, f.srv.billingClock(context.Background()), f.acct) |
| + errs <- err |
| + }() |
| + wg.Wait() |
| + if err := <-errs; err != nil { |
| + t.Fatal(err) |
| + } |
| + if ref := <-refs; ref != nil { |
| + t.Fatalf("purchase: %+v", ref) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatalf("customer creates: %d", f.sent(billing.PreparedCustomer)) |
| + } |
| +} |
| + |
| +func TestPurchaseSponsoredReachesAttached(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + f.srv.cfg.Registry = attachRegistry(t, registry.Route{Host: "app.example.test", Account: f.acct.Sqid, App: "kass", Kind: "static", Status: "ready", Channel: "canary/live"}) |
| + p := f.start(t) |
| + f.authorise(t, p) |
| + f.until(t, p.ID, PurchaseDone) |
| + for _, host := range []string{p.Domain, "www." + p.Domain} { |
| + claim, err := domains.GetClaim(context.Background(), f.rel, host) |
| + if err != nil || claim.Account != f.acct.Sqid || claim.App != "kass" { |
| + t.Fatalf("sponsored attachment: %+v %v", claim, err) |
| + } |
| + } |
| + row, err := f.st.AccountPlan(f.acct.ID) |
| + if err != nil || row.Source != PlanSourceSponsored || row.Plan != "free" { |
| + t.Fatalf("plan changed: %+v %v", row, err) |
| + } |
| +} |
| + |
| +func TestPaymentCustomerRefusesConflictingSubscriptionCurrency(t *testing.T) { |
| + for _, state := range []string{intentOpen, intentCompleted} { |
| + t.Run(state, func(t *testing.T) { |
| + o := newCheckoutFixture(t, false) |
| + r := o.checkout(t, "plan", "personal", "currency", "usd") |
| + if r.Status != 303 || r.Flash != "" { |
| + t.Fatalf("checkout: %+v", r) |
| + } |
| + ci := o.intent(t) |
| + ci.State = state |
| + if err := o.st.PutCheckoutIntent(*ci); err != nil { |
| + t.Fatal(err) |
| + } |
| + sent := len(o.fake.Sent) |
| + h, release, err := o.srv.holdBilling(o.acct) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer release() |
| + _, err = o.srv.paymentCustomerLocked(h, o.srv.billingClock(context.Background()), o.acct, "IE", "D01 A123", true) |
| + if err != errCheckoutUncertain { |
| + t.Fatalf("conflicting subscription: %v", err) |
| + } |
| + b, err := o.st.BillingAccount(o.acct.ID) |
| + if err != nil || b.Currency != "" || len(o.fake.Sent) != sent { |
| + t.Fatalf("conflict wrote billing or sent requests: %+v %v", b, err) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/domainbuy_registry_test.go b/internal/console/domainbuy_registry_test.go| new file mode 100644 |
| index 000000000..9a70eb2f1 |
| --- /dev/null |
| +++ b/internal/console/domainbuy_registry_test.go |
| @@ -0,0 +1,54 @@ |
| +package console |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "fmt" |
| + "log" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/registrar/openprovider" |
| +) |
| + |
| +func TestPurchaseRegistryErrors(t *testing.T) { |
| + for _, code := range []int{399, 309, 19010} { |
| + t.Run(fmt.Sprint(code), func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + const message = "Nameserver creation or update failed: Parent domain does not exist for host" |
| + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path == "/v1/auth/login" { |
| + fmt.Fprint(w, `{"code":0,"data":{"token":"test-token"}}`) |
| + return |
| + } |
| + fmt.Fprintf(w, `{"code":%d,"desc":%q}`, code, message) |
| + })) |
| + defer ts.Close() |
| + reg, err := openprovider.New(openprovider.Config{BaseURL: ts.URL + "/v1", Username: "test-user", Password: "test-pass", HTTP: ts.Client()}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + f.srv.cfg.Registrar = reg |
| + var logs bytes.Buffer |
| + old := log.Writer() |
| + log.SetOutput(&logs) |
| + defer log.SetOutput(old) |
| + alerts := 0 |
| + pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil } |
| + for i := 0; i < 2; i++ { |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + if ref == nil || ref.Msg != domainBuyCopy["unavailable"] { |
| + t.Fatalf("refusal: %+v", ref) |
| + } |
| + } |
| + if !strings.Contains(logs.String(), message) { |
| + t.Fatalf("missing registry message: %s", logs.String()) |
| + } |
| + if code != 399 && alerts != 1 { |
| + t.Fatalf("alerts=%d", alerts) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/domainbuy_round1_test.go b/internal/console/domainbuy_round1_test.go| new file mode 100644 |
| index 000000000..6d2e4567c |
| --- /dev/null |
| +++ b/internal/console/domainbuy_round1_test.go |
| @@ -0,0 +1,278 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| + "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/registrar" |
| +) |
| + |
| +func TestPurchaseCheckUsesSavedCountry(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + tok := buyToken(t, f) |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"shop.com"}`) |
| + var q struct { |
| + Currency string |
| + Price int64 |
| + } |
| + if err := json.Unmarshal([]byte(body), &q); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status != 200 || q.Currency != "eur" || q.Price != 1600 { |
| + t.Fatalf("check: %d %s", status, body) |
| + } |
| + status, body = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, `{"name":"shop.com","app":"kass","currency":"eur","price":1600}`) |
| + if status != 200 { |
| + t.Fatalf("purchase: %d %s", status, body) |
| + } |
| + var out struct{ ID string } |
| + if err := json.Unmarshal([]byte(body), &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := f.read(t, out.ID) |
| + if p.Currency != q.Currency || p.Amount != q.Price { |
| + t.Fatalf("charged %+v after quote %+v", p, q) |
| + } |
| + var checkout struct { |
| + Request billing.PaymentCheckoutRequest |
| + } |
| + if err := json.Unmarshal(p.CheckoutPrepared.Body, &checkout); err != nil { |
| + t.Fatal(err) |
| + } |
| + if checkout.Request.Currency != q.Currency || checkout.Request.Amount != q.Price { |
| + t.Fatalf("checkout differs from confirmation: %+v", checkout.Request) |
| + } |
| + b, err := f.st.BillingAccount(f.acct.ID) |
| + if err != nil || b.Currency != "eur" || f.sent(billing.PreparedCustomer) != 1 { |
| + t.Fatalf("billing: %+v %v", b, err) |
| + } |
| +} |
| + |
| +func TestPurchaseConfirmedPriceMismatch(t *testing.T) { |
| + for _, fields := range []string{`"currency":"usd","price":1500`, `"currency":"eur","price":1599`, `"currency":"usd","price":1600`, `"currency":"eur"`, `"price":1600`, `"currency":"eur","price":0`} { |
| + t.Run(fields, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + f.reg.BalanceMoney.Minor = 0 // A changed price must refuse before balance alerts or billing. |
| + if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass",`+fields+`}`) |
| + var out struct { |
| + Code, Currency string |
| + Price int64 |
| + } |
| + if err := json.Unmarshal([]byte(body), &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status != 409 || out.Code != "price_changed" || out.Currency != "eur" || out.Price != 1600 { |
| + t.Fatalf("refusal: %d %s", status, body) |
| + } |
| + assertNoPurchaseEffects(t, f) |
| + }) |
| + } |
| +} |
| + |
| +func assertNoPurchaseEffects(t *testing.T, f *purchaseFixture) { |
| + t.Helper() |
| + b, err := f.st.BillingAccount(f.acct.ID) |
| + if err != nil || b != nil { |
| + t.Fatalf("wrote billing: %+v %v", b, err) |
| + } |
| + var count int |
| + if err := f.st.db.QueryRow(`SELECT count(*) FROM domain_purchases WHERE account_id=?`, f.acct.ID).Scan(&count); err != nil || count != 0 { |
| + t.Fatalf("purchase count=%d err=%v", count, err) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 0 || f.sent(billing.PreparedPaymentCheckout) != 0 || purchaseCalls(f.reg.Calls, "contact:") != 0 { |
| + t.Fatal("refusal made provider writes") |
| + } |
| +} |
| + |
| +func TestBrowserBuyConfirmedPrice(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + 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) |
| + if status != 200 || !strings.Contains(body, `name="currency" value="eur"`) || !strings.Contains(body, `name="price" value="1600"`) { |
| + t.Fatalf("confirm: %d %s", status, body) |
| + } |
| + contact := purchaseContact() |
| + contact.Country = "GB" |
| + for _, field := range buyContactFields(contact) { |
| + values.Set(field.Name, field.Value) |
| + } |
| + 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"`) { |
| + 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) |
| + if status != 303 || !strings.HasPrefix(loc, "https://checkout.example.test/") { |
| + t.Fatalf("confirmed: %d %s", status, loc) |
| + } |
| +} |
| + |
| +func TestPurchaseSponsoredLimitsStillGate(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + partial := plans.Limits{RunningThings: 40} |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceSponsored, &partial, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.srv.checkCustomDomains(f.acct); !isPlanCap(err) { |
| + t.Fatalf("partial sponsorship allowed domains: %v", err) |
| + } |
| +} |
| + |
| +func TestPaymentCustomerFailureDoesNotFixCurrency(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + f.fake.Err = billing.ErrRefused |
| + h, release, err := f.srv.holdBilling(f.acct) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer release() |
| + if _, err := f.srv.paymentCustomerLocked(h, f.srv.billingClock(context.Background()), f.acct, "IE", "D01 A123", true); err == nil { |
| + t.Fatal("expected customer failure") |
| + } |
| + b, err := f.st.BillingAccount(f.acct.ID) |
| + if err != nil || (b != nil && (b.Currency != "" || b.Customer != "")) { |
| + t.Fatalf("failed customer fixed currency: %+v %v", b, err) |
| + } |
| +} |
| + |
| +func TestPaymentCustomerCurrencyBoundAtomically(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + // A persisted currency with no customer is forbidden, even between writes. |
| + for _, event := range []string{"INSERT", "UPDATE"} { |
| + _, err := f.st.db.Exec(fmt.Sprintf(`CREATE TRIGGER test_currency_%s BEFORE %s ON billing_accounts WHEN NEW.currency != '' AND NEW.customer = '' BEGIN SELECT RAISE(ABORT, 'currency before customer'); END`, event, event)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + h, release, err := f.srv.holdBilling(f.acct) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer release() |
| + b, err := f.srv.paymentCustomerLocked(h, f.srv.billingClock(context.Background()), f.acct, "IE", "D01 A123", true) |
| + if err != nil || b.Customer == "" || b.Currency != "eur" { |
| + t.Fatalf("customer/currency: %+v %v", b, err) |
| + } |
| +} |
| + |
| +func TestBillingAddCardRequiresDomainBuying(t *testing.T) { |
| + for _, mode := range []string{"enabled", "disabled", "free", "partial"} { |
| + t.Run(mode, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + switch mode { |
| + case "disabled": |
| + f.srv.cfg.DomainCatalog = nil |
| + case "free": |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + case "partial": |
| + partial := plans.Limits{RunningThings: 40} |
| + if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceSponsored, &partial, "test", "operator", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + c := newBrowser(t) |
| + f.setUser("owner" + f.acct.Sqid + "@example.com") |
| + signUp(t, f.consoleFixture, c, "card-visibility") |
| + status, _, body := get(t, c, f.ts.URL+billingPagePath(f.acct.Sqid)) |
| + want := mode == "enabled" |
| + if status != 200 || strings.Contains(body, "/billing/card") != want || strings.Contains(body, billingCopy["card.hint"]) != want { |
| + t.Fatalf("mode=%s status=%d card=%t", mode, status, strings.Contains(body, "/billing/card")) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// Run a competing billing action between admission and the purchase's hold. |
| +type currencyChangeRegistrar struct { |
| + registrar.Registrar |
| + change func() |
| +} |
| + |
| +func (r currencyChangeRegistrar) Check(ctx context.Context, name string) (registrar.Availability, error) { |
| + r.change() |
| + return r.Registrar.Check(ctx, name) |
| +} |
| +func TestPurchaseConfirmsCurrencyUnderBillingHold(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + f.srv.cfg.Registrar = currencyChangeRegistrar{f.reg, func() { |
| + h, release, err := f.srv.holdBilling(f.acct) |
| + if err != nil { |
| + t.Error(err) |
| + return |
| + } |
| + defer release() |
| + _, err = f.srv.paymentCustomerLocked(h, f.srv.billingClock(context.Background()), f.acct, "US", "10001", true) |
| + if err != nil { |
| + t.Error(err) |
| + } |
| + }} |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", buyToken(t, f), `{"name":"shop.com","app":"kass","currency":"eur","price":1600}`) |
| + if status != 409 || !strings.Contains(body, `"currency":"usd"`) || !strings.Contains(body, `"price":1500`) { |
| + t.Fatalf("race: %d %s", status, body) |
| + } |
| + if f.sent(billing.PreparedCustomer) != 1 || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| + t.Fatal("purchase did provider writes after concurrent customer creation") |
| + } |
| + b, err := f.st.BillingAccount(f.acct.ID) |
| + if err != nil || b.Currency != "usd" { |
| + t.Fatalf("changed concurrent currency: %+v %v", b, err) |
| + } |
| +} |
| + |
| +func TestPurchaseCheckDefaultAndFixedCurrency(t *testing.T) { |
| + for _, fixed := range []bool{false, true} { |
| + t.Run(fmt.Sprint(fixed), func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + if fixed { |
| + if err := f.st.SetBillingCustomer(f.acct.ID, "cus_fixed", time.Now(), "usd"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := f.st.SetDomainContact(f.acct.ID, purchaseContact(), ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", buyToken(t, f), `{"name":"shop.com"}`) |
| + if status != 200 || !strings.Contains(body, `"currency":"usd"`) || !strings.Contains(body, `"price":1500`) { |
| + t.Fatalf("check: %d %s", status, body) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/domainbuy_round2_test.go b/internal/console/domainbuy_round2_test.go| new file mode 100644 |
| index 000000000..4cb21af52 |
| --- /dev/null |
| +++ b/internal/console/domainbuy_round2_test.go |
| @@ -0,0 +1,173 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "fmt" |
| + "net/http" |
| + "net/url" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/billing" |
| +) |
| + |
| +func TestPurchaseCheckCountry(t *testing.T) { |
| + for _, browser := range []bool{false, true} { |
| + for _, tc := range []struct { |
| + name, country, saved, fixed, currency string |
| + price int64 |
| + }{ |
| + {"first IE", "IE", "", "", "eur", 1600}, |
| + {"first GB", "GB", "", "", "gbp", 1700}, |
| + {"overrides saved", "GB", "IE", "", "gbp", 1700}, |
| + {"fixed currency wins", "IE", "GB", "usd", "usd", 1500}, |
| + {"saved fallback", "", "IE", "", "eur", 1600}, |
| + {"default fallback", "", "", "", "usd", 1500}, |
| + } { |
| + t.Run(fmt.Sprintf("browser=%t/%s", browser, tc.name), func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + if tc.saved != "" { |
| + c := purchaseContact() |
| + c.Country = tc.saved |
| + if err := f.st.SetDomainContact(f.acct.ID, c, ""); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if tc.fixed != "" { |
| + if err := f.st.SetBillingCustomer(f.acct.ID, "cus_fixed", time.Now(), tc.fixed); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + if browser { |
| + 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}}) |
| + 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+`"`) { |
| + t.Fatal("confirmation contact lost requested country") |
| + } |
| + } else { |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", buyToken(t, f), fmt.Sprintf(`{"name":"shop.com","country":%q}`, tc.country)) |
| + var q struct { |
| + Currency string |
| + Price int64 |
| + } |
| + if err := json.Unmarshal([]byte(body), &q); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status != 200 || q.Currency != tc.currency || q.Price != tc.price { |
| + t.Fatalf("check: %d %s", status, body) |
| + } |
| + } |
| + if tc.fixed == "" { |
| + assertNoPurchaseEffects(t, f) |
| + } |
| + }) |
| + } |
| + } |
| +} |
| + |
| +func TestPurchaseCheckCountryValidation(t *testing.T) { |
| + for _, country := range []string{"ie", "I", "IRL", "I1", " IE", "ÉI"} { |
| + t.Run(country, func(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", buyToken(t, f), fmt.Sprintf(`{"name":"shop.com","country":%q}`, country)) |
| + if status != 422 || !strings.Contains(body, domainBuyCopy["contactError"]) { |
| + t.Fatalf("API: %d %s", status, body) |
| + } |
| + 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}}) |
| + if status != 422 || !strings.Contains(body, domainBuyCopy["contactError"]) { |
| + t.Fatalf("browser: %d %s", status, body) |
| + } |
| + assertNoPurchaseEffects(t, f) |
| + if len(f.reg.Calls) != 0 { |
| + t.Fatalf("invalid country reached registrar: %v", f.reg.Calls) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +func TestPurchaseCheckCountryChargedEUR(t *testing.T) { |
| + f := newPurchaseFixture(t) |
| + firstPurchaseAccount(t, f) |
| + tok := buyToken(t, f) |
| + status, body := buyRequest(t, f, "POST", buyAPIPath(f)+"/check", tok, `{"name":"shop.com","country":"IE"}`) |
| + var q struct { |
| + Currency string |
| + Price int64 |
| + } |
| + if err := json.Unmarshal([]byte(body), &q); err != nil { |
| + t.Fatal(err) |
| + } |
| + if status != 200 || q.Currency != "eur" || q.Price != 1600 { |
| + t.Fatalf("check: %d %s", status, body) |
| + } |
| + request, _ := json.Marshal(map[string]any{"name": "shop.com", "app": "kass", "contact": purchaseContact(), "currency": q.Currency, "price": q.Price}) |
| + status, body = buyRequest(t, f, "POST", buyAPIPath(f)+"/purchases", tok, string(request)) |
| + if status != 200 { |
| + t.Fatalf("first purchase: %d %s", status, body) |
| + } |
| + var out struct{ ID string } |
| + if err := json.Unmarshal([]byte(body), &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := f.read(t, out.ID) |
| + f.authorise(t, p) |
| + p = f.until(t, p.ID, PurchaseCaptured) |
| + payment, err := f.fake.PaymentCheckout(context.Background(), p.CheckoutSession) |
| + if err != nil || payment.IntentStatus != "succeeded" || p.Currency != "eur" || p.Amount != 1600 || f.sent(billing.PreparedCapture) != 1 { |
| + t.Fatalf("capture: %+v %+v %v", p, payment, err) |
| + } |
| + var prepared struct { |
| + Request billing.PaymentCheckoutRequest |
| + } |
| + if err := json.Unmarshal(p.CheckoutPrepared.Body, &prepared); err != nil { |
| + t.Fatal(err) |
| + } |
| + if prepared.Request.Currency != "eur" || prepared.Request.Amount != 1600 { |
| + t.Fatalf("charged: %+v", prepared.Request) |
| + } |
| +} |
| + |
| +func TestBillingAddCardUnavailableAction(t *testing.T) { |
| + for _, reason := range []string{"not configured", "plan disallows", "exempt"} { |
| + t.Run(reason, func(t *testing.T) { |
| + o := newCheckoutFixture(t, false) |
| + if reason != "not configured" { |
| + f := newPurchaseFixture(t) |
| + o.srv.cfg.Registrar, o.srv.cfg.ZoneHost, o.srv.cfg.DomainCatalog = f.reg, f.zone, f.srv.cfg.DomainCatalog |
| + } |
| + if reason == "exempt" { |
| + o.st.planExemptID = o.acct.ID |
| + } |
| + o.stepUp(t) |
| + o.reset() |
| + in, err := o.srv.billingPageInputFor(o.acct, RoleOwner, time.Now()) |
| + if err != nil || in.CanBuyDomains { |
| + t.Fatalf("fixture: %+v %v", in, err) |
| + } |
| + r := o.request(t, http.MethodPost, o.billingBase()+"/card", nil) |
| + key := "card.failed" |
| + if reason == "exempt" { |
| + key = errBillingExempt.Key |
| + } |
| + o.wantRefused(t, r, billingCopy[key]) |
| + if b, err := o.st.BillingAccount(o.acct.ID); err != nil || b != nil { |
| + t.Fatalf("gate wrote billing: %+v %v", b, err) |
| + } |
| + if len(o.fake.Sent) != 0 { |
| + t.Fatal("gate sent provider writes") |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/console/domainbuy_test.go b/internal/console/domainbuy_test.go| index 34777a145..f123319ec 100644 |
| --- a/internal/console/domainbuy_test.go |
| +++ b/internal/console/domainbuy_test.go |
| @@ -63,7 +63,7 @@ func purchaseContact() registrar.Contact { |
| } |
| func (f *purchaseFixture) start(t *testing.T) *DomainPurchase { |
| t.Helper() |
| - p, url, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + p, url, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| if ref != nil || p == nil || url == "" { |
| t.Fatalf("start: %+v %q %+v", p, url, ref) |
| } |
| @@ -228,7 +228,7 @@ func TestStartRefusesClaimHeldElsewhereBeforePayment(t *testing.T) { |
| if _, _, err := domains.AttachClaim(context.Background(), f.rel, domains.Claim{Schema: 1, Host: host, Account: "foreign", App: "other", CreatedBy: "other"}); err != nil { |
| t.Fatal(err) |
| } |
| - _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| want := claimRefusal(host, domains.ErrHostUnavailable) |
| if ref == nil || *ref != *want || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| t.Fatalf("refusal: %+v", ref) |
| @@ -241,7 +241,7 @@ func TestStartRefusesFreePlan(t *testing.T) { |
| if _, err := f.st.SetAccountPlan(f.acct.ID, "free", nil, 0, PlanSourceOperator, nil, "test", "operator", time.Now()); err != nil { |
| t.Fatal(err) |
| } |
| - _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| if ref == nil || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| t.Fatal("free plan bought domain") |
| } |
| @@ -252,7 +252,7 @@ func TestStartRefusesOverDailyCap(t *testing.T) { |
| if err := f.st.CreateDomainPurchase(DomainPurchase{AccountID: f.acct.ID, Domain: "earlier.com", App: "kass", State: PurchaseExpired}); err != nil { |
| t.Fatal(err) |
| } |
| - _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| if ref == nil || f.sent(billing.PreparedPaymentCheckout) != 0 { |
| t.Fatal("cap bypassed") |
| } |
| @@ -262,7 +262,7 @@ func TestStartRefusesLowRegistrarBalance(t *testing.T) { |
| alerts := 0 |
| pageDomainPurchase = func(context.Context, string, string, string) error { alerts++; return nil } |
| f.reg.BalanceMoney.Minor = 1 |
| - _, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| + _, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer") |
| if ref == nil || ref.Msg != "buying domains is unavailable right now" || f.sent(billing.PreparedPaymentCheckout) != 0 || alerts != 1 { |
| t.Fatalf("balance refusal: %+v", ref) |
| } |
| @@ -381,7 +381,7 @@ func setupClaimPurchase(t *testing.T, cx *claimCase) { |
| func TestPurchaseCheckoutLostResponseReplaysStoredRequest(t *testing.T) { |
| f := newPurchaseFixture(t) |
| f.fake.LoseNextResponse = true |
| - p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + p, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| if p == nil || ref == nil { |
| t.Fatalf("lost checkout response: %+v %+v", p, ref) |
| } |
| @@ -403,7 +403,7 @@ func TestPurchaseCheckoutLostResponseReplaysStoredRequest(t *testing.T) { |
| func TestPurchaseCheckoutUnknownPastExpiryStaysLive(t *testing.T) { |
| f := newPurchaseFixture(t) |
| f.fake.LoseNextResponse = true |
| - p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + p, _, _ := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| if p == nil { |
| t.Fatal("missing pending purchase") |
| } |
| @@ -674,11 +674,11 @@ func TestPurchaseHappyPathWithClaimSQLGate(t *testing.T) { |
| cx.srv.cfg.DomainCatalog = &domainreg.Catalog{Version: "test", DailyCap: 3, TLDs: map[string]domainreg.TLD{"com": {Register: map[string]int64{"usd": 1500}, MaxCost: registrar.Money{Currency: "usd", Minor: 1000}}}} |
| cx.srv.billing.ready.Store(true) |
| f := &purchaseFixture{billingFixture: bf, reg: reg, zone: zone} |
| - p, _, ref := f.srv.startDomainPurchase(context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test") |
| + p, _, ref := startQuotedPurchase(f.srv, context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test") |
| if ref != nil || p == nil { |
| t.Fatalf("start: %+v", ref) |
| } |
| - resumed, checkout, duplicate := f.srv.startDomainPurchase(context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test") |
| + resumed, checkout, duplicate := startQuotedPurchase(f.srv, context.Background(), acct, "titogo", "shop.com", purchaseContact(), "buyer@example.test") |
| if duplicate != nil || resumed == nil || resumed.ID != p.ID || checkout == "" || f.sent(billing.PreparedPaymentCheckout) != 1 { |
| t.Fatalf("resume: %+v %q %+v", resumed, checkout, duplicate) |
| } |
| @@ -817,7 +817,7 @@ func TestRegisteringAlertsOperatorAfterAnHour(t *testing.T) { |
| func TestCheckoutCreateRefusedFailsAtOnce(t *testing.T) { |
| f := newPurchaseFixture(t) |
| f.fake.BeforeSend = func(billing.Prepared) error { return billing.ErrRefused } |
| - p, _, ref := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + p, _, ref := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| if p == nil || ref == nil { |
| t.Fatal("expected refused create") |
| } |
| @@ -866,7 +866,7 @@ func TestStepErrorsAreReturnedAndLogged(t *testing.T) { |
| func TestLostCheckoutCreateExpiresWhenNoneListed(t *testing.T) { |
| f := newPurchaseFixture(t) |
| f.fake.Err = billing.ErrIndeterminate |
| - p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + p, _, _ := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| if p == nil { |
| t.Fatal("missing purchase") |
| } |
| @@ -891,7 +891,7 @@ func TestLostCheckoutCreateExpiresWhenNoneListed(t *testing.T) { |
| func TestLostCheckoutCreateAdoptsListedSession(t *testing.T) { |
| f := newPurchaseFixture(t) |
| f.fake.LoseNextResponse = true |
| - p, _, _ := f.srv.startDomainPurchase(context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| + p, _, _ := startQuotedPurchase(f.srv, context.Background(), f.acct, "kass", "shop.com", purchaseContact(), "buyer@example.test") |
| if p == nil || p.CheckoutSession != "" { |
| t.Fatal("expected lost response") |
| } |
| @@ -1000,3 +1000,16 @@ func TestPurchaseRereadsJournalInsideOperation(t *testing.T) { |
| t.Fatalf("purchase=%+v error=%v", fresh, err) |
| } |
| } |
| + |
| +func startQuotedPurchase(s *Server, ctx context.Context, acct *Account, app, name string, c registrar.Contact, principal string) (*DomainPurchase, string, *doorRefusal) { |
| + currency, _ := s.billing.cfg.Book.ChooseCurrency("", c.Country) |
| + if b, _ := s.store.BillingAccount(acct.ID); b != nil && b.Currency != "" { |
| + currency = b.Currency |
| + } |
| + q := domainreg.Quote{Currency: currency, Price: s.cfg.DomainCatalog.TLDs["com"].Register[currency]} |
| + if own, _ := s.ownLiveDomainPurchase(ctx, acct.ID, name); own != nil { |
| + q.Currency, q.Price = own.Currency, own.Amount |
| + } |
| + p, link, _, ref := s.startDomainPurchase(ctx, acct, app, name, c, principal, q) |
| + return p, link, ref |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index f20927d19..6057e8c16 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1961,6 +1961,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| // Plans 6b: an owner's way to the provider's locked portal for cards |
| // and invoices (billingportal.go). 404 with billing off. |
| s.registerRoute("POST /a/{sqid}/billing/portal", s.handleBillingPortal) |
| + s.registerRoute("POST /a/{sqid}/billing/card", s.handleBillingCard) |
| // The billing page (billingpage.go): member-readable, its forms the |
| // owner's. 404 with billing off. |
| s.registerRoute("GET /a/{sqid}/billing", s.handleBilling) |
diff --git a/internal/console/templates/billing.html b/internal/console/templates/billing.html| index 52cadfa5d..11c599702 100644 |
| --- a/internal/console/templates/billing.html |
| +++ b/internal/console/templates/billing.html |
| @@ -144,6 +144,10 @@ |
| <input type="hidden" name="renewal" value="stop"> |
| <button class="linkish danger" type="submit">{{billingText "button.stop"}}</button> |
| </form></div>{{end}} |
| +{{if eq . "card"}}<div class="settings-row"><form method="post" action="{{$.Base}}/billing/card"> |
| + <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| + <button type="submit">{{billingText "button.card"}}</button> |
| +</form><p class="muted">{{billingText "card.hint"}}</p></div>{{end}} |
| {{if eq . "portal"}}<div class="settings-row"><form method="post" action="{{$.Base}}/billing/portal"> |
| <input type="hidden" name="csrf" value="{{$.CSRF}}"> |
| <button type="submit">{{billingText "button.portal"}}</button> |
diff --git a/internal/console/templates/domain_buy.html b/internal/console/templates/domain_buy.html| index 323356fdc..0a96b85bb 100644 |
| --- a/internal/console/templates/domain_buy.html |
| +++ b/internal/console/templates/domain_buy.html |
| @@ -29,6 +29,7 @@ |
| })(); |
| </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> |
| @@ -38,6 +39,8 @@ |
| <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> |
| @@ -49,6 +52,8 @@ |
| <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}} |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index c33982f6f..95dd2a3d7 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -199,6 +199,7 @@ route POST /a/{sqid}/apps/{app}/rollback |
| route POST /a/{sqid}/apps/{app}/star |
| route POST /a/{sqid}/apps/{app}/store/destroy |
| route POST /a/{sqid}/apps/{app}/swap |
| +route POST /a/{sqid}/billing/card |
| route POST /a/{sqid}/billing/change |
| route POST /a/{sqid}/billing/checkout |
| route POST /a/{sqid}/billing/confirm |
diff --git a/internal/provision/domains_buy_nosub_census_test.go b/internal/provision/domains_buy_nosub_census_test.go| new file mode 100644 |
| index 000000000..4774863e1 |
| --- /dev/null |
| +++ b/internal/provision/domains_buy_nosub_census_test.go |
| @@ -0,0 +1,22 @@ |
| +package provision |
| + |
| +// Author's record-write classification for domains-buy-nosub; independent |
| +// census review is still required. NewServer adds POST /a/{sqid}/billing/card |
| +// with the billing owner, CSRF, fresh-auth and billing-hold gates. The handler |
| +// reuses customer creation and opens setup Checkout, writing billing state |
| +// and provider customer/session objects only. No deployment record write or |
| +// new read in NewServer; the existing instances literal stays key-site. |
| +func domainsBuyNosubWriteCensusInventory() []censusEntry { |
| + entries := append([]censusEntry(nil), devboxIdentityWriteCensusInventory()...) |
| + r := censusEntry{"internal/console/server.go", "NewServer", "key-site", "lit:instances", "53e266e2e25e579c89471f34674b8b79dffc805a38151de303d44b2e528144c4"} |
| + for i, e := range entries { |
| + if e.File == r.File && e.Unit == r.Unit { |
| + if e.Class != r.Class || e.Kinds != r.Kinds { |
| + panic("domains-buy-nosub re-pin changes the class or kinds of " + r.File + ":" + r.Unit) |
| + } |
| + entries[i] = r |
| + return entries |
| + } |
| + } |
| + panic("domains-buy-nosub re-pin of an unlisted unit " + r.File + ":" + r.Unit) |
| +} |
diff --git a/internal/provision/plan9_b8_census_test.go b/internal/provision/plan9_b8_census_test.go| index a3aa2a17e..dcbf5279a 100644 |
| --- a/internal/provision/plan9_b8_census_test.go |
| +++ b/internal/provision/plan9_b8_census_test.go |
| @@ -366,7 +366,7 @@ func TestPlan9B8RecordWriteCensus(t *testing.T) { |
| if len(got) < 100 { |
| t.Fatalf("census found only %d units under %s; the walk is broken", len(got), root) |
| } |
| - inventory := devboxIdentityWriteCensusInventory() |
| + inventory := domainsBuyNosubWriteCensusInventory() |
| problems := append(censusDiff(inventory, got), censusPolicy(inventory)...) |
| if len(problems) > 0 { |
| t.Fatalf("record-write census rejected %d site(s); update the explicit inventory only after reviewing the source:\n %s", len(problems), strings.Join(problems, "\n ")) |
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv| index 09e41a0a4..eae19e409 100644 |
| --- a/internal/provision/testdata/plan14-root-reads-chain.tsv |
| +++ b/internal/provision/testdata/plan14-root-reads-chain.tsv |
| @@ -69,3 +69,4 @@ plan14-root-reads-region-ha-home-placement.tsv b0304f75d2c5f1b9818d0f282b89c00c0 |
| plan14-root-reads-storedoor-stream-get.tsv 7e30dee4fb52370555ad173512d7f03782f0fbed725a8a6bf4f7e31f52c23668 |
| plan14-root-reads-design-pdf-service.tsv 09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6 |
| plan14-root-reads-region-ha-placement-survivor.tsv 09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6 |
| +plan14-root-reads-domains-buy-nosub.tsv 09ad1d7267b9598c64e89ec0faa7b18839c785c5c63905b398afe681cf9777c6 |
diff --git a/internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv b/internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv| new file mode 100644 |
| index 000000000..0dddd7750 |
| --- /dev/null |
| +++ b/internal/provision/testdata/plan14-root-reads-domains-buy-nosub.tsv |
| @@ -0,0 +1,4 @@ |
| +# Census overlay domains-buy-nosub, written by census-propose (#369). census-ruling-domains-buy-nosub, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-domains-buy-nosub.md. |
| +# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended. |
| +@coverage . ecf8cb88c9cc640b8b95fe71ed448c962ba29b86ca483910ee7f5448bfd5af26 |
| +@coverage internal/registrar 438f7149d09aa6a151338c68bfe428f704a09628f56e942b8fd4de8cebadd932 |
diff --git a/internal/registrar/openprovider/client.go b/internal/registrar/openprovider/client.go| index 4bb8fbfc1..e3d419bc4 100644 |
| --- a/internal/registrar/openprovider/client.go |
| +++ b/internal/registrar/openprovider/client.go |
| @@ -459,8 +459,14 @@ func (c *Client) send(ctx context.Context, method, path string, payload []byte, |
| if answer.Code != nil { |
| code = *answer.Code |
| } |
| + message := answer.Description |
| + for _, secret := range []string{c.username, c.password, token} { |
| + if secret != "" { |
| + message = strings.ReplaceAll(message, secret, "[redacted]") |
| + } |
| + } |
| if status >= 500 || status < 200 || (status >= 300 && status < 400) { |
| - return nil, status, responseError(method, path, fmt.Sprintf("HTTP %d", status)) |
| + return nil, status, &providerError{kind: responseError(method, path, fmt.Sprintf("HTTP %d", status)), status: status, code: code, message: message} |
| } |
| if status >= 400 || (decodeErr == nil && answer.Code != nil && code != 0) { |
| kind := registrar.ErrRefused |
| @@ -472,11 +478,8 @@ func (c *Client) send(ctx context.Context, method, path string, payload []byte, |
| if code == 311 { |
| kind = registrar.ErrUnavailable |
| } |
| - message := answer.Description |
| - for _, secret := range []string{c.username, c.password, token} { |
| - if secret != "" { |
| - message = strings.ReplaceAll(message, secret, "[redacted]") |
| - } |
| + if code == 309 || code == 19010 { |
| + kind = errors.Join(registrar.ErrRefused, registrar.ErrSetup) |
| } |
| return nil, status, &providerError{kind: kind, status: status, code: code, message: message} |
| } |
diff --git a/internal/registrar/openprovider/client_test.go b/internal/registrar/openprovider/client_test.go| index e79b57b89..ee84296ed 100644 |
| --- a/internal/registrar/openprovider/client_test.go |
| +++ b/internal/registrar/openprovider/client_test.go |
| @@ -536,3 +536,30 @@ func TestRegisterUnknownProviderOutcomeIsIndeterminate(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| + |
| +func TestRegistryErrorMessagesAndSetupCodes(t *testing.T) { |
| + for _, status := range []int{200, 400, 500} { |
| + for _, code := range []int{399, 309, 19010} { |
| + t.Run(fmt.Sprintf("%d/%d", status, code), func(t *testing.T) { |
| + const message = "Nameserver creation or update failed: Parent domain does not exist for host" |
| + c := newClient(t, func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(status) |
| + fmt.Fprintf(w, `{"code":%d,"desc":%q}`, code, message+" "+password+" "+token) |
| + }, time.Second) |
| + _, err := c.Register(context.Background(), registration()) |
| + if err == nil || !strings.Contains(err.Error(), message) { |
| + t.Fatalf("missing registry message: %v", err) |
| + } |
| + if strings.Contains(err.Error(), password) || strings.Contains(err.Error(), token) { |
| + t.Fatal("credentials leaked") |
| + } |
| + if status < 500 && (code == 309 || code == 19010) && (!errors.Is(err, registrar.ErrSetup) || !errors.Is(err, registrar.ErrRefused)) { |
| + t.Fatalf("setup not refused: %v", err) |
| + } |
| + if status == 500 && !errors.Is(err, registrar.ErrIndeterminate) { |
| + t.Fatalf("ambiguous register was made definite: %v", err) |
| + } |
| + }) |
| + } |
| + } |
| +} |
diff --git a/internal/registrar/registrar.go b/internal/registrar/registrar.go| index 8c08b18b1..d2c019d5a 100644 |
| --- a/internal/registrar/registrar.go |
| +++ b/internal/registrar/registrar.go |
| @@ -94,3 +94,6 @@ func (c Contact) Validate() error { |
| } |
| return nil |
| } |
| + |
| +// ErrSetup requires the operator to complete the registrar account setup. |
| +var ErrSetup = errors.New("registrar: account setup incomplete") |