diff --git a/config.yaml b/config.yaml index bdec5d7..f3a07c1 100644 --- a/config.yaml +++ b/config.yaml @@ -221,6 +221,7 @@ credentials: client_id: "" client_secret: "" # omit or leave blank for public-client apps oauth2_access_token: "" # populated automatically by `coremarketing auth twitter` + oauth2_refresh_token: "" # linkedin: # OAuth 2.0 credentials for posting. Run `coremarketing auth linkedin` to # obtain access_token and author_urn automatically. diff --git a/internal/auth/auth.go b/internal/auth/auth.go index 65752d1..721b69a 100644 --- a/internal/auth/auth.go +++ b/internal/auth/auth.go @@ -18,11 +18,12 @@ import ( const ( authURL = "https://twitter.com/i/oauth2/authorize" tokenURL = "https://api.twitter.com/2/oauth2/token" - scopes = "tweet.read tweet.write users.read" + scopes = "tweet.read tweet.write users.read offline.access" ) type Result struct { - AccessToken string + AccessToken string + RefreshToken string } func listenOnFreePort() (net.Listener, string, error) { @@ -143,7 +144,8 @@ func exchangeCode(ctx context.Context, clientID, clientSecret, code, verifier, r } var out struct { - AccessToken string `json:"access_token"` + AccessToken string `json:"access_token"` + RefreshToken string `json:"refresh_token"` } if err := json.Unmarshal(raw, &out); err != nil { return nil, err @@ -151,7 +153,50 @@ func exchangeCode(ctx context.Context, clientID, clientSecret, code, verifier, r if out.AccessToken == "" { return nil, fmt.Errorf("no access_token in response: %s", raw) } - return &Result{AccessToken: out.AccessToken}, nil + return &Result{AccessToken: out.AccessToken, RefreshToken: out.RefreshToken}, nil +} + +// RefreshTwitterToken exchanges a refresh token for a new access token. +func RefreshTwitterToken(ctx context.Context, clientID, clientSecret, refreshToken string) (*Result, error) { + data := url.Values{ + "grant_type": {"refresh_token"}, + "refresh_token": {refreshToken}, + } + if clientSecret == "" { + data.Set("client_id", clientID) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, tokenURL, 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) + } + + res, err := http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + defer res.Body.Close() + + raw, _ := io.ReadAll(res.Body) + if res.StatusCode != http.StatusOK { + return nil, fmt.Errorf("token refresh 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 refresh response: %s", raw) + } + return &Result{AccessToken: out.AccessToken, RefreshToken: out.RefreshToken}, nil } // LinkedInOAuth2 runs the standard OAuth 2.0 authorization code flow for diff --git a/internal/config/config.go b/internal/config/config.go index 7c2b4ee..e34b5ae 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -12,10 +12,11 @@ import ( ) type TwitterCreds struct { - BearerToken string `yaml:"bearer_token"` - ClientID string `yaml:"client_id"` - ClientSecret string `yaml:"client_secret"` - OAuth2AccessToken string `yaml:"oauth2_access_token"` + BearerToken string `yaml:"bearer_token"` + ClientID string `yaml:"client_id"` + ClientSecret string `yaml:"client_secret"` + OAuth2AccessToken string `yaml:"oauth2_access_token"` + OAuth2RefreshToken string `yaml:"oauth2_refresh_token"` } type YouTubeCreds struct { @@ -120,24 +121,33 @@ func (c *Config) HasLinkedInPost() bool { } var ( - oauth2TokenRe = regexp.MustCompile(`oauth2_access_token:\s*"[^"]*"`) - liAccessTokenRe = regexp.MustCompile(`access_token:\s*"[^"]*"`) - liAuthorURNRe = regexp.MustCompile(`author_urn:\s*"[^"]*"`) - liSectionRe = regexp.MustCompile(`^ linkedin:\s*$`) - credentialSectionRe = regexp.MustCompile(`^ [a-z]`) + oauth2AccessTokenRe = regexp.MustCompile(`oauth2_access_token:\s*"[^"]*"`) + oauth2RefreshTokenRe = regexp.MustCompile(`oauth2_refresh_token:\s*"[^"]*"`) + liAccessTokenRe = regexp.MustCompile(`access_token:\s*"[^"]*"`) + liAuthorURNRe = regexp.MustCompile(`author_urn:\s*"[^"]*"`) + liSectionRe = regexp.MustCompile(`^ linkedin:\s*$`) + credentialSectionRe = regexp.MustCompile(`^ [a-z]`) ) -// UpdateOAuth2Token rewrites the oauth2_access_token value in the named -// config file in-place, preserving all other content and formatting. -func UpdateOAuth2Token(path, token string) error { +// UpdateOAuth2Tokens rewrites both oauth2_access_token and oauth2_refresh_token +// in the named config file in-place, preserving all other content and formatting. +// If refreshToken is empty the refresh_token field is left unchanged. +func UpdateOAuth2Tokens(path, accessToken, refreshToken string) error { data, err := os.ReadFile(path) if err != nil { return err } - updated := oauth2TokenRe.ReplaceAllLiteralString(string(data), `oauth2_access_token: "`+token+`"`) - if updated == string(data) { + s := string(data) + + updated := oauth2AccessTokenRe.ReplaceAllLiteralString(s, `oauth2_access_token: "`+accessToken+`"`) + if updated == s { return fmt.Errorf("oauth2_access_token field not found in %s", path) } + + if refreshToken != "" { + updated = oauth2RefreshTokenRe.ReplaceAllLiteralString(updated, `oauth2_refresh_token: "`+refreshToken+`"`) + } + return os.WriteFile(path, []byte(updated), 0600) } diff --git a/main.go b/main.go index 49718aa..ec827b6 100644 --- a/main.go +++ b/main.go @@ -57,14 +57,38 @@ func main() { os.Exit(1) } - // If Twitter is configured but has no access token, run auth before the TUI. + // If Twitter is configured but has no access token, try a silent refresh + // first (if a refresh token is stored), then fall back to full re-auth. if cfg.Credentials.Twitter.ClientID != "" && !cfg.HasTwitterPost() { - fmt.Println("No Twitter access token found. Starting authorization...") - runAuth(cfgPath) - cfg, err = config.Load(cfgPath) - if err != nil { - fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err) - os.Exit(1) + tw := cfg.Credentials.Twitter + if tw.OAuth2RefreshToken != "" { + result, err := auth.RefreshTwitterToken(context.Background(), tw.ClientID, tw.ClientSecret, tw.OAuth2RefreshToken) + if err == nil { + if saveErr := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); saveErr != nil { + fmt.Fprintf(os.Stderr, "Warning: could not save refreshed token: %v\n", saveErr) + } + cfg, err = config.Load(cfgPath) + if err != nil { + fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err) + os.Exit(1) + } + } else { + fmt.Printf("Token refresh failed (%v), re-authorizing...\n", err) + runAuth(cfgPath) + cfg, err = config.Load(cfgPath) + if err != nil { + fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err) + os.Exit(1) + } + } + } else { + fmt.Println("No Twitter access token found. Starting authorization...") + runAuth(cfgPath) + cfg, err = config.Load(cfgPath) + if err != nil { + fmt.Fprintf(os.Stderr, "Error reloading config: %v\n", err) + os.Exit(1) + } } } @@ -211,7 +235,7 @@ func runAuth(cfgPath string) { fmt.Printf("Authorized as @%s\n", username) } - if err := config.UpdateOAuth2Token(cfgPath, result.AccessToken); err != nil { + if err := config.UpdateOAuth2Tokens(cfgPath, result.AccessToken, result.RefreshToken); err != nil { fmt.Fprintf(os.Stderr, "Could not save token automatically: %v\n", err) fmt.Printf("\nAdd this to %s manually:\n oauth2_access_token: \"%s\"\n", cfgPath, result.AccessToken) os.Exit(1)