carlos / platform Public

Merge origin/main into sec-h5-edge-availability

Takes main's census chain (cli-contact-prompts); this branch's overlay
is re-proposed on top in a later commit.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2d495239015e45a5c1dc20935c5927a2ef67175b parent 8426236parent 9f52923
25 files changed, +1,932 −161
  • .amadan/code-health.tsv +1 −1
  • account_choose.go +1 −0
  • apimode.go +0 −46
  • approved_domains_buy_copy_test.go +42 −12
  • cli_spinner.go +128 −0
  • cli_spinner_test.go +135 −0
  • console_moved.go +56 −0
  • docs/superpowers/notes/census-proposal-cli-contact-prompts.md +11 −0
  • docs/superpowers/specs/LUNA-COPY-BRIEF-CONTACT-PROMPTS.md +87 −0
  • docs/superpowers/specs/LUNA-COPY-RESULT-CONTACT-PROMPTS.md +37 −0
  • domains_account_cli.go +31 −21
  • domains_buy_cli.go +54 −42
  • domains_buy_cli_test.go +2 −2
  • domains_buy_copy.go +58 −12
  • domains_calling_codes.go +84 −0
  • domains_contact_prompt.go +377 −0
  • domains_contact_prompt_test.go +665 −0
  • domains_transfer_cli.go +85 −22
  • internal/console/accountdomainbuy_test.go +1 −0
  • internal/console/accountdomaintransfer_test.go +1 −0
  • internal/console/apidomainbuy.go +5 −2
  • internal/console/apidomainbuy_test.go +21 −0
  • internal/console/contact_autocomplete_test.go +46 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −1
  • internal/provision/testdata/plan14-root-reads-cli-contact-prompts.tsv +3 −0
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv
index fece09da2..e03de6a10 100644
--- a/.amadan/code-health.tsv
+++ b/.amadan/code-health.tsv
@@ -2218,7 +2218,7 @@ func-lines internal/registry (*Registry).haJournal - 402 # raised: ha-departure-
func-lines internal/release PassFilter - 399
func-lines internal/release adoptHost - 494
func-lines internal/team TestFixture - 421
-file-lines . apimode.go - 4175
+file-lines . apimode.go - 4150
file-lines . apimode_test.go - 3530 # raised: fdc912b (batch 2, #1123) landed before the ratchet; tests for the system update refusals
file-lines internal/activator activator.go - 3785 # raised: the Service.ConfigBeforeWake field and doWakeOnce's one call to it (the body lives in configbeforewake.go); before it, #1290 step 2c
file-lines internal/activator activator_test.go - 5471
diff --git a/account_choose.go b/account_choose.go
index c3d8e65e5..058738862 100644
--- a/account_choose.go
+++ b/account_choose.go
@@ -69,6 +69,7 @@ func chooserScanner() *bufio.Scanner {
// promptLine prints one prompt and reads one trimmed line; EOF answers "".
func promptLine(out io.Writer, prompt string) string {
+ pauseBusyLine()
fmt.Fprint(out, prompt)
sc := chooserScanner()
if !sc.Scan() {
diff --git a/apimode.go b/apimode.go
index 1276aab9b..cb3b5230d 100644
--- a/apimode.go
+++ b/apimode.go
@@ -229,52 +229,6 @@ func consoleMoved(from string, status int, location string) *consoleMovedError {
return &consoleMovedError{From: from, To: origin}
}
-// consoleMovedOffered makes the offer once-per-process: polling verbs
-// (`logs -f`, authLogin's approval loop) hit the same 3xx every interval,
-// and prompting on each would eat the terminal's stdin; and the offer
-// itself runs authLogin, whose polls reach these same response sites — the
-// guard is also the re-entrancy stop for a redirect chain. After the one
-// offer (taken or declined), every further hit is the typed error.
-var consoleMovedOffered bool
-
-// quietConsoleOffers suppresses the offer entirely — set around calls
-// whose contract is to degrade silently (whoami's memberships bonus line),
-// where even one prompt would make a working command look broken.
-var quietConsoleOffers bool
-
-// offerConsoleMoved is the terminal's version of consoleMovedError: explain
-// the move, offer the standard device flow against the new host, and — when
-// a .carlos/config names the old console — offer to repoint it (keeping
-// every other key, account included: the pair moves together). The verb
-// still ends nonzero: its request died against the old host mid-flight, and
-// "logged in — re-run your command" is the honest state.
-func offerConsoleMoved(e *consoleMovedError) error {
- if !interactiveTerminal() || quietConsoleOffers || consoleMovedOffered {
- return e
- }
- consoleMovedOffered = true
- fmt.Fprintf(stdout, "this console has moved: %s -> %s\n", e.From, e.To)
- if !promptYes(stdout, fmt.Sprintf("log in to %s now? [y/N] ", e.To)) {
- return e
- }
- if err := authLogin(stdout, []string{"--console", e.To}); err != nil {
- return err
- }
- if cfgConsole, src, err := configDefault(); err == nil && cfgConsole == e.From && src != "" {
- // The destination is named in the prompt, not only the file: a y
- // here changes where future ships go, and that must never rest on
- // remembering what the previous prompt said.
- if promptYes(stdout, fmt.Sprintf("update %s to point at %s too? [y/N] ", src, e.To)) {
- if err := saveConfigFile(src, e.To, 0o755); err != nil {
- warnf(stdout, "not updated (%s): %v", src, err)
- } else {
- mutedf(stdout, "updated: %s now names %s", src, e.To)
- }
- }
- }
- return fmt.Errorf("logged in to %s — re-run your command against it", e.To)
-}
-
// errNoDeploymentTarget is resolveMode's "nothing configured at all"
// refusal — a var so offerLogin can recognize it by identity rather than
// by matching its wording.
diff --git a/approved_domains_buy_copy_test.go b/approved_domains_buy_copy_test.go
index 722ce45f2..c8baea675 100644
--- a/approved_domains_buy_copy_test.go
+++ b/approved_domains_buy_copy_test.go
@@ -77,18 +77,48 @@ func TestApprovedDomainsBuyCopy(t *testing.T) {
{"cli.contactJSON", "domains_buy_copy.go", "--contact-file must contain one contact JSON object"},
{"cli.contactSize", "domains_buy_copy.go", "--contact-file is too large (maximum 16 KiB)"},
{"cli.contactPrompt", "domains_buy_copy.go", "enter your contact details"},
- {"cli.firstName", "domains_buy_copy.go", "first name: "},
- {"cli.lastName", "domains_buy_copy.go", "last name: "},
- {"cli.company", "domains_buy_copy.go", "company (optional): "},
- {"cli.email", "domains_buy_copy.go", "email: "},
- {"cli.phoneCountryCode", "domains_buy_copy.go", "phone country code (digits only): "},
- {"cli.phone", "domains_buy_copy.go", "phone number (digits only): "},
- {"cli.street", "domains_buy_copy.go", "street: "},
- {"cli.houseNumber", "domains_buy_copy.go", "house number (optional): "},
- {"cli.city", "domains_buy_copy.go", "city: "},
- {"cli.state", "domains_buy_copy.go", "state or province (optional): "},
- {"cli.postalCode", "domains_buy_copy.go", "postal code: "},
- {"cli.country", "domains_buy_copy.go", "country (two uppercase letters): "},
+ // The contact prompt labels: Title Case by Paul's ruling, 2026-11-27
+ // (cli-contact-prompts). One Phone field replaced the calling code
+ // and number pair, so cli.phoneCountryCode is gone; the ": " moved
+ // to the prompt's format (cli.contactField, a draft).
+ {"cli.firstName", "domains_buy_copy.go", "First Name"},
+ {"cli.lastName", "domains_buy_copy.go", "Last Name"},
+ {"cli.company", "domains_buy_copy.go", "Company (optional)"},
+ {"cli.email", "domains_buy_copy.go", "Email"},
+ {"cli.phone", "domains_buy_copy.go", "Phone"},
+ {"cli.street", "domains_buy_copy.go", "Street"},
+ {"cli.houseNumber", "domains_buy_copy.go", "House Number (optional)"},
+ {"cli.city", "domains_buy_copy.go", "City"},
+ {"cli.state", "domains_buy_copy.go", "State or Province (optional)"},
+ {"cli.postalCode", "domains_buy_copy.go", "Postal Code"},
+ {"cli.country", "domains_buy_copy.go", "Country"},
+ // The contact form's other strings and the busy line, approved by
+ // delegation (Luna), 2026-11-27:
+ // docs/superpowers/specs/LUNA-COPY-RESULT-CONTACT-PROMPTS.md.
+ {"cli.contactField", "domains_buy_copy.go", "%s: "},
+ {"cli.contactFieldDefault", "domains_buy_copy.go", "%s [%s]: "},
+ {"cli.contactRequired", "domains_buy_copy.go", "enter a value for %s"},
+ {"cli.contactPhoneRequired", "domains_buy_copy.go", "enter a phone number. domain registries require one. for example +353 87 123 4567"},
+ {"cli.contactPhoneChars", "domains_buy_copy.go", "use digits, spaces, dashes, dots and brackets. for an international number, start with + and the calling code. for example +353 87 123 4567"},
+ {"cli.contactPhoneCode", "domains_buy_copy.go", "start with + and the calling code. for example +353 87 123 4567"},
+ {"cli.contactPhoneNumber", "domains_buy_copy.go", "enter the number after the calling code. for example +353 87 123 4567"},
+ // Follow-up, approved by delegation (Luna), 2026-11-27: the same
+ // spec, under its Follow-up heading.
+ {"cli.contactPhoneLength", "domains_buy_copy.go", "that number is too short or too long. enter it with its calling code, for example +353 87 123 4567"},
+ {"cli.contactEmailInvalid", "domains_buy_copy.go", "enter an email address. for example name@example.com"},
+ {"cli.contactCountryInvalid", "domains_buy_copy.go", "use the country's two-letter code. for example IE"},
+ {"cli.contactPickHeader", "domains_buy_copy.go", "saved contacts:"},
+ {"cli.contactPickLine", "domains_buy_copy.go", " %d %s\n"},
+ {"cli.contactPickPrompt", "domains_buy_copy.go", "choose a contact by number, or enter n for a new one [1]: "},
+ {"cli.contactPickInvalid", "domains_buy_copy.go", "enter a number from 1 to %d, or n for a new contact"},
+ {"cli.contactSaveOffer", "domains_buy_copy.go", "save these details as a contact? [Y/n] "},
+ {"cli.contactSavedAs", "domains_buy_copy.go", "saved as contact %s. use it next time with --contact %s\n"},
+ {"cli.contactSaveFailed", "domains_buy_copy.go", "could not save the contact: %v. save the details below as contact.json, then pass --contact-file contact.json next time:\n"},
+ {"cli.spinCheck", "domains_buy_copy.go", "checking %s…"},
+ {"cli.spinStartBuy", "domains_buy_copy.go", "starting the purchase…"},
+ {"cli.spinStartTransfer", "domains_buy_copy.go", "starting the transfer…"},
+ {"cli.spinSaveContact", "domains_buy_copy.go", "saving the contact…"},
+ {"cli.spinWait", "domains_buy_copy.go", "waiting for %s…"},
{"cli.inputEnded", "domains_buy_copy.go", "input ended before the answer was complete"},
{"cli.checkout", "domains_buy_copy.go", "checkout: %s\n"},
{"cli.purchaseState", "domains_buy_copy.go", "purchase: %s\n"},
diff --git a/cli_spinner.go b/cli_spinner.go
new file mode 100644
index 000000000..411f678d8
--- /dev/null
+++ b/cli_spinner.go
@@ -0,0 +1,128 @@
+package main
+
+// A busy line for the CLI's slow calls (`carlos domains buy` and
+// `carlos domains transfer`, Paul 2026-11-27): a turning mark and a label on
+// stderr, only when stderr is a terminal, so pipes, CI and recorded output
+// never see it. The line is cleared when the call ends, before anything
+// else is printed or asked, and on an interrupt.
+
+import (
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "strings"
+ "sync"
+ "time"
+ "unicode/utf8"
+
+ "github.com/mattn/go-isatty"
+)
+
+const spinnerEvery = 120 * time.Millisecond
+
+// spinnerFrames are ASCII, which every terminal (Windows' among them) draws.
+const spinnerFrames = `-\|/`
+
+// stderrSpinner is the busy line for stderr, or nil when stderr is not a
+// terminal: a nil spinner draws nothing (startSpin).
+func stderrSpinner() func(string) func() {
+ return spinnerFor(os.Stderr, isatty.IsTerminal(os.Stderr.Fd()))
+}
+
+// spinnerFor draws on w when terminal says w is one; nil otherwise.
+func spinnerFor(w io.Writer, terminal bool) func(string) func() {
+ if !terminal {
+ return nil
+ }
+ return func(label string) func() { return startLineSpinner(w, label, spinnerEvery, transferCodeSignals) }
+}
+
+// startSpin starts spin's busy line with label and returns what stops it;
+// with no spinner, a stop that does nothing.
+func startSpin(spin func(string) func(), label string) func() {
+ if spin == nil {
+ return func() {}
+ }
+ return spin(label)
+}
+
+// busyLine is the busy line drawing now, if any: at most one at a time.
+// A prompt or offer reached while it draws (pauseBusyLine) stops and clears
+// it first, so nothing is ever drawn over a question: the console-moved
+// offer inside an HTTP helper, say, or any promptLine or domainBuyAnswer.
+var busyLine struct {
+ mu sync.Mutex
+ stop func()
+ id *int // which line stop is, so a line stopped since is not cleared twice
+}
+
+// pauseBusyLine stops and clears the busy line drawing now, if any. Its
+// owner's own stop is then a no-op; the line does not come back.
+func pauseBusyLine() {
+ busyLine.mu.Lock()
+ stop := busyLine.stop
+ busyLine.stop, busyLine.id = nil, nil
+ busyLine.mu.Unlock()
+ if stop != nil {
+ stop()
+ }
+}
+
+// startLineSpinner draws label at once and turns its mark every interval
+// until the returned stop is called, which clears the line and returns only
+// once nothing more will be written. One of signals clears the line too,
+// then is delivered again with its default action, as readTransferCodeTerminal
+// does, so Ctrl-C ends the process as it would have, on a clean line.
+func startLineSpinner(w io.Writer, label string, every time.Duration, signals []os.Signal) func() {
+ pauseBusyLine()
+ width := 2 + utf8.RuneCountInString(label)
+ blank := "\r" + strings.Repeat(" ", width) + "\r"
+ fmt.Fprintf(w, "\r%c %s", spinnerFrames[0], label)
+ sigs := make(chan os.Signal, 1)
+ if len(signals) > 0 {
+ signal.Notify(sigs, signals...)
+ }
+ stopc, done := make(chan struct{}), make(chan struct{})
+ go func() {
+ defer close(done)
+ tick := time.NewTicker(every)
+ defer tick.Stop()
+ for i := 1; ; i++ {
+ select {
+ case <-tick.C:
+ fmt.Fprintf(w, "\r%c %s", spinnerFrames[i%len(spinnerFrames)], label)
+ case sig := <-sigs:
+ io.WriteString(w, blank)
+ signal.Stop(sigs)
+ if self, err := os.FindProcess(os.Getpid()); err == nil && self.Signal(sig) != nil {
+ _ = self.Kill()
+ }
+ return
+ case <-stopc:
+ io.WriteString(w, blank)
+ return
+ }
+ }
+ }()
+ var once sync.Once
+ stop := func() {
+ once.Do(func() {
+ close(stopc)
+ <-done
+ signal.Stop(sigs)
+ })
+ }
+ id := new(int)
+ busyLine.mu.Lock()
+ busyLine.stop, busyLine.id = stop, id
+ busyLine.mu.Unlock()
+ return func() {
+ busyLine.mu.Lock()
+ if busyLine.id == id {
+ busyLine.stop, busyLine.id = nil, nil
+ }
+ busyLine.mu.Unlock()
+ stop()
+ }
+}
diff --git a/cli_spinner_test.go b/cli_spinner_test.go
new file mode 100644
index 000000000..403edcc91
--- /dev/null
+++ b/cli_spinner_test.go
@@ -0,0 +1,135 @@
+package main
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "regexp"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestSpinnerOffWhenNotATerminal: stderr that is not a terminal gets no
+// spinner, and a nil spinner writes nothing at all.
+func TestSpinnerOffWhenNotATerminal(t *testing.T) {
+ var w bytes.Buffer
+ spin := spinnerFor(&w, false)
+ if spin != nil {
+ t.Fatal("a spinner for a non-terminal")
+ }
+ startSpin(spin, "checking shop.com…")()
+ if w.Len() != 0 {
+ t.Fatalf("wrote %q", w.String())
+ }
+}
+
+// TestSpinnerDrawsAndClears: the label is drawn at once, and stop blanks
+// the whole line and returns the cursor before anything else is written.
+// Stopping twice is harmless.
+func TestSpinnerDrawsAndClears(t *testing.T) {
+ var w bytes.Buffer
+ stop := startLineSpinner(&w, "checking shop.com…", time.Hour, nil)
+ stop()
+ stop()
+ want := "\r- checking shop.com…" + "\r" + strings.Repeat(" ", 2+len([]rune("checking shop.com…"))) + "\r"
+ if w.String() != want {
+ t.Fatalf("got %q want %q", w.String(), want)
+ }
+}
+
+// TestDomainsBuySpinnerClearedBeforeOutput runs a buy with stdout and the
+// spinner on one terminal: every busy line is cleared before the next
+// output or prompt, the check, the start and each poll show one, and
+// nothing else carries a carriage return.
+func TestDomainsBuySpinnerClearedBeforeOutput(t *testing.T) {
+ polls := 0
+ 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) {
+ polls++
+ if polls < 2 {
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ return
+ }
+ fmt.Fprint(w, `{"id":"p1","state":"done","domain_state":"live"}`)
+ })
+ var term bytes.Buffer
+ o := buyTestOptions(&term)
+ o.yes, o.terminal, o.in = false, true, strings.NewReader("y\n")
+ o.spin = func(label string) func() { return startLineSpinner(&term, label, time.Hour, nil) }
+ if err := domainsBuy(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil {
+ t.Fatalf("%v\n%q", err, term.String())
+ }
+ text := term.String()
+ busy := regexp.MustCompile(`\r- ([^\r]*)\r( *)\r`)
+ labels := []string{}
+ for _, m := range busy.FindAllStringSubmatch(text, -1) {
+ if len(m[2]) != 2+len([]rune(m[1])) {
+ t.Errorf("busy line %q cleared with %d spaces", m[1], len(m[2]))
+ }
+ labels = append(labels, m[1])
+ }
+ want := []string{"checking shop.com…", "starting the purchase…", "waiting for shop.com…", "waiting for shop.com…"}
+ if strings.Join(labels, "|") != strings.Join(want, "|") {
+ t.Errorf("busy lines %q want %q", labels, want)
+ }
+ if rest := busy.ReplaceAllString(text, ""); strings.Contains(rest, "\r") {
+ t.Errorf("a busy line was not cleared before the next output: %q", text)
+ }
+ if !strings.Contains(text, "\r"+strings.Repeat(" ", 2+len([]rune("checking shop.com…")))+"\r"+"shop.com: available") {
+ t.Errorf("the quote must follow the cleared line: %q", text)
+ }
+}
+
+// TestSpinnerClearedBeforeConsoleMovedOffer: the console-moved offer runs
+// inside an HTTP helper, while the caller's busy line draws. It clears the
+// line before it speaks, and the caller's own stop afterwards writes
+// nothing more.
+func TestSpinnerClearedBeforeConsoleMovedOffer(t *testing.T) {
+ useTempCredentials(t)
+ clearDeploymentEnv(t)
+ out := captureStdout(t)
+ forceTerminal(t, true)
+ resetMovedOffer(t)
+ moved := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Location", "https://console.example.test"+r.URL.Path)
+ w.WriteHeader(http.StatusPermanentRedirect)
+ }))
+ t.Cleanup(moved.Close)
+ oldIn := chooserIn
+ chooserIn = strings.NewReader("n\n") // log in? no.
+ t.Cleanup(func() { chooserIn = oldIn })
+
+ label := "checking shop.com…"
+ stop := startLineSpinner(out, label, time.Hour, nil)
+ _, _, err := newTestSession(moved.URL).getJSON(context.Background(), "/api/cli/accounts/bab/domains/contacts")
+ stop()
+ if err == nil || !strings.Contains(err.Error(), "this console has moved") {
+ t.Fatalf("err=%v", err)
+ }
+ blank := "\r" + strings.Repeat(" ", 2+len([]rune(label))) + "\r"
+ want := "\r- " + label + blank + "this console has moved: "
+ if !strings.HasPrefix(out.String(), want) {
+ t.Fatalf("the offer was not on a clean line: %q", out.String())
+ }
+ if strings.Count(out.String(), "\r") != 3 {
+ t.Fatalf("the busy line drew again after the offer: %q", out.String())
+ }
+}
+
+// TestSpinnerPausedByPrompt: any prompt reached while a busy line draws
+// clears it first.
+func TestSpinnerPausedByPrompt(t *testing.T) {
+ var w bytes.Buffer
+ stop := startLineSpinner(&w, "saving the contact…", time.Hour, nil)
+ answer, err := domainBuyAnswer(bufio.NewScanner(strings.NewReader("y\n")), &w, "save? ")
+ stop()
+ blank := "\r" + strings.Repeat(" ", 2+len([]rune("saving the contact…"))) + "\r"
+ if err != nil || answer != "y" || w.String() != "\r- saving the contact…"+blank+"save? " {
+ t.Fatalf("answer=%q err=%v out=%q", answer, err, w.String())
+ }
+}
diff --git a/console_moved.go b/console_moved.go
new file mode 100644
index 000000000..39e8bc96c
--- /dev/null
+++ b/console_moved.go
@@ -0,0 +1,56 @@
+package main
+
+// The interactive half of a console that has moved (#160): consoleMoved and
+// consoleMovedError, in apimode.go, find and word the move; this offers to
+// log in to the new host. Split from apimode.go by concern.
+
+import "fmt"
+
+// consoleMovedOffered makes the offer once-per-process: polling verbs
+// (`logs -f`, authLogin's approval loop) hit the same 3xx every interval,
+// and prompting on each would eat the terminal's stdin; and the offer
+// itself runs authLogin, whose polls reach these same response sites — the
+// guard is also the re-entrancy stop for a redirect chain. After the one
+// offer (taken or declined), every further hit is the typed error.
+var consoleMovedOffered bool
+
+// quietConsoleOffers suppresses the offer entirely — set around calls
+// whose contract is to degrade silently (whoami's memberships bonus line),
+// where even one prompt would make a working command look broken.
+var quietConsoleOffers bool
+
+// offerConsoleMoved is the terminal's version of consoleMovedError: explain
+// the move, offer the standard device flow against the new host, and — when
+// a .carlos/config names the old console — offer to repoint it (keeping
+// every other key, account included: the pair moves together). The verb
+// still ends nonzero: its request died against the old host mid-flight, and
+// "logged in — re-run your command" is the honest state.
+func offerConsoleMoved(e *consoleMovedError) error {
+ if !interactiveTerminal() || quietConsoleOffers || consoleMovedOffered {
+ return e
+ }
+ consoleMovedOffered = true
+ // Reached inside an HTTP helper, perhaps under a busy line: clear it
+ // before speaking.
+ pauseBusyLine()
+ fmt.Fprintf(stdout, "this console has moved: %s -> %s\n", e.From, e.To)
+ if !promptYes(stdout, fmt.Sprintf("log in to %s now? [y/N] ", e.To)) {
+ return e
+ }
+ if err := authLogin(stdout, []string{"--console", e.To}); err != nil {
+ return err
+ }
+ if cfgConsole, src, err := configDefault(); err == nil && cfgConsole == e.From && src != "" {
+ // The destination is named in the prompt, not only the file: a y
+ // here changes where future ships go, and that must never rest on
+ // remembering what the previous prompt said.
+ if promptYes(stdout, fmt.Sprintf("update %s to point at %s too? [y/N] ", src, e.To)) {
+ if err := saveConfigFile(src, e.To, 0o755); err != nil {
+ warnf(stdout, "not updated (%s): %v", src, err)
+ } else {
+ mutedf(stdout, "updated: %s now names %s", src, e.To)
+ }
+ }
+ }
+ return fmt.Errorf("logged in to %s — re-run your command against it", e.To)
+}
diff --git a/docs/superpowers/notes/census-proposal-cli-contact-prompts.md b/docs/superpowers/notes/census-proposal-cli-contact-prompts.md
new file mode 100644
index 000000000..ec04c9ab5
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-cli-contact-prompts.md
@@ -0,0 +1,11 @@
+# Census approval: cli-contact-prompts
+
+Ruling `census-ruling-cli-contact-prompts`. 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: `.`.
+
+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: `dbdeb2e3a1a89cb8f33584fdb80a3bf1c5adef14ce222fef9d442ed8e059699c` → `dbdeb2e3a1a89cb8f33584fdb80a3bf1c5adef14ce222fef9d442ed8e059699c`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-cli-contact-prompts.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/docs/superpowers/specs/LUNA-COPY-BRIEF-CONTACT-PROMPTS.md b/docs/superpowers/specs/LUNA-COPY-BRIEF-CONTACT-PROMPTS.md
new file mode 100644
index 000000000..06a89432d
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-BRIEF-CONTACT-PROMPTS.md
@@ -0,0 +1,87 @@
+You are the copy-review gate for this set. Paul delegated copy review to you on 2026-10-25, so your verdicts ARE the review. Do NOT run the copy-review skill or start any server. Do not edit files.
+
+# Copy pass: carlos domains contact prompts and busy line (CLI)
+
+`carlos domains buy` and `carlos domains transfer` ask for the registrant's contact details when the account has no usable saved contact.
+
+The form now does the following:
+- It asks one field at a time. Each field shows a default as `Label [value]: `, and Enter keeps it.
+- It checks each answer as it is typed. A bad answer prints a reason line and asks the same field again.
+- It takes the phone number as one field, after the country, so a number without + uses the country's calling code.
+- When no purchase or transfer started, it offers to save what was typed as a contact.
+
+The form opens with a choice of saved contacts. A busy line (a spinner, on a terminal only, on stderr, cleared before any other output) shows while the CLI waits on the console.
+
+Reference for the surrounding approved strings: the `domainsBuyCopy` and `domainsTransferCopy` maps in domains_buy_copy.go, on branch cli-contact-prompts, in the worktree /home/paulca/.cache/tmp/cli-contact-prompts.
+
+## House rules for cli strings
+
+- Lower case, no final full stop (prompts keep their trailing space; output lines keep their `\n`).
+- Plain short words: lead with the state, then what to do.
+- No em or en dashes.
+- No exclamation marks.
+- Keep every placeholder (`%s`, `%d`, `%v`), the same number of each and in the same order.
+- Keep command names and flags exactly as written: `--contact`, `--contact-file`, `contact.json`, `[Y/n]`, `n`.
+- Example values are data: `+353 87 123 4567`, `name@example.com`, `IE`.
+- The `…` in busy lines is the single ellipsis character; keep it or replace it with nothing, never with three dots.
+
+## Fixed by Paul (do not review)
+
+The field labels are Title Case (Paul's ruling, 2026-11-27):
+- First Name
+- Last Name
+- Company (optional)
+- Email
+- Street
+- House Number (optional)
+- City
+- State or Province (optional)
+- Postal Code
+- Country
+- Phone
+
+A label fills `%s` in `contactField` / `contactFieldDefault`. A label also fills `contactRequired`'s `%s`, giving for example `Postal Code is required`. Say if that reads badly, and propose the fix as a new text for `contactRequired` only.
+
+## Strings to review (key: draft)
+
+- contactField: `%s: `
+- contactFieldDefault: `%s [%s]: `
+- contactRequired: `%s is required`
+- contactPhoneRequired: `a phone number is required, because domain registries need one. for example +353 87 123 4567`
+- contactPhoneChars: `use digits, spaces, dashes and brackets, with + before the calling code. for example +353 87 123 4567`
+- contactPhoneCode: `start with + and the calling code. for example +353 87 123 4567`
+- contactPhoneSplit: `put a space after the calling code. for example +353 87 123 4567`
+- contactPhoneNumber: `enter the number after the calling code. for example +353 87 123 4567`
+- contactEmailInvalid: `that does not look like an email address. for example name@example.com`
+- contactCountryInvalid: `use the country's two-letter code. for example IE`
+- contactPickHeader: `saved contacts:`
+- contactPickLine: ` %d %s\n`
+- contactPickPrompt: `use which contact? a number, or n for a new one [1]: `
+- contactPickInvalid: `enter a number from 1 to %d, or n for a new contact`
+- contactSaveOffer: `save these details as a contact? [Y/n] `
+- contactSavedAs: `saved as contact %s. use it next time with --contact %s\n`
+- contactSaveFailed: `could not save the contact: %v. to use these details next time, save this as contact.json and pass --contact-file contact.json:\n` (followed by the JSON)
+- spinCheck: `checking %s…` (%s is the domain)
+- spinStartBuy: `starting the purchase…`
+- spinStartTransfer: `starting the transfer…`
+- spinSaveContact: `saving the contact…`
+- spinWait: `waiting for %s…` (%s is the domain)
+
+Note: sentences inside one line are joined with ". " and the line stays lower case after the full stop. That is the existing CLI pattern; keep it unless it misleads.
+
+Answer with a `key | new text | why` table for every key (new text = the draft when you keep it), then a Flags section.
+
+## Follow-up
+
+You are the copy-review gate for this set. Paul delegated copy review to you on 2026-10-25, so your verdict IS the review. Do NOT run the copy-review skill or start any server. Do not edit files.
+
+This is a follow-up to /home/paulca/.cache/cli-contact-prompts/LUNA-BRIEF.md (same CLI contact form; your verdict on it is in LUNA-RESULT.md). The same house rules for cli strings apply.
+
+Changes since your pass:
+- The phone field now accepts any number without a space after the calling code, so `contactPhoneSplit` was removed.
+- One new string. It appears when the whole number, calling code included, has fewer than 7 or more than 15 digits:
+ - contactPhoneLength: `that number is too short or too long. enter it with its calling code, for example +353 87 123 4567`
+
+Keep it consistent with your approved siblings. For example, contactPhoneRequired reads `enter a phone number. domain registries require one. for example +353 87 123 4567`.
+
+Answer with a `key | new text | why` row, then Flags.
diff --git a/docs/superpowers/specs/LUNA-COPY-RESULT-CONTACT-PROMPTS.md b/docs/superpowers/specs/LUNA-COPY-RESULT-CONTACT-PROMPTS.md
new file mode 100644
index 000000000..dd11935e8
--- /dev/null
+++ b/docs/superpowers/specs/LUNA-COPY-RESULT-CONTACT-PROMPTS.md
@@ -0,0 +1,37 @@
+| key | new text | why |
+|---|---|---|
+| contactField | `%s: ` | keep |
+| contactFieldDefault | `%s [%s]: ` | keep |
+| contactRequired | `enter a value for %s` | `Postal Code is required` reads like a heading with Title Case labels; this is more natural and actionable |
+| contactPhoneRequired | `enter a phone number. domain registries require one. for example +353 87 123 4567` | clearer action and simpler grammar |
+| contactPhoneChars | `use digits, spaces, dashes, dots and brackets. for an international number, start with + and the calling code. for example +353 87 123 4567` | includes dots, which are accepted, and clarifies the international-number rule |
+| contactPhoneCode | `start with + and the calling code. for example +353 87 123 4567` | keep |
+| contactPhoneSplit | `put a space after the calling code. for example +353 87 123 4567` | keep |
+| contactPhoneNumber | `enter the number after the calling code. for example +353 87 123 4567` | keep |
+| contactEmailInvalid | `enter an email address. for example name@example.com` | more direct than “that does not look like” |
+| contactCountryInvalid | `use the country's two-letter code. for example IE` | keep |
+| contactPickHeader | `saved contacts:` | keep |
+| contactPickLine | ` %d %s\n` | keep |
+| contactPickPrompt | `choose a contact by number, or enter n for a new one [1]: ` | “use which contact?” is unidiomatic |
+| contactPickInvalid | `enter a number from 1 to %d, or n for a new contact` | keep |
+| contactSaveOffer | `save these details as a contact? [Y/n] ` | keep |
+| contactSavedAs | `saved as contact %s. use it next time with --contact %s\n` | keep |
+| contactSaveFailed | `could not save the contact: %v. save the details below as contact.json, then pass --contact-file contact.json next time:\n` | makes clear that the JSON below should be saved |
+| spinCheck | `checking %s…` | keep |
+| spinStartBuy | `starting the purchase…` | keep |
+| spinStartTransfer | `starting the transfer…` | keep |
+| spinSaveContact | `saving the contact…` | keep |
+| spinWait | `waiting for %s…` | keep |
+
+### Flags
+
+- P1: none.
+- Apply the six copy changes above; the remaining strings pass.
+- Placeholders, command names, flags, trailing spaces, newlines, and ellipsis usage are preserved.
+- No files were edited.
+
+## Follow-up
+
+contactPhoneLength | that number is too short or too long. enter it with its calling code, for example +353 87 123 4567 | Consistent with the approved phone-validation wording and example.
+
+Flags: none
diff --git a/domains_account_cli.go b/domains_account_cli.go
index 56bba2e60..32e3e0dcf 100644
--- a/domains_account_cli.go
+++ b/domains_account_cli.go
@@ -74,24 +74,30 @@ type noContactsDoorError struct{ error }
func (e *noContactsDoorError) Unwrap() error { return e.error }
-func (s *apiSession) domainContacts(ctx context.Context, acct apiAcct) ([]apiSavedContact, error) {
+// apiSavedContacts is the contacts list door's answer: the saved contacts,
+// most recently used first, and the account's own billing currency, ""
+// while none is set (and from a console that predates the field).
+type apiSavedContacts struct {
+ Contacts []apiSavedContact `json:"contacts"`
+ BillingCurrency string `json:"billing_currency"`
+}
+
+func (s *apiSession) domainContacts(ctx context.Context, acct apiAcct) (apiSavedContacts, error) {
+ var out apiSavedContacts
status, body, err := s.getJSON(ctx, domainBuyAPIPath(acct, "/contacts"))
if err != nil {
- return nil, err
+ return out, err
}
if status == http.StatusNotFound {
- return nil, &noContactsDoorError{apiErrorFromBody(status, body)}
+ return out, &noContactsDoorError{apiErrorFromBody(status, body)}
}
if status != http.StatusOK {
- return nil, apiErrorFromBody(status, body)
- }
- var out struct {
- Contacts []apiSavedContact `json:"contacts"`
+ return out, apiErrorFromBody(status, body)
}
if err := json.Unmarshal(body, &out); err != nil {
- return nil, fmt.Errorf(domainsAccountCopy["unreadableContacts"], err)
+ return apiSavedContacts{}, fmt.Errorf(domainsAccountCopy["unreadableContacts"], err)
}
- return out.Contacts, nil
+ return out, nil
}
// writeDomainContact adds (id "") or edits a saved contact.
@@ -129,30 +135,33 @@ func (s *apiSession) removeDomainContact(ctx context.Context, acct apiAcct, id s
}
// pickSavedContact is the saved contact a buy registers to: id, or with
-// id "" the most recently used (the door lists that one first). nil, nil
-// is none saved, or a console without the door, where the purchase door
-// picks for itself and asks for a contact when it has none (Plan 1).
-func pickSavedContact(ctx context.Context, s *apiSession, acct apiAcct, id string) (*apiSavedContact, error) {
- contacts, err := s.domainContacts(ctx, acct)
+// id "" the most recently used (the door lists that one first), and the
+// whole list (every saved contact and the billing currency) for the contact
+// form's defaults. A nil contact is none saved, or a console without the
+// door, where the purchase door picks for itself and asks for a contact
+// when it has none (Plan 1).
+func pickSavedContact(ctx context.Context, s *apiSession, acct apiAcct, id string) (*apiSavedContact, apiSavedContacts, error) {
+ list, err := s.domainContacts(ctx, acct)
var missing *noContactsDoorError
if errors.As(err, &missing) && id == "" {
- return nil, nil
+ return nil, apiSavedContacts{}, nil
}
if err != nil {
- return nil, err
+ return nil, apiSavedContacts{}, err
}
+ contacts := list.Contacts
if id == "" {
if len(contacts) == 0 {
- return nil, nil
+ return nil, list, nil
}
- return &contacts[0], nil
+ return &contacts[0], list, nil
}
for i := range contacts {
if contacts[i].ID == id {
- return &contacts[i], nil
+ return &contacts[i], list, nil
}
}
- return nil, fmt.Errorf(domainsAccountCopy["contactUnknown"], id)
+ return nil, apiSavedContacts{}, fmt.Errorf(domainsAccountCopy["contactUnknown"], id)
}
// savedContactLabel names a contact in one line: its name, else its
@@ -353,10 +362,11 @@ func runDomainsContacts(verb string, args []string) error {
}
func domainsContactsList(ctx context.Context, s *apiSession, acct apiAcct, out io.Writer) error {
- contacts, err := s.domainContacts(ctx, acct)
+ list, err := s.domainContacts(ctx, acct)
if err != nil {
return err
}
+ contacts := list.Contacts
if len(contacts) == 0 {
mutedf(out, "%s", domainsAccountCopy["noContacts"])
return nil
diff --git a/domains_buy_cli.go b/domains_buy_cli.go
index 72ce1d367..752f0d4a0 100644
--- a/domains_buy_cli.go
+++ b/domains_buy_cli.go
@@ -75,7 +75,7 @@ func runDomainBuyVerb(args []string, buy bool) {
err = domainsBuy(ctx, sess, acct, strings.TrimSpace(pos[0]), app, domainBuyOptions{
yes: yes, noWait: noWait, notYet: notYet, contactFile: contactFile, contactID: contactID,
in: os.Stdin, out: stdout, terminal: isatty.IsTerminal(os.Stdin.Fd()),
- now: time.Now, wait: waitDomainBuy,
+ now: time.Now, wait: waitDomainBuy, spin: stderrSpinner(),
})
} else {
err = domainsCheck(ctx, sess, acct, strings.TrimSpace(pos[0]), country, stdout)
@@ -124,32 +124,41 @@ type domainBuyOptions struct {
out io.Writer
now func() time.Time
wait func(context.Context, time.Duration) error
+ // spin starts the busy line (stderrSpinner) and returns its stop; nil
+ // draws none, as when stderr is not a terminal.
+ spin func(label string) (stop func())
}
func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app string, o domainBuyOptions) error {
o.name, o.app = name, app
var contact *registrar.Contact
var saved *apiSavedContact
+ var contacts apiSavedContacts
if o.contactFile != "" {
var err error
contact, err = readContactFile(o.contactFile, buyContactFileErrors)
if err != nil {
return err
}
- } else {
- var err error
- if saved, err = pickSavedContact(ctx, s, acct, o.contactID); err != nil {
- return err
- }
- }
- country := ""
- switch {
- case contact != nil:
- country = contact.Country
- case saved != nil:
- country = saved.Contact.Country
}
- q, err := s.postDomainCheck(ctx, acct, name, country)
+ stop := startSpin(o.spin, fmt.Sprintf(domainsBuyCopy["spinCheck"], name))
+ q, err := func() (domainQuoteResp, error) {
+ if contact == nil {
+ var err error
+ if saved, contacts, err = pickSavedContact(ctx, s, acct, o.contactID); err != nil {
+ return domainQuoteResp{}, err
+ }
+ }
+ country := ""
+ switch {
+ case contact != nil:
+ country = contact.Country
+ case saved != nil:
+ country = saved.Contact.Country
+ }
+ return s.postDomainCheck(ctx, acct, name, country)
+ }()
+ stop()
if err != nil {
return err
}
@@ -179,13 +188,26 @@ func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app stri
}
}
var p domainPurchaseResp
- contactRetried, priceRetried := false, false
+ contactRetried, priceRetried, typed := false, false, false
+ // keep ends a purchase that did not start: details typed into the form
+ // are offered for saving first, after a definite refusal or a declined
+ // price (err nil) only. An uncertain outcome offers nothing: the start
+ // may have happened and saved the contact, and the add door does not
+ // deduplicate.
+ keep := func(err error) error {
+ if typed && contact != nil && (err == nil || startDefinitelyRefused(err)) {
+ offerSaveContact(ctx, s, acct, input, o.out, contact, o.spin)
+ }
+ return err
+ }
for {
req := domainPurchaseReq{Name: name, App: app, NotYet: o.notYet, Contact: contact}
if contact == nil && saved != nil {
req.ContactID = saved.ID
}
+ stop := startSpin(o.spin, domainsBuyCopy["spinStartBuy"])
p, err = s.postDomainPurchase(ctx, acct, req, q)
+ stop()
var contactErr *domainContactError
var priceErr *domainPriceChangedError
if errors.As(err, &contactErr) && !contactRetried {
@@ -194,8 +216,14 @@ func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app stri
}
contactRetried = true
fmt.Fprintln(o.out, err)
- contact, err = promptDomainContact(input, o.out)
- if err != nil {
+ if o.contactFile != "" {
+ // The contact file's path has not read the list: read it now,
+ // for the account's defaults. Best effort: a refusal leaves
+ // none, and the form still asks.
+ contacts, _ = s.domainContacts(ctx, acct)
+ }
+ known := contactKnown{saved: contacts.Contacts, prefill: contact, email: sessionEmail(s), billingCurrency: contacts.BillingCurrency}
+ if contact, typed, err = promptDomainContact(input, o.out, known); err != nil {
return err
}
continue
@@ -203,12 +231,12 @@ func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app stri
if errors.As(err, &priceErr) {
printDomainQuote(o.out, priceErr.Quote)
if priceRetried {
- return err
+ return keep(err)
}
priceRetried = true
if o.yes {
if q.Currency != priceErr.Quote.Currency || q.Price != priceErr.Quote.Price {
- return err
+ return keep(err)
}
} else {
if !o.terminal {
@@ -220,14 +248,14 @@ func domainsBuy(ctx context.Context, s *apiSession, acct apiAcct, name, app stri
}
if !strings.EqualFold(answer, "y") && !strings.EqualFold(answer, "yes") {
fmt.Fprintln(o.out, domainsBuyCopy["cancelled"])
- return nil
+ return keep(nil)
}
}
q = priceErr.Quote
continue
}
if err != nil {
- return err
+ return keep(err)
}
break
}
@@ -277,6 +305,7 @@ func readContactFile(path string, words contactFileErrors) (*registrar.Contact,
}
func domainBuyAnswer(input *bufio.Scanner, out io.Writer, prompt string) (string, error) {
+ pauseBusyLine()
fmt.Fprint(out, prompt)
if !input.Scan() {
if err := input.Err(); err != nil {
@@ -287,27 +316,6 @@ func domainBuyAnswer(input *bufio.Scanner, out io.Writer, prompt string) (string
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()
@@ -372,10 +380,13 @@ func waitDomainPurchase(ctx context.Context, s *apiSession, acct apiAcct, p doma
if id == "" {
return errors.New(domainsBuyCopy["missingID"])
}
+ stop := startSpin(o.spin, fmt.Sprintf(domainsBuyCopy["spinWait"], o.name))
if err := o.wait(ctx, delay); err != nil {
+ stop()
return err
}
if !doneAt.IsZero() && o.now().Sub(doneAt) >= domainBuyLiveTimeout {
+ stop()
fmt.Fprintln(o.out, domainsBuyCopy["background"])
return nil
}
@@ -388,6 +399,7 @@ func waitDomainPurchase(ctx context.Context, s *apiSession, acct apiAcct, p doma
p, err = s.getDomainPurchase(pollCtx, acct, id)
liveTimeout := errors.Is(pollCtx.Err(), context.DeadlineExceeded) && ctx.Err() == nil
cancel()
+ stop()
if liveTimeout {
fmt.Fprintln(o.out, domainsBuyCopy["background"])
return nil
diff --git a/domains_buy_cli_test.go b/domains_buy_cli_test.go
index 32c0a25b6..059c260fb 100644
--- a/domains_buy_cli_test.go
+++ b/domains_buy_cli_test.go
@@ -218,7 +218,7 @@ func TestDomainsBuyContactInputs(t *testing.T) {
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")
+ o.in = strings.NewReader("yes\nAda\nLovelace\n\nada@example.com\nExample Road\n12\nLondon\n\nN1 1AA\nGB\n+44 20 7123 4567\n")
} else {
o.contactFile = filepath.Join(t.TempDir(), "contact.json")
if err := os.WriteFile(o.contactFile, []byte(contactJSON), 0600); err != nil {
@@ -603,7 +603,7 @@ func TestDomainsBuyChangedPriceAfterContact(t *testing.T) {
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")
+ o.in = strings.NewReader("y\nJane\nBuyer\n\nbuyer@example.test\nMain Street\n\nDublin\n\nD01 A123\nIE\n087 123 4567\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)
}
diff --git a/domains_buy_copy.go b/domains_buy_copy.go
index e4fcfbb1a..d473e4530 100644
--- a/domains_buy_copy.go
+++ b/domains_buy_copy.go
@@ -54,18 +54,6 @@ var domainsBuyCopy = map[string]string{
"contactJSON": "--contact-file must contain one contact JSON object",
"contactSize": "--contact-file is too large (maximum 16 KiB)",
"contactPrompt": "enter your contact details",
- "firstName": "first name: ",
- "lastName": "last name: ",
- "company": "company (optional): ",
- "email": "email: ",
- "phoneCountryCode": "phone country code (digits only): ",
- "phone": "phone 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",
@@ -78,6 +66,64 @@ var domainsBuyCopy = map[string]string{
"failedNoReason": "purchase failed. nothing was charged",
"expired": "checkout was not completed. nothing was charged",
"unpaid": "the domain is registered but the payment did not go through. we will contact you about paying",
+
+ // The contact prompts' labels, in Title Case by Paul's ruling of
+ // 2026-11-27 (the cli-contact-prompts brief): an exception to the
+ // lower-case cli.* rule for these labels only. One Phone field replaces
+ // the calling code and number pair, and Country is asked before it.
+ "firstName": "First Name",
+ "lastName": "Last Name",
+ "company": "Company (optional)",
+ "email": "Email",
+ "street": "Street",
+ "houseNumber": "House Number (optional)",
+ "city": "City",
+ "state": "State or Province (optional)",
+ "postalCode": "Postal Code",
+ "country": "Country",
+ "phone": "Phone",
+
+ // The form's other strings, approved by delegation (Luna), 2026-11-27:
+ // docs/superpowers/specs/LUNA-COPY-RESULT-CONTACT-PROMPTS.md.
+ // approved by delegation (Luna), 2026-11-27
+ "contactField": "%s: ",
+ "contactFieldDefault": "%s [%s]: ",
+ // approved by delegation (Luna), 2026-11-27
+ "contactRequired": "enter a value for %s",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPhoneRequired": "enter a phone number. domain registries require one. for example +353 87 123 4567",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPhoneChars": "use digits, spaces, dashes, dots and brackets. for an international number, start with + and the calling code. for example +353 87 123 4567",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPhoneCode": "start with + and the calling code. for example +353 87 123 4567",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPhoneNumber": "enter the number after the calling code. for example +353 87 123 4567",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPhoneLength": "that number is too short or too long. enter it with its calling code, for example +353 87 123 4567",
+ // approved by delegation (Luna), 2026-11-27
+ "contactEmailInvalid": "enter an email address. for example name@example.com",
+ // approved by delegation (Luna), 2026-11-27
+ "contactCountryInvalid": "use the country's two-letter code. for example IE",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPickHeader": "saved contacts:",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPickLine": " %d %s\n",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPickPrompt": "choose a contact by number, or enter n for a new one [1]: ",
+ // approved by delegation (Luna), 2026-11-27
+ "contactPickInvalid": "enter a number from 1 to %d, or n for a new contact",
+ // approved by delegation (Luna), 2026-11-27
+ "contactSaveOffer": "save these details as a contact? [Y/n] ",
+ // approved by delegation (Luna), 2026-11-27
+ "contactSavedAs": "saved as contact %s. use it next time with --contact %s\n",
+ // approved by delegation (Luna), 2026-11-27
+ "contactSaveFailed": "could not save the contact: %v. save the details below as contact.json, then pass --contact-file contact.json next time:\n",
+ // approved by delegation (Luna), 2026-11-27: the busy line's labels.
+ "spinCheck": "checking %s…",
+ "spinStartBuy": "starting the purchase…",
+ "spinStartTransfer": "starting the transfer…",
+ "spinSaveContact": "saving the contact…",
+ "spinWait": "waiting for %s…",
}
// Approved by delegation (Luna), 2026-11-19:
diff --git a/domains_calling_codes.go b/domains_calling_codes.go
new file mode 100644
index 000000000..821171810
--- /dev/null
+++ b/domains_calling_codes.go
@@ -0,0 +1,84 @@
+package main
+
+// callingCodes are the ITU-T E.164 country calling codes (ITU-T E.164
+// Annex to Operational Bulletin, "List of ITU-T Recommendation E.164
+// assigned country codes"), by ISO 3166-1 alpha-2 code, plus Kosovo (XK).
+// The North American Numbering Plan's members share 1 (their area code is
+// part of the number), Kazakhstan shares Russia's 7, and the Vatican dials
+// as Italy, 39. Codes are prefix-free, so a number's code is the one entry
+// it starts with (callingCodeOf); TestCallingCodesArePrefixFree holds that.
+// No dependency: this is the whole table.
+var callingCodes = map[string]string{
+ "AD": "376", "AE": "971", "AF": "93", "AG": "1", "AI": "1", "AL": "355", "AM": "374", "AO": "244",
+ "AR": "54", "AS": "1", "AT": "43", "AU": "61", "AW": "297", "AX": "358", "AZ": "994",
+ "BA": "387", "BB": "1", "BD": "880", "BE": "32", "BF": "226", "BG": "359", "BH": "973", "BI": "257",
+ "BJ": "229", "BL": "590", "BM": "1", "BN": "673", "BO": "591", "BQ": "599", "BR": "55", "BS": "1",
+ "BT": "975", "BW": "267", "BY": "375", "BZ": "501",
+ "CA": "1", "CC": "61", "CD": "243", "CF": "236", "CG": "242", "CH": "41", "CI": "225", "CK": "682",
+ "CL": "56", "CM": "237", "CN": "86", "CO": "57", "CR": "506", "CU": "53", "CV": "238", "CW": "599",
+ "CX": "61", "CY": "357", "CZ": "420",
+ "DE": "49", "DJ": "253", "DK": "45", "DM": "1", "DO": "1", "DZ": "213",
+ "EC": "593", "EE": "372", "EG": "20", "EH": "212", "ER": "291", "ES": "34", "ET": "251",
+ "FI": "358", "FJ": "679", "FK": "500", "FM": "691", "FO": "298", "FR": "33",
+ "GA": "241", "GB": "44", "GD": "1", "GE": "995", "GF": "594", "GG": "44", "GH": "233", "GI": "350",
+ "GL": "299", "GM": "220", "GN": "224", "GP": "590", "GQ": "240", "GR": "30", "GS": "500", "GT": "502",
+ "GU": "1", "GW": "245", "GY": "592",
+ "HK": "852", "HN": "504", "HR": "385", "HT": "509", "HU": "36",
+ "ID": "62", "IE": "353", "IL": "972", "IM": "44", "IN": "91", "IO": "246", "IQ": "964", "IR": "98",
+ "IS": "354", "IT": "39",
+ "JE": "44", "JM": "1", "JO": "962", "JP": "81",
+ "KE": "254", "KG": "996", "KH": "855", "KI": "686", "KM": "269", "KN": "1", "KP": "850", "KR": "82",
+ "KW": "965", "KY": "1", "KZ": "7",
+ "LA": "856", "LB": "961", "LC": "1", "LI": "423", "LK": "94", "LR": "231", "LS": "266", "LT": "370",
+ "LU": "352", "LV": "371", "LY": "218",
+ "MA": "212", "MC": "377", "MD": "373", "ME": "382", "MF": "590", "MG": "261", "MH": "692", "MK": "389",
+ "ML": "223", "MM": "95", "MN": "976", "MO": "853", "MP": "1", "MQ": "596", "MR": "222", "MS": "1",
+ "MT": "356", "MU": "230", "MV": "960", "MW": "265", "MX": "52", "MY": "60", "MZ": "258",
+ "NA": "264", "NC": "687", "NE": "227", "NF": "672", "NG": "234", "NI": "505", "NL": "31", "NO": "47",
+ "NP": "977", "NR": "674", "NU": "683", "NZ": "64",
+ "OM": "968",
+ "PA": "507", "PE": "51", "PF": "689", "PG": "675", "PH": "63", "PK": "92", "PL": "48", "PM": "508",
+ "PN": "64", "PR": "1", "PS": "970", "PT": "351", "PW": "680", "PY": "595",
+ "QA": "974",
+ "RE": "262", "RO": "40", "RS": "381", "RU": "7", "RW": "250",
+ "SA": "966", "SB": "677", "SC": "248", "SD": "249", "SE": "46", "SG": "65", "SH": "290", "SI": "386",
+ "SJ": "47", "SK": "421", "SL": "232", "SM": "378", "SN": "221", "SO": "252", "SR": "597", "SS": "211",
+ "ST": "239", "SV": "503", "SX": "1", "SY": "963", "SZ": "268",
+ "TC": "1", "TD": "235", "TG": "228", "TH": "66", "TJ": "992", "TK": "690", "TL": "670", "TM": "993",
+ "TN": "216", "TO": "676", "TR": "90", "TT": "1", "TV": "688", "TW": "886", "TZ": "255",
+ "UA": "380", "UG": "256", "US": "1", "UY": "598", "UZ": "998",
+ "VA": "39", "VC": "1", "VE": "58", "VG": "1", "VI": "1", "VN": "84", "VU": "678",
+ "WF": "681", "WS": "685",
+ "XK": "383",
+ "YE": "967", "YT": "262",
+ "ZA": "27", "ZM": "260", "ZW": "263",
+}
+
+// codeOnlyCallingCodes are assigned geographic codes with no ISO 3166-1
+// country of their own: Ascension (247) dials apart from Saint Helena (290),
+// whose country code SH it shares.
+var codeOnlyCallingCodes = []string{"247"}
+
+// knownCallingCodes is every distinct code in callingCodes, and the
+// code-only ones.
+var knownCallingCodes = func() map[string]bool {
+ m := map[string]bool{}
+ for _, code := range callingCodes {
+ m[code] = true
+ }
+ for _, code := range codeOnlyCallingCodes {
+ m[code] = true
+ }
+ return m
+}()
+
+// callingCodeOf is the calling code digits start with, by longest prefix
+// (codes are one to three digits), or "" when none is assigned.
+func callingCodeOf(digits string) string {
+ for n := min(3, len(digits)); n >= 1; n-- {
+ if knownCallingCodes[digits[:n]] {
+ return digits[:n]
+ }
+ }
+ return ""
+}
diff --git a/domains_contact_prompt.go b/domains_contact_prompt.go
new file mode 100644
index 000000000..caea2edad
--- /dev/null
+++ b/domains_contact_prompt.go
@@ -0,0 +1,377 @@
+package main
+
+// The contact form `carlos domains buy` and `carlos domains transfer` ask
+// when the console wants a contact (cli-contact-prompts, Paul 2026-11-27).
+// Each answer is checked as it is typed and asked again with a reason when
+// it is wrong, so one bad field never costs the rest. Known values are
+// offered as defaults: a saved contact picked first, else the contact file
+// the console refused, else the signed-in address and a country inferred
+// from the account's billing currency, when one is set. Details typed here and not used by a started
+// purchase are offered for saving (offerSaveContact).
+
+import (
+ "bufio"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strconv"
+ "strings"
+
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+// contactKnown is what the form can offer as defaults.
+type contactKnown struct {
+ saved []apiSavedContact // the account's saved contacts, most recent first
+ prefill *registrar.Contact // a contact already given (a refused --contact-file)
+ email string // the signed-in address, when it is one
+ // billingCurrency is the account's own billing currency, for a
+ // last-resort country: "" when none is set. Never the quote's currency,
+ // which for such an account is only the price book's default.
+ billingCurrency string
+}
+
+// keepsTrunkZero are the calling codes whose numbers keep their leading 0
+// after the code: Italy's (+39 06 ...).
+var keepsTrunkZero = map[string]bool{"39": true}
+
+// currencyCountry is the one country an account's billing currency names,
+// the last source of a default country. The euro names many, so none.
+var currencyCountry = map[string]string{"gbp": "GB", "usd": "US"}
+
+// serverValidContact passes registrar.Contact.Validate, the rule the
+// console applies to every contact. A field is required when blanking it
+// here fails that rule (contactFieldRequired): the CLI asks for what the
+// server asks for and invents nothing.
+var serverValidContact = registrar.Contact{FirstName: "A", LastName: "B", Email: "a@example.com",
+ PhoneCountryCode: "1", Phone: "5550100", Street: "S", City: "C", PostalCode: "P", Country: "US"}
+
+func contactFieldRequired(set func(*registrar.Contact, string)) bool {
+ c := serverValidContact
+ set(&c, "")
+ return c.Validate() != nil
+}
+
+// contactField is one question of the form: its label, the default it
+// shows for a known contact, and apply, which checks an answer and writes
+// it, or says why it is wrong.
+type contactField struct {
+ key string
+ shown func(registrar.Contact) string
+ apply func(c *registrar.Contact, answer string) error
+}
+
+func plainContactField(key string, get func(*registrar.Contact) *string) contactField {
+ return contactField{key: key,
+ shown: func(c registrar.Contact) string { return *get(&c) },
+ apply: func(c *registrar.Contact, answer string) error {
+ answer = strings.TrimSpace(answer)
+ if answer == "" && contactFieldRequired(func(c *registrar.Contact, v string) { *get(c) = v }) {
+ return fmt.Errorf(domainsBuyCopy["contactRequired"], strings.ToLower(domainsBuyCopy[key]))
+ }
+ *get(c) = answer
+ return nil
+ }}
+}
+
+// contactFields is the form in order: the country comes before the phone,
+// so a number typed without its calling code takes the country's.
+var contactFields = []contactField{
+ plainContactField("firstName", func(c *registrar.Contact) *string { return &c.FirstName }),
+ plainContactField("lastName", func(c *registrar.Contact) *string { return &c.LastName }),
+ plainContactField("company", func(c *registrar.Contact) *string { return &c.Company }),
+ {key: "email", shown: func(c registrar.Contact) string { return c.Email }, apply: applyContactEmail},
+ plainContactField("street", func(c *registrar.Contact) *string { return &c.Street }),
+ plainContactField("houseNumber", func(c *registrar.Contact) *string { return &c.HouseNumber }),
+ plainContactField("city", func(c *registrar.Contact) *string { return &c.City }),
+ plainContactField("state", func(c *registrar.Contact) *string { return &c.State }),
+ plainContactField("postalCode", func(c *registrar.Contact) *string { return &c.PostalCode }),
+ {key: "country", shown: func(c registrar.Contact) string { return c.Country }, apply: applyContactCountry},
+ {key: "phone", shown: shownContactPhone, apply: applyContactPhone},
+}
+
+func applyContactEmail(c *registrar.Contact, answer string) error {
+ answer = strings.TrimSpace(answer)
+ if answer == "" {
+ return fmt.Errorf(domainsBuyCopy["contactRequired"], strings.ToLower(domainsBuyCopy["email"]))
+ }
+ if !looksLikeEmail(answer) {
+ return errors.New(domainsBuyCopy["contactEmailInvalid"])
+ }
+ c.Email = answer
+ return nil
+}
+
+// looksLikeEmail is a shape check, not a delivery check, kept loose enough
+// to take what the server takes: split at the last @, a local part that is
+// not empty (a quoted one, "a b" or "a@b", may hold spaces and @), and a
+// dotted domain with no spaces. No control characters anywhere.
+func looksLikeEmail(s string) bool {
+ if len(s) > 254 || strings.ContainsFunc(s, func(r rune) bool { return r < ' ' || r == 0x7f }) {
+ return false
+ }
+ at := strings.LastIndexByte(s, '@')
+ if at < 0 {
+ return false
+ }
+ local, domain := s[:at], s[at+1:]
+ quoted := len(local) >= 2 && local[0] == '"' && local[len(local)-1] == '"'
+ if local == "" || (!quoted && strings.ContainsAny(local, " @")) {
+ return false
+ }
+ dot := strings.LastIndexByte(domain, '.')
+ return dot > 0 && dot < len(domain)-1 && !strings.Contains(domain, " ") && !strings.Contains(domain, "..") && domain[0] != '.'
+}
+
+func applyContactCountry(c *registrar.Contact, answer string) error {
+ answer = strings.ToUpper(strings.TrimSpace(answer))
+ if answer == "" {
+ return fmt.Errorf(domainsBuyCopy["contactRequired"], strings.ToLower(domainsBuyCopy["country"]))
+ }
+ if len(answer) != 2 || answer[0] < 'A' || answer[0] > 'Z' || answer[1] < 'A' || answer[1] > 'Z' {
+ return errors.New(domainsBuyCopy["contactCountryInvalid"])
+ }
+ c.Country = answer
+ return nil
+}
+
+func shownContactPhone(c registrar.Contact) string {
+ if c.PhoneCountryCode == "" || c.Phone == "" {
+ return ""
+ }
+ return "+" + c.PhoneCountryCode + " " + c.Phone
+}
+
+func applyContactPhone(c *registrar.Contact, answer string) error {
+ code, number, err := parseContactPhone(answer, c.Country)
+ if err != nil {
+ return err
+ }
+ c.PhoneCountryCode, c.Phone = code, number
+ return nil
+}
+
+// parseContactPhone splits one phone answer into the calling code and the
+// number the registrar takes, digits only. Spaces, dashes, dots and
+// brackets may separate the digits, anywhere. With + (or 00) the calling
+// code is the assigned one the digits start with (callingCodeOf), however
+// they are spaced; an unassigned one is refused. Without, the code is
+// country's. The trunk 0 after the code (087 in Ireland, +353 (0)87) is
+// dropped, except where the number keeps it (keepsTrunkZero). The whole
+// number, code included, must be 7 to 15 digits: E.164 allows 15, and the
+// smallest plans (Saint Helena, Niue) have 7.
+func parseContactPhone(answer, country string) (code, number string, err error) {
+ s := strings.TrimSpace(answer)
+ if s == "" {
+ return "", "", errors.New(domainsBuyCopy["contactPhoneRequired"])
+ }
+ international := false
+ switch {
+ case strings.HasPrefix(s, "+"):
+ international, s = true, s[1:]
+ case strings.HasPrefix(s, "00"):
+ international, s = true, s[2:]
+ }
+ var digits strings.Builder
+ for _, r := range s {
+ switch {
+ case r >= '0' && r <= '9':
+ digits.WriteRune(r)
+ case r == ' ' || r == '-' || r == '.' || r == '(' || r == ')':
+ default:
+ return "", "", errors.New(domainsBuyCopy["contactPhoneChars"])
+ }
+ }
+ all := digits.String()
+ if international {
+ if all == "" {
+ return "", "", errors.New(domainsBuyCopy["contactPhoneNumber"])
+ }
+ if code = callingCodeOf(all); code == "" {
+ return "", "", errors.New(domainsBuyCopy["contactPhoneCode"])
+ }
+ number = all[len(code):]
+ } else {
+ if code = callingCodes[strings.ToUpper(country)]; code == "" {
+ return "", "", errors.New(domainsBuyCopy["contactPhoneCode"])
+ }
+ number = all
+ }
+ if !keepsTrunkZero[code] {
+ number = strings.TrimLeft(number, "0")
+ }
+ if number == "" {
+ return "", "", errors.New(domainsBuyCopy["contactPhoneNumber"])
+ }
+ if n := len(code) + len(number); n < 7 || n > 15 {
+ return "", "", errors.New(domainsBuyCopy["contactPhoneLength"])
+ }
+ return code, number, nil
+}
+
+// promptDomainContact asks for a contact. typed is false when a saved
+// contact was picked and used as it is; true when the details went through
+// the form, and so are not saved anywhere until a purchase starts.
+//
+// The defaults are merged field by field (mergeContactDefaults), first
+// known wins. A refused contact file is filled in only from the account
+// (the signed-in address, then the country the billing currency names),
+// never from a saved contact: that is someone else's details. Without a
+// file, the first question picks a saved contact (Enter is the most
+// recent), filled in from the account the same way; a new contact has
+// only the account's two.
+func promptDomainContact(input *bufio.Scanner, out io.Writer, known contactKnown) (c *registrar.Contact, typed bool, err error) {
+ account := registrar.Contact{Email: known.email, Country: currencyCountry[strings.ToLower(known.billingCurrency)]}
+ var prefill registrar.Contact
+ switch {
+ case known.prefill != nil:
+ prefill = mergeContactDefaults(*known.prefill, account)
+ case len(known.saved) > 0:
+ picked, err := pickContactPrompt(input, out, known.saved)
+ if err != nil {
+ return nil, false, err
+ }
+ if picked == nil {
+ prefill = account
+ break
+ }
+ // A saved contact every check passes is used as it is; one that
+ // fails some walks the form with its values as defaults.
+ if ok, valid := checkedContact(*picked); ok {
+ return &valid, false, nil
+ }
+ prefill = mergeContactDefaults(*picked, account)
+ default:
+ prefill = account
+ }
+ fmt.Fprintln(out, domainsBuyCopy["contactPrompt"])
+ c = new(registrar.Contact)
+ for _, f := range contactFields {
+ def := f.shown(prefill)
+ for {
+ prompt := fmt.Sprintf(domainsBuyCopy["contactField"], domainsBuyCopy[f.key])
+ if def != "" {
+ prompt = fmt.Sprintf(domainsBuyCopy["contactFieldDefault"], domainsBuyCopy[f.key], def)
+ }
+ answer, err := domainBuyAnswer(input, out, prompt)
+ if err != nil {
+ return nil, true, err
+ }
+ if answer == "" {
+ answer = def
+ }
+ if err := f.apply(c, answer); err != nil {
+ fmt.Fprintln(out, err)
+ continue
+ }
+ break
+ }
+ }
+ return c, true, nil
+}
+
+// mergeContactDefaults is each field's first non-blank value across
+// sources, in order. The phone's code and number travel as a pair, from
+// the first source that has both.
+func mergeContactDefaults(sources ...registrar.Contact) registrar.Contact {
+ var out registrar.Contact
+ first := func(get func(*registrar.Contact) *string) {
+ for i := range sources {
+ if v := strings.TrimSpace(*get(&sources[i])); v != "" {
+ *get(&out) = v
+ return
+ }
+ }
+ }
+ for _, get := range []func(*registrar.Contact) *string{
+ func(c *registrar.Contact) *string { return &c.FirstName }, func(c *registrar.Contact) *string { return &c.LastName },
+ func(c *registrar.Contact) *string { return &c.Company }, func(c *registrar.Contact) *string { return &c.Email },
+ func(c *registrar.Contact) *string { return &c.Street }, func(c *registrar.Contact) *string { return &c.HouseNumber },
+ func(c *registrar.Contact) *string { return &c.City }, func(c *registrar.Contact) *string { return &c.State },
+ func(c *registrar.Contact) *string { return &c.PostalCode }, func(c *registrar.Contact) *string { return &c.Country },
+ } {
+ first(get)
+ }
+ for _, src := range sources {
+ if src.PhoneCountryCode != "" && src.Phone != "" {
+ out.PhoneCountryCode, out.Phone = src.PhoneCountryCode, src.Phone
+ break
+ }
+ }
+ return out
+}
+
+// checkedContact runs every field's check over a known contact, as if each
+// default were accepted.
+func checkedContact(known registrar.Contact) (bool, registrar.Contact) {
+ var c registrar.Contact
+ for _, f := range contactFields {
+ if f.apply(&c, f.shown(known)) != nil {
+ return false, registrar.Contact{}
+ }
+ }
+ return true, c
+}
+
+// pickContactPrompt lists the saved contacts and asks which; Enter is the
+// first, the most recently used. nil is a new contact.
+func pickContactPrompt(input *bufio.Scanner, out io.Writer, saved []apiSavedContact) (*registrar.Contact, error) {
+ fmt.Fprintln(out, domainsBuyCopy["contactPickHeader"])
+ for i, sc := range saved {
+ fmt.Fprintf(out, domainsBuyCopy["contactPickLine"], i+1, savedContactLabel(sc.Contact))
+ }
+ for {
+ answer, err := domainBuyAnswer(input, out, domainsBuyCopy["contactPickPrompt"])
+ if err != nil {
+ return nil, err
+ }
+ if answer == "" {
+ answer = "1"
+ }
+ if strings.EqualFold(answer, "n") || strings.EqualFold(answer, "new") {
+ return nil, nil
+ }
+ if n, err := strconv.Atoi(answer); err == nil && n >= 1 && n <= len(saved) {
+ c := saved[n-1].Contact
+ return &c, nil
+ }
+ fmt.Fprintln(out, fmt.Sprintf(domainsBuyCopy["contactPickInvalid"], len(saved)))
+ }
+}
+
+// sessionEmail is the signed-in address as a default for Email: "" for a
+// service credential or anything that is not an address.
+func sessionEmail(s *apiSession) string {
+ if s == nil || !looksLikeEmail(s.address) {
+ return ""
+ }
+ return s.address
+}
+
+// offerSaveContact keeps details typed into the form when no purchase or
+// transfer started with them (a start saves its contact itself): it offers
+// to save them as a contact, so the next run can name it with --contact.
+// When saving fails, the details are printed as a contact file instead, so
+// they are never lost without a word. Input that has ended asks nothing.
+func offerSaveContact(ctx context.Context, s *apiSession, acct apiAcct, input *bufio.Scanner, out io.Writer, c *registrar.Contact, spin func(string) func()) {
+ answer, err := domainBuyAnswer(input, out, domainsBuyCopy["contactSaveOffer"])
+ if err != nil {
+ fmt.Fprintln(out)
+ return
+ }
+ if answer != "" && !strings.EqualFold(answer, "y") && !strings.EqualFold(answer, "yes") {
+ return
+ }
+ stop := startSpin(spin, domainsBuyCopy["spinSaveContact"])
+ sc, err := s.writeDomainContact(ctx, acct, "", c)
+ stop()
+ if err != nil {
+ fmt.Fprintf(out, domainsBuyCopy["contactSaveFailed"], err)
+ data, _ := json.MarshalIndent(c, "", " ")
+ fmt.Fprintln(out, string(data))
+ return
+ }
+ fmt.Fprintf(out, domainsBuyCopy["contactSavedAs"], sc.ID, sc.ID)
+}
diff --git a/domains_contact_prompt_test.go b/domains_contact_prompt_test.go
new file mode 100644
index 000000000..c8b001eb1
--- /dev/null
+++ b/domains_contact_prompt_test.go
@@ -0,0 +1,665 @@
+package main
+
+import (
+ "bufio"
+ "bytes"
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/carlosframework/platform/internal/registrar"
+)
+
+func TestDomainsContactPhoneParse(t *testing.T) {
+ for _, tc := range []struct {
+ in, country, code, number, err string
+ }{
+ {in: "+353 87 123 4567", code: "353", number: "871234567"},
+ {in: "087 123 4567", country: "IE", code: "353", number: "871234567"},
+ {in: "087-123-4567", country: "ie", code: "353", number: "871234567"},
+ {in: "+353 (0)87 123-4567", code: "353", number: "871234567"},
+ {in: "+3538712345 67", code: "353", number: "871234567"},
+ {in: "+353871234567", code: "353", number: "871234567"},
+ {in: "0035387 1234567", code: "353", number: "871234567"},
+ {in: "+1 (555) 010-0123", code: "1", number: "5550100123"},
+ {in: "+15550100123", code: "1", number: "5550100123"},
+ {in: "(555) 010.0123", country: "US", code: "1", number: "5550100123"},
+ {in: "020 7123 4567", country: "GB", code: "44", number: "2071234567"},
+ {in: "+44 (0)20 7123 4567", country: "IE", code: "44", number: "2071234567"},
+ {in: "06 1234 5678", country: "IT", code: "39", number: "0612345678"},
+ {in: "+39 06 1234 5678", code: "39", number: "0612345678"},
+ {in: "+81 3 1234 5678", code: "81", number: "312345678"},
+ {in: "", country: "IE", err: "contactPhoneRequired"},
+ {in: " ", country: "IE", err: "contactPhoneRequired"},
+ {in: "3 1234 5678", country: "JP", code: "81", number: "312345678"},
+ {in: "87 123 4567", err: "contactPhoneCode"},
+ // The code is found by its digits, however they are spaced.
+ {in: "+81312345678", code: "81", number: "312345678"},
+ {in: "+120 2555 0123", code: "1", number: "2025550123"},
+ {in: "+1 202 555 0123", country: "IE", code: "1", number: "2025550123"},
+ {in: "+44 7700 900123", code: "44", number: "7700900123"},
+ {in: "+7 495 123 45 67", code: "7", number: "4951234567"},
+ {in: "+380 44 123 4567", code: "380", number: "441234567"},
+ {in: "044 123 4567", country: "UA", code: "380", number: "441234567"},
+ {in: "+999 123", err: "contactPhoneCode"},
+ {in: "+999123456789", err: "contactPhoneCode"},
+ {in: "+0 87 123 4567", err: "contactPhoneCode"},
+ {in: "87 123 4567", country: "AQ", err: "contactPhoneCode"},
+ // The whole number, code included, is 7 to 15 digits; the
+ // smallest plans pass.
+ {in: "+290 2345", code: "290", number: "2345"},
+ {in: "+683 4002", code: "683", number: "4002"},
+ {in: "+353 87 1", err: "contactPhoneLength"},
+ {in: "+353 87 123 4567 8901", err: "contactPhoneLength"},
+ {in: "+353 871 234 567 890", code: "353", number: "871234567890"},
+ {in: "0871", country: "IE", err: "contactPhoneLength"},
+ {in: "087 ABC 4567", country: "IE", err: "contactPhoneChars"},
+ {in: "+353 87 123 4567 ext 2", err: "contactPhoneChars"},
+ {in: "+353", err: "contactPhoneNumber"},
+ {in: "+353 0", err: "contactPhoneNumber"},
+ {in: "+", err: "contactPhoneNumber"},
+ } {
+ t.Run(tc.in+"/"+tc.country, func(t *testing.T) {
+ code, number, err := parseContactPhone(tc.in, tc.country)
+ if tc.err != "" {
+ if err == nil || err.Error() != domainsBuyCopy[tc.err] {
+ t.Fatalf("err=%v want %q", err, domainsBuyCopy[tc.err])
+ }
+ return
+ }
+ if err != nil || code != tc.code || number != tc.number {
+ t.Fatalf("got %q %q %v, want %q %q", code, number, err, tc.code, tc.number)
+ }
+ // What the parse gives, the server takes.
+ c := serverValidContact
+ c.PhoneCountryCode, c.Phone = code, number
+ if err := c.Validate(); err != nil {
+ t.Fatalf("server refuses the parsed phone: %v", err)
+ }
+ })
+ }
+}
+
+func TestDomainsContactFieldChecks(t *testing.T) {
+ field := func(key string) contactField {
+ for _, f := range contactFields {
+ if f.key == key {
+ return f
+ }
+ }
+ t.Fatalf("no field %s", key)
+ return contactField{}
+ }
+ required := func(key string) string {
+ return fmt.Sprintf(domainsBuyCopy["contactRequired"], strings.ToLower(domainsBuyCopy[key]))
+ }
+ for _, tc := range []struct {
+ key, in, want, err string
+ }{
+ {key: "firstName", in: " Paul ", want: "Paul"},
+ {key: "firstName", in: "", err: required("firstName")},
+ {key: "lastName", in: "", err: required("lastName")},
+ {key: "company", in: "", want: ""},
+ {key: "houseNumber", in: "", want: ""},
+ {key: "state", in: "", want: ""},
+ {key: "street", in: "", err: required("street")},
+ {key: "city", in: "", err: required("city")},
+ {key: "postalCode", in: "", err: required("postalCode")},
+ {key: "postalCode", in: "D01 A123", want: "D01 A123"},
+ {key: "email", in: "paul@example.com", want: "paul@example.com"},
+ {key: "email", in: "p.c+domains@mail.example.ie", want: "p.c+domains@mail.example.ie"},
+ {key: "email", in: "", err: required("email")},
+ {key: "email", in: "paul", err: domainsBuyCopy["contactEmailInvalid"]},
+ {key: "email", in: "paul@example", err: domainsBuyCopy["contactEmailInvalid"]},
+ {key: "email", in: "@example.com", err: domainsBuyCopy["contactEmailInvalid"]},
+ {key: "email", in: "paul@@example.com", err: domainsBuyCopy["contactEmailInvalid"]},
+ // Quoted local parts, which the server takes, may hold @ and spaces;
+ // the address splits at its last @.
+ {key: "email", in: `"a@b"@example.com`, want: `"a@b"@example.com`},
+ {key: "email", in: `"a b"@example.com`, want: `"a b"@example.com`},
+ {key: "email", in: `"a b"@example .com`, err: domainsBuyCopy["contactEmailInvalid"]},
+ {key: "email", in: `a b"@example.com`, err: domainsBuyCopy["contactEmailInvalid"]},
+ {key: "email", in: "paul @example.com", err: domainsBuyCopy["contactEmailInvalid"]},
+ {key: "email", in: "paul@example.com.", err: domainsBuyCopy["contactEmailInvalid"]},
+ {key: "email", in: "paul@.example.com", err: domainsBuyCopy["contactEmailInvalid"]},
+ {key: "country", in: "ie", want: "IE"},
+ {key: "country", in: " Gb ", want: "GB"},
+ {key: "country", in: "", err: required("country")},
+ {key: "country", in: "IRL", err: domainsBuyCopy["contactCountryInvalid"]},
+ {key: "country", in: "I3", err: domainsBuyCopy["contactCountryInvalid"]},
+ } {
+ t.Run(tc.key+"/"+tc.in, func(t *testing.T) {
+ var c registrar.Contact
+ err := field(tc.key).apply(&c, tc.in)
+ if tc.err != "" {
+ if err == nil || err.Error() != tc.err {
+ t.Fatalf("err=%v want %q", err, tc.err)
+ }
+ return
+ }
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := field(tc.key).shown(c); got != tc.want {
+ t.Fatalf("got %q want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+// TestDomainsContactFormAsksWhatTheServerRequires: a blank answer is refused
+// exactly for the fields registrar.Contact.Validate requires, and a contact
+// every check passes is one the server takes.
+func TestDomainsContactFormAsksWhatTheServerRequires(t *testing.T) {
+ if err := serverValidContact.Validate(); err != nil {
+ t.Fatalf("the sample contact is not valid: %v", err)
+ }
+ for _, f := range contactFields {
+ blank := serverValidContact
+ var probe registrar.Contact
+ probe.Country = "IE"
+ blankErr := f.apply(&probe, "")
+ switch f.key {
+ case "phone":
+ blank.Phone, blank.PhoneCountryCode = "", ""
+ default:
+ plainSet := map[string]*string{"firstName": &blank.FirstName, "lastName": &blank.LastName, "company": &blank.Company,
+ "email": &blank.Email, "street": &blank.Street, "houseNumber": &blank.HouseNumber, "city": &blank.City,
+ "state": &blank.State, "postalCode": &blank.PostalCode, "country": &blank.Country}
+ *plainSet[f.key] = ""
+ }
+ if serverRequires := blank.Validate() != nil; serverRequires != (blankErr != nil) {
+ t.Errorf("%s: server requires=%v, form refuses blank=%v", f.key, serverRequires, blankErr != nil)
+ }
+ }
+ ok, c := checkedContact(registrar.Contact{FirstName: "Jane", LastName: "Buyer", Email: "jane@example.com",
+ PhoneCountryCode: "353", Phone: "0871234567", Street: "Main Street", City: "Dublin", PostalCode: "D01 A123", Country: "ie"})
+ if !ok {
+ t.Fatal("a good contact failed the checks")
+ }
+ if err := c.Validate(); err != nil || c.Country != "IE" || c.Phone != "871234567" {
+ t.Fatalf("checked contact %+v: %v", c, err)
+ }
+}
+
+// contactFlowServer is a console for the contact flow tests: a check, a
+// purchase door, the saved contacts and the contact save, recording each
+// purchase and save body.
+type contactFlowServer struct {
+ *httptest.Server
+ mu sync.Mutex
+ purchases []map[string]json.RawMessage
+ saves []registrar.Contact
+}
+
+func newContactFlowServer(t *testing.T, quoteCurrency, contacts string, purchase func(n int, w http.ResponseWriter)) *contactFlowServer {
+ t.Helper()
+ cs := &contactFlowServer{}
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST "+buyTestPath+"/check", func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprintf(w, `{"domain":"shop.com","available":true,"price":1299,"currency":%q}`, quoteCurrency)
+ })
+ mux.HandleFunc("GET "+buyTestPath+"/contacts", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, contacts) })
+ mux.HandleFunc("POST "+buyTestPath+"/contacts", func(w http.ResponseWriter, r *http.Request) {
+ var c registrar.Contact
+ if err := json.NewDecoder(r.Body).Decode(&c); err != nil {
+ t.Error(err)
+ }
+ cs.mu.Lock()
+ cs.saves = append(cs.saves, c)
+ cs.mu.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"id": "dc_new", "contact": c})
+ })
+ mux.HandleFunc("POST "+buyTestPath+"/purchases", func(w http.ResponseWriter, r *http.Request) {
+ var in map[string]json.RawMessage
+ if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
+ t.Error(err)
+ }
+ cs.mu.Lock()
+ cs.purchases = append(cs.purchases, in)
+ n := len(cs.purchases)
+ cs.mu.Unlock()
+ purchase(n, w)
+ })
+ cs.Server = httptest.NewServer(mux)
+ t.Cleanup(cs.Close)
+ return cs
+}
+
+// recorded is the purchase and save bodies so far, read under the lock the
+// handlers write them under.
+func (cs *contactFlowServer) recorded() ([]map[string]json.RawMessage, []registrar.Contact) {
+ cs.mu.Lock()
+ defer cs.mu.Unlock()
+ return append([]map[string]json.RawMessage(nil), cs.purchases...), append([]registrar.Contact(nil), cs.saves...)
+}
+
+func contactRefused(w http.ResponseWriter) {
+ w.WriteHeader(422)
+ fmt.Fprint(w, `{"code":"contact","error":"check the contact details"}`)
+}
+
+// TestDomainsBuyContactFormFlow: with no saved contact, the form offers the
+// signed-in address and the country the account's billing currency names
+// (GBP, so GB), and Enter keeps
+// them; a blank phone says why and asks again; the number takes the
+// country's calling code; and when the console still refuses the contact,
+// the details are offered for saving and saved through the contacts door.
+func TestDomainsBuyContactFormFlow(t *testing.T) {
+ cs := newContactFlowServer(t, "gbp", `{"contacts":[],"billing_currency":"gbp"}`, func(n int, w http.ResponseWriter) { contactRefused(w) })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.yes, o.terminal, o.noWait = false, true, true
+ o.in = strings.NewReader(strings.Join([]string{
+ "y", // buy this domain?
+ "Jane", "Buyer", "", // names, no company
+ "", // Email: keep the signed-in address
+ "Main Street", "4", "Leeds", // street, house number, city
+ "", "LS1 1AA", // no state, postal code
+ "", // Country: keep GB, from the billing currency
+ "", // Phone left blank: asked again
+ "0113 496 0000", // a national number: GB's code, trunk 0 dropped
+ "", // save these details? Enter is yes
+ }, "\n") + "\n")
+ err := domainsBuy(context.Background(), newTestSession(cs.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o)
+ if err == nil || !strings.Contains(err.Error(), "check the contact details") {
+ t.Fatalf("err=%v, want the console's refusal; output:\n%s", err, &out)
+ }
+ text := out.String()
+ for _, want := range []string{
+ "First Name: ", "Company (optional): ",
+ "Email [a@keymail.dev]: ",
+ "Country [GB]: ",
+ domainsBuyCopy["contactPhoneRequired"] + "\n",
+ domainsBuyCopy["contactSaveOffer"],
+ "saved as contact dc_new. use it next time with --contact dc_new\n",
+ } {
+ if !strings.Contains(text, want) {
+ t.Errorf("output lacks %q:\n%s", want, text)
+ }
+ }
+ if n := strings.Count(text, "Phone: "); n != 2 {
+ t.Errorf("Phone asked %d times, want 2 (blank, then again):\n%s", n, text)
+ }
+ if !strings.Contains(text, "Postal Code: ") || strings.Index(text, "Country [GB]: ") > strings.Index(text, "Phone: ") {
+ t.Errorf("country must be asked before the phone:\n%s", text)
+ }
+ want := registrar.Contact{FirstName: "Jane", LastName: "Buyer", Email: "a@keymail.dev", PhoneCountryCode: "44", Phone: "1134960000",
+ Street: "Main Street", HouseNumber: "4", City: "Leeds", PostalCode: "LS1 1AA", Country: "GB"}
+ purchases, saves := cs.recorded()
+ if len(purchases) != 2 || len(saves) != 1 || saves[0] != want {
+ t.Fatalf("purchases=%d saves=%+v, want one save of %+v", len(purchases), saves, want)
+ }
+ var sent registrar.Contact
+ if err := json.Unmarshal(purchases[1]["contact"], &sent); err != nil || sent != want {
+ t.Fatalf("second purchase sent %+v (%v), want %+v", sent, err, want)
+ }
+}
+
+// TestDomainsBuyContactFormPicksSavedFirst: with saved contacts, the first
+// question picks one, Enter taking the most recent. One the console
+// refused walks the form with its values as defaults, Enter keeping each;
+// only what it lacks (here the phone) needs typing. A purchase that then
+// starts offers no save: the start saved the contact.
+func TestDomainsBuyContactFormPicksSavedFirst(t *testing.T) {
+ const contacts = `{"contacts":[
+ {"id":"dc_recent","contact":{"first_name":"Ada","last_name":"Lovelace","email":"ada@example.com","street":"Example Road","city":"London","postal_code":"N1 1AA","country":"GB"}},
+ {"id":"dc_older","contact":{"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":"IE"}}]}`
+ cs := newContactFlowServer(t, "gbp", contacts, func(n int, w http.ResponseWriter) {
+ if n == 1 {
+ contactRefused(w)
+ return
+ }
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment","checkout_url":"https://checkout.example/p1"}`)
+ })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.yes, o.terminal, o.noWait = false, true, true
+ // confirm, Enter picks 1, Enter keeps ten fields, a blank phone, then one.
+ o.in = strings.NewReader("y\n" + "\n" + strings.Repeat("\n", 10) + "\n" + "+44 20 7123 4567\n")
+ if err := domainsBuy(context.Background(), newTestSession(cs.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil {
+ t.Fatalf("err=%v output:\n%s", err, &out)
+ }
+ text := out.String()
+ for _, want := range []string{
+ domainsBuyCopy["contactPickHeader"] + "\n 1 Ada Lovelace (ada@example.com)\n 2 Jane Buyer (buyer@example.test)\n",
+ domainsBuyCopy["contactPickPrompt"],
+ "First Name [Ada]: ", "Last Name [Lovelace]: ", "Email [ada@example.com]: ", "Postal Code [N1 1AA]: ", "Country [GB]: ",
+ "Phone: ", domainsBuyCopy["contactPhoneRequired"],
+ } {
+ if !strings.Contains(text, want) {
+ t.Errorf("output lacks %q:\n%s", want, text)
+ }
+ }
+ if strings.Index(text, domainsBuyCopy["contactPickPrompt"]) > strings.Index(text, "First Name") {
+ t.Errorf("picking a saved contact must be the first question:\n%s", text)
+ }
+ purchases, saves := cs.recorded()
+ if strings.Contains(text, domainsBuyCopy["contactSaveOffer"]) || len(saves) != 0 {
+ t.Errorf("a started purchase offered a save:\n%s", text)
+ }
+ var sent registrar.Contact
+ json.Unmarshal(purchases[1]["contact"], &sent)
+ want := registrar.Contact{FirstName: "Ada", LastName: "Lovelace", Email: "ada@example.com", PhoneCountryCode: "44", Phone: "2071234567",
+ Street: "Example Road", City: "London", PostalCode: "N1 1AA", Country: "GB"}
+ if sent != want {
+ t.Fatalf("sent %+v want %+v", sent, want)
+ }
+}
+
+// TestDomainsContactPickUsesAValidSavedContactAsIs: a saved contact every
+// check passes is used without walking the form, and is not typed.
+func TestDomainsContactPickUsesAValidSavedContactAsIs(t *testing.T) {
+ saved := []apiSavedContact{
+ {ID: "dc_a", Contact: registrar.Contact{FirstName: "Ada"}},
+ {ID: "dc_b", Contact: registrar.Contact{FirstName: "Jane", LastName: "Buyer", Email: "buyer@example.test", PhoneCountryCode: "353",
+ Phone: "871234567", Street: "Main Street", City: "Dublin", PostalCode: "D01 A123", Country: "IE"}},
+ }
+ var out bytes.Buffer
+ c, typed, err := promptDomainContact(bufio.NewScanner(strings.NewReader("7\n2\n")), &out, contactKnown{saved: saved})
+ if err != nil || typed || c == nil || *c != saved[1].Contact {
+ t.Fatalf("c=%+v typed=%v err=%v\n%s", c, typed, err, &out)
+ }
+ if !strings.Contains(out.String(), fmt.Sprintf(domainsBuyCopy["contactPickInvalid"], 2)) || strings.Contains(out.String(), "First Name") {
+ t.Fatalf("output:\n%s", &out)
+ }
+}
+
+// TestDomainsTransferOffersToSaveTypedContact: a transfer that fails to
+// start after the form keeps the details: they are offered for saving.
+func TestDomainsTransferOffersToSaveTypedContact(t *testing.T) {
+ var mu sync.Mutex
+ var saves []registrar.Contact
+ starts := 0
+ mux := http.NewServeMux()
+ mux.HandleFunc("POST "+buyTestPath+"/transfers/check", func(w http.ResponseWriter, r *http.Request) {
+ fmt.Fprint(w, `{"domain":"shop.com","price":1200,"currency":"eur","nameservers":["ns1.example-dns.test"]}`)
+ })
+ mux.HandleFunc("GET "+buyTestPath+"/contacts", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, `{"contacts":[]}`) })
+ mux.HandleFunc("POST "+buyTestPath+"/contacts", func(w http.ResponseWriter, r *http.Request) {
+ var c registrar.Contact
+ json.NewDecoder(r.Body).Decode(&c)
+ mu.Lock()
+ saves = append(saves, c)
+ mu.Unlock()
+ json.NewEncoder(w).Encode(map[string]any{"id": "dc_new", "contact": c})
+ })
+ mux.HandleFunc("POST "+buyTestPath+"/transfers", func(w http.ResponseWriter, r *http.Request) {
+ mu.Lock()
+ starts++
+ n := starts
+ mu.Unlock()
+ if n == 1 {
+ contactRefused(w)
+ return
+ }
+ w.WriteHeader(409)
+ fmt.Fprint(w, `{"error":"the domain is locked at its current registrar"}`)
+ })
+ ts := httptest.NewServer(mux)
+ t.Cleanup(ts.Close)
+ var out bytes.Buffer
+ o := transferTestOptions(t, &out)
+ o.contactFile, o.yes, o.terminal, o.noWait = "", false, true, true
+ o.in = strings.NewReader(strings.Join([]string{"y", "Jane", "Buyer", "", "jane@example.ie", "Main Street", "", "Dublin", "", "D01 A123",
+ "ie", "+353 87 123 4567", "y"}, "\n") + "\n")
+ err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", o)
+ if err == nil || !strings.Contains(err.Error(), "locked") {
+ t.Fatalf("err=%v\n%s", err, &out)
+ }
+ if strings.Contains(out.String(), "Country [") {
+ t.Errorf("the euro names no one country, so none is offered:\n%s", &out)
+ }
+ want := registrar.Contact{FirstName: "Jane", LastName: "Buyer", Email: "jane@example.ie", PhoneCountryCode: "353", Phone: "871234567",
+ Street: "Main Street", City: "Dublin", PostalCode: "D01 A123", Country: "IE"}
+ mu.Lock()
+ got := append([]registrar.Contact(nil), saves...)
+ mu.Unlock()
+ if len(got) != 1 || got[0] != want || !strings.Contains(out.String(), "saved as contact dc_new") {
+ t.Fatalf("saves=%+v\n%s", got, &out)
+ }
+}
+
+// TestDomainsBuyNoBillingCurrencyNoCountryDefault: an account with no
+// billing currency of its own is quoted in the price book's default (USD
+// here, or any other), and that names no country: the form offers no
+// Country default, from a console that says "" and from one that predates
+// the field alike.
+func TestDomainsBuyNoBillingCurrencyNoCountryDefault(t *testing.T) {
+ for _, tc := range []struct{ name, quote, contacts string }{
+ {"usd default, none set", "usd", `{"contacts":[],"billing_currency":""}`},
+ {"gbp quote, none set", "gbp", `{"contacts":[],"billing_currency":""}`},
+ {"console without the field", "usd", `{"contacts":[]}`},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cs := newContactFlowServer(t, tc.quote, tc.contacts, func(n int, w http.ResponseWriter) {
+ if n == 1 {
+ contactRefused(w)
+ return
+ }
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.yes, o.terminal, o.noWait = false, true, true
+ o.in = strings.NewReader(strings.Join([]string{"y", "Jane", "Buyer", "", "", "Main Street", "", "Austin", "TX", "78701",
+ "", // Country: no default, so Enter is refused and it is asked again
+ "us", "512 555 0100", // then a national number takes the country's code
+ }, "\n") + "\n")
+ if err := domainsBuy(context.Background(), newTestSession(cs.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil {
+ t.Fatalf("err=%v\n%s", err, &out)
+ }
+ text := out.String()
+ if strings.Contains(text, "Country [") {
+ t.Fatalf("a Country default with no billing currency set:\n%s", text)
+ }
+ if n := strings.Count(text, "Country: "); n != 2 {
+ t.Fatalf("Country asked %d times, want 2:\n%s", n, text)
+ }
+ var sent registrar.Contact
+ purchases, _ := cs.recorded()
+ json.Unmarshal(purchases[1]["contact"], &sent)
+ if sent.Country != "US" || sent.PhoneCountryCode != "1" || sent.Phone != "5125550100" {
+ t.Fatalf("sent %+v", sent)
+ }
+ })
+ }
+}
+
+// TestCallingCodesArePrefixFree: every code is one to three digits and none
+// is the start of another, so the longest-prefix match is the only one;
+// each country the price book names by currency, and US, has its code.
+func TestCallingCodesArePrefixFree(t *testing.T) {
+ if len(callingCodes) < 230 {
+ t.Fatalf("%d countries, want the whole E.164 table", len(callingCodes))
+ }
+ for country, code := range callingCodes {
+ if len(country) != 2 || len(code) < 1 || len(code) > 3 || strings.Trim(code, "0123456789") != "" || code[0] == '0' {
+ t.Errorf("%s: code %q", country, code)
+ }
+ for other := range knownCallingCodes {
+ if other != code && strings.HasPrefix(other, code) {
+ t.Errorf("%s's code %s is a prefix of %s", country, code, other)
+ }
+ }
+ }
+ for country, code := range map[string]string{"IE": "353", "GB": "44", "US": "1", "AT": "43", "BE": "32", "BG": "359", "HR": "385",
+ "CY": "357", "CZ": "420", "DK": "45", "EE": "372", "FI": "358", "FR": "33", "DE": "49", "GR": "30", "HU": "36", "IT": "39",
+ "LV": "371", "LT": "370", "LU": "352", "MT": "356", "NL": "31", "PL": "48", "PT": "351", "RO": "40", "SK": "421", "SI": "386",
+ "ES": "34", "SE": "46"} {
+ if callingCodes[country] != code {
+ t.Errorf("%s: %q, want %q", country, callingCodes[country], code)
+ }
+ }
+ // Every assigned geographic code (ITU-T E.164 list) is known, Ascension's
+ // 247 included, so no reachable number is refused for its code.
+ for _, code := range strings.Fields(`1 7 20 27 30 31 32 33 34 36 39 40 41 43 44 45 46 47 48 49 51 52 53 54 55 56 57 58
+ 60 61 62 63 64 65 66 81 82 84 86 90 91 92 93 94 95 98 211 212 213 216 218 220 221 222 223 224 225 226 227 228 229
+ 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
+ 260 261 262 263 264 265 266 267 268 269 290 291 297 298 299 350 351 352 353 354 355 356 357 358 359 370 371 372 373
+ 374 375 376 377 378 380 381 382 383 385 386 387 389 420 421 423 500 501 502 503 504 505 506 507 508 509 590 591 592
+ 593 594 595 596 597 598 599 670 672 673 674 675 676 677 678 679 680 681 682 683 685 686 687 688 689 690 691 692 850
+ 852 853 855 856 880 886 960 961 962 963 964 965 966 967 968 970 971 972 973 974 975 976 977 992 993 994 995 996 998`) {
+ if !knownCallingCodes[code] {
+ t.Errorf("assigned code %s is not known", code)
+ }
+ }
+ if got := callingCodeOf("2476666"); got != "247" {
+ t.Errorf("Ascension: %q, want 247", got)
+ }
+}
+
+// TestDomainsBuyNoSaveOfferWhenTheStartIsUncertain: after the form, a start
+// whose outcome is not known (the answer lost, a 5xx, an unreadable 200)
+// may have started and saved the contact itself, so nothing is offered:
+// the error is printed as it is, and no contact is added.
+func TestDomainsBuyNoSaveOfferWhenTheStartIsUncertain(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ answer func(w http.ResponseWriter)
+ }{
+ {"response lost", func(w http.ResponseWriter) {
+ conn, _, err := http.NewResponseController(w).Hijack()
+ if err != nil {
+ t.Error(err)
+ return
+ }
+ conn.Close()
+ }},
+ {"5xx", func(w http.ResponseWriter) {
+ w.WriteHeader(502)
+ fmt.Fprint(w, `{"error":"bad gateway"}`)
+ }},
+ {"unreadable 200", func(w http.ResponseWriter) { fmt.Fprint(w, `{"id":`) }},
+ {"4xx without words", func(w http.ResponseWriter) { w.WriteHeader(400); fmt.Fprint(w, `<html>`) }},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ cs := newContactFlowServer(t, "gbp", `{"contacts":[],"billing_currency":"gbp"}`, func(n int, w http.ResponseWriter) {
+ if n == 1 {
+ contactRefused(w)
+ return
+ }
+ tc.answer(w)
+ })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.yes, o.terminal, o.noWait = false, true, true
+ o.in = strings.NewReader(strings.Join([]string{"y", "Jane", "Buyer", "", "jane@example.com", "Main Street", "", "Leeds", "", "LS1 1AA",
+ "", "0113 496 0000", "y"}, "\n") + "\n")
+ err := domainsBuy(context.Background(), newTestSession(cs.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o)
+ if err == nil {
+ t.Fatalf("no error\n%s", &out)
+ }
+ purchases, saves := cs.recorded()
+ if strings.Contains(out.String(), domainsBuyCopy["contactSaveOffer"]) || len(saves) != 0 || len(purchases) != 2 {
+ t.Fatalf("uncertain start offered a save (saves=%d purchases=%d):\n%s", len(saves), len(purchases), &out)
+ }
+ })
+ }
+}
+
+// TestDomainsBuyContactFileDefaultsMergeFieldByField: a refused contact
+// file without an email or a country gets them from the account: the
+// signed-in address and the billing currency's country, read from the
+// contacts list on this path too. What the file has wins.
+func TestDomainsBuyContactFileDefaultsMergeFieldByField(t *testing.T) {
+ cs := newContactFlowServer(t, "gbp", `{"contacts":[],"billing_currency":"gbp"}`, func(n int, w http.ResponseWriter) {
+ if n == 1 {
+ contactRefused(w)
+ return
+ }
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.yes, o.terminal, o.noWait = false, true, true
+ o.contactFile = filepath.Join(t.TempDir(), "contact.json")
+ writeTransferTestFile(t, o.contactFile, `{"first_name":"Jane","last_name":"Buyer","phone_country_code":"44","phone":"1134960000","street":"Main Street","city":"Leeds","postal_code":"LS1 1AA"}`)
+ o.in = strings.NewReader("y\n" + strings.Repeat("\n", 11))
+ if err := domainsBuy(context.Background(), newTestSession(cs.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil {
+ t.Fatalf("err=%v\n%s", err, &out)
+ }
+ text := out.String()
+ for _, want := range []string{"First Name [Jane]: ", "Email [a@keymail.dev]: ", "Country [GB]: ", "Phone [+44 1134960000]: "} {
+ if !strings.Contains(text, want) {
+ t.Errorf("output lacks %q:\n%s", want, text)
+ }
+ }
+ var sent registrar.Contact
+ purchases, _ := cs.recorded()
+ json.Unmarshal(purchases[1]["contact"], &sent)
+ want := registrar.Contact{FirstName: "Jane", LastName: "Buyer", Email: "a@keymail.dev", PhoneCountryCode: "44", Phone: "1134960000",
+ Street: "Main Street", City: "Leeds", PostalCode: "LS1 1AA", Country: "GB"}
+ if sent != want {
+ t.Fatalf("sent %+v want %+v", sent, want)
+ }
+}
+
+func TestMergeContactDefaultsOrder(t *testing.T) {
+ file := registrar.Contact{FirstName: "File", Phone: "871234567"} // a phone without its code is no phone
+ saved := registrar.Contact{FirstName: "Saved", LastName: "Contact", Email: "saved@example.com", PhoneCountryCode: "44", Phone: "2071234567", Country: "GB"}
+ account := registrar.Contact{Email: "login@example.com", Country: "US"}
+ got := mergeContactDefaults(file, saved, account)
+ want := registrar.Contact{FirstName: "File", LastName: "Contact", Email: "saved@example.com", PhoneCountryCode: "44", Phone: "2071234567", Country: "GB"}
+ if got != want {
+ t.Fatalf("got %+v want %+v", got, want)
+ }
+ if got := mergeContactDefaults(file, account); got.Email != "login@example.com" || got.Country != "US" || got.Phone != "" {
+ t.Fatalf("got %+v", got)
+ }
+}
+
+// TestDomainsBuyContactFileNeverTakesSavedDetails: a refused contact file
+// is filled in from the account only, never from a saved contact, which
+// may be someone else: a field the file lacks and the account does not
+// know is asked with no default, though a saved contact has a value.
+func TestDomainsBuyContactFileNeverTakesSavedDetails(t *testing.T) {
+ const contacts = `{"billing_currency":"gbp","contacts":[
+ {"id":"dc_other","contact":{"first_name":"Ada","last_name":"Lovelace","company":"Engines Ltd","email":"ada@example.com","phone_country_code":"44","phone":"2071234567","street":"Example Road","house_number":"12","city":"London","state":"Greater London","postal_code":"N1 1AA","country":"GB"}}]}`
+ cs := newContactFlowServer(t, "gbp", contacts, func(n int, w http.ResponseWriter) {
+ if n == 1 {
+ contactRefused(w)
+ return
+ }
+ fmt.Fprint(w, `{"id":"p1","state":"awaiting_payment"}`)
+ })
+ var out bytes.Buffer
+ o := buyTestOptions(&out)
+ o.yes, o.terminal, o.noWait = false, true, true
+ o.contactFile = filepath.Join(t.TempDir(), "contact.json")
+ writeTransferTestFile(t, o.contactFile, `{"first_name":"Jane","last_name":"Buyer"}`)
+ // Enter keeps each default; the fields with none are typed.
+ o.in = strings.NewReader(strings.Join([]string{"y", "", "", "", "", "Main Street", "", "Leeds", "", "LS1 1AA", "", "0113 496 0000"}, "\n") + "\n")
+ if err := domainsBuy(context.Background(), newTestSession(cs.URL), apiAcct{Seg: "bab"}, "shop.com", "shop", o); err != nil {
+ t.Fatalf("err=%v\n%s", err, &out)
+ }
+ text := out.String()
+ for _, want := range []string{"First Name [Jane]: ", "Company (optional): ", "Email [a@keymail.dev]: ", "Street: ", "House Number (optional): ",
+ "City: ", "State or Province (optional): ", "Postal Code: ", "Country [GB]: ", "Phone: "} {
+ if !strings.Contains(text, want) {
+ t.Errorf("output lacks %q:\n%s", want, text)
+ }
+ }
+ for _, leaked := range []string{"Ada", "Lovelace", "Engines", "ada@example.com", "Example Road", "London", "N1 1AA", "2071234567"} {
+ if strings.Contains(text, leaked) {
+ t.Errorf("a saved contact's %q was offered on the contact-file path:\n%s", leaked, text)
+ }
+ }
+ if strings.Contains(text, domainsBuyCopy["contactPickHeader"]) {
+ t.Errorf("the contact-file path asked to pick a saved contact:\n%s", text)
+ }
+ purchases, _ := cs.recorded()
+ var sent registrar.Contact
+ json.Unmarshal(purchases[1]["contact"], &sent)
+ want := registrar.Contact{FirstName: "Jane", LastName: "Buyer", Email: "a@keymail.dev", PhoneCountryCode: "44", Phone: "1134960000",
+ Street: "Main Street", City: "Leeds", PostalCode: "LS1 1AA", Country: "GB"}
+ if sent != want {
+ t.Fatalf("sent %+v want %+v", sent, want)
+ }
+}
diff --git a/domains_transfer_cli.go b/domains_transfer_cli.go
index 6e0e22715..cd59e528d 100644
--- a/domains_transfer_cli.go
+++ b/domains_transfer_cli.go
@@ -82,6 +82,9 @@ type domainTransferOptions struct {
out io.Writer
now func() time.Time
wait func(context.Context, time.Duration) error
+ // spin starts the busy line (stderrSpinner) and returns its stop; nil
+ // draws none. It never runs while the transfer code is read.
+ spin func(label string) (stop func())
}
func runDomainsTransfer(args []string) error {
@@ -110,7 +113,7 @@ func runDomainsTransfer(args []string) error {
authCode: *authCode, contactFile: *contactFile, contactID: id, yes: *yes, noWait: *noWait,
in: os.Stdin, out: stdout, terminal: isatty.IsTerminal(os.Stdin.Fd()),
readSecret: func() (string, error) { return readTransferCodeTerminal(int(os.Stdin.Fd())) },
- now: time.Now, wait: waitDomainBuy,
+ now: time.Now, wait: waitDomainBuy, spin: stderrSpinner(),
})
}
@@ -185,22 +188,31 @@ func domainsTransfer(ctx context.Context, s *apiSession, acct apiAcct, name stri
func startDomainTransfer(ctx context.Context, s *apiSession, acct apiAcct, name, code string, input *bufio.Scanner, o domainTransferOptions) error {
var contact *registrar.Contact
var saved *apiSavedContact
+ var contacts apiSavedContacts
var err error
if o.contactFile != "" {
if contact, err = readContactFile(o.contactFile, buyContactFileErrors); err != nil {
return err
}
- } else if saved, err = pickSavedContact(ctx, s, acct, o.contactID); err != nil {
- return err
- }
- country := ""
- switch {
- case contact != nil:
- country = contact.Country
- case saved != nil:
- country = saved.Contact.Country
}
- tq, err := s.postDomainTransferCheck(ctx, acct, name, country)
+ stop := startSpin(o.spin, fmt.Sprintf(domainsBuyCopy["spinCheck"], name))
+ tq, err := func() (domainTransferQuoteResp, error) {
+ if contact == nil {
+ var err error
+ if saved, contacts, err = pickSavedContact(ctx, s, acct, o.contactID); err != nil {
+ return domainTransferQuoteResp{}, err
+ }
+ }
+ country := ""
+ switch {
+ case contact != nil:
+ country = contact.Country
+ case saved != nil:
+ country = saved.Contact.Country
+ }
+ return s.postDomainTransferCheck(ctx, acct, name, country)
+ }()
+ stop()
if err != nil {
return err
}
@@ -223,13 +235,26 @@ func startDomainTransfer(ctx context.Context, s *apiSession, acct apiAcct, name,
}
}
var p domainPurchaseResp
- contactRetried, priceRetried := false, false
+ contactRetried, priceRetried, typed := false, false, false
+ // keep ends a transfer that did not start: details typed into the form
+ // are offered for saving first, after a definite refusal or a declined
+ // price (err nil) only. An uncertain outcome offers nothing: the start
+ // may have happened and saved the contact, and the add door does not
+ // deduplicate.
+ keep := func(err error) error {
+ if typed && contact != nil && (err == nil || startDefinitelyRefused(err)) {
+ offerSaveContact(ctx, s, acct, input, o.out, contact, o.spin)
+ }
+ return err
+ }
for {
req := domainTransferReq{Name: name, AuthCode: code, Contact: contact}
if contact == nil && saved != nil {
req.ContactID = saved.ID
}
+ stop := startSpin(o.spin, domainsBuyCopy["spinStartTransfer"])
p, err = s.postDomainTransfer(ctx, acct, req, q)
+ stop()
var contactErr *domainContactError
var priceErr *domainPriceChangedError
switch {
@@ -239,25 +264,35 @@ func startDomainTransfer(ctx context.Context, s *apiSession, acct apiAcct, name,
}
contactRetried = true
fmt.Fprintln(o.out, redactTransferCode(err, code))
- if contact, err = promptDomainContact(input, o.out); err != nil {
+ if o.contactFile != "" {
+ // The contact file's path has not read the list: read it now,
+ // for the account's defaults. Best effort: a refusal leaves
+ // none, and the form still asks.
+ contacts, _ = s.domainContacts(ctx, acct)
+ }
+ known := contactKnown{saved: contacts.Contacts, prefill: contact, email: sessionEmail(s), billingCurrency: contacts.BillingCurrency}
+ if contact, typed, err = promptDomainContact(input, o.out, known); err != nil {
return err
}
continue
case errors.As(err, &priceErr):
printDomainTransferQuote(o.out, priceErr.Quote)
if priceRetried || (o.yes && (q.Currency != priceErr.Quote.Currency || q.Price != priceErr.Quote.Price)) || (!o.yes && !o.terminal) {
- return err
+ return keep(err)
}
priceRetried = true
if !o.yes {
if ok, err := domainTransferYes(input, o.out, domainsTransferCopy["confirmChanged"]); !ok || err != nil {
- return err
+ if err != nil {
+ return err
+ }
+ return keep(nil)
}
}
q = priceErr.Quote
continue
case err != nil:
- return err
+ return keep(err)
}
break
}
@@ -335,10 +370,14 @@ func waitDomainTransfer(ctx context.Context, s *apiSession, acct apiAcct, p doma
noted = true
}
}
- if err := o.wait(ctx, delay); err != nil {
- return err
- }
- next, err := pollDomainTransfer(ctx, s, acct, id, o)
+ stop := startSpin(o.spin, fmt.Sprintf(domainsBuyCopy["spinWait"], domain))
+ next, err := func() (domainPurchaseResp, error) {
+ if err := o.wait(ctx, delay); err != nil {
+ return domainPurchaseResp{}, err
+ }
+ return pollDomainTransfer(ctx, s, acct, id, o)
+ }()
+ stop()
if err != nil {
return err
}
@@ -519,11 +558,14 @@ func (s *apiSession) postDomainTransfer(ctx context.Context, acct apiAcct, in do
}
// domainStartError is a refused purchase or transfer start: a changed
-// price to confirm, a contact to put right, or the console's words.
+// price to confirm, a contact to put right, or the console's words. A
+// readable 4xx (the console's own refusal in its JSON) is a
+// *domainStartRefusedError: nothing started.
func domainStartError(status int, body []byte) error {
err := apiErrorFromBody(status, body)
var refusal struct {
- Code string `json:"code"`
+ Code string `json:"code"`
+ Error string `json:"error"`
domainQuoteResp
}
if status == http.StatusConflict && json.Unmarshal(body, &refusal) == nil && refusal.Code == "price_changed" && refusal.Currency != "" && refusal.Price > 0 {
@@ -532,5 +574,26 @@ func domainStartError(status int, body []byte) error {
if status == http.StatusUnprocessableEntity && json.Unmarshal(body, &refusal) == nil && refusal.Code == "contact" {
return &domainContactError{err}
}
+ if status >= 400 && status < 500 && json.Unmarshal(body, &refusal) == nil && refusal.Error != "" {
+ return &domainStartRefusedError{err}
+ }
return err
}
+
+// domainStartRefusedError is a start the console refused in words, with a
+// 4xx: definitely nothing started.
+type domainStartRefusedError struct{ error }
+
+func (e *domainStartRefusedError) Unwrap() error { return e.error }
+
+// startDefinitelyRefused reports whether err is a start the console
+// definitely refused before anything started: a readable 4xx, a contact
+// refusal or a changed price. A transport error, a 5xx, a lost or
+// unreadable answer is not: the start may have happened, and saved its
+// contact itself.
+func startDefinitelyRefused(err error) bool {
+ var refused *domainStartRefusedError
+ var contactErr *domainContactError
+ var priceErr *domainPriceChangedError
+ return errors.As(err, &refused) || errors.As(err, &contactErr) || errors.As(err, &priceErr)
+}
diff --git a/internal/console/accountdomainbuy_test.go b/internal/console/accountdomainbuy_test.go
index d361663a0..f02ffa0e3 100644
--- a/internal/console/accountdomainbuy_test.go
+++ b/internal/console/accountdomainbuy_test.go
@@ -131,6 +131,7 @@ func TestAccountBuyThreeStepsToCheckout(t *testing.T) {
!strings.Contains(body, `name="price" value="1500"`) || !strings.Contains(body, `name="app" value="blog"`) || !strings.Contains(body, `value="new"`) {
t.Fatalf("step 3: %d %s", status, body)
}
+ wantContactAutocomplete(t, body, 1)
if saved && !strings.Contains(body, `value="`+savedID+`" checked`) {
t.Fatal("step 3 does not preselect the most recently used saved contact")
}
diff --git a/internal/console/accountdomaintransfer_test.go b/internal/console/accountdomaintransfer_test.go
index 47ad597cf..e55d7dd9d 100644
--- a/internal/console/accountdomaintransfer_test.go
+++ b/internal/console/accountdomaintransfer_test.go
@@ -74,6 +74,7 @@ func TestTransferFormShowsNameserversAndPrice(t *testing.T) {
t.Errorf("form lacks %q:\n%s", want, main)
}
}
+ wantContactAutocomplete(t, main, 1)
if strings.Contains(main, "?auth_code") || strings.Contains(main, `method="get"`) {
t.Errorf("the form could send the code in a URL:\n%s", main)
}
diff --git a/internal/console/apidomainbuy.go b/internal/console/apidomainbuy.go
index e6f3f783c..d41a7c909 100644
--- a/internal/console/apidomainbuy.go
+++ b/internal/console/apidomainbuy.go
@@ -475,7 +475,10 @@ func writeContactRefusal(w http.ResponseWriter) {
}
// handleAPIDomainContacts is GET .../domains/contacts: most recently used
-// first, the order a purchase with no contact picks from.
+// first, the order a purchase with no contact picks from. billing_currency
+// is the account's own billing currency, "" while none is set (a quote then
+// prices in the book's default): the CLI's contact form infers a default
+// country from it only when one is set.
func (s *Server) handleAPIDomainContacts(w http.ResponseWriter, r *http.Request) {
acct, ok := s.domainContactsAPIGate(w, r)
if !ok {
@@ -491,7 +494,7 @@ func (s *Server) handleAPIDomainContacts(w http.ResponseWriter, r *http.Request)
for _, c := range contacts {
out = append(out, apiSavedContactOf(c))
}
- writeJSON(w, http.StatusOK, map[string]any{"contacts": out})
+ writeJSON(w, http.StatusOK, map[string]any{"contacts": out, "billing_currency": s.domainCurrency(acct)})
}
func (s *Server) handleAPIDomainContactAdd(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/console/apidomainbuy_test.go b/internal/console/apidomainbuy_test.go
index 587a227c4..45439ff15 100644
--- a/internal/console/apidomainbuy_test.go
+++ b/internal/console/apidomainbuy_test.go
@@ -685,10 +685,31 @@ func TestAPIContactsOwnerOnly(t *testing.T) {
ID string `json:"id"`
Contact registrar.Contact `json:"contact"`
} `json:"contacts"`
+ BillingCurrency *string `json:"billing_currency"`
}
if status != 200 || json.Unmarshal([]byte(b), &listed) != nil || len(listed.Contacts) != 1 || listed.Contacts[0].ID != added.ID {
t.Fatalf("list: %d %s", status, b)
}
+ // billing_currency is the account's own billing currency, and "" while
+ // none is set, never the book's default.
+ for _, currency := range []string{"", "gbp"} {
+ b0, err := f.st.BillingAccount(f.acct.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if b0 == nil {
+ b0 = &billingAccount{AccountID: f.acct.ID, PaidPacks: map[string]int{}, Annual: -1}
+ }
+ b0.Currency = currency
+ if err := f.st.PutBillingState(*b0); err != nil {
+ t.Fatal(err)
+ }
+ status, b = buyRequest(t, f, "GET", path, tok, "")
+ listed.BillingCurrency = nil
+ if status != 200 || json.Unmarshal([]byte(b), &listed) != nil || listed.BillingCurrency == nil || *listed.BillingCurrency != currency {
+ t.Fatalf("billing_currency with %q set: %d %s", currency, status, b)
+ }
+ }
edited := purchaseContact()
edited.City = "Cork"
editBody, _ := json.Marshal(edited)
diff --git a/internal/console/contact_autocomplete_test.go b/internal/console/contact_autocomplete_test.go
new file mode 100644
index 000000000..bb849d068
--- /dev/null
+++ b/internal/console/contact_autocomplete_test.go
@@ -0,0 +1,46 @@
+package console
+
+import (
+ "context"
+ "regexp"
+ "testing"
+ "time"
+)
+
+// contactAutocomplete is the autofill token (HTML's autocomplete
+// attribute) each contact field carries, so a browser fills a saved
+// address into the form: on the saved-contact forms, the buy form's
+// Registered to and the transfer form's.
+var contactAutocomplete = map[string]string{
+ "FirstName": "given-name", "LastName": "family-name", "Company": "organization", "Email": "email",
+ "PhoneCountryCode": "tel-country-code", "Phone": "tel-national", "Street": "address-line1",
+ "HouseNumber": "address-line2", "City": "address-level2", "State": "address-level1",
+ "PostalCode": "postal-code", "Country": "country",
+}
+
+// wantContactAutocomplete fails unless every contact field in body is drawn
+// with its token, at least min times each.
+func wantContactAutocomplete(t *testing.T, body string, min int) {
+ t.Helper()
+ for name, token := range contactAutocomplete {
+ re := regexp.MustCompile(`<(?:input|select) [^>]*name="` + name + `"[^>]* autocomplete="` + regexp.QuoteMeta(token) + `"`)
+ if n := len(re.FindAllString(body, -1)); n < min {
+ t.Errorf("%s drawn with autocomplete=%q %d times, want at least %d", name, token, n, min)
+ }
+ }
+}
+
+// TestSavedContactFormsAutocomplete: the Domains page's saved-contact edit
+// form and its add form both carry the autofill tokens.
+func TestSavedContactFormsAutocomplete(t *testing.T) {
+ f := newPurchaseFixture(t)
+ if _, err := f.st.AddSavedContact(context.Background(), f.acct.ID, purchaseContact(), time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ c, _ := f.ownerBrowser(t)
+ status, _, body := get(t, c, f.acctURL("/domains"))
+ if status != 200 {
+ t.Fatalf("GET domains: %d %s", status, body)
+ }
+ wantContactAutocomplete(t, body, 2)
+}
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index 3f02da460..c15fd7ce8 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -301,4 +301,4 @@ plan14-root-reads-static-error-page-headers.tsv 4d4fdb77961d811bcfeae751b17089f0
plan14-root-reads-replica-read-lock-1443.tsv 4d4fdb77961d811bcfeae751b17089f0104d2333923a15b4c1ab5cc05d58d89f
plan14-root-reads-litestream-pin-1443.tsv 022a082b517b59ada965bbd7673e941be7c8bb4ae7547a5632f6be0570c97551
plan14-root-reads-fleet-first-reconcile-speed-5.tsv dbdeb2e3a1a89cb8f33584fdb80a3bf1c5adef14ce222fef9d442ed8e059699c
-plan14-root-reads-sec-h5-edge-availability.tsv a25dc3c6168c2315d882e88b8f795ef2644837b837f28546d61da85beb602d2f
+plan14-root-reads-cli-contact-prompts.tsv dbdeb2e3a1a89cb8f33584fdb80a3bf1c5adef14ce222fef9d442ed8e059699c
diff --git a/internal/provision/testdata/plan14-root-reads-cli-contact-prompts.tsv b/internal/provision/testdata/plan14-root-reads-cli-contact-prompts.tsv
new file mode 100644
index 000000000..4b9b08925
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-cli-contact-prompts.tsv
@@ -0,0 +1,3 @@
+# Census overlay cli-contact-prompts, written by census-propose (#369). census-ruling-cli-contact-prompts, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-cli-contact-prompts.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage . b97e9522df130f1327d9f7ea2a5df9740e845356a96abf61326cff544fc99ebc