Skip to content
quarry Artifact [3a33075d54]
Login

Artifact [3a33075d54]

Artifact 3a33075d54e7cd2f49c8ab3c69847c613f1e4f16de18d36c2136899939a2f4c1:


package pickupclient

import (
	"bufio"
	"bytes"
	"context"
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"os/signal"
	"runtime"
	"strconv"
	"strings"
	"syscall"
	"time"
	"unicode/utf8"

	"craftdesign.group/quarry/internal/nextstep"
)

// apiBodyLimit is the largest answer printed; a larger one is refused,
// never cut off.
var apiBodyLimit int64 = 64 << 20

var errBodyTooBig = errors.New("answer too big")

// apiStreamBackoff is the first wait before a dropped event stream is
// opened again; it doubles up to apiStreamBackoffMax.
var apiStreamBackoff = time.Second

const apiStreamBackoffMax = 30 * time.Second

const (
	apiPrefix       = "/api/v1"
	apiInputMax     = 8 << 20
	apiWaitLimit    = 10 * time.Minute
	browserOnlyCode = "browser_only"
)

const apiHelp = `usage: quarry api METHOD PATH [-d JSON|@FILE|-] [-f FIELD]... [flags]

Call the forge's API as this machine's login. PATH is under /api/v1 and
stays on the forge; the answer is the forge's JSON, printed as it came.
"quarry api GET /" is the index of every op.

  -d JSON|@FILE|-   the request body: JSON text, a file's, or standard input
  -f key=value      a string field          -f key=@FILE   a file's text
  -f key=@-         standard input          -f key:=JSON   a number, boolean,
                                                           array or object
  --host URL        the forge (default: QUARRY_HOST, else the checkout's
                    remote, else the installer's)
  --wait            when the call is for a browser, follow the repository's
                    events and retry it when something changes (up to 10 min)
  --open            open the page the refusal names, on a terminal only
  --ask "reason"    when the call is for a browser, ask for your approval
                    instead: the forge files a request, this prints its page
                    (/me/signoffs/ID) and waits for you to approve it there,
                    then prints the result (exit 0), or exits 1 if denied or
                    failed, 3 if it is still waiting
  --pickup-file F   with --ask, for a call that mints a credential: F is a
                    private (0600) file of 32 key bytes; its hex SHA-256 is
                    sent as Quarry-Pickup, and the credential is collected
                    with that key, never printed here
  --ask-wait DUR    how long --ask waits for the approval (default 10m)
  --json            accepted; the answer is always the forge's JSON

A route that answers text/event-stream (GET /events/stream, GET
/r/{repo}/events/stream) is followed, not read whole: each event's JSON
is printed as one line as it arrives, until Ctrl-C (exit 0). A dropped
connection is reopened with Last-Event-ID; the live and gap notices go to
stderr.

Fields are the body (a JSON object) on POST, PUT, PATCH and DELETE, and
the query on GET. -f and -d together are a usage error. Standard input is
read only when - or @- is given. {repo} in PATH is the checkout's O/N.

Exit: 0 done, 1 refused, 2 usage, 3 still waiting, 4 not logged in.

A GET that gets no answer, or a 502, 503 or 504, is asked again by itself,
up to 3 times in all, with a line on stderr each time. A POST, PUT, PATCH
or DELETE is never sent twice. Codes on exit 1 that mean no answer:
  unreachable       nothing was sent (connection refused, no such host)
  outcome_unknown   the request was sent and no answer came: the forge may or
                    may not have applied it; read it back with quarry api GET
                    before sending it again
  forge_busy        the forge answered 503 or says it is still starting; wait
                    the seconds named (its Retry-After) and run this again

Example:
  quarry api POST /r/{repo}/forum -f title='Release plan' -f [email protected]
`

type apiField struct {
	key, val string // val: the text, "@file", "@-", or JSON when typed
	file     bool
	stdin    bool
	typed    bool
}

type apiArgs struct {
	method, path, host   string
	data                 string
	hasData              bool
	fields               []apiField
	wait, open, jsonFlag bool
	ask, pickupFile      string
	askWait              time.Duration
}

