cli: transfer code without echo; the wait outlasts failed polls
Final-review fixes F6 and F7, and F5's CLI side. - --auth-code - on a terminal reads the code with x/term ReadPassword (golang.org/x/term v0.47.0 added; it needs x/sys v0.49.0, already required). The terminal is restored on return and on SIGINT/SIGTERM. Pipes keep the line reader. Tested through a seam over the reader. - The wait retries transport errors, 5xx and 429 (Retry-After honoured), 5 s doubling to 5 min, keeping the last state; after 30 minutes of failures it stops, saying the move carries on and to check with carlos domains list --all. Other 4xx end it at once. - The failed line states the refund the console reports (tax included), falling back to the confirmed price. - Adds the deferred failed-state wait test (stage equal to state prints once).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
6 files changed,
+323
−15
apimode.go+4 −0domains_buy_copy.go+3 −0domains_transfer_cli.go+152 −15domains_transfer_cli_test.go+161 −0go.mod+1 −0go.sum+2 −0
diff --git a/apimode.go b/apimode.go| index 27552f89e..bbd408ad1 100644 |
| --- a/apimode.go |
| +++ b/apimode.go |
| @@ -4958,6 +4958,10 @@ type domainPurchaseResp struct { |
| Pointed *bool `json:"pointed"` // nil from a console that predates it |
| Stage string `json:"stage"` // a transfer's card stage |
| Money string `json:"money"` // a failed transfer's money outcome |
| + // Refund is what a failed transfer's refund returned (minor units of |
| + // Currency, tax included); 0 from a console that predates it. |
| + Refund int64 `json:"refund"` |
| + Currency string `json:"currency"` |
| } |
| type domainContactError struct{ error } |
diff --git a/domains_buy_copy.go b/domains_buy_copy.go| index 26d2077e7..455f3e84f 100644 |
| --- a/domains_buy_copy.go |
| +++ b/domains_buy_copy.go |
| @@ -183,6 +183,9 @@ var domainsTransferCopy = map[string]string{ |
| "unreadableCheck": "domains transfer: unreadable response: %w", |
| "unreadableStart": "domains transfer: unreadable response: %w", |
| "redacted": "[transfer code]", |
| + // Draft for the Luna pass (final review fixes, F7): the wait gave up |
| + // after half an hour of failed status polls. %v is the last failure. |
| + "pollGaveUp": "can’t reach the console to check on the move (%v). the move carries on. check on it with carlos domains list --all", |
| } |
| // domainsTransferFailureReason is a failed transfer's reason in plain |
diff --git a/domains_transfer_cli.go b/domains_transfer_cli.go| index 8645dbe38..1be04faea 100644 |
| --- a/domains_transfer_cli.go |
| +++ b/domains_transfer_cli.go |
| @@ -6,8 +6,9 @@ package main |
| // purchase status door's, which `buy` waits on too. |
| // |
| // The transfer code is a secret: it is read from the flag or one line of |
| -// stdin, sent only in the start's POST body, and never printed, in output |
| -// or in an error (redactTransferCode). |
| +// stdin (on a terminal without echo, readTransferCodeTerminal), sent only |
| +// in the start's POST body, and never printed, in output or in an error |
| +// (redactTransferCode). |
| import ( |
| "bufio" |
| @@ -18,13 +19,18 @@ import ( |
| "fmt" |
| "io" |
| "net/http" |
| + "net/url" |
| "os" |
| + "os/signal" |
| + "strconv" |
| "strings" |
| + "syscall" |
| "time" |
| "github.com/carlosframework/platform/internal/plans" |
| "github.com/carlosframework/platform/internal/registrar" |
| "github.com/mattn/go-isatty" |
| + "golang.org/x/term" |
| ) |
| // domainTransferWaitPoll is how often the wait asks while the current |
| @@ -32,6 +38,18 @@ import ( |
| // seconds. |
| const domainTransferWaitPoll = time.Minute |
| +// The wait outlasts a console it cannot reach: a poll that fails in |
| +// transport, with a 5xx or with a 429 is tried again after |
| +// domainTransferRetryFirst, doubling to domainTransferRetryMax (a 429's |
| +// Retry-After instead, when it says, within the same bound), keeping the |
| +// last state it read. After domainTransferGiveUp of nothing but failures it |
| +// stops, saying the move carries on and how to check on it. |
| +const ( |
| + domainTransferRetryFirst = 5 * time.Second |
| + domainTransferRetryMax = 5 * time.Minute |
| + domainTransferGiveUp = 30 * time.Minute |
| +) |
| + |
| // domainTransferQuoteResp is the transfer check's answer. |
| type domainTransferQuoteResp struct { |
| Domain string `json:"domain"` |
| @@ -56,10 +74,13 @@ type domainTransferOptions struct { |
| contactFile string // a new contact, from a file |
| contactID string // a saved contact; "" with no file is the last used |
| yes, noWait, terminal bool |
| - in io.Reader |
| - out io.Writer |
| - now func() time.Time |
| - wait func(context.Context, time.Duration) error |
| + // readSecret reads the code from a terminal without echo; nil reads it |
| + // as a line, as from a pipe. |
| + readSecret func() (string, error) |
| + in io.Reader |
| + out io.Writer |
| + now func() time.Time |
| + wait func(context.Context, time.Duration) error |
| } |
| func runDomainsTransfer(args []string) error { |
| @@ -87,10 +108,40 @@ func runDomainsTransfer(args []string) error { |
| return domainsTransfer(context.Background(), sess, acct, strings.TrimSpace(pos[0]), domainTransferOptions{ |
| authCode: *authCode, contactFile: *contactFile, contactID: id, yes: *yes, noWait: *noWait, |
| in: os.Stdin, out: stdout, terminal: isatty.IsTerminal(os.Stdin.Fd()), |
| - now: time.Now, wait: waitDomainBuy, |
| + readSecret: func() (string, error) { return readTransferCodeTerminal(int(os.Stdin.Fd())) }, |
| + now: time.Now, wait: waitDomainBuy, |
| }) |
| } |
| +// readTransferCodeTerminal reads one line from the terminal fd without |
| +// echoing it. The terminal is restored when the read returns, and on an |
| +// interrupt or termination during it, after which the process exits as |
| +// the signal would have it. |
| +func readTransferCodeTerminal(fd int) (string, error) { |
| + state, err := term.GetState(fd) |
| + if err != nil { |
| + return "", err |
| + } |
| + signals := make(chan os.Signal, 1) |
| + signal.Notify(signals, os.Interrupt, syscall.SIGTERM) |
| + done := make(chan struct{}) |
| + defer func() { |
| + signal.Stop(signals) |
| + close(done) |
| + }() |
| + go func() { |
| + select { |
| + case sig := <-signals: |
| + _ = term.Restore(fd, state) |
| + fmt.Fprintln(os.Stderr) |
| + os.Exit(signalExit(sig)) |
| + case <-done: |
| + } |
| + }() |
| + line, err := term.ReadPassword(fd) |
| + return string(line), err |
| +} |
| + |
| // domainsTransfer checks name, shows the price and the nameservers it keeps, |
| // confirms, starts the transfer, prints the Checkout link and waits. Every |
| // error it returns has the transfer code taken out. |
| @@ -98,13 +149,26 @@ func domainsTransfer(ctx context.Context, s *apiSession, acct apiAcct, name stri |
| input := bufio.NewScanner(o.in) |
| code := strings.TrimSpace(o.authCode) |
| if o.authCode == "-" { |
| - if o.terminal { |
| + code = "" |
| + switch { |
| + case o.terminal && o.readSecret != nil: |
| + // Typed at a terminal: never echoed, so it stays out of the |
| + // scrollback and any recording. |
| fmt.Fprint(o.out, domainsTransferCopy["codePrompt"]) |
| + line, err := o.readSecret() |
| + fmt.Fprintln(o.out) |
| + if err != nil { |
| + return errors.New(domainsTransferCopy["codeEmpty"]) |
| + } |
| + code = strings.TrimSpace(line) |
| + default: |
| + if o.terminal { |
| + fmt.Fprint(o.out, domainsTransferCopy["codePrompt"]) |
| + } |
| + if input.Scan() { |
| + code = strings.TrimSpace(input.Text()) |
| + } |
| } |
| - if !input.Scan() { |
| - return errors.New(domainsTransferCopy["codeEmpty"]) |
| - } |
| - code = strings.TrimSpace(input.Text()) |
| if code == "" { |
| return errors.New(domainsTransferCopy["codeEmpty"]) |
| } |
| @@ -268,17 +332,90 @@ func waitDomainTransfer(ctx context.Context, s *apiSession, acct apiAcct, p doma |
| if err := o.wait(ctx, delay); err != nil { |
| return err |
| } |
| - var err error |
| - if p, err = s.getDomainPurchase(ctx, acct, id); err != nil { |
| + next, err := pollDomainTransfer(ctx, s, acct, id, o) |
| + if err != nil { |
| return err |
| } |
| + p = next |
| } |
| } |
| +// pollDomainTransfer reads the transfer's status, trying again over a |
| +// failure the console may get over (transportError, a 5xx, a 429) as |
| +// domainTransferRetryFirst says. Any other refusal ends the wait at once. |
| +func pollDomainTransfer(ctx context.Context, s *apiSession, acct apiAcct, id string, o domainTransferOptions) (domainPurchaseResp, error) { |
| + var failingSince time.Time |
| + backoff := domainTransferRetryFirst |
| + for { |
| + p, retryAfter, err := getDomainTransferStatus(ctx, s, acct, id) |
| + var transient *transientPollError |
| + if err == nil || !errors.As(err, &transient) || ctx.Err() != nil { |
| + return p, err |
| + } |
| + now := o.now() |
| + if failingSince.IsZero() { |
| + failingSince = now |
| + } |
| + if now.Sub(failingSince) >= domainTransferGiveUp { |
| + return p, fmt.Errorf(domainsTransferCopy["pollGaveUp"], transient.err) |
| + } |
| + delay := backoff |
| + if retryAfter > 0 { |
| + delay = min(retryAfter, domainTransferRetryMax) |
| + } |
| + backoff = min(backoff*2, domainTransferRetryMax) |
| + if err := o.wait(ctx, delay); err != nil { |
| + return p, err |
| + } |
| + } |
| +} |
| + |
| +// transientPollError is a status poll that failed in a way worth trying |
| +// again: no answer, a 5xx or a 429. |
| +type transientPollError struct{ err error } |
| + |
| +func (e *transientPollError) Error() string { return e.err.Error() } |
| +func (e *transientPollError) Unwrap() error { return e.err } |
| + |
| +// getDomainTransferStatus is one status read: the reply, a 429's |
| +// Retry-After, and an error that is a *transientPollError when the read |
| +// may succeed later. |
| +func getDomainTransferStatus(ctx context.Context, s *apiSession, acct apiAcct, id string) (domainPurchaseResp, time.Duration, error) { |
| + var out domainPurchaseResp |
| + status, header, body, err := s.getJSONHeader(ctx, domainBuyAPIPath(acct, "/purchases/"+url.PathEscape(id))) |
| + if err != nil { |
| + if status == 0 { |
| + return out, 0, &transientPollError{err} |
| + } |
| + return out, 0, err |
| + } |
| + switch { |
| + case status == http.StatusTooManyRequests: |
| + var after time.Duration |
| + if n, perr := strconv.Atoi(strings.TrimSpace(header.Get("Retry-After"))); perr == nil && n > 0 { |
| + after = time.Duration(n) * time.Second |
| + } |
| + return out, after, &transientPollError{apiErrorFromBody(status, body)} |
| + case status >= 500: |
| + return out, 0, &transientPollError{apiErrorFromBody(status, body)} |
| + case status != http.StatusOK: |
| + return out, 0, apiErrorFromBody(status, body) |
| + } |
| + if err := json.Unmarshal(body, &out); err != nil { |
| + return out, 0, fmt.Errorf(domainsBuyCopy["unreadablePurchase"], err) |
| + } |
| + return out, 0, nil |
| +} |
| + |
| // transferFailedError is a failed transfer's line: its reason in plain |
| // words, then what happened to the money as the card says it (the status |
| -// reply's money), else the general line. |
| +// reply's money), else the general line. A refund states what the console |
| +// says it returned (tax included), else amount, the confirmed price, from a |
| +// console that predates it. |
| func transferFailedError(p domainPurchaseResp, amount string) error { |
| + if p.Refund > 0 && p.Currency != "" { |
| + amount = plans.FormatMinor(p.Currency, p.Refund) |
| + } |
| reason, ok := domainsTransferFailureReason[p.Reason] |
| if !ok { |
| reason = domainsTransferFailureReason[""] |
diff --git a/domains_transfer_cli_test.go b/domains_transfer_cli_test.go| index e570f8103..8c21f28da 100644 |
| --- a/domains_transfer_cli_test.go |
| +++ b/domains_transfer_cli_test.go |
| @@ -352,3 +352,164 @@ func TestDomainsTransferFailedSaysWhatHappenedToTheMoney(t *testing.T) { |
| t.Fatal("a refund made another way must not name the card") |
| } |
| } |
| + |
| +// TestDomainsTransferReadsCodeWithoutEcho: with --auth-code - on a |
| +// terminal, the code is read through the no-echo reader (the |
| +// readTransferCodeTerminal seam; the repo has no pseudo-terminal harness), |
| +// never from the line reader, and never printed; the prompt is followed |
| +// by a newline. A failed read is the empty-code refusal. Off a terminal, |
| +// the line reader is used, as for a pipe. |
| +func TestDomainsTransferReadsCodeWithoutEcho(t *testing.T) { |
| + ts := newTransferTestServer(t, nil, nil) |
| + var out bytes.Buffer |
| + o := transferTestOptions(t, &out) |
| + o.authCode, o.terminal, o.noWait = "-", true, true |
| + o.in = strings.NewReader("line-reader-must-not-be-used\n") |
| + reads := 0 |
| + o.readSecret = func() (string, error) { reads++; return " " + transferTestCode + " ", nil } |
| + if err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", o); err != nil { |
| + t.Fatalf("%v\n%s", err, &out) |
| + } |
| + starts := ts.startBodies() |
| + if reads != 1 || len(starts) != 1 || starts[0]["auth_code"] != transferTestCode { |
| + t.Fatalf("reads %d, starts %+v", reads, starts) |
| + } |
| + if strings.Contains(out.String(), transferTestCode) || !strings.HasPrefix(out.String(), domainsTransferCopy["codePrompt"]+"\n") { |
| + t.Fatalf("output:\n%q", out.String()) |
| + } |
| + |
| + out.Reset() |
| + o.readSecret = func() (string, error) { return "", errors.New("read interrupted") } |
| + if err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", o); err == nil || err.Error() != domainsTransferCopy["codeEmpty"] || len(ts.startBodies()) != 1 { |
| + t.Fatalf("a failed read: %v", err) |
| + } |
| + |
| + out.Reset() |
| + o.terminal, o.in = false, strings.NewReader(transferTestCode+"\n") |
| + o.readSecret = func() (string, error) { t.Fatal("the no-echo reader used off a terminal"); return "", nil } |
| + if err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", o); err != nil || len(ts.startBodies()) != 2 { |
| + t.Fatalf("a pipe: %v", err) |
| + } |
| +} |
| + |
| +// TestDomainsTransferWaitSurvivesFailedPolls: a poll that fails in |
| +// transport, with a 5xx or with a 429 is tried again with backoff (a 429's |
| +// Retry-After honoured) and the wait goes on to the end; half an hour of |
| +// nothing but failures stops it, saying the move carries on and how to |
| +// check; any other refusal ends it at once. |
| +func TestDomainsTransferWaitSurvivesFailedPolls(t *testing.T) { |
| + t.Run("a blip, then the answer", func(t *testing.T) { |
| + polls := 0 |
| + ts := newTransferTestServer(t, nil, func(w http.ResponseWriter, r *http.Request) { |
| + polls++ |
| + switch polls { |
| + case 1: |
| + json.NewEncoder(w).Encode(map[string]any{"id": "t1", "kind": "transfer", "state": "transfer_pending", "stage": "waiting"}) |
| + case 2: |
| + http.Error(w, `{"error":"down"}`, http.StatusBadGateway) |
| + case 3: |
| + w.Header().Set("Retry-After", "7") |
| + http.Error(w, `{"error":"slow down"}`, http.StatusTooManyRequests) |
| + default: |
| + json.NewEncoder(w).Encode(map[string]any{"id": "t1", "kind": "transfer", "state": "done", "stage": "done", "domain": "shop.com"}) |
| + } |
| + }) |
| + var out bytes.Buffer |
| + o := transferTestOptions(t, &out) |
| + var delays []time.Duration |
| + wait := o.wait |
| + o.wait = func(ctx context.Context, d time.Duration) error { delays = append(delays, d); return wait(ctx, d) } |
| + if err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", o); err != nil { |
| + t.Fatalf("%v\n%s", err, &out) |
| + } |
| + if polls != 4 || !strings.Contains(out.String(), fmt.Sprintf(domainsTransferCopy["done"], "shop.com")) { |
| + t.Fatalf("%d polls:\n%s", polls, &out) |
| + } |
| + // The waits before the first two polls, then the 502's backoff, |
| + // then the 429's Retry-After. |
| + if len(delays) < 4 || delays[2] != domainTransferRetryFirst || delays[3] != 7*time.Second { |
| + t.Fatalf("delays %v", delays) |
| + } |
| + }) |
| + t.Run("half an hour of failures", func(t *testing.T) { |
| + polls := 0 |
| + ts := newTransferTestServer(t, nil, func(w http.ResponseWriter, r *http.Request) { |
| + polls++ |
| + if polls == 1 { |
| + json.NewEncoder(w).Encode(map[string]any{"id": "t1", "kind": "transfer", "state": "transfer_pending", "stage": "waiting"}) |
| + return |
| + } |
| + http.Error(w, "", http.StatusServiceUnavailable) |
| + }) |
| + var out bytes.Buffer |
| + err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", transferTestOptions(t, &out)) |
| + if err == nil || !strings.Contains(err.Error(), "the move carries on") || !strings.Contains(err.Error(), "carlos domains list --all") || strings.Contains(err.Error(), "%!") { |
| + t.Fatalf("gave up with %v after %d polls", err, polls) |
| + } |
| + // 5 s doubling to 5 min over 30 min: a bounded number of tries. |
| + if polls < 5 || polls > 15 { |
| + t.Fatalf("%d polls over half an hour", polls) |
| + } |
| + }) |
| + t.Run("no console at all", func(t *testing.T) { |
| + ts := newTransferTestServer(t, nil, nil) |
| + session := newTestSession(ts.URL) |
| + var out bytes.Buffer |
| + o := transferTestOptions(t, &out) |
| + ts.Close() // every poll is a transport error |
| + _, err := pollDomainTransfer(context.Background(), session, apiAcct{Seg: "bab"}, "t1", o) |
| + if err == nil || !strings.Contains(err.Error(), "the move carries on") { |
| + t.Fatalf("transport errors: %v", err) |
| + } |
| + }) |
| + t.Run("a refusal ends it at once", func(t *testing.T) { |
| + polls := 0 |
| + ts := newTransferTestServer(t, nil, func(w http.ResponseWriter, r *http.Request) { |
| + polls++ |
| + if polls == 1 { |
| + json.NewEncoder(w).Encode(map[string]any{"id": "t1", "kind": "transfer", "state": "transfer_pending", "stage": "waiting"}) |
| + return |
| + } |
| + http.Error(w, `{"error":"not found"}`, http.StatusNotFound) |
| + }) |
| + var out bytes.Buffer |
| + err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", transferTestOptions(t, &out)) |
| + if err == nil || polls != 2 || strings.Contains(err.Error(), "carries on") { |
| + t.Fatalf("404: %v after %d polls", err, polls) |
| + } |
| + }) |
| +} |
| + |
| +// TestDomainsTransferFailedStatePrintedOnce: an ended transfer's stage is |
| +// its state, so "failed" is printed once, as the state alone. |
| +func TestDomainsTransferFailedStatePrintedOnce(t *testing.T) { |
| + polls := 0 |
| + ts := newTransferTestServer(t, nil, func(w http.ResponseWriter, r *http.Request) { |
| + polls++ |
| + state, stage := "transfer_pending", "waiting" |
| + if polls > 1 { |
| + state, stage = "failed", "failed" |
| + } |
| + json.NewEncoder(w).Encode(map[string]any{"id": "t1", "kind": "transfer", "state": state, "stage": stage, "reason": "rejected", "money": "not_charged"}) |
| + }) |
| + var out bytes.Buffer |
| + if err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", transferTestOptions(t, &out)); err == nil { |
| + t.Fatal("no error at failed") |
| + } |
| + if got := out.String(); strings.Count(got, "transfer state: failed") != 1 || !strings.Contains(got, "transfer state: failed\n") || strings.Contains(got, "failed (failed)") { |
| + t.Fatalf("failed printed wrongly:\n%s", got) |
| + } |
| +} |
| + |
| +// TestDomainsTransferRefundStatesTheTotal: a console that says what the |
| +// refund returned (tax included) is quoted, not the confirmed price. |
| +func TestDomainsTransferRefundStatesTheTotal(t *testing.T) { |
| + ts := newTransferTestServer(t, nil, func(w http.ResponseWriter, r *http.Request) { |
| + json.NewEncoder(w).Encode(map[string]any{"id": "t1", "kind": "transfer", "state": "failed", "stage": "failed", "reason": "rejected", "money": "refunded", "refund": 1476, "currency": "usd"}) |
| + }) |
| + var out bytes.Buffer |
| + err := domainsTransfer(context.Background(), newTestSession(ts.URL), apiAcct{Seg: "bab"}, "shop.com", transferTestOptions(t, &out)) |
| + if want := fmt.Sprintf(domainsTransferCopy["failedRefunded"], domainsTransferFailureReason["rejected"], "$14.76"); err == nil || err.Error() != want { |
| + t.Fatalf("err %v, want %q", err, want) |
| + } |
| +} |
diff --git a/go.mod b/go.mod| index ec89b2262..fe142fbdb 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -93,6 +93,7 @@ require ( |
| github.com/aws/aws-sdk-go-v2/service/sns v1.43.0 |
| github.com/klauspost/compress v1.20.2 |
| github.com/oschwald/maxminddb-golang v1.13.1 |
| + golang.org/x/term v0.47.0 |
| golang.org/x/tools v0.51.0 |
| ) |
diff --git a/go.sum b/go.sum| index 795d715bc..4e50516c3 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -253,6 +253,8 @@ golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= |
| golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= |
| golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= |
| golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= |
| +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= |
| +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= |
| golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= |
| golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= |
| golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= |