login

package
v1.51.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 21, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package login implements Stripe authentication flows.

Index

Constants

View Source
const (
	// DefaultAccessBaseURL is the default (production) base URL for access-srv.
	DefaultAccessBaseURL = "https://access.stripe.com"
	// QAAccessBaseURL is the QA base URL for access-srv, used via --access-base.
	QAAccessBaseURL = "https://qa-access.stripe.com"

	// StripeCLIClientIDProd is the registered OAuth client ID for production.
	StripeCLIClientIDProd = "oacli_V18aOD6v0hs9CU"
	// StripeCLIClientIDQA is the registered OAuth client ID for the QA environment.
	StripeCLIClientIDQA = "oacli_UjA5npk5UKXd9u"
)
View Source
const OAuthRefreshTokenKeychainKey = config.OAuthRefreshTokenKeychainKey

OAuthRefreshTokenKeychainKey is the keyring key for the OAuth refresh token.

Variables

This section is empty.

Functions

func ClearOAuthCredentials added in v1.45.3

func ClearOAuthCredentials(cfg *config.Config) error

ClearOAuthCredentials removes the stored access token, refresh token, and compartment data. Call this when the server returns invalid_grant on a refresh attempt.

func InitiateLogin added in v1.39.0

func InitiateLogin(ctx context.Context, baseURL, accessBaseURL string, cfg *config.Config) error

InitiateLogin prints JSON with browser_url, verification_code, and a next_step command, then returns. Intended for non-interactive (agent/script) use. For the OAuth device-code flow it saves pending state to disk and emits `stripe login --complete-device` as the next_step.

func InitiateReauth added in v1.50.11

func InitiateReauth(ctx context.Context, accessBaseURL, accessToken string) error

InitiateReauth fetches a reauthentication URL for the active OAuth session and prints it as JSON with a next_step command, then returns immediately. Intended for non-interactive (agent/script) use.

func InteractiveLogin

func InteractiveLogin(ctx context.Context, cfg *config.Config) error

InteractiveLogin lets the user set configuration on the command line

func ListAuthorizedAccounts added in v1.45.3

func ListAuthorizedAccounts(ctx context.Context, accessBaseURL, accessToken string) ([]config.AuthorizedAccount, error)

ListAuthorizedAccounts returns the Stripe accounts accessible to accessToken.

func Login

func Login(ctx context.Context, dashboardBaseURL, accessBaseURL string, cfg *config.Config) error

Login is the main entrypoint for logging in to the CLI.

When the /stripecli/auth server responds with a 3xx, the machine UUID is enrolled in the OAuth feature flag and the OAuth device-code flow is used instead of the legacy RAK flow. accessBaseURL controls which access-srv environment is used (production by default; QA via --access-base).

func LoginWithDeviceCode added in v1.45.3

func LoginWithDeviceCode(ctx context.Context, accessBaseURL string, cfg *config.Config) error

LoginWithDeviceCode runs the full OAuth 2.1 device-code flow and saves credentials.

func PollForLogin added in v1.39.0

func PollForLogin(ctx context.Context, pollURL string, cfg *config.Config) error

PollForLogin polls the given legacy poll URL until browser auth completes, then saves credentials. Intended as the second step of a non-interactive legacy login flow. For OAuth, use PollPendingDeviceAuth instead.

func PollPendingDeviceAuth added in v1.45.3

func PollPendingDeviceAuth(ctx context.Context, cfg *config.Config) error

PollPendingDeviceAuth loads the OAuth device auth state saved by InitiateLogin and polls the token endpoint until the user approves.

func PollPendingReauth added in v1.50.11

func PollPendingReauth(ctx context.Context, accessBaseURL, accessToken string) error

PollPendingReauth checks, immediately on invocation, whether the authorized-accounts list already differs from the snapshot InitiateReauth saved - covering both a user who finished in the browser before running this, and one who runs `--complete-reauth` without a snapshot at all (e.g. skipped `--non-interactive`). Only if there's a snapshot and nothing has changed yet does it fall back to waiting/polling for a change.

func PrintAuthorizedContexts added in v1.45.3

func PrintAuthorizedContexts(ctx context.Context, accessBaseURL, accessToken string) error