func parseAPIArgs(args []string) (apiArgs, string) {
	var a apiArgs
	var pos []string
	next := func(i *int, name string) (string, bool) {
		if *i+1 >= len(args) {
			return "", false
		}
		*i++
		return args[*i], true
	}
	for i := 0; i < len(args); i++ {
		s := args[i]
		switch {
		case s == "-d" || s == "--data":
			v, ok := next(&i, s)
			if !ok {
				return a, s + " needs a value"
			}
			a.data, a.hasData = v, true
		case strings.HasPrefix(s, "--data="):
			a.data, a.hasData = strings.TrimPrefix(s, "--data="), true
		case s == "-f" || s == "--field":
			v, ok := next(&i, s)
			if !ok {
				return a, s + " needs key=value"
			}
			f, msg := parseField(v)
			if msg != "" {
				return a, msg
			}
			a.fields = append(a.fields, f)
		case s == "--host":
			v, ok := next(&i, s)
			if !ok {
				return a, "--host needs a URL"
			}
			a.host = v
		case strings.HasPrefix(s, "--host="):
			a.host = strings.TrimPrefix(s, "--host=")
		case s == "--wait":
			a.wait = true
		case s == "--open":
			a.open = true
		case s == "--ask":
			v, ok := next(&i, s)
			if !ok || strings.TrimSpace(v) == "" {
				return a, "--ask needs a reason"
			}
			a.ask = v
		case strings.HasPrefix(s, "--ask="):
			a.ask = strings.TrimPrefix(s, "--ask=")
			if strings.TrimSpace(a.ask) == "" {
				return a, "--ask needs a reason"
			}
		case s == "--pickup-file":
			v, ok := next(&i, s)
			if !ok || v == "" {
				return a, "--pickup-file needs a file"
			}
			a.pickupFile = v
		case strings.HasPrefix(s, "--pickup-file="):
			a.pickupFile = strings.TrimPrefix(s, "--pickup-file=")
		case s == "--ask-wait" || strings.HasPrefix(s, "--ask-wait="):
			v := strings.TrimPrefix(s, "--ask-wait=")
			if s == "--ask-wait" {
				var ok bool
				if v, ok = next(&i, s); !ok {
					return a, "--ask-wait needs a duration such as 10m"
				}
			}
			d, err := time.ParseDuration(v)
			if err != nil || d <= 0 {
				return a, "--ask-wait is a duration such as 90s or 10m"
			}
			a.askWait = d
		case s == "--json" || s == "-F=json":
			a.jsonFlag = true
		case s == "-F" && i+1 < len(args) && args[i+1] == "json":
			a.jsonFlag, i = true, i+1
		case len(s) > 1 && strings.HasPrefix(s, "-"):
			return a, "unknown flag " + s
		default:
			pos = append(pos, s)
		}
	}
	if len(pos) != 2 {
		return a, "give a METHOD and a PATH"
	}
	a.method, a.path = pos[0], pos[1]
	if a.hasData && len(a.fields) > 0 {
		return a, "use -d or -f, not both"
	}
	return a, ""
}

func parseField(s string) (apiField, string) {
	i := strings.Index(s, "=")
	if i <= 0 {
		return apiField{}, "a field is key=value, key=@FILE, key=@- or key:=JSON"
	}
	f := apiField{key: s[:i], val: s[i+1:]}
	if strings.HasSuffix(f.key, ":") {
		f.key, f.typed = strings.TrimSuffix(f.key, ":"), true
		if f.key == "" {
			return apiField{}, "a field has no name"
		}
		if f.val == "@-" {
			f.stdin = true
		} else if strings.HasPrefix(f.val, "@") {
			f.file, f.val = true, f.val[1:]
		}
		return f, ""
	}
	switch {
	case f.val == "@-":
		f.stdin = true
	case strings.HasPrefix(f.val, "@"):
		f.file, f.val = true, f.val[1:]
	}
	return f, ""
}

