package ocapi import ( "context" "crypto/sha256" "crypto/tls" "crypto/x509" "encoding/hex" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/url" "strconv" "strings" "time" xproxy "golang.org/x/net/proxy" ) // Options configures a Client. type Options struct { // Proxy is an optional HTTP(S) or SOCKS5 proxy URL, e.g. // "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080". No proxy // authentication is supported. Proxy string // InsecureSkipVerify disables certificate verification. Prefer // CertFingerprint for a self-signed server. InsecureSkipVerify bool // CertFingerprint pins the server's leaf certificate: the SHA-256 of // its DER bytes, as hex, with or without colons. CertFingerprint string // Timeout bounds normal requests. Streaming requests ignore it. Timeout time.Duration // UserAgent is sent on every request. UserAgent string // HTTPClient replaces the constructed client (tests). HTTPClient *http.Client } // Client talks to one OpenChamber server. type Client struct { base *url.URL token string http *http.Client ua string } // New builds a client for base. A base without a scheme gets https, except // for loopback and private addresses, which get http. func New(base string, opts Options) (*Client, error) { normalized, err := NormalizeBaseURL(base) if err != nil { return nil, err } u, err := url.Parse(normalized) if err != nil { return nil, fmt.Errorf("ocapi: invalid server URL: %w", err) } ua := opts.UserAgent if ua == "" { ua = "OpenChamber-Native/0.1" } hc := opts.HTTPClient if hc == nil { tr, err := newTransport(opts) if err != nil { return nil, err } timeout := opts.Timeout if timeout <= 0 { timeout = 30 * time.Second } hc = &http.Client{Transport: tr, Timeout: timeout} } return &Client{base: u, http: hc, ua: ua}, nil } // NormalizeBaseURL trims a user-entered server address, adds a scheme when // missing, and drops trailing slashes. func NormalizeBaseURL(raw string) (string, error) { s := strings.TrimSpace(raw) if s == "" { return "", errors.New("ocapi: server URL is empty") } if !strings.Contains(s, "://") { if isPrivateHost(s) { s = "http://" + s } else { s = "https://" + s } } u, err := url.Parse(s) if err != nil { return "", fmt.Errorf("ocapi: invalid server URL: %w", err) } if u.Scheme != "http" && u.Scheme != "https" { return "", fmt.Errorf("ocapi: unsupported scheme %q", u.Scheme) } if u.Host == "" { return "", errors.New("ocapi: server URL has no host") } u.Path = strings.TrimRight(u.Path, "/") return u.String(), nil } func isPrivateHost(s string) bool { host := s if h, _, err := net.SplitHostPort(s); err == nil { host = h } host = strings.Trim(host, "[]") if host == "localhost" || strings.HasSuffix(host, ".local") { return true } ip := net.ParseIP(host) if ip == nil { return false } return ip.IsLoopback() || ip.IsPrivate() || ip.IsLinkLocalUnicast() } func newTransport(opts Options) (*http.Transport, error) { tr := &http.Transport{ // No overall dial timeout for streaming; normal requests carry a // per-request deadline through context. DialContext: (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext, TLSHandshakeTimeout: 15 * time.Second, IdleConnTimeout: 90 * time.Second, ForceAttemptHTTP2: true, } if raw := strings.TrimSpace(opts.Proxy); raw != "" { pu, err := url.Parse(raw) if err != nil { return nil, fmt.Errorf("ocapi: invalid proxy URL: %w", err) } switch pu.Scheme { case "http", "https": tr.Proxy = http.ProxyURL(pu) case "socks5", "socks5h": dialer, err := xproxy.SOCKS5("tcp", pu.Host, nil, xproxy.Direct) if err != nil { return nil, fmt.Errorf("ocapi: socks5 proxy: %w", err) } tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) { type ctxDialer interface { DialContext(context.Context, string, string) (net.Conn, error) } if cd, ok := dialer.(ctxDialer); ok { return cd.DialContext(ctx, network, addr) } return dialer.Dial(network, addr) } tr.Proxy = nil default: return nil, fmt.Errorf("ocapi: unsupported proxy scheme %q", pu.Scheme) } } if opts.InsecureSkipVerify || opts.CertFingerprint != "" { cfg := &tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: opts.InsecureSkipVerify} if fp := normalizeFingerprint(opts.CertFingerprint); fp != "" { cfg.VerifyPeerCertificate = func(rawCerts [][]byte, _ [][]*x509.Certificate) error { if len(rawCerts) == 0 { return errors.New("ocapi: server sent no certificate") } sum := sha256.Sum256(rawCerts[0]) if got := hex.EncodeToString(sum[:]); got != fp { return fmt.Errorf("ocapi: certificate fingerprint mismatch: got %s", formatFingerprint(got)) } return nil } } tr.TLSClientConfig = cfg } return tr, nil } func normalizeFingerprint(s string) string { clean := strings.ToLower(strings.NewReplacer(":", "", " ", "").Replace(strings.TrimSpace(s))) if clean == "" { return "" } if _, err := hex.DecodeString(clean); err != nil || len(clean) != 64 { return "" } return clean } func formatFingerprint(hexString string) string { var b strings.Builder for i := 0; i < len(hexString); i += 2 { if i > 0 { b.WriteByte(':') } b.WriteString(strings.ToUpper(hexString[i : i+2])) } return b.String() } // SetToken sets the bearer token used for subsequent requests. func (c *Client) SetToken(token string) { c.token = strings.TrimSpace(token) } // Token returns the current bearer token. func (c *Client) Token() string { return c.token } // BaseURL returns the client's base URL. func (c *Client) BaseURL() string { return c.base.String() } // APIError is a non-2xx answer. type APIError struct { Status int Message string RetryAfter time.Duration Locked bool Raw string } func (e *APIError) Error() string { if e.Message != "" { return fmt.Sprintf("ocapi: %s (HTTP %d)", e.Message, e.Status) } return fmt.Sprintf("ocapi: HTTP %d", e.Status) } // IsUnauthorized reports whether err is a 401 (token expired or wrong). func IsUnauthorized(err error) bool { var apiErr *APIError return errors.As(err, &apiErr) && apiErr.Status == http.StatusUnauthorized } // IsRateLimited reports whether err is a 429, and how long to wait. func IsRateLimited(err error) (time.Duration, bool) { var apiErr *APIError if errors.As(err, &apiErr) && apiErr.Status == http.StatusTooManyRequests { return apiErr.RetryAfter, true } return 0, false } type requestOptions struct { directory string query url.Values rawQuery bool } func (c *Client) buildURL(path string, ro requestOptions) string { u := *c.base u.Path = strings.TrimRight(u.Path, "/") + "/" + strings.TrimLeft(path, "/") q := u.Query() for k, vs := range ro.query { for _, v := range vs { q.Add(k, v) } } u.RawQuery = q.Encode() return u.String() } func (c *Client) newRequest(ctx context.Context, method, path string, ro requestOptions, body any) (*http.Request, error) { var rdr io.Reader if body != nil { buf, err := json.Marshal(body) if err != nil { return nil, err } rdr = strings.NewReader(string(buf)) } req, err := http.NewRequestWithContext(ctx, method, c.buildURL(path, ro), rdr) if err != nil { return nil, err } req.Header.Set("Accept", "application/json") req.Header.Set("User-Agent", c.ua) if body != nil { req.Header.Set("Content-Type", "application/json") } if c.token != "" { req.Header.Set("Authorization", "Bearer "+c.token) } if ro.directory != "" { req.Header.Set("x-opencode-directory", url.PathEscape(ro.directory)) } return req, nil } func (c *Client) do(ctx context.Context, method, path string, ro requestOptions, body, out any) error { req, err := c.newRequest(ctx, method, path, ro, body) if err != nil { return err } return c.send(req, out) } // send performs an already-built request and decodes it. func (c *Client) send(req *http.Request, out any) error { res, err := c.http.Do(req) if err != nil { return err } defer res.Body.Close() if res.StatusCode < 200 || res.StatusCode >= 300 { raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<16)) apiErr := &APIError{Status: res.StatusCode, Raw: string(raw)} var payload struct { Error string `json:"error"` Locked bool `json:"locked"` RetryAfter json.RawMessage `json:"retryAfter"` } if json.Unmarshal(raw, &payload) == nil { apiErr.Message = payload.Error apiErr.Locked = payload.Locked apiErr.RetryAfter = parseRetryAfter(payload.RetryAfter, res.Header.Get("Retry-After")) } return apiErr } if out == nil || res.StatusCode == http.StatusNoContent { _, _ = io.Copy(io.Discard, res.Body) return nil } dec := json.NewDecoder(io.LimitReader(res.Body, 64<<20)) if err := dec.Decode(out); err != nil && !errors.Is(err, io.EOF) { return fmt.Errorf("ocapi: decode response: %w", err) } return nil } func parseRetryAfter(raw json.RawMessage, header string) time.Duration { if len(raw) > 0 { var secs float64 if json.Unmarshal(raw, &secs) == nil && secs > 0 { return time.Duration(secs * float64(time.Second)) } var text string if json.Unmarshal(raw, &text) == nil { if n, err := strconv.Atoi(strings.TrimSpace(text)); err == nil && n > 0 { return time.Duration(n) * time.Second } } } if n, err := strconv.Atoi(strings.TrimSpace(header)); err == nil && n > 0 { return time.Duration(n) * time.Second } return 0 } // Health reads the server's unauthenticated health document. func (c *Client) Health(ctx context.Context) (Health, error) { var h Health err := c.do(ctx, http.MethodGet, "/health", requestOptions{}, nil, &h) return h, err } // SessionStatus probes /auth/session. func (c *Client) SessionStatus(ctx context.Context) (AuthStatus, error) { var s AuthStatus err := c.do(ctx, http.MethodGet, "/auth/session", requestOptions{}, nil, &s) return s, err } // Login exchanges the UI password for a device client token and stores it. func (c *Client) Login(ctx context.Context, req LoginRequest) (LoginResult, error) { if !req.TrustDevice { req.TrustDevice = true } if !req.IssueClientToken { req.IssueClientToken = true } if req.ClientKind == "" { req.ClientKind = "mobile" } if req.ClientLabel == "" { req.ClientLabel = "OpenChamber Native" } var out LoginResult if err := c.do(ctx, http.MethodPost, "/auth/session", requestOptions{}, req, &out); err != nil { return LoginResult{}, err } if out.ClientToken != "" { c.SetToken(out.ClientToken) } return out, nil }