Files
davidandClaude Opus 5.5 cd2dc6145b Sign-ins finish only in the browser that started them
A Core sign-in, and a posting account's or Search Console's OAuth sign-in,
now sets a short-lived cookie whose hash the flow keeps on the server. The
callback refuses one without it (constant-time compare), clears the cookie
either way, and the flow is used up regardless. This stops login CSRF: a
callback URL brought to another browser signs nobody in.

The cookie uses the __Host- prefix over https, so its Path is "/".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 08:07:21 -07:00

306 lines
9.9 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)
Browser string `json:",omitempty"` // the hash of the cookie that ties it to a browser
}
// --- 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
}