// apiPath checks PATH and returns the request's path, as written, and
// raw query; the checks run on its decoded form. The
// forge's origin is put in front of it by the caller, so the only way to
// reach another origin is a path that is not a path.
func apiPath(p string) (path, query string, err error) {
	if p == "" || p[0] != '/' || strings.HasPrefix(p, "//") {
		return "", "", errors.New("PATH starts with one / and is under /api/v1")
	}
	if strings.ContainsAny(p, "\\#") || nextstep.Clean(p) != p || strings.ContainsAny(p, " \t") {
		return "", "", errors.New("PATH has a character it may not")
	}
	path, query, _ = strings.Cut(p, "?")
	dec, derr := url.PathUnescape(path)
	if derr != nil {
		return "", "", errors.New("PATH is not a valid path")
	}
	if strings.ContainsAny(dec, "\\") || nextstep.Clean(dec) != dec {
		return "", "", errors.New("PATH has a character it may not")
	}
	for _, seg := range strings.Split(dec, "/") {
		if seg == ".." || seg == "." {
			return "", "", errors.New("PATH may not climb out of /api/v1 with . or ..")
		}
	}
	// A segment that decodes to a slash is another path; it is refused
	// rather than sent encoded.
	for _, seg := range strings.Split(path, "/") {
		if d, _ := url.PathUnescape(seg); strings.Contains(d, "/") {
			return "", "", errors.New("PATH may not hide a / inside a segment as %2F")
		}
	}
	for _, seg := range strings.Split(path, "/") {
		if strings.Contains(seg, ":") && strings.Contains(seg, "//") {
			return "", "", errors.New("PATH may not carry an address")
		}
	}
	return path, query, nil
}

// apiTarget is base with an escaped path: Path decoded, RawPath kept when
// the writing differs, so a path sent as written is not encoded twice.
func apiTarget(base *url.URL, escaped string) (*url.URL, error) {
	p, err := url.Parse(escaped)
	if err != nil || p.Host != "" || p.Scheme != "" {
		return nil, errors.New("PATH is not a valid path")
	}
	u := *base
	u.Path, u.RawPath, u.RawQuery, u.Fragment, u.User = p.Path, p.RawPath, "", "", nil
	return &u, nil
}

func (e *Env) apiStdin() io.Reader {
	if e.Stdin != nil {
		return e.Stdin
	}
	return os.Stdin
}

func readCapped(r io.Reader, what string) (string, error) {
	b, err := io.ReadAll(io.LimitReader(r, apiInputMax+1))
	if err != nil {
		return "", fmt.Errorf("%s cannot be read: %v", what, err)
	}
	if len(b) > apiInputMax {
		return "", fmt.Errorf("%s is over %d MB", what, apiInputMax>>20)
	}
	if !utf8.Valid(b) {
		return "", fmt.Errorf("%s is not text", what)
	}
	return string(b), nil
}

// resolve fills each field's text from its file or standard input, once.
func (e *Env) apiResolve(a *apiArgs) error {
	usedStdin := false
	stdin := func() (string, error) {
		if usedStdin {
			return "", errors.New("standard input is named twice")
		}
		usedStdin = true
		return readCapped(e.apiStdin(), "standard input")
	}
	if a.hasData {
		switch {
		case a.data == "-":
			s, err := stdin()
			if err != nil {
				return err
			}
			a.data = s
		case strings.HasPrefix(a.data, "@"):
			b, err := readFileCapped(a.data[1:])
			if err != nil {
				return err
			}
			a.data = b
		}
		if !json.Valid([]byte(a.data)) {
			return errors.New("-d is not JSON; for text use -f key=value")
		}
	}
	for i := range a.fields {
		f := &a.fields[i]
		switch {
		case f.stdin:
			s, err := stdin()
			if err != nil {
				return err
			}
			f.val = s
		case f.file:
			s, err := readFileCapped(f.val)
			if err != nil {
				return err
			}
			f.val = s
		}
		if f.typed && !json.Valid([]byte(f.val)) {
			return fmt.Errorf("-f %s:= is not JSON", f.key)
		}
	}
	return nil
}

func readFileCapped(name string) (string, error) {
	f, err := os.Open(name)
	if err != nil {
		return "", fmt.Errorf("%s cannot be read", name)
	}
	defer f.Close()
	return readCapped(f, name)
}

// fieldsBody is the fields as one JSON object.
func fieldsBody(fs []apiField) ([]byte, error) {
	m := map[string]json.RawMessage{}
	for _, f := range fs {
		if f.typed {
			m[f.key] = json.RawMessage(f.val)
			continue
		}
		b, err := json.Marshal(f.val)
		if err != nil {
			return nil, err
		}
		m[f.key] = b
	}
	return json.Marshal(m)
}

