package relay import ( "context" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "time" ) // DefaultURL is the OAuth callback relay that collects authorization codes. const DefaultURL = "https://deploy.site.latha.org" type pollResponse struct { Status string `json:"status"` Code string `json:"code,omitempty"` Error string `json:"error,omitempty"` } // RedirectURI is the redirect URI registered for the relay. func RedirectURI(relayURL string) string { return strings.TrimRight(relayURL, "/") + "/oauth/callback" } // Poll waits for the relay to receive the authorization code for state. func Poll(ctx context.Context, client *http.Client, relayURL, state string, interval time.Duration) (string, error) { if client == nil { client = &http.Client{Timeout: 15 * time.Second} } if interval <= 0 { interval = 2 * time.Second } pollURL := strings.TrimRight(relayURL, "/") + "/api/oauth/poll?state=" + url.QueryEscape(state) ticker := time.NewTicker(interval) defer ticker.Stop() for { code, ready, err := pollOnce(ctx, client, pollURL) if err != nil { return "", err } if ready { return code, nil } select { case <-ctx.Done(): return "", ctx.Err() case <-ticker.C: } } } func pollOnce(ctx context.Context, client *http.Client, pollURL string) (string, bool, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, pollURL, nil) if err != nil { return "", false, err } resp, err := client.Do(req) if err != nil { return "", false, err } defer resp.Body.Close() body, err := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) if err != nil { return "", false, err } var out pollResponse if err := json.Unmarshal(body, &out); err != nil { return "", false, fmt.Errorf("invalid poll response (%d): %w", resp.StatusCode, err) } switch resp.StatusCode { case http.StatusAccepted: return "", false, nil case http.StatusOK: if out.Status == "ready" && out.Code != "" { return out.Code, true, nil } return "", false, fmt.Errorf("unexpected ready payload: %s", string(body)) default: return "", false, fmt.Errorf("relay poll failed (%d): %s", resp.StatusCode, string(body)) } }