PrintAuthorizedContexts fetches the authorized accounts for accessToken and prints them as a formatted list, marking the active context.

func PrintAuthorizedContextsList added in v1.50.4

func PrintAuthorizedContextsList(accounts []config.AuthorizedAccount)

PrintAuthorizedContextsList prints already-fetched authorized accounts as a formatted list, marking the active context.

func Reauth added in v1.45.3

func Reauth(ctx context.Context, accessBaseURL, accessToken string) error

Reauth fetches a reauthentication URL for the active OAuth session and directs the user to it. If a browser is available it is opened automatically; otherwise the URL is printed for the user to visit manually. It then waits for the authorized-accounts list to change before printing the updated list of authorized contexts.

func RevokeToken added in v1.45.3

func RevokeToken(ctx context.Context, accessBaseURL string) error

RevokeToken revokes the stored refresh token via the revocation endpoint. Returns nil if no refresh token is stored. Errors from the server are returned to callers, who should log and continue with credential cleanup.

func SetOpenBrowserForTesting added in v1.42.2

func SetOpenBrowserForTesting(fn func(string) error) (restore func())

SetOpenBrowserForTesting overrides the browser-opening function used by the login flow. It returns a restore function that resets to the default.

func SuccessMessage added in v0.2.2

func SuccessMessage(ctx context.Context, account *acct.Account, baseURL string, apiKey string) (string, error)

SuccessMessage returns the display message for a successfully authenticated user

func UpdateOAuthTokens added in v1.45.3

func UpdateOAuthTokens(cfg *config.Config, resp *OAuthTokenResponse) error

UpdateOAuthTokens replaces the stored access token and refresh token after a successful token refresh. If resp.RefreshToken is empty, the refresh token is left unchanged.

func ValidateAccessBaseURL added in v1.50.1

func ValidateAccessBaseURL(accessBaseURL string) error

ValidateAccessBaseURL returns an error unless accessBaseURL is exactly the production or QA access-srv origin.

Requests built from this value carry the OAuth user access token (Authorization: Bearer) or the stored refresh token (form body), so unlike --api-base/--dashboard-base there is no dev-host, localhost, or path allowance: any scheme, host, port, userinfo, path, query, or fragment other than these two exact strings risks sending live credentials to an attacker-controlled destination.

Types

type AsyncInputReader added in v1.12.4

type AsyncInputReader interface {
	// contains filtered or unexported methods
}

AsyncInputReader is an interface that has an async version of scanln

type AsyncStdinReader added in v1.12.4

type AsyncStdinReader struct {
}

AsyncStdinReader implements scanln(ch chan int), an async version of scanln

type Authenticator added in v1.13.12

type Authenticator struct {
	// contains filtered or unexported fields
}

Authenticator handles the login flow

func NewAuthenticator added in v1.13.12

func NewAuthenticator(keytransfer keys.KeyTransfer) *Authenticator

NewAuthenticator creates a new authenticator object

func (*Authenticator) Login added in v1.13.12

func (a *Authenticator) Login(ctx context.Context, links *Links) error

Login function is used to obtain credentials via stripe dashboard.

type AuthorizedAccountsResult added in v1.51.1

type AuthorizedAccountsResult struct {
	Accounts        []config.AuthorizedAccount
	ActiveAccountID string
	ActiveLivemode  bool
}

AuthorizedAccountsResult bundles the accounts a user has authorized with which account and mode are currently active.

func ListAuthorizedAccountsForActiveSession added in v1.51.1

func ListAuthorizedAccountsForActiveSession(ctx context.Context, accessBaseURL string, cfg *config.Config) (*AuthorizedAccountsResult, error)

ListAuthorizedAccountsForActiveSession fetches the accounts authorized for cfg's stored OAuth session, along with which account and mode are currently active. Returns an error if cfg isn't logged in via OAuth.

type DeviceAuthResponse added in v1.45.3

type DeviceAuthResponse struct {
	DeviceCode      string `json:"device_code"`
	UserCode        string `json:"user_code"`
	VerificationURI string `json:"verification_uri"`
	ExpiresIn       int    `json:"expires_in"`
	Interval        int    `json:"interval"`
}