// fieldsQuery is the fields as a query. A typed field must be a scalar
// or an array of scalars; an array repeats the key.
func fieldsQuery(fs []apiField) (url.Values, error) {
	q := url.Values{}
	for _, f := range fs {
		if !f.typed {
			q.Add(f.key, f.val)
			continue
		}
		dec := json.NewDecoder(strings.NewReader(f.val))
		dec.UseNumber()
		var v any
		if err := dec.Decode(&v); err != nil {
			return nil, err
		}
		items, isArr := v.([]any)
		if !isArr {
			items = []any{v}
		}
		for _, it := range items {
			switch x := it.(type) {
			case string:
				q.Add(f.key, x)
			case json.Number:
				q.Add(f.key, x.String())
			case bool:
				q.Add(f.key, strconv.FormatBool(x))
			default:
				return nil, fmt.Errorf("-f %s:= is null, an object or a nested array, which a query cannot carry", f.key)
			}
		}
	}
	return q, nil
}

func (e *Env) isTerminal(w io.Writer) bool {
	if e.IsTerminal != nil {
		return e.IsTerminal(w)
	}
	f, ok := w.(*os.File)
	if !ok {
		return false
	}
	st, err := f.Stat()
	return err == nil && st.Mode()&os.ModeCharDevice != 0
}

func openBrowser(u string) error {
	switch runtime.GOOS {
	case "darwin":
		return exec.Command("open", u).Start()
	case "windows":
		return exec.Command("rundll32", "url.dll,FileProtocolHandler", u).Start()
	}
	return exec.Command("xdg-open", u).Start()
}

type apiRefusal struct {
	Code  string         `json:"code"`
	Error string         `json:"error"`
	Next  *nextstep.Next `json:"next"`
}

