Files
supermarket/internal/oauth/oauth.go
T
davidandClaude Opus 5.5 5451fe6d63 Reddit: posted by hand, with the rules pasted
Reddit's API isn't open to apps like this one, so Supermarket no longer
signs in to Reddit, publishes or schedules there, or reads subreddits and
the account's posts. The internal/api/reddit client, Reddit's OAuth, its
keys and its Social accounts card are gone.

Supermarket still writes the post. Each Reddit draft in Posts has a box
for its subreddit's rules, with a link to them on Reddit: pasted once,
they're kept (subreddits.data, as pasted_rules) and given to the model
for later drafts. Open in Reddit saves the edits and opens the submit
page filled in; Copy title and Copy text (with the tagged source link)
cover a box that comes up empty; Mark as posted records it. Warnings come
from the pasted rules and the posts marked as posted. Fill's subreddit
suggestions are kept unchecked, and say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 11:48:54 -07:00

305 lines
9.8 KiB
Go

// Package oauth runs the OAuth 2.0 authorization-code flows for X,
// LinkedIn 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
For int64 `json:",omitempty"` // a person signing in their own posting account; 0: the company's
Team int64 `json:",omitempty"` // the team it was started in (multi-tenant)
}
// --- 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"
)
// LinkedInPageScopes are asked of the company page's app (the Community
// Management API): posting as the page, and listing the pages the member
// administers. The approved app's Auth tab shows what it may ask for.
const LinkedInPageScopes = "w_organization_social r_organization_admin"
// LinkedInStart begins LinkedIn's authorization-code flow (client secret,
// no PKCE).
func LinkedInStart(clientID, redirectURI string) (string, *Pending, error) {
return LinkedInStartScopes("linkedin", clientID, redirectURI, linkedInScopes)
}
// LinkedInStartScopes begins it for another LinkedIn app (the company
// page's), with its own provider name and scopes.
func LinkedInStartScopes(provider, clientID, redirectURI, scopes 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": {scopes},
"state": {state},
}
p := &Pending{Provider: provider, 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"`
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
}