DeviceAuthResponse holds the device authorization endpoint response.

func RequestDeviceCode added in v1.45.3

func RequestDeviceCode(ctx context.Context, accessBaseURL, clientID string) (*DeviceAuthResponse, error)

RequestDeviceCode calls the device authorization endpoint and returns the response.

func RequestDeviceCodeForAccessBase added in v1.50.11

func RequestDeviceCodeForAccessBase(ctx context.Context, accessBaseURL string) (authResp *DeviceAuthResponse, clientID string, err error)

RequestDeviceCodeForAccessBase requests a device code using the client ID registered for accessBaseURL, returning that client ID alongside the response so callers can later poll for the token with PollAndSaveDeviceCredentials.

type DeviceCodeLoginResult added in v1.50.11

type DeviceCodeLoginResult struct {
	Accounts          []config.AuthorizedAccount
	ActiveAccountID   string
	ActiveDisplayName string
	ActiveLivemode    bool
}

DeviceCodeLoginResult holds the accounts and the active account/mode saved by a completed OAuth device-code login.

func CheckPendingOAuthLogin added in v1.51.1

func CheckPendingOAuthLogin(ctx context.Context, cfg *config.Config) (*DeviceCodeLoginResult, error)

CheckPendingOAuthLogin makes a single, non-blocking check on the login started by InitiateOAuthLogin (or InitiateLogin's OAuth path). Unlike PollPendingOAuthLogin, it never waits for the user - it makes one request and returns immediately, so callers that want to wait (e.g. a plugin driving its own retry loop) should call this repeatedly on their own schedule instead. Returns (nil, nil) if the device code is still valid but the user hasn't completed authentication yet. Returns an error and clears the pending state if the device code has actually expired, the server returned a terminal OAuth error (e.g. access_denied), or the token exchange succeeded but saving the resulting credentials failed (the device code is already consumed at that point, so it can't be retried); on success, also clears the pending state.

func PollAndSaveDeviceCredentials added in v1.50.11

func PollAndSaveDeviceCredentials(ctx context.Context, accessBaseURL, clientID, deviceCode string, interval time.Duration, cfg *config.Config) (*DeviceCodeLoginResult, error)

PollAndSaveDeviceCredentials polls the token endpoint until the user approves, ctx is canceled, or ctx's deadline is exceeded, then saves the resulting OAuth credentials and populates cfg's profile with the active account. Unlike LoginWithDeviceCode, it does not print progress to stdout, so callers with their own UX (e.g. the RPC service) can drive completion themselves.

func PollPendingOAuthLogin added in v1.51.1

func PollPendingOAuthLogin(ctx context.Context, cfg *config.Config) (*DeviceCodeLoginResult, error)

PollPendingOAuthLogin waits for the login started by InitiateOAuthLogin (or InitiateLogin's OAuth path) to complete. Returns (nil, nil) if ctx is done before the user completes authentication and the device code's own expiry hasn't been reached yet - callers should call this again to keep waiting. Returns an error and clears the pending state if the device code has actually expired or the server returned a terminal OAuth error (e.g. access_denied); on success, also clears the pending state.

type Links struct {
	BrowserURL       string `json:"browser_url"`
	PollURL          string `json:"poll_url"`
	VerificationCode string `json:"verification_code"`
}

Links provides the URLs for the CLI to continue the login flow

func GetLinks(ctx context.Context, baseURL string, deviceName string, machineUUID string) (*Links, bool, error)

GetLinks provides the URLs for the CLI to continue the login flow.

The machineUUID is sent to the server so it can gate individual machines into the OAuth device-code flow via feature flag. When the server responds with a 3xx, the caller should switch to LoginWithDeviceCode instead of proceeding with the legacy RAK flow; in that case GetLinks returns (nil, true, nil).

type OAuthError added in v1.45.3

type OAuthError struct {
	Code        string
	Description string
	HTTPStatus  int
}

OAuthError is a structured OAuth error returned by the access-srv token or device-authorization endpoint.

func (*OAuthError) Error added in v1.45.3

func (e *OAuthError) Error() string

type OAuthLoginSession added in v1.51.1

type OAuthLoginSession struct {
	BrowserURL       string
	VerificationCode string
	ExpiresIn        int // seconds remaining until the device code expires
}

OAuthLoginSession describes a non-interactive OAuth device-code login that's ready for the user to complete out-of-band, whether just minted or resumed from a still-valid pending one.

func FindPendingOAuthLogin added in v1.51.1

func FindPendingOAuthLogin(accessBaseURL string) (*OAuthLoginSession, error)

FindPendingOAuthLogin looks for an OAuth device-code login already in progress for accessBaseURL (started by this process or another one, e.g. `stripe login --non-interactive`), without starting a new one. Returns nil, nil if there is no pending login attempt, it's for a different accessBaseURL, or it has expired.

func InitiateOAuthLogin added in v1.51.1

func InitiateOAuthLogin(ctx context.Context, accessBaseURL string) (*OAuthLoginSession, error)

InitiateOAuthLogin starts (or resumes) a non-interactive OAuth device-code login for accessBaseURL, without printing anything. Unlike `stripe login --non-interactive` (see initiateOAuthDeviceLogin), which always mints a fresh device code, this resumes a still-valid pending one instead of minting a new one - see initiateOrResumeOAuthDeviceLogin. This is the resume behavior exposed to plugins via the OAuthInitiateLogin RPC.

type OAuthTokenResponse added in v1.45.3

type OAuthTokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	ExpiresIn    int    `json:"expires_in"`
	Scope        string `json:"scope"`
}

OAuthTokenResponse holds the token endpoint response.

func CheckDeviceToken added in v1.51.1

func CheckDeviceToken(ctx context.Context, accessBaseURL, clientID, deviceCode string) (*OAuthTokenResponse, error)

CheckDeviceToken makes a single, non-blocking request to the token endpoint and returns immediately with whatever the server reports right now - unlike PollDeviceToken, it never loops or sleeps waiting for the user to complete authentication. A non-nil *OAuthError with Code "authorization_pending" or "slow_down" means the user hasn't completed authentication yet, not that the device code is dead.

func PollDeviceToken added in v1.45.3

func PollDeviceToken(ctx context.Context, accessBaseURL, clientID, deviceCode string, interval time.Duration) (*OAuthTokenResponse, error)

PollDeviceToken polls the token endpoint until the user approves, ctx is canceled or times out, or a terminal error is returned.

Callers should create ctx with a deadline matching DeviceAuthResponse.ExpiresIn to automatically stop polling when the device code expires.

func RefreshAccessToken added in v1.45.3

func RefreshAccessToken(ctx context.Context, accessBaseURL, clientID, refreshToken string) (*OAuthTokenResponse, error)

RefreshAccessToken exchanges a refresh token for a new access token. On success, callers must persist the returned OAuthTokenResponse.RefreshToken (replacing the previously stored value) before discarding the old token. If the response does not include a refresh token, the caller must require a new interactive login when the access token next expires.

On invalid_grant, callers should clear stored credentials and start a new device authorization flow.

type SwitchResult added in v1.50.7

type SwitchResult struct {
	Account config.AuthorizedAccount
	// Mode is the API's mode value ("test" or "live"); use DisplayMode for the CLI's
	// user-facing terminology.
	Mode string
}

SwitchResult describes the account and mode a SwitchContext call activated.

func SwitchContext added in v1.45.3

func SwitchContext(ctx context.Context, accessBaseURL string, cfg *config.Config, accountID string, livemode bool) (*SwitchResult, error)

SwitchContext updates the active OAuth context and returns the account and mode that became active. If accountID is non-empty it selects that account directly (test mode by default, live if livemode is true). Otherwise it shows an interactive list, returning a nil result if the user cancels it.

func (*SwitchResult) DisplayMode added in v1.50.7

func (r *SwitchResult) DisplayMode() string

DisplayMode maps Mode to the CLI's user-facing terminology, e.g. "test" -> "sandbox".

Directories

Path Synopsis
Package acct provides Stripe account retrieval during login.
Package acct provides Stripe account retrieval during login.
Package keys handles API key retrieval and configuration during login.
Package keys handles API key retrieval and configuration during login.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL