// Package oauth runs the OAuth 2.0 authorization-code flows for X, // LinkedIn, Reddit and Google. 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 ExpiresIn time.Duration // how long the access token lasts, if the provider said } // 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) } // --- Reddit --- const ( redditAuthURL = "https://www.reddit.com/api/v1/authorize" redditTokenURL = "https://www.reddit.com/api/v1/access_token" // identity: who signed in; submit: post; read: subreddit rules and the // account's own posts; history: the account's posts for the warnings. redditScopes = "identity submit read history" ) // RedditStart begins Reddit's authorization-code flow. duration=permanent // returns a refresh token: access tokens last an hour. func RedditStart(clientID, redirectURI string) (string, *Pending, error) { state, err := randomString() if err != nil { return "", nil, err } params := url.Values{ "client_id": {clientID}, "response_type": {"code"}, "state": {state}, "redirect_uri": {redirectURI}, "duration": {"permanent"}, "scope": {redditScopes}, } p := &Pending{Provider: "reddit", State: state, RedirectURI: redirectURI, Started: time.Now()} return redditAuthURL + "?" + params.Encode(), p, nil } // RedditExchange swaps the callback's code for tokens. func RedditExchange(ctx context.Context, clientID, clientSecret, userAgent, code string, p *Pending) (*Result, error) { return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{ "grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {p.RedirectURI}, }) } // RefreshReddit gets a new access token. Reddit keeps the refresh token. func RefreshReddit(ctx context.Context, clientID, clientSecret, userAgent, refreshToken string) (*Result, error) { return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{ "grant_type": {"refresh_token"}, "refresh_token": {refreshToken}, }) } // RedditAppToken gets an app-only token, for reading subreddits' rules // before anyone has signed in. func RedditAppToken(ctx context.Context, clientID, clientSecret, userAgent string) (*Result, error) { return redditToken(ctx, clientID, clientSecret, userAgent, url.Values{"grant_type": {"client_credentials"}}) } func redditToken(ctx context.Context, clientID, clientSecret, userAgent string, data url.Values) (*Result, error) { req, err := http.NewRequestWithContext(ctx, http.MethodPost, redditTokenURL, strings.NewReader(data.Encode())) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.Header.Set("User-Agent", userAgent) req.SetBasicAuth(clientID, clientSecret) 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"` ExpiresIn int64 `json:"expires_in"` } 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, ExpiresIn: time.Duration(out.ExpiresIn) * time.Second}, 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 } // --- Google (Search Console) --- var ( googleAuthURL = "https://accounts.google.com/o/oauth2/v2/auth" googleTokenURL = "https://oauth2.googleapis.com/token" ) // GoogleScopes: read-only Search Console, and the account's email to show // who is signed in. const GoogleScopes = "https://www.googleapis.com/auth/webmasters.readonly openid email" // GoogleStart begins Google's authorization-code flow with PKCE, asking for // a refresh token (offline access) so the daily sync runs on its own. func GoogleStart(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": {GoogleScopes}, "state": {state}, "code_challenge": {challenge}, "code_challenge_method": {"S256"}, "access_type": {"offline"}, "prompt": {"consent"}, // always return a refresh token } p := &Pending{Provider: "google", State: state, Verifier: verifier, RedirectURI: redirectURI, Started: time.Now()} return googleAuthURL + "?" + params.Encode(), p, nil } // GoogleExchange swaps the callback's code for tokens. func GoogleExchange(ctx context.Context, clientID, clientSecret, code string, p *Pending) (*Result, error) { return googleToken(ctx, url.Values{ "grant_type": {"authorization_code"}, "code": {code}, "redirect_uri": {p.RedirectURI}, "code_verifier": {p.Verifier}, "client_id": {clientID}, "client_secret": {clientSecret}, }) } // RefreshGoogle gets a new access token (good for an hour) from the refresh // token. func RefreshGoogle(ctx context.Context, clientID, clientSecret, refreshToken string) (*Result, error) { return googleToken(ctx, url.Values{ "grant_type": {"refresh_token"}, "refresh_token": {refreshToken}, "client_id": {clientID}, "client_secret": {clientSecret}, }) } func googleToken(ctx context.Context, data url.Values) (*Result, error) { req, err := http.NewRequestWithContext(ctx, http.MethodPost, googleTokenURL, strings.NewReader(data.Encode())) if err != nil { return nil, err } req.Header.Set("Content-Type", "application/x-www-form-urlencoded") return tokenResponse(req) } var googleUserInfoURL = "https://openidconnect.googleapis.com/v1/userinfo" // GoogleEmail is the signed-in account's email. func GoogleEmail(ctx context.Context, accessToken string) (string, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, googleUserInfoURL, nil) if err != nil { return "", err } req.Header.Set("Authorization", "Bearer "+accessToken) res, err := httpClient.Do(req) if err != nil { return "", err } defer res.Body.Close() if res.StatusCode != http.StatusOK { return "", fmt.Errorf("userinfo HTTP %d", res.StatusCode) } var out struct { Email string `json:"email"` } err = json.NewDecoder(res.Body).Decode(&out) return out.Email, err } // SetGoogleURLs points the Google flow at other servers (for tests). func SetGoogleURLs(auth, token, userinfo string) { googleAuthURL, googleTokenURL, googleUserInfoURL = auth, token, userinfo }