// API is quarry api: 0 done, 1 refused, 2 usage, 3 still waiting (--wait
// ran out), 4 not logged in. The forge's answer goes to stdout as it
// came, indented; what a person needs from a refusal goes to stderr.
func API(ctx context.Context, args []string, e *Env) int {
	e.fillLogin()
	if e.Stdin == nil {
		e.Stdin = os.Stdin
	}
	for _, s := range args {
		if s == "-h" || s == "--help" || s == "-help" {
			fmt.Fprint(e.Stdout, apiHelp)
			return 0
		}
	}
	a, msg := parseAPIArgs(args)
	v := voice{e, e.named("api"), a.jsonFlag, nil}
	usage := func(msg string) int {
		return v.refuse(2, "usage", msg, false, &nextstep.Next{Say: "See quarry api --help.", Cmd: "quarry api --help"})
	}
	if msg != "" {
		return usage(show(msg))
	}
	switch a.method = strings.ToUpper(a.method); a.method {
	case "GET", "POST", "PUT", "PATCH", "DELETE":
	default:
		return usage("METHOD is GET, POST, PUT, PATCH or DELETE")
	}
	if a.method == "GET" && a.hasData {
		return usage("a GET has no body; put its parameters in -f fields")
	}
	if a.pickupFile != "" && a.ask == "" {
		return usage("--pickup-file goes with --ask")
	}
	pickup := ""
	if a.pickupFile != "" {
		var perr error
		if pickup, perr = pickupCodeOfFile(a.pickupFile); perr != nil {
			return usage(show(perr.Error()))
		}
	}
	if strings.ContainsAny(a.ask, "\r\n\x00") || a.ask != nextstep.Clean(a.ask) {
		return usage("--ask's reason is one line of plain text")
	}

	var remote *url.URL
	if strings.Contains(a.path, "{repo}") {
		cwd, err := e.Getwd()
		if err != nil {
			return v.refuse(1, "refused", "this directory cannot be read: "+show(err.Error()), false, nil)
		}
		kind, root := checkoutKind(cwd)
		if kind != "" {
			remote = e.checkoutRemote(ctx, kind, root)
		}
		segs, serr := remoteSegments(remote)
		switch {
		case errors.Is(serr, errBadRepoSegment):
			return v.refuse(2, "usage", "the checkout's remote names a repository with characters a name may not have", false,
				&nextstep.Next{Say: "Write the repository out as OWNER/NAME."})
		case serr != nil:
			return v.refuse(1, "no_repo", "{repo} needs a checkout whose remote is a repository of the forge", false,
				&nextstep.Next{Say: "Run this inside a checkout, or write the repository out as OWNER/NAME."})
		}
		key := segs[0]
		if len(segs) == 2 {
			rb, berr := e.forgeFor(a.host, remote)
			if berr != nil {
				return usage(show(berr.Error()))
			}
			tok := ""
			if rec, ok := e.token(rb); ok {
				tok = rec.Token
			}
			ref, rerr := e.resolveRepo(ctx, rb, tok, segs, false)
			switch {
			case errors.Is(rerr, errNoSuchRepo):
				return v.refuse(1, "no_repo", "the forge has no repository "+strings.Join(segs, "/"), false,
					&nextstep.Next{Say: "Check the checkout's remote."})
			case rerr != nil:
				return e.netRefuse(ctx, v, rb, rerr, "quarry api GET "+a.path)
			}
			key = ref.Key
		}
		a.path = strings.ReplaceAll(a.path, "{repo}", key)
	}
	path, rawQuery, err := apiPath(a.path)
	if err != nil {
		return usage(show(err.Error()))
	}
	base, err := e.forgeFor(a.host, remote)
	if err != nil {
		return usage(show(err.Error()))
	}
	v.base = base
	if remote != nil && a.host == "" && !nextstep.SameOrigin(remote, base) {
		return v.refuse(1, "other_forge", "the checkout's remote is on "+show(remote.Host)+", not "+show(base.Host), false, nil)
	}
	if base.Scheme == "http" && !isLoopbackHost(base.Host) {
		return v.refuse(1, "insecure_forge", "the forge is plain http at "+show(base.Host)+"; a login is not sent that way", false,
			&nextstep.Next{Say: "Use the forge's https address with --host."})
	}

	if err := e.apiResolve(&a); err != nil {
		return usage(show(err.Error()))
	}
	var body []byte
	query := rawQuery
	switch {
	case a.hasData:
		body = []byte(a.data)
	case len(a.fields) > 0 && a.method == "GET":
		q, err := fieldsQuery(a.fields)
		if err != nil {
			return usage(show(err.Error()))
		}
		if query != "" {
			query += "&"
		}
		query += q.Encode()
	case len(a.fields) > 0:
		if body, err = fieldsBody(a.fields); err != nil {
			return usage(show(err.Error()))
		}
	}

	rec, ok := e.token(base)
	if !ok {
		return v.noLogin(base)
	}
	target, err := apiTarget(base, apiPrefix+path)
	if err != nil {
		return usage(show(err.Error()))
	}
	target.RawQuery = query

	var busyAfter int
	streamed, streamExit := false, 0
	client := e.Client
	if a.method == "GET" && strings.HasSuffix(path, "/events/stream") {
		c := *e.Client
		c.Timeout = 0 // a stream has no end for a timeout to cut
		client = &c
	}
	newReq := func(rctx context.Context) (*http.Request, error) {
		var rd io.Reader
		if body != nil {
			rd = bytes.NewReader(body)
		}
		req, err := http.NewRequestWithContext(rctx, a.method, target.String(), rd)
		if err != nil {
			return nil, err
		}
		req.Header.Set("Authorization", "Bearer "+rec.Token)
		req.Header.Set("Accept", "application/json")
		if a.ask != "" {
			req.Header.Set("Quarry-Ask", a.ask)
		}
		if pickup != "" {
			req.Header.Set("Quarry-Pickup", pickup)
		}
		if body != nil {
			req.Header.Set("Content-Type", "application/json")
		}
		return req, nil
	}
	do := func() (int, []byte, error) {
		req, err := newReq(ctx)
		if err != nil {
			return 0, nil, err
		}
		resp, err := client.Do(req)
		if err != nil {
			var ue *url.Error
			if errors.As(err, &ue) {
				err = ue.Err
			}
			return 0, nil, err
		}
		defer resp.Body.Close()
		busyAfter = retryAfter(resp)
		if a.method == "GET" && resp.StatusCode == http.StatusOK && isEventStream(resp) {
			streamed = true
			streamExit = e.apiStream(ctx, &v, a, base, client, newReq, resp)
			return resp.StatusCode, nil, nil
		}
		raw, err := io.ReadAll(io.LimitReader(resp.Body, apiBodyLimit+1))
		if err == nil && int64(len(raw)) > apiBodyLimit {
			err = errBodyTooBig
		}
		return resp.StatusCode, raw, err
	}

	fail := func(err error) int {
		if errors.Is(err, errBodyTooBig) {
			return v.refuse(1, "too_big", "the forge's answer is over the client's limit and was not printed", false,
				&nextstep.Next{Say: "Ask for less, with a narrower path or a query."})
		}
		return e.netRefuse(ctx, v, base, err, "quarry api GET "+a.path)
	}
	status, raw, err := do()
	if err != nil {
		return fail(err)
	}
	if streamed {
		return streamExit
	}
	shown := false
	limit := e.WaitMax
	if limit <= 0 {
		limit = apiWaitLimit
	}
	waitCtx, cancel := context.WithTimeout(ctx, limit)
	defer cancel()
	for a.wait && status == http.StatusForbidden {
		if code, _ := apiRefusalOf(status, raw); code != browserOnlyCode {
			break
		}
		if !shown {
			e.apiShowRefusal(&v, status, raw)
			shown = true
		}
		if werr := e.apiWaitEvent(waitCtx, base, rec.Token, path); werr != nil {
			e.apiOut(raw)
			if !v.json {
				fmt.Fprintf(e.Stderr, "%s: still waiting: %s\n", v.verb, show(werr.Error()))
			}
			return 3
		}
		if status, raw, err = do(); err != nil {
			return fail(err)
		}
	}
	if status == http.StatusServiceUnavailable {
		return v.busy(busyAfter)
	}
	if a.ask != "" && status == http.StatusAccepted {
		if id := askedSignOffID(raw); id != "" {
			return e.apiAwaitSignOff(ctx, &v, a, base, rec.Token, id)
		}
	}
	return e.apiFinish(&v, a, base, status, raw, shown)
}

