package bot import ( "bytes" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "sync" "time" ) // The Go port of agent/dnsimple.mjs: a tiny DNSimple client for the // connected-services prototype (docs/connected-services.md). The access token // arrives inside a time-boxed, sealed capability grant, is held only for the // duration of one call, and is never persisted on this host. // dnsimpleClient talks to the DNSimple API (base overridable for tests via // LCHAT_DNSIMPLE_BASE) and to the connect broker for the confidential OAuth // exchange (the broker holds the client_secret; this sidecar never does). type dnsimpleClient struct { base string http *http.Client } func newDNSimpleClient(base string) *dnsimpleClient { if base == "" { base = "https://api.dnsimple.com" } return &dnsimpleClient{base: strings.TrimRight(base, "/"), http: &http.Client{Timeout: 30 * time.Second}} } // apiGet does an authorized GET and decodes JSON, surfacing DNSimple's error // message on a non-2xx (matching the Node client's error text). func (c *dnsimpleClient) apiGet(token, path string, out any) error { req, err := http.NewRequest("GET", c.base+path, nil) if err != nil { return err } req.Header.Set("Authorization", "Bearer "+token) req.Header.Set("Accept", "application/json") resp, err := c.http.Do(req) if err != nil { return err } defer resp.Body.Close() body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if resp.StatusCode/100 != 2 { if msg := jsonMessage(body); msg != "" { return fmt.Errorf("%s", msg) } return fmt.Errorf("DNSimple %d", resp.StatusCode) } if out != nil { return json.Unmarshal(body, out) } return nil } // jsonMessage pulls a {"message": "..."} field out of an error body, if present. func jsonMessage(body []byte) string { var e struct { Message string `json:"message"` } _ = json.Unmarshal(body, &e) return e.Message } // whoami resolves the single account the token acts for. A user token spanning // several accounts has no single account id — we refuse it, since registrar // calls are account-scoped and we won't guess which account to spend from. func (c *dnsimpleClient) whoami(token string) (int64, error) { var d struct { Data struct { Account struct { ID int64 `json:"id"` } `json:"account"` } `json:"data"` } if err := c.apiGet(token, "/v2/whoami", &d); err != nil { return 0, err } if d.Data.Account.ID == 0 { return 0, fmt.Errorf("that token isn't scoped to a single account — create an account access token") } return d.Data.Account.ID, nil } // Domain is one row for the DNSimple app's table. type Domain struct { Name string `json:"name"` State string `json:"state"` AutoRenew bool `json:"auto_renew"` ExpiresOn string `json:"expires_on"` AccountID int64 `json:"account_id"` Price *float64 `json:"price,omitempty"` } // listDomains returns the account's domains with best-effort per-domain renewal // pricing (bounded concurrency — the list payload omits price). A pricing // failure leaves that row's price nil ("—" in the app), never fails the list. func (c *dnsimpleClient) listDomains(token string) ([]Domain, error) { account, err := c.whoami(token) if err != nil { return nil, err } var d struct { Data []struct { Name string `json:"name"` State string `json:"state"` AutoRenew bool `json:"auto_renew"` ExpiresOn string `json:"expires_on"` AccountID int64 `json:"account_id"` } `json:"data"` } if err := c.apiGet(token, fmt.Sprintf("/v2/%d/domains?per_page=100", account), &d); err != nil { return nil, err } rows := make([]Domain, 0, len(d.Data)) for _, r := range d.Data { if r.Name == "" { continue } acct := r.AccountID if acct == 0 { acct = account } rows = append(rows, Domain{Name: r.Name, State: r.State, AutoRenew: r.AutoRenew, ExpiresOn: r.ExpiresOn, AccountID: acct}) } // Fetch renewal prices with at most 8 requests in flight. sem := make(chan struct{}, 8) var wg sync.WaitGroup for i := range rows { wg.Add(1) go func(i int) { defer wg.Done() sem <- struct{}{} defer func() { <-sem }() var p struct { Data struct { RenewalPrice *float64 `json:"renewal_price"` RegistrationPrice *float64 `json:"registration_price"` } `json:"data"` } path := fmt.Sprintf("/v2/%d/registrar/domains/%s/prices", account, url.PathEscape(rows[i].Name)) if c.apiGet(token, path, &p) != nil { return // pricing is best-effort } if p.Data.RenewalPrice != nil { rows[i].Price = p.Data.RenewalPrice } else if p.Data.RegistrationPrice != nil { rows[i].Price = p.Data.RegistrationPrice } }(i) } wg.Wait() return rows, nil } // tokenPair is what the broker's exchange/refresh answer: an access token, // and — for providers with expiring user tokens (GitHub Apps) — the rotated // refresh token and lifetime. type tokenPair struct { Access string `json:"access_token"` Refresh string `json:"refresh_token"` ExpiresIn int64 `json:"expires_in"` // seconds; 0 = non-expiring } // sealable renders the pair as the member-blob shape (docs/integrations.md): // what the client stores sealed to its own key and what a renewed pair rides // back as. Absent fields are omitted so non-expiring providers keep the // legacy {secret} shape. func (p *tokenPair) sealable() map[string]any { out := map[string]any{"secret": p.Access} if p.Refresh != "" { out["refresh"] = p.Refresh } if p.ExpiresIn > 0 { out["expires_at"] = time.Now().UnixMilli() + p.ExpiresIn*1000 } return out } // exchangeViaBroker swaps an authorization code for a token pair via the // connect broker (docs/connected-services.md), for any service the broker has // an OAuth app for; refreshViaBroker rotates an expiring pair the same way. // These providers are confidential clients — both calls need the // client_secret, which lives ONLY on the broker; this sidecar authenticates // with a per-instance bearer token and gets back just the member's tokens // (which the caller seals to the member and drops). func exchangeViaBroker(service, code, state, brokerURL, brokerToken string) (*tokenPair, error) { return brokerTokenCall("/api/exchange", map[string]string{"service": service, "code": code, "state": state}, brokerURL, brokerToken) } func refreshViaBroker(service, refresh, brokerURL, brokerToken string) (*tokenPair, error) { return brokerTokenCall("/api/refresh", map[string]string{"service": service, "refresh_token": refresh}, brokerURL, brokerToken) } func brokerTokenCall(path string, payload map[string]string, brokerURL, brokerToken string) (*tokenPair, error) { if brokerURL == "" || brokerToken == "" { return nil, fmt.Errorf("connect broker not configured on this sidecar (set LCHAT_CONNECT_BROKER_URL/_TOKEN)") } body, _ := json.Marshal(payload) req, err := http.NewRequest("POST", strings.TrimRight(brokerURL, "/")+path, bytes.NewReader(body)) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+brokerToken) resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req) if err != nil { return nil, err } defer resp.Body.Close() raw, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) var d struct { tokenPair Message string `json:"message"` } _ = json.Unmarshal(raw, &d) if resp.StatusCode/100 != 2 || d.Access == "" { if d.Message != "" { return nil, fmt.Errorf("%s", d.Message) } return nil, fmt.Errorf("broker %s %d", strings.TrimPrefix(path, "/api/"), resp.StatusCode) } return &d.tokenPair, nil }