carlos / platform Public

cli: carlos domains check and buy

Co-Authored-By: Astra (gpt-6-astra) via Codex <noreply@openai.com>
Paul Campbell pushed by claude agent, operated by paul@keymail.dev 6cff93718372482dab5dc7258add805583974fb4 parent cf401da
10 files changed, +882 −3
  • apimode.go +88 −0
  • docs/site/cli.md +5 −0
  • docs/superpowers/notes/census-proposal-domain-registration-task-9.md +15 −0
  • domains_buy_cli.go +287 −0
  • domains_buy_cli_test.go +416 −0
  • domains_buy_copy.go +54 −0
  • domains_cli.go +8 −2
  • go.mod +1 −1
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-domain-registration-task-9.tsv +7 −0
diff --git a/apimode.go b/apimode.go
index 06cc24c33..095fc59b9 100644
--- a/apimode.go
+++ b/apimode.go
@@ -42,6 +42,7 @@ import (
"github.com/carlosframework/platform/internal/ledger"
"github.com/carlosframework/platform/internal/objstore"
"github.com/carlosframework/platform/internal/ratelimit"
+ "github.com/carlosframework/platform/internal/registrar"
"github.com/carlosframework/platform/internal/release"
"github.com/carlosframework/platform/internal/schedule"
"github.com/carlosframework/platform/internal/telemetry"
@@ -4645,6 +4646,93 @@ func (s *apiSession) postDomainAttachFull(ctx context.Context, a apiAcct, app st
Verified: out.Verified == nil || *out.Verified, Verify: out.Verify}, nil
}
+type domainQuoteResp struct {
+ Domain string `json:"domain"`
+ Available bool `json:"available"`
+ Price int64 `json:"price"`
+ Currency string `json:"currency"`
+}
+
+type domainPurchaseResp struct {
+ ID string `json:"id"`
+ CheckoutURL string `json:"checkout_url"`
+ Domain string `json:"domain"`
+ App string `json:"app"`
+ State string `json:"state"`
+ Reason string `json:"reason"`
+ DomainState string `json:"domain_state"`
+}
+
+type domainContactError struct{ error }
+
+func (e *domainContactError) Unwrap() error { return e.error }
+
+func domainBuyAPIPath(acct apiAcct, tail string) string {
+ path := "/api/cli/accounts/" + url.PathEscape(acct.Seg) + "/domains" + tail
+ if acct.Exact {
+ path += "?exact=sqid"
+ }
+ return path
+}
+
+func (s *apiSession) postDomainCheck(ctx context.Context, acct apiAcct, name string) (domainQuoteResp, error) {
+ var out domainQuoteResp
+ status, body, err := s.postJSON(ctx, domainBuyAPIPath(acct, "/check"), struct {
+ Name string `json:"name"`
+ }{name})
+ if err != nil {
+ return out, err
+ }
+ if status != http.StatusOK {
+ return out, apiErrorFromBody(status, body)
+ }
+ if err := json.Unmarshal(body, &out); err != nil {
+ return out, fmt.Errorf(domainsBuyCopy["unreadableCheck"], err)
+ }
+ return out, nil
+}
+
+func (s *apiSession) postDomainPurchase(ctx context.Context, acct apiAcct, name, app string, contact *registrar.Contact) (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})
+ if err != nil {
+ return out, err
+ }
+ if status != http.StatusOK {
+ err := apiErrorFromBody(status, body)
+ var refusal struct {
+ Code string `json:"code"`
+ }
+ if status == http.StatusUnprocessableEntity && json.Unmarshal(body, &refusal) == nil && refusal.Code == "contact" {
+ return out, &domainContactError{err}
+ }
+ return out, err
+ }
+ if err := json.Unmarshal(body, &out); err != nil {
+ return out, fmt.Errorf(domainsBuyCopy["unreadablePurchase"], err)
+ }
+ return out, nil
+}
+
+func (s *apiSession) getDomainPurchase(ctx context.Context, acct apiAcct, id string) (domainPurchaseResp, error) {
+ var out domainPurchaseResp
+ status, body, err := s.getJSON(ctx, domainBuyAPIPath(acct, "/purchases/"+url.PathEscape(id)))
+ if err != nil {
+ return out, err
+ }
+ if status != http.StatusOK {
+ return out, apiErrorFromBody(status, body)
+ }
+ if err := json.Unmarshal(body, &out); err != nil {
+ return out, fmt.Errorf(domainsBuyCopy["unreadablePurchase"], err)
+ }
+ return out, nil
+}
+
// domainDetach releases a hostname claim. Always 200 on a live console
// (handleAPIDomainDetach's own contract): removed is false for a hostname
// this app never held, one it no longer holds, or one another account
diff --git a/docs/site/cli.md b/docs/site/cli.md
index 6cf69e8e0..2eed1a74b 100644
--- a/docs/site/cli.md
+++ b/docs/site/cli.md
@@ -1341,6 +1341,11 @@ The REGION column names where each route or box runs, such as London (UK).
### carlos domains
+```sh
+carlos domains check shop.example
+carlos domains buy shop.example --app shop
+```
+
Attaches a customer's own hostname to one of the app's routes, detaches it,
or lists what is claimed.
diff --git a/docs/superpowers/notes/census-proposal-domain-registration-task-9.md b/docs/superpowers/notes/census-proposal-domain-registration-task-9.md
new file mode 100644
index 000000000..3d8e846ac
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-domain-registration-task-9.md
@@ -0,0 +1,15 @@
+# Census approval: domain-registration-task-9
+
+Ruling `census-ruling-domain-registration-task-9`. The independent reviewer approves or rejects every change below, 1 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.
+
+New dispositions, which census-propose wrote and the reviewer checks against the unit's reads and the diff:
+
+- new `domains_buy_cli.go:readDomainContact`: reads +file:Open, +file:ReadAll; written legacy, accepted-legacy, frozen
+
+Seal: `5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc` → `4b5a2b6d51c1460669dd22b93851d240b0c3b4b8e711cf3c4c28fa0209c873cc`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-domain-registration-task-9.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/domains_buy_cli.go b/domains_buy_cli.go
new file mode 100644
index 000000000..ecc181361
--- /dev/null
+++ b/domains_buy_cli.go
@@ -0,0 +1,287 @@
+package main
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "errors"
+ "flag"
+ "fmt"
+ "io"
+ "log"
+ "os"
+ "strings"
+ "time"
+
+ "github.com/carlosframework/platform/internal/plans"
+ "github.com/carlosframework/platform/internal/registrar"
+ "github.com/mattn/go-isatty"
+)
+
+const domainBuyPollInterval = 3 * time.Second
+const domainBuyLiveTimeout = 10 * time.Minute
+
+func runDomainsCheck(args []string) { runDomainBuyVerb(args, false) }
+func runDomainsBuy(args []string) { runDomainBuyVerb(args, true) }
+
+func runDomainBuyVerb(args []string, buy bool) {
+ verb, usage := "check", domainsCheckUsage
+ if buy {
+ verb, usage = "buy", domainsBuyUsage
+ }
+ fs := flag.NewFlagSet("domains "+verb, flag.ExitOnError)
+ acctRaw := fs.String("account", "", domainsBuyCopy["accountFlag"])
+ acctID := fs.String("account-id", "", domainsBuyCopy["accountIDFlag"])
+ console := consoleOption(fs, domainsBuyCopy["consoleFlag"])
+ var app, contactFile string
+ var yes, noWait bool
+ if buy {
+ fs.StringVar(&app, "app", "", domainsBuyCopy["appFlag"])
+ fs.StringVar(&contactFile, "contact-file", "", domainsBuyCopy["contactFileFlag"])
+ fs.BoolVar(&yes, "yes", false, domainsBuyCopy["yesFlag"])
+ fs.BoolVar(&noWait, "no-wait", false, domainsBuyCopy["noWaitFlag"])
+ }
+ fs.Usage = flagUsage(fs, usage)
+ pos, err := parseInterspersed(fs, args)
+ if err != nil {
+ log.Fatal(err)
+ }
+ if len(pos) != 1 || strings.TrimSpace(pos[0]) == "" || (buy && strings.TrimSpace(app) == "") {
+ log.Fatal(usage)
+ }
+ sess := requireAPISession(verb, *console)
+ printUsing(stdout, sess)
+ acct := resolvedAccount(sess, acctRaw, acctID)
+ ctx := context.Background()
+ if buy {
+ err = domainsBuy(ctx, sess, acct, strings.TrimSpace(pos[0]), strings.TrimSpace(app), domainBuyOptions{
+ yes: yes, noWait: noWait, contactFile: contactFile,
+ in: os.Stdin, out: stdout, terminal: isatty.IsTerminal(os.Stdin.Fd()),
+ now: time.Now, wait: waitDomainBuy,
+ })
+ } else {
+ err = domainsCheck(ctx, sess, acct, strings.TrimSpace(pos[0]), stdout)
+ }
+ if err != nil {
+ log.Fatal(err)
+ }
+}
+
+func printDomainQuote(out io.Writer, q domainQuoteResp) {
+ availability := domainsBuyCopy["unavailable"]
+ if q.Available {
+ availability = domainsBuyCopy["available"]
+ }
+ fmt.Fprintf(out, domainsBuyCopy["quote"], q.Domain, availability, plans.FormatMinor(q.Currency, q.Price), strings.ToUpper(q.Currency))
+}
+
+func domainsCheck(ctx context.Context, s *apiSession, acct apiAcct, name string, out io.Writer) error {
+ q, err := s.postDomainCheck(ctx, acct, name)
+ if err != nil {
+ return err
+ }
+ printDomainQuote(out, q)
+ return nil
+}
+
+type domainBuyOptions struct {
+ yes, noWait, terminal bool
+ contactFile string
+ in io.Reader
+ out io.Writer
+ now func() time.Time
+ wait func(context.Context, time.Duration) error
+}
+
+func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app string, o domainBuyOptions) error {
+ var contact *registrar.Contact
+ if o.contactFile != "" {
+ var err error
+ contact, err = readDomainContact(o.contactFile)
+ if err != nil {
+ return err
+ }
+ }
+ q, err := s.postDomainCheck(ctx, acct, name)
+ if err != nil {
+ return err
+ }
+ printDomainQuote(o.out, q)
+ if !q.Available {
+ return errors.New(domainsBuyCopy["unavailable"])
+ }
+ input := bufio.NewScanner(o.in)
+ if !o.yes {
+ if !o.terminal {
+ return errors.New(domainsBuyCopy["confirmNonTTY"])
+ }
+ answer, err := domainBuyAnswer(input, o.out, domainsBuyCopy["confirm"])
+ if err != nil {
+ return err
+ }
+ if !strings.EqualFold(answer, "y") && !strings.EqualFold(answer, "yes") {
+ fmt.Fprintln(o.out, domainsBuyCopy["cancelled"])
+ 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)
+ }
+ // 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
+ }
+ if p.CheckoutURL != "" {
+ fmt.Fprintf(o.out, domainsBuyCopy["checkout"], p.CheckoutURL)
+ }
+ return waitDomainPurchase(ctx, s, acct, p, o)
+}
+
+func readDomainContact(path string) (*registrar.Contact, error) {
+ f, err := os.Open(path)
+ if err != nil {
+ return nil, fmt.Errorf(domainsBuyCopy["contactFile"], err)
+ }
+ defer f.Close()
+ data, err := io.ReadAll(io.LimitReader(f, (16<<10)+1))
+ if err != nil {
+ return nil, fmt.Errorf(domainsBuyCopy["contactFile"], err)
+ }
+ if len(data) > 16<<10 {
+ return nil, errors.New(domainsBuyCopy["contactSize"])
+ }
+ dec := json.NewDecoder(strings.NewReader(string(data)))
+ dec.DisallowUnknownFields()
+ var contact *registrar.Contact
+ if err := dec.Decode(&contact); err != nil {
+ return nil, fmt.Errorf(domainsBuyCopy["contactFile"], err)
+ }
+ if contact == nil {
+ return nil, errors.New(domainsBuyCopy["contactJSON"])
+ }
+ if err := dec.Decode(new(any)); err != io.EOF {
+ return nil, errors.New(domainsBuyCopy["contactJSON"])
+ }
+ return contact, nil
+}
+
+func domainBuyAnswer(input *bufio.Scanner, out io.Writer, prompt string) (string, error) {
+ fmt.Fprint(out, prompt)
+ if !input.Scan() {
+ if err := input.Err(); err != nil {
+ return "", err
+ }
+ return "", errors.New(domainsBuyCopy["inputEnded"])
+ }
+ return strings.TrimSpace(input.Text()), nil
+}
+
+func promptDomainContact(input *bufio.Scanner, out io.Writer) (*registrar.Contact, error) {
+ fmt.Fprintln(out, domainsBuyCopy["contactPrompt"])
+ c := new(registrar.Contact)
+ for _, field := range []struct {
+ key string
+ dst *string
+ }{
+ {"firstName", &c.FirstName}, {"lastName", &c.LastName}, {"company", &c.Company},
+ {"email", &c.Email}, {"phoneCountryCode", &c.PhoneCountryCode}, {"phone", &c.Phone},
+ {"street", &c.Street}, {"houseNumber", &c.HouseNumber}, {"city", &c.City},
+ {"state", &c.State}, {"postalCode", &c.PostalCode}, {"country", &c.Country},
+ } {
+ answer, err := domainBuyAnswer(input, out, domainsBuyCopy[field.key])
+ if err != nil {
+ return nil, err
+ }
+ *field.dst = answer
+ }
+ return c, nil
+}
+
+func waitDomainBuy(ctx context.Context, d time.Duration) error {
+ timer := time.NewTimer(d)
+ defer timer.Stop()
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case <-timer.C:
+ return nil
+ }
+}
+
+func waitDomainPurchase(ctx context.Context, s *apiSession, acct apiAcct, p domainPurchaseResp, o domainBuyOptions) error {
+ id := p.ID
+ seen, domainSeen := map[string]bool{}, map[string]bool{}
+ var doneAt time.Time
+ for {
+ if err := ctx.Err(); err != nil {
+ return err
+ }
+ if p.State != "" && !seen[p.State] {
+ fmt.Fprintf(o.out, domainsBuyCopy["purchaseState"], p.State)
+ seen[p.State] = true
+ }
+ switch p.State {
+ case "failed", "expired", "unpaid":
+ return fmt.Errorf(domainsBuyCopy["failed"], p.State, p.Reason)
+ case "done":
+ if doneAt.IsZero() {
+ doneAt = o.now()
+ }
+ if !domainSeen[p.DomainState] {
+ fmt.Fprintf(o.out, domainsBuyCopy["domainState"], p.DomainState)
+ domainSeen[p.DomainState] = true
+ }
+ if p.DomainState == "live" {
+ return nil
+ }
+ }
+ if o.noWait {
+ return nil
+ }
+ delay := domainBuyPollInterval
+ if !doneAt.IsZero() {
+ remaining := domainBuyLiveTimeout - o.now().Sub(doneAt)
+ if remaining <= 0 {
+ fmt.Fprintln(o.out, domainsBuyCopy["background"])
+ return nil
+ }
+ delay = min(delay, remaining)
+ }
+ if id == "" {
+ return errors.New(domainsBuyCopy["missingID"])
+ }
+ if err := o.wait(ctx, delay); err != nil {
+ return err
+ }
+ if !doneAt.IsZero() && o.now().Sub(doneAt) >= domainBuyLiveTimeout {
+ fmt.Fprintln(o.out, domainsBuyCopy["background"])
+ return nil
+ }
+ pollCtx := ctx
+ cancel := func() {}
+ if !doneAt.IsZero() {
+ pollCtx, cancel = context.WithTimeout(ctx, domainBuyLiveTimeout-o.now().Sub(doneAt))
+ }
+ var err error
+ p, err = s.getDomainPurchase(pollCtx, acct, id)
+ liveTimeout := errors.Is(pollCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil
+ cancel()
+ if liveTimeout {
+ fmt.Fprintln(o.out, domainsBuyCopy["background"])
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+ }
+}
diff --git a/domains_buy_cli_test.go b/domains_buy_cli_test.go
new file mode 100644
index 000000000..c02a80995
--- /dev/null
+++ b/domains_buy_cli_test.go
@@ -0,0 +1,416 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+)
+
+const buyTestPath = "/api/cli/accounts/bab/domains"
+
+func buyTestServer(t *testing.T, purchase http.HandlerFunc, status http.HandlerFunc) *httptest.Server {
+ t.Helper()
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST "+buyTestPath+"/check", func(w http.ResponseWriter, r *http.Request) {
+ var in struct {
+ Name string `json:"name"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Name != "shop.com" {
+ t.Errorf("check body: %+v, %v", in, err)
+ }
+ fmt.Fprint(w, `{"domain":"shop.com","available":true,"price":1299,"currency":"eur"}`)
+ })
+ if purchase != nil {
+ mux.HandleFunc("POST "+buyTestPath+"/purchases", purchase)
+ }
+ if status != nil {
+ mux.HandleFunc("GET "+buyTestPath+"/purchases/p1", status)
+ }
+ ts := httptest.NewServer(mux)
+ t.Cleanup(ts.Close)
+ return ts
+}
+
+func buyTestOptions(out *bytes.Buffer) domainBuyOptions {
+ now := time.Unix(1700000000, 0)
+ return domainBuyOptions{yes: true, in: strings.NewReader(""), out: out,
+ now: func() time.Time { return now },
+ wait: func(ctx context.Context, d time.Duration) error { now = now.Add(d); return ctx.Err() },
+ }
+}
+
+func TestDomainsCheckPrintsPrice(t *testing.T) {
+ ts := buyTestServer(t, nil, nil)
+ var out bytes.Buffer
+ if err := domainsCheck(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", &out); err != nil {
+ t.Fatal(err)
+ }
+ for _, want := range []string{"shop.com", "available", "12.99", "EUR"} {
+ if !strings.Contains(out.String(), want) {
+ t.Fatalf("output %q missing %q", out.String(), want)
+ }
+ }
+}
+
+func TestDomainsBuyPrintsCheckoutAndWaitsToLive(t *testing.T) {
+ states := []string{"awaiting_payment", "authorised", "authorised", "registered", "captured", "done", "done", "done"}
+ n := 0
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ var in struct{ Name, App string }
+ if err := json.NewDecoder(r.Body).Decode(&in); err != nil || in.Name != "shop.com" || in.App != "shop" {
+ t.Errorf("purchase: %+v, %v", in, err)
+ }
+ fmt.Fprint(w, `{"id":"p1","checkout_url":"https://checkout.example/p1","state":"awaiting_payment"}`)
+ }, func(w http.ResponseWriter, r *http.Request) {
+ if n >= len(states) {
+ t.Error("polled past live")
+ http.Error(w, "too many polls", 500)
+ return
+ }
+ ds := ""
+ if n >= 5 {
+ ds = "issuing-cert"
+ }
+ if n == 7 {
+ ds = "live"
+ }
+ json.NewEncoder(w).Encode(map[string]string{"id": "p1", "state": states[n], "domain_state": ds})
+ n++
+ })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ 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"} {
+ if strings.Count(out.String(), want) != 1 {
+ t.Fatalf("expected %q once: %s", want, &out)
+ }
+ }
+ if n != len(states) {
+ t.Fatalf("poll count %d", n)
+ }
+}
+
+func runBuyTestCommand(t *testing.T, base string, args ...string) (string, error) {
+ t.Helper()
+ bin := buildCarlos(t)
+ scratch := t.TempDir()
+ creds := filepath.Join(scratch, "credentials")
+ writeTestCredential(t, creds, base)
+ argv := append([]string{"domains", "buy", "shop.com", "--app", "shop", "--account", "bab", "--console", base, "--yes"}, args...)
+ cmd := exec.Command(bin, argv...)
+ cmd.Dir = scratch
+ cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+creds, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=", "CARLOS_CONFIG=")
+ out, err := cmd.CombinedOutput()
+ return string(out), err
+}
+
+func TestDomainsBuyFailedExitsNonZeroWithReason(t *testing.T) {
+ for _, state := range []string{"failed", "expired", "unpaid"} {
+ t.Run(state, func(t *testing.T) {
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ }, func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]string{"id": "p1", "state": state, "reason": "payment not completed"})
+ })
+ out, err := runBuyTestCommand(t, ts.URL)
+ if err == nil || !strings.Contains(out, state) || !strings.Contains(out, "payment not completed") {
+ t.Fatalf("err=%v output=%s", err, out)
+ }
+ })
+ }
+}
+
+func TestDomainsBuyContactMissingNonTTYNamesFlag(t *testing.T) {
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(422)
+ fmt.Fprint(w, `{"code":"contact","error":"contact details required"}`)
+ }, nil)
+ out, err := runBuyTestCommand(t, ts.URL)
+ if err == nil || !strings.Contains(out, "--contact-file") || !strings.Contains(out, "contact details required") {
+ t.Fatalf("err=%v output=%s", err, out)
+ }
+}
+
+func TestDomainsBuyConfirmation(t *testing.T) {
+ for _, tc := range []struct {
+ name, input string
+ terminal, yes, purchase, wantError bool
+ }{
+ {name: "decline", input: "n\n", terminal: true},
+ {name: "default decline", input: "\n", terminal: true},
+ {name: "confirm", input: "yes\n", terminal: true, purchase: true},
+ {name: "non terminal", input: "yes\n", wantError: true},
+ {name: "yes flag", yes: true, purchase: true},
+ {name: "end of input", terminal: true, wantError: true},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ purchased := false
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ purchased = true
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment","checkout_url":"https://checkout.example/p1"}`)
+ }, nil)
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.yes, o.noWait, o.terminal, o.in = tc.yes, true, tc.terminal, strings.NewReader(tc.input)
+ err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o)
+ if (err != nil) != tc.wantError || purchased != tc.purchase {
+ t.Fatalf("purchased=%v err=%v output=%s", purchased, err, &out)
+ }
+ if !strings.Contains(out.String(), "12.99") {
+ t.Fatalf("missing quote: %s", &out)
+ }
+ })
+ }
+}
+
+func TestDomainsBuyContactInputs(t *testing.T) {
+ const contactJSON = `{"first_name":"Ada","last_name":"Lovelace","company":"","email":"ada@example.com","phone_country_code":"44","phone":"2071234567","street":"Example Road","house_number":"12","city":"London","state":"","postal_code":"N1 1AA","country":"GB"}`
+ for _, interactive := range []bool{false, true} {
+ t.Run(fmt.Sprint(interactive), func(t *testing.T) {
+ calls := 0
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ calls++
+ var in map[string]json.RawMessage
+ if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
+ t.Error(err)
+ }
+ if interactive && calls == 1 {
+ if _, ok := in["contact"]; ok {
+ t.Error("first purchase should reuse saved contact")
+ }
+ w.WriteHeader(422)
+ fmt.Fprint(w, `{"code":"contact","error":"contact details required"}`)
+ return
+ }
+ var got, want map[string]string
+ if err := json.Unmarshal(in["contact"], &got); err != nil {
+ t.Error(err)
+ }
+ json.Unmarshal([]byte(contactJSON), &want)
+ if !reflect.DeepEqual(got, want) {
+ t.Errorf("contact=%v want=%v", got, want)
+ }
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment","checkout_url":"https://checkout.example/p1"}`)
+ }, func(w http.ResponseWriter, r *http.Request) { t.Error("--no-wait polled"); w.WriteHeader(500) })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.noWait = true
+ if interactive {
+ o.yes, o.terminal = false, true
+ o.in = strings.NewReader("yes\nAda\nLovelace\n\nada@example.com\n44\n2071234567\nExample Road\n12\nLondon\n\nN1 1AA\nGB\n")
+ } else {
+ o.contactFile = filepath.Join(t.TempDir(), "contact.json")
+ if err := os.WriteFile(o.contactFile, []byte(contactJSON), 0600); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil {
+ t.Fatal(err)
+ }
+ wantCalls := 1
+ if interactive {
+ wantCalls = 2
+ }
+ if calls != wantCalls {
+ t.Fatalf("purchase calls=%d want=%d", calls, wantCalls)
+ }
+ if !strings.Contains(out.String(), "https://checkout.example/p1") {
+ t.Fatalf("missing checkout: %s", &out)
+ }
+ })
+ }
+}
+
+func TestDomainsBuyInvalidContactFile(t *testing.T) {
+ for _, data := range []string{"null", "[]", `{"unknown":"x"}`, `{} {}`, strings.Repeat(" ", 16385)} {
+ path := filepath.Join(t.TempDir(), "contact.json")
+ if err := os.WriteFile(path, []byte(data), 0600); err != nil {
+ t.Fatal(err)
+ }
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.contactFile = path
+ if err := domainsBuy(context.Background(), nil, apiAcct{}, "shop.com", "shop", o); err == nil || !strings.Contains(err.Error(), "--contact-file") {
+ t.Fatalf("expected file error, got %v", err)
+ }
+ }
+}
+
+func TestDomainsBuyLiveTimeout(t *testing.T) {
+ polls := 0
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ }, func(w http.ResponseWriter, r *http.Request) {
+ polls++
+ // The deadline starts at done, even if payment took more than ten minutes.
+ state, ds := "awaiting_payment", ""
+ if polls >= 210 {
+ state, ds = "done", "issuing-cert"
+ }
+ json.NewEncoder(w).Encode(map[string]string{"id": "p1", "state": state, "domain_state": ds})
+ })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ start := o.now()
+ wait := o.wait
+ o.wait = func(ctx context.Context, d time.Duration) error {
+ if d != 3*time.Second {
+ t.Errorf("poll interval=%v want 3s", d)
+ }
+ return wait(ctx, d)
+ }
+ if err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil {
+ t.Fatal(err)
+ }
+ if elapsed := o.now().Sub(start); elapsed != 1230*time.Second {
+ t.Fatalf("waited %v want 20m30s", elapsed)
+ }
+ if strings.Count(out.String(), "done") != 1 || strings.Count(out.String(), "issuing-cert") != 1 || !strings.Contains(out.String(), "background") {
+ t.Fatalf("output=%s", &out)
+ }
+}
+
+func TestDomainsBuyCancellation(t *testing.T) {
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ }, func(w http.ResponseWriter, r *http.Request) { t.Error("polled after cancellation") })
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.wait = func(ctx context.Context, _ time.Duration) error { cancel(); return waitDomainBuy(ctx, time.Hour) }
+ if err := domainsBuy(ctx, newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); !errors.Is(err, context.Canceled) {
+ t.Fatalf("got %v", err)
+ }
+}
+
+func TestDomainsBuyDoorErrors(t *testing.T) {
+ for _, status := range []int{409, 422, 429} {
+ for _, door := range []string{"check", "purchase", "status"} {
+ t.Run(fmt.Sprintf("%s/%d", door, status), func(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.WriteHeader(status)
+ fmt.Fprint(w, `{"error":"hostname unavailable"}`)
+ }))
+ defer ts.Close()
+ s := newTestSession(ts.URL)
+ var err error
+ switch door {
+ case "check":
+ _, err = s.postDomainCheck(context.Background(), apiAcct{Seg: "bab"}, "shop.com")
+ case "purchase":
+ _, err = s.postDomainPurchase(context.Background(), apiAcct{Seg: "bab"}, "shop.com", "shop", nil)
+ case "status":
+ _, err = s.getDomainPurchase(context.Background(), apiAcct{Seg: "bab"}, "p1")
+ }
+ if err == nil || err.Error() != "hostname unavailable" {
+ t.Fatalf("error=%v", err)
+ }
+ var ce *domainContactError
+ if errors.As(err, &ce) {
+ t.Fatal("ordinary refusal treated as contact error")
+ }
+ })
+ }
+ }
+}
+
+func TestDomainsBuyAPIExactAccountAndEscapedID(t *testing.T) {
+ for _, door := range []string{"check", "purchase", "status"} {
+ t.Run(door, func(t *testing.T) {
+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ path, method := "/api/cli/accounts/a%2Fb/domains/", "POST"
+ switch door {
+ case "check":
+ path += "check"
+ case "purchase":
+ path += "purchases"
+ case "status":
+ path += "purchases/p%2F1"
+ method = "GET"
+ }
+ if r.URL.EscapedPath() != path || r.URL.Query().Get("exact") != "sqid" || r.Method != method {
+ t.Errorf("request %s %s", r.Method, r.URL)
+ }
+ fmt.Fprint(w, `{}`)
+ }))
+ defer ts.Close()
+ s, a := newTestSession(ts.URL), apiAcct{Seg: "a/b", Exact: true}
+ var err error
+ switch door {
+ case "check":
+ _, err = s.postDomainCheck(context.Background(), a, "shop.com")
+ case "purchase":
+ _, err = s.postDomainPurchase(context.Background(), a, "shop.com", "shop", nil)
+ case "status":
+ _, err = s.getDomainPurchase(context.Background(), a, "p/1")
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
+
+func TestDomainsBuyCommandNoWait(t *testing.T) {
+ ts := buyTestServer(t, func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment","checkout_url":"https://checkout.example/p1"}`)
+ }, func(w http.ResponseWriter, r *http.Request) { t.Error("--no-wait polled") })
+ out, err := runBuyTestCommand(t, ts.URL, "--no-wait")
+ if err != nil || !strings.Contains(out, "12.99") || !strings.Contains(out, "https://checkout.example/p1") {
+ t.Fatalf("error=%v output=%s", err, out)
+ }
+}
+
+func TestDomainsCheckCommand(t *testing.T) {
+ ts := buyTestServer(t, nil, nil)
+ bin := buildCarlos(t)
+ scratch := t.TempDir()
+ creds := filepath.Join(scratch, "credentials")
+ writeTestCredential(t, creds, ts.URL)
+ cmd := exec.Command(bin, "domains", "check", "shop.com", "--account", "bab", "--console", ts.URL)
+ cmd.Dir = scratch
+ cmd.Env = carlosTestEnv(t, "CARLOS_CREDENTIALS="+creds, "CARLOS_DEPLOYMENT_BUCKET=", "CARLOS_DEPLOYMENT_DIR=", "CARLOS_CONFIG=")
+ out, err := cmd.CombinedOutput()
+ if err != nil || !strings.Contains(string(out), "12.99") || !strings.Contains(string(out), "EUR") {
+ t.Fatalf("error=%v output=%s", err, out)
+ }
+}
+
+type domainBuyRoundTrip func(*http.Request) (*http.Response, error)
+
+func (f domainBuyRoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
+
+func TestDomainsBuyLivePollHasRemainingDeadline(t *testing.T) {
+ s := newTestSession("http://127.0.0.1")
+ s.c.httpc.Transport = domainBuyRoundTrip(func(r *http.Request) (*http.Response, error) {
+ deadline, ok := r.Context().Deadline()
+ remaining := time.Until(deadline)
+ if !ok || remaining > 597*time.Second || remaining < 596*time.Second {
+ t.Errorf("live poll deadline: present=%v remaining=%v", ok, remaining)
+ }
+ return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"id":"p1","state":"done","domain_state":"live"}`))}, nil
+ })
+ // Remove the normal HTTP client's 30-second cap to observe the caller's deadline.
+ s.c.httpc.Timeout = 0
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ err := waitDomainPurchase(context.Background(), s, apiAcct{Seg: "bab"}, domainPurchaseResp{ID: "p1", State: "done", DomainState: "issuing-cert"}, o)
+ if err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/domains_buy_copy.go b/domains_buy_copy.go
new file mode 100644
index 000000000..042640ab6
--- /dev/null
+++ b/domains_buy_copy.go
@@ -0,0 +1,54 @@
+package main
+
+// Plan 1 drafts, replaced by the Luna pass (Task 11).
+const domainsBuyHelp = ` check <name> [flags]
+ check availability and the price for one year
+ buy <name> --app <a> [--contact-file contact.json] [--yes] [--no-wait] [flags]
+ buy a domain and wait for it to serve the app
+
+`
+
+const domainsCheckUsage = "usage: carlos domains check <name> [--account <a>] [--account-id <id>] [--console <origin>]\n"
+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{
+ "appFlag": "app the domain will serve",
+ "accountFlag": "account (sqid or name)",
+ "accountIDFlag": "account sqid, matched as a sqid only",
+ "consoleFlag": "console to use (default: the only logged-in one)",
+ "contactFileFlag": "JSON file containing the registrant's contact details",
+ "yesFlag": "confirm the purchase without prompting",
+ "noWaitFlag": "print the payment link without waiting for completion",
+ "quote": "%s: %s, %s %s for one year\n",
+ "available": "available",
+ "unavailable": "unavailable",
+ "confirm": "Buy this domain? [y/N] ",
+ "confirmNonTTY": "use --yes to confirm the purchase when stdin is not a terminal",
+ "cancelled": "Purchase cancelled.",
+ "contactNonTTY": "%w; supply contact details with --contact-file contact.json",
+ "contactFile": "read --contact-file: %w",
+ "contactJSON": "--contact-file must contain one contact JSON object",
+ "contactSize": "--contact-file is too large (maximum 16 KiB)",
+ "contactPrompt": "Enter the registrant's contact details.",
+ "firstName": "First name: ",
+ "lastName": "Last name: ",
+ "company": "Company (optional): ",
+ "email": "Email: ",
+ "phoneCountryCode": "Phone country code (digits only): ",
+ "phone": "Phone national number (digits only): ",
+ "street": "Street: ",
+ "houseNumber": "House number (optional): ",
+ "city": "City: ",
+ "state": "State or province (optional): ",
+ "postalCode": "Postal code: ",
+ "country": "Country (two uppercase letters): ",
+ "inputEnded": "input ended before the answer was complete",
+ "checkout": "Checkout: %s\n",
+ "purchaseState": "Purchase: %s\n",
+ "domainState": "Domain: %s\n",
+ "failed": "%s: %s",
+ "background": "The domain will finish setting up in the background.",
+ "missingID": "purchase response is missing its ID",
+ "unreadableCheck": "domains check: unreadable response: %w",
+ "unreadablePurchase": "domains buy: unreadable response: %w",
+}
diff --git a/domains_cli.go b/domains_cli.go
index 1c6f8689c..eb1fbfdcd 100644
--- a/domains_cli.go
+++ b/domains_cli.go
@@ -19,9 +19,9 @@ import (
"time"
)
-const domainsUsage = `usage: carlos domains <attach|verify|detach|list|paths|placements> [flags]
+const domainsUsage = `usage: carlos domains <check|buy|attach|verify|detach|list|paths|placements> [flags]
- attach --app <a> [--route <r>] [--wildcard] [--catchall] [--platform] [flags] <hostname>
+` + domainsBuyHelp + ` attach --app <a> [--route <r>] [--wildcard] [--catchall] [--platform] [flags] <hostname>
claim a customer's hostname for the app, pointed at
--route (default: the app's single instance record, if it
has exactly one — otherwise --route is required).
@@ -95,6 +95,12 @@ const domainsPlacementsUsage = `usage: carlos domains placements --app <a> [--se
func runDomains(args []string) {
if len(args) > 0 {
switch args[0] {
+ case "check":
+ runDomainsCheck(args[1:])
+ return
+ case "buy":
+ runDomainsBuy(args[1:])
+ return
case "attach":
runDomainsAttach(args[1:])
return
diff --git a/go.mod b/go.mod
index d1432938e..1190f0976 100644
--- a/go.mod
+++ b/go.mod
@@ -20,6 +20,7 @@ require (
github.com/aws/aws-sdk-go-v2/service/sts v1.45.6
github.com/aws/smithy-go v1.28.1
github.com/benbjohnson/litestream v0.5.14
+ github.com/mattn/go-isatty v0.0.20
github.com/pion/logging v0.2.4
github.com/pion/stun/v3 v3.1.5
github.com/pion/turn/v4 v4.1.4
@@ -57,7 +58,6 @@ require (
github.com/lmittmann/tint v1.1.3 // indirect
github.com/magefile/mage v1.14.0 // indirect
github.com/markusmobius/go-dateparser v1.2.4 // indirect
- github.com/mattn/go-isatty v0.0.20 // indirect
github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0 // indirect
github.com/ncruces/go-strftime v1.0.0 // indirect
github.com/pierrec/lz4/v4 v4.1.22 // indirect
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index b14a7a4e3..4693127b3 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -56,3 +56,4 @@ plan14-root-reads-fix-set-aside-exdev.tsv f9d3016cc6803338f9db19311f3f598e20c37c
plan14-root-reads-durability-3a-escrow.tsv 03a92257beb9b8aac421559e247d191bd69f28a0b26243397a1344a90d59fc2a
plan14-root-reads-rootfs-default-home.tsv 7a0a3da3d6fe7e3c77abb22676db000af2a276c3d13ccae0f038190f51287ed5
plan14-root-reads-probe-burst-limit.tsv 5f805400717bad7726bd9d62744b8103a40eb5f5823b0ab7c960a5c0965cb3bc
+plan14-root-reads-domain-registration-task-9.tsv 4b5a2b6d51c1460669dd22b93851d240b0c3b4b8e711cf3c4c28fa0209c873cc
diff --git a/internal/provision/testdata/plan14-root-reads-domain-registration-task-9.tsv b/internal/provision/testdata/plan14-root-reads-domain-registration-task-9.tsv
new file mode 100644
index 000000000..258e8bbaa
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-domain-registration-task-9.tsv
@@ -0,0 +1,7 @@
+# Census overlay domain-registration-task-9, written by census-propose (#369). census-ruling-domain-registration-task-9, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-domain-registration-task-9.md.
+# 0 body, 0 sites, 2 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+# 1 new dispositions: 0 reads re-frozen at their disposition with the claim, 1 new units frozen accepted-legacy, 0 quiet units retired while they read nothing, 0 other.
+@legacy bef611f50c90828c8824dcb0df11cdfd38d813d3eb66cbb8d42f8b9bbaa27cc5 domains_buy_cli.go readDomainContact legacy accepted-legacy accepted-legacy;rev3=census-ruling-domain-registration-task-9;basis=CLI-only --contact-file input: explicitly named local JSON file, opened read-only, limited to 16 KiB, decoded with unknown fields and trailing JSON refused; no root-owned runtime state or production storage read or written. file:Open@77,file:ReadAll@203 a3b2a9c922e08d9749701fa4ad56f910ae4ce16fea02cf9a56d1524aba2feed9
+domains_buy_cli.go readDomainContact legacy accepted-legacy accepted-legacy;rev3=census-ruling-domain-registration-task-9;basis=CLI-only --contact-file input: explicitly named local JSON file, opened read-only, limited to 16 KiB, decoded with unknown fields and trailing JSON refused; no root-owned runtime state or production storage read or written. file:Open@77,file:ReadAll@203 a3b2a9c922e08d9749701fa4ad56f910ae4ce16fea02cf9a56d1524aba2feed9
+@coverage . d2506794e0b166e3e47b7cae152744ea8f86e52a965720e233368ae6802ac9cf
+@coverage internal/registrar 72e4c38f5c4cc6cb852cb73f3d6c98a4b801378843fd7ec6817d8c4e0f0c9beb