// pickupCodeOfFile is the public code of the pickup key in a private
// file: the hex SHA-256 of its 32 bytes.
func pickupCodeOfFile(name string) (string, error) {
	st, err := os.Stat(name)
	if err != nil {
		return "", fmt.Errorf("%s cannot be read", name)
	}
	if st.Mode().Perm()&0o077 != 0 {
		return "", fmt.Errorf("%s is readable by others; make it private (chmod 600)", name)
	}
	key, err := os.ReadFile(name)
	if err != nil || len(key) != 32 {
		return "", fmt.Errorf("%s is not a 32-byte key", name)
	}
	sum := sha256.Sum256(key)
	return hex.EncodeToString(sum[:]), nil
}

// askedSignOffID is the id of the request a 202 answer filed, or "".
func askedSignOffID(raw []byte) string {
	var r struct {
		SignOff struct {
			ID string `json:"id"`
		} `json:"signoff"`
	}
	if json.Unmarshal(raw, &r) != nil {
		return ""
	}
	return r.SignOff.ID
}

// apiAwaitSignOff says where the request is approved and polls it until
// it leaves pending or the deadline passes: 0 approved, 1 denied or
// failed (a request unanswered for its day reads denied), 3 still waiting.
func (e *Env) apiAwaitSignOff(ctx context.Context, v *voice, a apiArgs, base *url.URL, token, id string) int {
	page := base.Scheme + "://" + base.Host + "/me/signoffs/" + url.PathEscape(id)
	if !v.json {
		fmt.Fprintf(e.Stderr, "%s: waiting for your approval; approve it signed in at %s\n", v.verb, page)
	}
	limit := a.askWait
	if limit <= 0 {
		limit = e.WaitMax
	}
	if limit <= 0 {
		limit = apiWaitLimit
	}
	pause := e.Poll
	if pause <= 0 {
		pause = 3 * time.Second
	}
	wctx, cancel := context.WithTimeout(ctx, limit)
	defer cancel()
	u, err := apiTarget(base, apiPrefix+"/signoffs/"+url.PathEscape(id))
	if err != nil {
		return v.refuse(1, "refused", show(err.Error()), false, nil)
	}
	for {
		req, err := http.NewRequestWithContext(wctx, "GET", u.String(), nil)
		if err != nil {
			return v.refuse(1, "refused", show(err.Error()), false, nil)
		}
		req.Header.Set("Authorization", "Bearer "+token)
		req.Header.Set("Accept", "application/json")
		if resp, err := e.Client.Do(req); err == nil {
			raw, _ := io.ReadAll(io.LimitReader(resp.Body, apiBodyLimit))
			resp.Body.Close()
			if resp.StatusCode/100 != 2 && resp.StatusCode != http.StatusServiceUnavailable && resp.StatusCode < 500 {
				e.apiOut(raw)
				return 1
			}
			var got struct {
				Request struct {
					State string `json:"state"`
				} `json:"request"`
			}
			if resp.StatusCode/100 == 2 && json.Unmarshal(raw, &got) == nil && got.Request.State != "" && got.Request.State != "pending" {
				e.apiOut(raw)
				if got.Request.State == "approved" {
					return 0
				}
				return 1
			}
		}
		if wctx.Err() != nil || e.Sleep(wctx, pause) != nil {
			if !v.json {
				fmt.Fprintf(e.Stderr, "%s: still waiting for your approval at %s\n", v.verb, page)
			}
			return 3
		}
	}
}

