Files
supermarket/internal/oauth/oauth.go
T
davidandClaude Opus 5.5 0e34f574b7 Phase 1, part 3: Reddit
- Sign in with a Reddit web app; access tokens refresh automatically,
  and an app-only token reads rules before sign-in.
- Reddit drafts: a title and text for one subreddit, chosen when
  writing. The subreddit's guidelines and rules go into the prompt, which
  asks for a community member's post that discloses the affiliation and
  avoids marketing language.
- The Inbox shows the subreddit's rules (cached for a day, with Refresh)
  and warns, without blocking, about promotion rules, restricted
  subreddits, link-only subreddits, posting in the same subreddit within
  a week, more than 1 in 10 recent posts linking to the company's sites,
  and new accounts.
- Publishing makes a text post with the source link at the end, or a
  link post where the subreddit takes only links.
- Migration 4 adds the draft's title and subreddit, and the rules cache.
  Publishers now take a Post, which carries the title and subreddit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 13:51:16 -07:00

254 lines
8.0 KiB
Go

// 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)
}
// --- 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"`
}
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
}