// Package equipo is Base's client for Equipo's person API (v1): signing a // device in for a member, and the Assistant's chat behind "Ask Base // anything". Base calls Equipo server to server with the member's bearer; // the bearer never reaches a browser. // // The shapes mirror Equipo's handlers (internal/wire/api.go and // assistant.go, internal/equipo/personapi/devices.go and // chat/assistant_http.go), reading only the fields Base uses. package equipo import ( "bytes" "context" "crypto/ed25519" "crypto/rand" "encoding/base64" "encoding/json" "errors" "fmt" "io" "net/http" "net/url" "strconv" "strings" "time" ) // Error is a non-2xx answer from Equipo: its status and error code, and // for an upload or a read its Retry-After, if it gave one. type Error struct { Status int Code string RetryAfter string } func (e *Error) Error() string { return fmt.Sprintf("equipo: %d %s", e.Status, e.Code) } // Is lets errors.Is match the sentinel errors below by status and code. func (e *Error) Is(target error) bool { t, ok := target.(*Error) return ok && t.Status == e.Status && (t.Code == "" || t.Code == e.Code) } var ( // ErrUnauthenticated: the bearer is revoked, expired or its person // removed. The member must reconnect. ErrUnauthenticated = &Error{Status: 401} // ErrPending: the sign-in code is not approved yet. ErrPending = &Error{Status: 409, Code: "authorization_pending"} // ErrSlowDown: asked again too soon. ErrSlowDown = &Error{Status: 429} // ErrExpired: the sign-in code expired; start again. ErrExpired = &Error{Status: 410} // ErrNoRunner: the person has no runner, so the Assistant cannot // answer a message or a question. ErrNoRunner = &Error{Status: 409, Code: "no_runner"} // ErrRunnerTooOld: the person's runner is too old for the Assistant. ErrRunnerTooOld = &Error{Status: 409, Code: "runner_too_old"} ) // Challenge is POST /api/v1/auth/devices's answer. type Challenge struct { ID string `json:"id"` DeviceSecret string `json:"device_secret"` UserCode string `json:"user_code"` Challenge string `json:"challenge"` VerificationURI string `json:"verification_uri"` ExpiresAt time.Time `json:"expires_at"` } // Proof is the body of POST /api/v1/auth/devices/exchange. type Proof struct { ID string `json:"id"` DeviceSecret string `json:"device_secret"` Challenge string `json:"challenge"` Nonce string `json:"nonce"` Signature string `json:"signature"` } // Credential is a device's bearer. Revision is the device's revision (the // exchange's ETag), which revoking it must name. type Credential struct { ID string `json:"id"` Token string `json:"token"` ExpiresAt time.Time `json:"expires_at"` Revision int64 `json:"-"` } // Client calls one Equipo instance. type Client struct { origin string http *http.Client // StreamHeaderTimeout bounds the wait for the event stream's headers. StreamHeaderTimeout time.Duration // FileTimeout bounds an upload, and the wait for a file's headers // (60 s when zero). FileTimeout time.Duration } // New is a client for the Equipo at origin. It never follows a redirect, // so a bearer goes nowhere but origin. func New(origin string) *Client { return &Client{origin: strings.TrimRight(origin, "/"), StreamHeaderTimeout: 15 * time.Second, http: &http.Client{ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, }} } // Origin is the instance's origin. func (c *Client) Origin() string { return c.origin } // callTimeout bounds every call but the event stream. const callTimeout = 20 * time.Second // call sends one request. token is the bearer ("" for the device routes); // key, when set, is the Idempotency-Key. A 2xx body is decoded into out. func (c *Client) call(ctx context.Context, method, path, token, key string, header http.Header, in, out any) (http.Header, error) { ctx, cancel := context.WithTimeout(ctx, callTimeout) defer cancel() var body io.Reader if in != nil { raw, err := json.Marshal(in) if err != nil { return nil, err } body = bytes.NewReader(raw) } req, err := http.NewRequestWithContext(ctx, method, c.origin+path, body) if err != nil { return nil, err } for k, v := range header { req.Header[k] = v } if in != nil { req.Header.Set("Content-Type", "application/json") } req.Header.Set("Accept", "application/json") setCapabilities(ctx, req) if token != "" { req.Header.Set("Authorization", "Bearer "+token) } if key != "" { req.Header.Set("Idempotency-Key", key) } res, err := c.http.Do(req) if err != nil { return nil, err } defer res.Body.Close() raw, err := io.ReadAll(io.LimitReader(res.Body, 4<<20)) if err != nil { return nil, err } if res.StatusCode < 200 || res.StatusCode > 299 { var e struct { Code string `json:"code"` } _ = json.Unmarshal(raw, &e) return res.Header, &Error{Status: res.StatusCode, Code: e.Code} } if out != nil && len(raw) > 0 { if err := json.Unmarshal(raw, out); err != nil { return nil, fmt.Errorf("equipo: %s %s: %w", method, path, err) } } return res.Header, nil } // NewKey is a fresh request key: Idempotency-Key, or a message's key. func NewKey() string { return rand.Text() } // BeginDevice asks Equipo to sign in a device with public key pub; label // is what the person sees when approving it. func (c *Client) BeginDevice(ctx context.Context, pub ed25519.PublicKey, label string) (Challenge, error) { var out Challenge in := map[string]string{"public_key": base64.RawURLEncoding.EncodeToString(pub), "label": label} _, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices", "", NewKey(), nil, in, &out) return out, err } // Prove signs ch with the device's key and nonce, as the exchange wants: // Ed25519 over the compact JSON array // ["equipo.person.device.v1", instance, id, challenge, nonce], where the // instance is the first element of the decoded challenge. func Prove(key ed25519.PrivateKey, ch Challenge, nonce string) (Proof, error) { raw, err := base64.RawURLEncoding.DecodeString(ch.Challenge) if err != nil { return Proof{}, fmt.Errorf("equipo: challenge: %w", err) } var parts []string if err := json.Unmarshal(raw, &parts); err != nil || len(parts) == 0 { return Proof{}, errors.New("equipo: challenge is not a JSON array") } p := Proof{ID: ch.ID, DeviceSecret: ch.DeviceSecret, Challenge: ch.Challenge, Nonce: nonce} msg, _ := json.Marshal([]string{"equipo.person.device.v1", parts[0], p.ID, p.Challenge, p.Nonce}) p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, msg)) return p, nil } // Exchange trades an approved proof for a bearer: ErrPending until the // person approves, ErrSlowDown when asked too soon, ErrExpired once the // code has expired. The same proof and nonce may be sent again. func (c *Client) Exchange(ctx context.Context, p Proof) (Credential, error) { var out Credential h, err := c.call(ctx, http.MethodPost, "/api/v1/auth/devices/exchange", "", NewKey(), nil, p, &out) if err != nil { return Credential{}, err } out.Revision, _ = strconv.ParseInt(strings.Trim(h.Get("ETag"), `"`), 10, 64) return out, nil } // RevokeDevice revokes device id, signed in as itself, at revision. func (c *Client) RevokeDevice(ctx context.Context, token, id string, revision int64) error { h := http.Header{"If-Match": {`"` + strconv.FormatInt(revision, 10) + `"`}} _, err := c.call(ctx, http.MethodDelete, "/api/v1/auth/devices/"+url.PathEscape(id), token, NewKey(), h, struct{}{}, nil) return err }