func apiRefusalOf(status int, raw []byte) (string, *nextstep.Next) {
	var r apiRefusal
	if status/100 != 2 {
		_ = json.Unmarshal(raw, &r)
	}
	return r.Code, r.Next
}

// apiOut writes the body to stdout as the forge sent it, indented when
// it is JSON.
func (e *Env) apiOut(raw []byte) {
	if len(raw) == 0 {
		return
	}
	var buf bytes.Buffer
	if json.Valid(raw) && json.Indent(&buf, bytes.TrimSpace(raw), "", "  ") == nil {
		buf.WriteByte('\n')
	} else {
		buf.Write(raw)
		if raw[len(raw)-1] != '\n' {
			buf.WriteByte('\n')
		}
	}
	out := buf.Bytes()
	if e.isTerminal(e.Stdout) {
		// A forge cannot write to a terminal: escapes, C1 and bidi
		// characters go, line by line so the line breaks stay.
		lines := strings.Split(string(out), "\n")
		for i, l := range lines {
			lines[i] = nextstep.Clean(l)
		}
		out = []byte(strings.Join(lines, "\n"))
	}
	e.Stdout.Write(out)
}

func (e *Env) apiShowRefusal(v *voice, status int, raw []byte) {
	if v.json {
		return
	}
	var r apiRefusal
	_ = json.Unmarshal(raw, &r)
	msg := r.Error
	if msg == "" {
		msg = fmt.Sprintf("the forge answered %d", status)
	}
	fmt.Fprintf(e.Stderr, "%s: %s\n", v.verb, show(msg))
	r.Next.Render(e.Stderr, "  ", v.base)
}

func (e *Env) apiFinish(v *voice, a apiArgs, base *url.URL, status int, raw []byte, shown bool) int {
	if status/100 == 3 {
		return v.refuse(1, "redirect", fmt.Sprintf("the forge answered %d with a redirect, which is not followed with a login", status), false, nil)
	}
	e.apiOut(raw)
	if status/100 == 2 {
		return 0
	}
	var r apiRefusal
	_ = json.Unmarshal(raw, &r)
	if !v.json && !shown {
		e.apiShowRefusal(v, status, raw)
	}
	if !v.json && a.ask == "" && r.Code == browserOnlyCode {
		fmt.Fprintf(e.Stderr, "%s: or send it again with --ask \"why\": the forge asks you to approve it in a browser, and runs it when you do\n", v.verb)
	}
	if a.open && r.Next != nil && r.Next.Open != "" && e.isTerminal(e.Stdout) {
		if u, err := base.Parse(r.Next.Open); err == nil && (u.Scheme == "http" || u.Scheme == "https") &&
			nextstep.SameOrigin(u, base) && nextstep.Clean(u.String()) == u.String() {
			open := e.Open
			if open == nil {
				open = openBrowser
			}
			_ = open(u.String())
		}
	}
	if status == http.StatusUnauthorized && r.Code == noLoginCode {
		return exitNoLogin
	}
	return 1
}

// apiWaitEvent blocks until the forge's event stream for the call's
// repository delivers an event or ctx (the one deadline) ends.
func (e *Env) apiWaitEvent(ctx context.Context, base *url.URL, token, path string) error {
	stream := apiPrefix + "/events/stream"
	if rest, ok := strings.CutPrefix(path, "/r/"); ok {
		if parts := strings.SplitN(rest, "/", 3); len(parts) >= 2 && parts[0] != "" && parts[1] != "" {
			stream = apiPrefix + "/r/" + parts[0] + "/" + parts[1] + "/events/stream"
		}
	}
	u, err := apiTarget(base, stream)
	if err != nil {
		return err
	}
	req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
	if err != nil {
		return err
	}
	req.Header.Set("Authorization", "Bearer "+token)
	req.Header.Set("Accept", "text/event-stream")
	c := *e.Client
	c.Timeout = 0
	resp, err := c.Do(req)
	if err != nil {
		if ctx.Err() != nil {
			return errors.New("nothing changed in time")
		}
		return errors.New("the event stream could not be opened")
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("the event stream answered %d", resp.StatusCode)
	}
	sc := bufio.NewScanner(resp.Body)
	sc.Buffer(make([]byte, 64<<10), 1<<20)
	name, data := "", false
	for sc.Scan() {
		line := sc.Text()
		switch {
		case line == "":
			if data && name != "live" && name != "gap" {
				return nil
			}
			name, data = "", false
		case strings.HasPrefix(line, "event:"):
			name = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
		case strings.HasPrefix(line, "data:"):
			data = true
		}
	}
	if ctx.Err() != nil {
		return errors.New("nothing changed in time")
	}
	return errors.New("the event stream ended")
}

