// Package oauth runs the OAuth 2.0 authorization-code flows for X and // LinkedIn. The web app sends the browser to AuthURL, and its callback // handler calls Exchange with the code the provider sends back. package oauth import ( "context" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "net/url" "strings" "time" ) var httpClient = &http.Client{Timeout: 20 * time.Second} // Result holds the tokens a flow or refresh returns. type Result struct { AccessToken string RefreshToken string } // Pending is a started flow, kept by the caller until the callback arrives. type Pending struct { Provider string State string Verifier string // PKCE, X only RedirectURI string Started time.Time } // --- X --- const ( xAuthURL = "https://twitter.com/i/oauth2/authorize" xTokenURL = "https://api.twitter.com/2/oauth2/token" xScopes = "tweet.read tweet.write users.read offline.access" ) // XStart begins X's OAuth 2.0 PKCE flow. It returns the URL to send the // browser to and the flow to keep for the callback. func XStart(clientID, redirectURI string) (string, *Pending, error) { verifier, challenge, err := pkce() if err != nil { return "", nil, err } state, err := randomString() if err != nil { return "", nil, err } params := url.Values{ "response_type": {"code"}, "client_id": {clientID}, "redirect_uri": {redirectURI}, "scope": {xScopes}, "state": {state}, "code_challenge": {challenge}, "code_challenge_method": {"S256"}, } p := &Pending{Provider: "x", State: state, Verifier: verifier, RedirectURI: redirectURI, Started: time.Now()} return xAuthURL + "?" + params.Encode(), p, nil } // XExchange swaps the callback's code for tokens. func XExchange(ctx context.Context, clientID, clientSecret, code string, p *Pending) (*Result, error) { data := url.Values{ "grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {p.RedirectURI}, "code_verifier": {p.Verifier}, } return xTokenRequest(ctx, clientID, clientSecret, data) } // RefreshX exchanges a refresh token for new tokens. X refresh tokens are // single-use: save the returned refresh token, or the next refresh fails. func RefreshX(ctx context.Context, clientID, clientSecret, refreshToken string) (*Result, error) { data := url.Values{ "grant_type": {"refresh_token"}, "refresh_token": {refreshToken}, } return xTokenRequest(ctx, clientID, clientSecret, data) } // xTokenRequest posts to X's token endpoint, authenticating as a confidential // client (Basic auth) if there's a secret and as a public client otherwise. func xTokenRequest(ctx context.Context, clientID, clientSecret string, data url.Values) (*Result, error) { if clientSecret == "" { data.Set("client_id", clientID) } req, err := http.NewRequestWithContext(ctx, http.MethodPost, xTokenURL, strings.NewReader(data.Encode())) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") if clientSecret != "" { req.SetBasicAuth(clientID, clientSecret) } return tokenResponse(req) } // --- LinkedIn --- const ( linkedInAuthURL = "https://www.linkedin.com/oauth/v2/authorization" linkedInTokenURL = "https://www.linkedin.com/oauth/v2/accessToken" linkedInScopes = "w_member_social openid profile" ) // LinkedInStart begins LinkedIn's authorization-code flow (client secret, // no PKCE). func LinkedInStart(clientID, redirectURI string) (string, *Pending, error) { state, err := randomString() if err != nil { return "", nil, err } params := url.Values{ "response_type": {"code"}, "client_id": {clientID}, "redirect_uri": {redirectURI}, "scope": {linkedInScopes}, "state": {state}, } p := &Pending{Provider: "linkedin", State: state, RedirectURI: redirectURI, Started: time.Now()} return linkedInAuthURL + "?" + params.Encode(), p, nil } // LinkedInExchange swaps the callback's code for an access token. func LinkedInExchange(ctx context.Context, clientID, clientSecret, code string, p *Pending) (*Result, error) { data := url.Values{ "grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {p.RedirectURI}, "client_id": {clientID}, "client_secret": {clientSecret}, } req, err := http.NewRequestWithContext(ctx, http.MethodPost, linkedInTokenURL, strings.NewReader(data.Encode())) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") return tokenResponse(req) } // --- shared --- func tokenResponse(req *http.Request) (*Result, error) { res, err := httpClient.Do(req) if err != nil { return nil, err } defer res.Body.Close() raw, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("token request HTTP %d: %s", res.StatusCode, raw) } var out struct { AccessToken string `json:"access_token"` RefreshToken string `json:"refresh_token"` } if err := json.Unmarshal(raw, &out); err != nil { return nil, err } if out.AccessToken == "" { return nil, fmt.Errorf("no access_token in the token response") } return &Result{AccessToken: out.AccessToken, RefreshToken: out.RefreshToken}, nil } func pkce() (verifier, challenge string, err error) { verifier, err = randomString() if err != nil { return "", "", err } h := sha256.Sum256([]byte(verifier)) return verifier, base64.RawURLEncoding.EncodeToString(h[:]), nil } func randomString() (string, error) { b := make([]byte, 32) if _, err := rand.Read(b); err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(b), nil }