func isEventStream(resp *http.Response) bool {
	mt, _, _ := strings.Cut(resp.Header.Get("Content-Type"), ";")
	return strings.EqualFold(strings.TrimSpace(mt), "text/event-stream")
}

// apiStream follows an event stream: each event's data goes to stdout as
// one line, flushed as it arrives; live and gap go to stderr as a short
// line; comments are dropped. A dropped connection is opened again with
// Last-Event-ID after a backoff. Ctrl-C and SIGTERM end it with 0; a 4xx
// on a reopen is the usual refusal.
func (e *Env) apiStream(ctx context.Context, v *voice, a apiArgs, base *url.URL, client *http.Client,
	newReq func(context.Context) (*http.Request, error), resp *http.Response) int {
	ctx, stop := signal.NotifyContext(ctx, os.Interrupt, syscall.SIGTERM)
	defer stop()
	lastID := ""
	wait := apiStreamBackoff
	for {
		if resp != nil {
			if e.apiStreamRead(v, resp.Body, &lastID) {
				wait = apiStreamBackoff
			}
			resp.Body.Close()
			resp = nil
		}
		if ctx.Err() != nil {
			return 0
		}
		for resp == nil {
			if e.Sleep(ctx, wait) != nil {
				return 0
			}
			if wait *= 2; wait > apiStreamBackoffMax {
				wait = apiStreamBackoffMax
			}
			req, err := newReq(ctx)
			if err != nil {
				return v.refuse(1, "refused", show(err.Error()), false, nil)
			}
			if lastID != "" {
				req.Header.Set("Last-Event-ID", lastID)
			}
			r, err := client.Do(req)
			if err != nil {
				if ctx.Err() != nil {
					return 0
				}
				continue
			}
			switch {
			case r.StatusCode == http.StatusOK && isEventStream(r):
				resp = r
			case r.StatusCode/100 == 4:
				raw, _ := io.ReadAll(io.LimitReader(r.Body, apiBodyLimit))
				r.Body.Close()
				return e.apiFinish(v, a, base, r.StatusCode, raw, false)
			default:
				r.Body.Close()
			}
		}
	}
}

// apiStreamRead prints one connection's events and reports whether any
// arrived (so the backoff starts over).
func (e *Env) apiStreamRead(v *voice, r io.Reader, lastID *string) bool {
	sc := bufio.NewScanner(r)
	sc.Buffer(make([]byte, 64<<10), 1<<20)
	name, got := "", false
	var data []string
	term := e.isTerminal(e.Stdout)
	for sc.Scan() {
		line := sc.Text()
		switch {
		case line == "":
			if len(data) > 0 || name != "" {
				got = true
				e.apiStreamEmit(v, name, data, term)
			}
			name, data = "", nil
		case strings.HasPrefix(line, ":"):
		case strings.HasPrefix(line, "event:"):
			name = strings.TrimSpace(strings.TrimPrefix(line, "event:"))
		case strings.HasPrefix(line, "id:"):
			if id := strings.TrimSpace(strings.TrimPrefix(line, "id:")); id != "" {
				*lastID = id
			}
		case strings.HasPrefix(line, "data:"):
			data = append(data, strings.TrimPrefix(strings.TrimPrefix(line, "data:"), " "))
		}
	}
	return got
}

func (e *Env) apiStreamEmit(v *voice, name string, data []string, term bool) {
	if name == "live" || name == "gap" {
		fmt.Fprintf(e.Stderr, "%s: %s\n", v.verb, name)
		return
	}
	if len(data) == 0 {
		return
	}
	text := strings.Join(data, "\n")
	var buf bytes.Buffer
	if json.Compact(&buf, []byte(text)) == nil {
		text = buf.String()
	} else {
		text = strings.Join(data, " ")
	}
	if term {
		text = nextstep.Clean(text)
	}
	io.WriteString(e.Stdout, text+"\n")
}