Skip to content

oauth

Describes github.com/stxapp/stx-go v0.3.1, the current release.

import "github.com/stxapp/stx-go/oauth"

Package oauth lets an app call STX for its members and as itself.

An app acting for a member sends them through the authorization code flow with PKCE (Client.Begin, Client.Complete), keeps their tokens in a TokenStore, and calls the API through Client.MemberClient, which refreshes the rotating tokens before expiry and once on a 401. An app acting as itself uses a client credentials token (Client.AppToken, Client.AppClient) for the market and event catalogs, the market data channels and creating markets. SignIn is sign in with STX: OpenID Connect on the same flow, with the ID token verified.

The token sources implement stx.Auth, so they also plug into stx.New with stx.WithAuth. Errors from OAuth endpoints are *Error values that match the sentinels in this package; an exchange without OAuth answers with an error matching stx.ErrNotAvailable.

Flows, scopes, tokens and errors are described at https://docs.stxapp.io/oauth/.

const (
DefaultAuthorizePath = "/oauth/authorize"
DefaultTokenPath = "/oauth/token"
DefaultRevokePath = "/oauth/revoke"
DefaultIntrospectPath = "/oauth/introspect"
DefaultRegisterPath = "/oauth/register"
)

Default endpoint paths, relative to the exchange’s base URL. Discovery supplies absolute URLs that take precedence.

const (
// ScopeProfileRead: who the member is (GET /api/v1/me).
ScopeProfileRead = "profile.read"
// ScopeBalanceRead: the cash balance and the balances channel.
ScopeBalanceRead = "balance.read"
// ScopePortfolioRead: positions, settlements and the ledgers, and their channels.
ScopePortfolioRead = "portfolio.read"
// ScopeOrdersRead: order and fill history, and the orders and fills channels.
ScopeOrdersRead = "orders.read"
// ScopeTransfersRead: deposit and withdrawal history (read only).
ScopeTransfersRead = "transfers.read"
// ScopeOrdersWrite: place and cancel orders, and arm cancel on disconnect.
ScopeOrdersWrite = "orders.write"
)

Member scopes, granted to a member token through consent, in the exchange’s canonical order. See https://docs.stxapp.io/oauth/scopes/. No scope moves money: there is no scope that starts, approves or cancels a transfer.

const (
// ScopeMarketData: the market catalog and the market data channels.
ScopeMarketData = "market_data"
// ScopeEvents: the event catalog, an event's players and the events channel.
ScopeEvents = "events"
// ScopeMarketsWrite: create markets (POST /api/v1/markets). Granted by STX only.
ScopeMarketsWrite = "markets.write"
)

App scopes, carried by a client credentials app token (no member, no consent).

const ScopeOpenID = "openid"

ScopeOpenID asks for an ID token, for sign in with STX.

const (
// WebSocketTokenHeader carries the access token on the WebSocket
// handshake.
WebSocketTokenHeader = "x-stx-oauth-token"
)

Header names the OAuth token travels in.

var (
// ErrAccessDenied: the member came back without connecting
// (error=access_denied): they declined, or their STX account cannot be
// connected. Nothing was granted.
ErrAccessDenied = errors.New("oauth: access denied")
// ErrAccountPending: the member's STX account is still being verified, so
// STX issues no tokens yet. On a refresh the connection has not ended:
// the stored tokens are kept, and the same refresh token works once the
// member is verified. See https://docs.stxapp.io/oauth/members-being-verified/.
ErrAccountPending = errors.New("oauth: account pending verification")
// ErrTermsNotAccepted: the member left the STX terms page without
// agreeing (error=terms_required on the callback). Nothing was granted. A
// member already connected when new terms take effect gets
// stx.ErrTermsRequired from their calls instead.
ErrTermsNotAccepted = errors.New("oauth: terms not accepted")
// ErrGrantRevoked: a refresh was refused with invalid_grant. The member
// revoked the app, or a reused refresh token tripped reuse detection and
// the whole grant was revoked. Send the member through consent again.
ErrGrantRevoked = errors.New("oauth: grant revoked; the member must authorize again")
// ErrInvalidState: the callback's state is unknown, used or expired.
ErrInvalidState = errors.New("oauth: invalid state")
// ErrNotConnected: the token store holds no tokens for the member.
ErrNotConnected = errors.New("oauth: member not connected")
)

Sentinel errors. An *Error matches the one that describes it, so test with errors.Is.

func AppScopes() []string

AppScopes returns every app scope, in canonical order.

func CanonicalScope(scope string) string

CanonicalScope returns the current name for scope: older names map forward, anything else is returned unchanged.

func FormatScopes(scopes []string) string

FormatScopes joins scopes into the space-delimited wire form.

func GenerateState() string

GenerateState returns an unguessable state value that ties an authorize redirect to its callback.

func GenerateVerifier() string

GenerateVerifier returns a PKCE code verifier (RFC 7636): 32 random bytes, base64url encoded, 43 characters.

func IsAppScope(scope string) bool

IsAppScope reports whether scope is an app scope.

func IsMemberScope(scope string) bool

IsMemberScope reports whether scope is a member scope.

func MemberScopes() []string

MemberScopes returns every member scope, in canonical order.

func ParseScopes(scope string) []string

ParseScopes splits a space-delimited scope string into canonical, de-duplicated scopes, leaving out retired ones.

func S256ChallengeFromVerifier(verifier string) string

S256ChallengeFromVerifier returns the S256 code challenge for verifier: base64url(SHA-256(verifier)). STX refuses the plain method.

func TermsURLWithReturn(termsURL, returnTo string) string

TermsURLWithReturn returns the URL to send a member to so they can accept the current STX terms and come back to your app: termsURL (from stx.APIError.TermsURL, or Token.TermsURL after a refresh) with return_to set. returnTo must be one of your registered redirect URIs, or on the same origin as one. See https://docs.stxapp.io/oauth/terms-and-conditions/.

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

AppToken is a cached client credentials token that mints itself again shortly before it expires. Concurrent callers share one mint. It implements stx.Auth (with reauthentication on a 401 and WebSocket handshakes), so pass it to stx.WithAuth to call the API as the app. Get one from Client.AppToken.

func (a *AppToken) AuthHeaders(ctx context.Context, _, _ string) (http.Header, error)

AuthHeaders returns the Bearer header for one request.

func (a *AppToken) Fresh(ctx context.Context) (*Token, error)

Fresh drops the cached token and mints one now.

func (a *AppToken) GrantedScope() string

GrantedScope returns the scope granted to the current token, or “” before the first mint.

func (a *AppToken) Invalidate()

Invalidate drops the cached token, so the next call mints one.

func (a *AppToken) Kind() string

Kind returns “oauth_app”.

func (a *AppToken) Reauthenticate(ctx context.Context) (bool, error)

Reauthenticate mints a new token after a 401.

func (a *AppToken) Token(ctx context.Context) (*Token, error)

Token returns a valid app token, minting one when there is none or it expires within a minute. A token without an expiry is kept until AppToken.Invalidate.

func (a *AppToken) WebSocketHeaders(ctx context.Context, reconnect bool) (http.Header, error)

WebSocketHeaders returns the handshake header. A reconnect mints a new token rather than reuse the one from the connection that dropped.

type AuthParams struct {
// Scopes to ask for; empty uses Config.Scopes.
Scopes []string
// State overrides the generated state.
State string
// Prompt is "none" for a silent reconnect, or "login" or "consent".
Prompt string
// RedirectURL overrides Config.RedirectURL.
RedirectURL string
// Connection goes straight to a sign-in provider instead of the STX
// login page: "google", "apple" or "x".
Connection string
// LoginHint is the member's email, if you know it, so the provider can
// preselect the account.
LoginHint string
// Extra holds further authorize parameters, sent as given.
Extra url.Values
}

AuthParams are the options of one authorize redirect.

type Authorization struct {
// URL is where to send the member's browser.
URL string
// State ties the callback to this redirect. Check it on return.
State string
// CodeVerifier is the PKCE verifier to keep server-side for the exchange.
CodeVerifier string
// CodeChallenge is the S256 challenge carried in URL.
CodeChallenge string
// RedirectURL is the redirect URI carried in URL.
RedirectURL string
}

Authorization is one prepared authorize redirect.

type AuthorizationServerMetadata struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
IntrospectionEndpoint string `json:"introspection_endpoint,omitempty"`
RegistrationEndpoint string `json:"registration_endpoint,omitempty"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
ResponseTypesSupported []string `json:"response_types_supported,omitempty"`
GrantTypesSupported []string `json:"grant_types_supported,omitempty"`
CodeChallengeMethodsSupported []string `json:"code_challenge_methods_supported,omitempty"`
TokenEndpointAuthMethodsSupported []string `json:"token_endpoint_auth_methods_supported,omitempty"`
}

AuthorizationServerMetadata is the exchange’s RFC 8414 discovery document. The exchange builds every URL on the host the request used, so discover from the same base URL you send members to.

func DiscoverMetadata(ctx context.Context, baseURL string, hc *http.Client) (*AuthorizationServerMetadata, error)

DiscoverMetadata fetches baseURL/.well-known/oauth-authorization-server. On an exchange without OAuth it returns a *stx.NotAvailableError (feature “oauth”) that matches stx.ErrNotAvailable. hc may be nil.

type BeginParams struct {
AuthParams
// Data is carried to the callback in the pending entry.
Data map[string]string
// TTL is how long the sign-in may take. Default 10 minutes.
TTL time.Duration
}

BeginParams are the options of Client.Begin.

type Callback struct {
Code string
Pending *PendingAuthorization
}

Callback is a validated authorize callback: the code and the pending sign-in its state named (now used up).

func ReadCallback(ctx context.Context, pending PendingStore, query url.Values) (*Callback, error)

ReadCallback validates an authorize callback’s query and takes its pending sign-in. The state is checked and used up before anything else, so an error on the callback counts only for a sign-in this app started. It makes no request.

Errors are *Error values: invalid_request (no code or state), invalid_state (matches ErrInvalidState), or the callback’s own error (matching ErrAccessDenied, ErrAccountPending or ErrTermsNotAccepted).

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

Client runs the OAuth flows for one app: the authorization code flow with PKCE for a member, refresh with rotation, revocation, introspection, and client credentials app tokens. It is safe for concurrent use.

See https://docs.stxapp.io/oauth/ for the flow and the scopes.

func Discover(ctx context.Context, cfg Config) (*Client, error)

Discover fetches the exchange’s discovery document and returns a client that uses the endpoints it advertises. On an exchange without OAuth it returns an error matching stx.ErrNotAvailable, so an app can tell “not here yet” from a misconfiguration at start-up.

func New(cfg Config) (*Client, error)

New returns a client for cfg. It makes no request.

func (c *Client) AppClient(scopes []string, opts ...stx.Option) (*stx.Client, error)

AppClient returns an *stx.Client acting as the app with a cached client credentials token for scopes: the market and event catalogs, the market data channels and, with markets.write, creating markets. No scopes asks for every app scope the client holds.

Example

An app token calls the API as the app itself.

app, err := oauth.New(oauth.Config{
BaseURL: "demo.stxapp.io",
ClientID: "stxapp_client_9f2c41d7",
ClientSecret: "stxapp_cs_your_secret",
})
if err != nil {
log.Fatal(err)
}
client, err := app.AppClient([]string{oauth.ScopeEvents})
if err != nil {
log.Fatal(err)
}
types, err := client.Markets.Types(context.Background())
if err != nil {
log.Fatal(err)
}
fmt.Println(types[stx.RulePlayerStatLine].PartnerCreate)
func (c *Client) AppToken(scopes ...string) *AppToken

AppToken returns the cached app token for scopes. The same scopes return the same *AppToken, so every client built from this one shares a token. No scopes asks for every app scope the client holds.

func (c *Client) AuthorizationURL(p AuthParams) (*Authorization, error)

AuthorizationURL creates a PKCE pair and a state, and builds the authorize URL. Keep State and CodeVerifier server-side for the callback, or use Client.Begin and Client.Complete, which do that for you.

func (c *Client) BaseURL() string

BaseURL returns the exchange’s base URL, such as “https://demo.stxapp.io”.

func (c *Client) Begin(ctx context.Context, pending PendingStore, p BeginParams) (*Authorization, error)

Begin starts a sign-in: it prepares the redirect, saves the verifier and Data in pending under the state, and returns the redirect. Finish with Client.Complete on the callback.

Example

Linking a member: Begin on your login route, Complete on the callback.

app, _ := oauth.New(oauth.Config{
BaseURL: "demo.stxapp.io",
ClientID: "stxapp_client_9f2c41d7",
ClientSecret: "stxapp_cs_your_secret",
RedirectURL: "https://your.app/stx/callback",
Scopes: []string{oauth.ScopeBalanceRead, oauth.ScopeOrdersWrite},
})
pending := &oauth.MemoryPendingStore{}
tokens := oauth.NewFileTokenStore("stx-tokens.json")
http.HandleFunc("/stx/login", func(w http.ResponseWriter, r *http.Request) {
auth, err := app.Begin(r.Context(), pending, oauth.BeginParams{Data: map[string]string{"user": "alice"}})
if err != nil {
http.Error(w, err.Error(), http.StatusBadGateway)
return
}
http.Redirect(w, r, auth.URL, http.StatusFound)
})
http.HandleFunc("/stx/callback", func(w http.ResponseWriter, r *http.Request) {
_, err := app.Complete(r.Context(), pending, r.URL.Query(), oauth.RedeemOptions{
Store: tokens,
MemberKeyFunc: func(data map[string]string) string { return data["user"] },
})
switch {
case errors.Is(err, oauth.ErrAccessDenied):
fmt.Fprint(w, "Not connected.")
case errors.Is(err, oauth.ErrAccountPending):
fmt.Fprint(w, "Your STX account is still being verified.")
case err != nil:
http.Error(w, err.Error(), http.StatusBadRequest)
default:
fmt.Fprint(w, "Connected.")
}
})
func (c *Client) ClientCredentials(ctx context.Context, scopes ...string) (*Token, error)

ClientCredentials mints an app token: the app acting as itself, with app scopes only and no refresh token. No scopes asks for every app scope the client holds. For a cached token that renews itself, use Client.AppToken.

func (c *Client) ClientID() string

ClientID returns the app’s client id.

func (c *Client) Complete(ctx context.Context, pending PendingStore, query url.Values, opts RedeemOptions) (*Completed, error)

Complete finishes a sign-in from the callback’s query: it reads the callback (see ReadCallback), exchanges the code with the stored PKCE verifier and, with a store, saves the tokens.

func (c *Client) Exchange(ctx context.Context, code, verifier, redirectURL string) (*Token, error)

Exchange trades an authorization code for tokens, proving PKCE with the verifier. redirectURL must repeat the authorize request’s; empty uses Config.RedirectURL.

func (c *Client) Host() string

Host returns the exchange host, such as “demo.stxapp.io”.

func (c *Client) Introspect(ctx context.Context, token string) (*Introspection, error)

Introspect reports whether a token is active, and its scope. Confidential clients only.

func (c *Client) IsPublic() bool

IsPublic reports whether the client has no secret.

func (c *Client) MemberClient(store TokenStore, memberKey string, sessionOpts *SessionOptions, opts ...stx.Option) (*stx.Client, error)

MemberClient returns an *stx.Client acting for one connected member: every REST call carries the member’s access token, refreshed before expiry and once on a 401, and WebSocket handshakes send it too. opts may add client options such as stx.WithLogger; the host and auth come from c. sessionOpts may be nil.

func (c *Client) Metadata() *AuthorizationServerMetadata

Metadata returns the discovery document the client was built from, or nil.

func (c *Client) ReadCallback(ctx context.Context, pending PendingStore, query url.Values) (*Callback, error)

ReadCallback is ReadCallback with errors naming this client’s authorize endpoint.

func (c *Client) Redeem(ctx context.Context, cb *Callback, opts RedeemOptions) (*Completed, error)

Redeem exchanges a callback read with ReadCallback. Use the pair when one callback URL serves several apps and the app is known only from the pending entry’s Data.

func (c *Client) Refresh(ctx context.Context, refreshToken string) (*Token, error)

Refresh trades a refresh token for a new pair. STX rotates the refresh token, so keep the one that comes back. A refused refresh matches ErrGrantRevoked; a member still being verified matches ErrAccountPending (keep the tokens). While the member has terms to accept the refresh succeeds with TermsRequired set.

func (c *Client) Revoke(ctx context.Context, token, hint string) error

Revoke revokes a token (RFC 7009). A refresh token ends the member’s whole grant; an access token revokes only its pair. hint is “access_token”, “refresh_token” or empty.

func (c *Client) Session(store TokenStore, memberKey string, opts *SessionOptions) *Session

Session returns the member session for memberKey in store. opts may be nil.

func (c *Client) Unlink(ctx context.Context, store TokenStore, memberKey string) (bool, error)

Unlink revokes a member’s grant at STX (best effort) and deletes their tokens from store. It reports whether STX confirmed the revocation; the local tokens are deleted either way.

type ClientRegistration struct {
ClientID string `json:"client_id"`
ClientIDIssuedAt int64 `json:"client_id_issued_at"`
// ClientSecret is present for a confidential client only. It is shown
// once and cannot be recovered.
ClientSecret string `json:"client_secret,omitempty"`
// ClientSecretExpiresAt is Unix seconds; 0 means never.
ClientSecretExpiresAt int64 `json:"client_secret_expires_at,omitempty"`
ClientName string `json:"client_name"`
RedirectURIs []string `json:"redirect_uris"`
Scope string `json:"scope"`
GrantTypes []string `json:"grant_types"`
ResponseTypes []string `json:"response_types"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
ClientURI string `json:"client_uri,omitempty"`
LogoURI string `json:"logo_uri,omitempty"`
SoftwareID string `json:"software_id,omitempty"`
SoftwareVersion string `json:"software_version,omitempty"`
}

ClientRegistration is the RFC 7591 answer.

func Register(ctx context.Context, baseURL string, req ClientRegistrationRequest, opts *RegisterOptions) (*ClientRegistration, error)

Register registers an OAuth client dynamically (RFC 7591). The registration is inert until a member consents. Refusals are *Error values (invalid_redirect_uri, invalid_client_metadata, or rate_limited with RetryAfter). An exchange without dynamic registration answers 404, which is an *Error with StatusCode 404; its discovery document then has no registration_endpoint.

type ClientRegistrationRequest struct {
ClientName string `json:"client_name"`
RedirectURIs []string `json:"redirect_uris"`
// Scope is space-delimited. Empty means the exchange's default member scopes.
Scope string `json:"scope,omitempty"`
// TokenEndpointAuthMethod is "client_secret_basic" (the default; a
// one-time secret is returned) or "none" (a public client, PKCE only).
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method,omitempty"`
// GrantTypes is a subset of authorization_code, refresh_token and
// client_credentials. Default authorization_code and refresh_token.
GrantTypes []string `json:"grant_types,omitempty"`
ResponseTypes []string `json:"response_types,omitempty"`
ClientURI string `json:"client_uri,omitempty"`
LogoURI string `json:"logo_uri,omitempty"`
SoftwareID string `json:"software_id,omitempty"`
SoftwareVersion string `json:"software_version,omitempty"`
}

ClientRegistrationRequest is RFC 7591 client metadata. The exchange accepts absolute https redirect URIs, or http on a loopback address.

type Completed struct {
Token *Token
// Scopes are the granted scopes, which may be narrower than asked.
Scopes []string
// Data is what was passed to Begin.
Data map[string]string
// MemberKey is the key the tokens were stored under, when a store was given.
MemberKey string
}

Completed is a finished sign-in.

type Config struct {
// BaseURL is the exchange's host or URL, such as "demo.stxapp.io". Empty
// falls back to the STX_HOST environment variable.
BaseURL string
// ClientID is your app's client id.
ClientID string
// ClientSecret is the secret of a confidential client, sent as HTTP Basic
// credentials. Leave it empty for a public client: it identifies with
// client_id in the form and PKCE is its proof. A public client cannot
// mint app tokens.
ClientSecret string
// RedirectURL is the redirect URI registered with STX (matched exactly).
// The authorization code flow needs it.
RedirectURL string
// Scopes are the scopes asked for when a call names none.
Scopes []string
// Endpoint overrides the endpoint paths.
Endpoint Endpoint
// Metadata is the exchange's discovery document, when you have it
// ([Discover] sets it). With it, an invalid_scope answer for a scope the
// exchange does not list becomes a *stx.NotAvailableError.
Metadata *AuthorizationServerMetadata
// HTTPClient sends the OAuth requests. Nil uses a client with a 30
// second timeout.
HTTPClient *http.Client
}

Config describes one registered app. A process serving several apps makes one Client per app.

func ConfigFromEnv() Config

ConfigFromEnv returns a Config from the environment: STX_HOST (or STX_BASE_URL), STX_OAUTH_CLIENT_ID, STX_OAUTH_CLIENT_SECRET, STX_OAUTH_REDIRECT_URI and STX_OAUTH_SCOPE (space-delimited).

type Endpoint struct {
AuthURL string
TokenURL string
RevokeURL string
IntrospectURL string
}

Endpoint holds the OAuth endpoints, as paths on the base URL or absolute URLs. An empty field takes the default path.

type Error struct {
// Code is the RFC error code, such as "invalid_grant" or "invalid_scope".
Code string
// Description is the error_description, when there is one.
Description string
// Reason is STX's narrower reason (error_reason), such as
// "account_pending" on an invalid_grant.
Reason string
// StatusCode is the HTTP status, or 0 for a check made locally.
StatusCode int
// Endpoint is the path that answered, such as "/oauth/token".
Endpoint string
// RetryAfter is the wait the endpoint asked for on a 429, or zero.
RetryAfter time.Duration
// RequestedScope is the scope the sign-in asked for, on an invalid_scope
// from the authorize callback.
RequestedScope string
// contains filtered or unexported fields
}

Error is an OAuth protocol error: an RFC 6749 section 5.2 answer from an OAuth endpoint, an error carried on the authorize callback, or a check this package made (invalid_state, invalid_id_token). See https://docs.stxapp.io/oauth/discovery-and-errors/.

func (e *Error) Error() string

Error returns “oauth: ENDPOINT STATUS CODE: description”.

func (e *Error) Is(target error) bool

Is matches the sentinel errors that describe e.

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

FileTokenStore is a TokenStore kept in one JSON file, written with mode 0600 and replaced atomically. It suits a command-line tool or a single server process; the tokens are not encrypted.

func NewFileTokenStore(path string) *FileTokenStore

NewFileTokenStore returns a store backed by path. The file and its directory are created on the first Set.

func (s *FileTokenStore) Delete(_ context.Context, key string) error

Delete forgets the member’s tokens.

func (s *FileTokenStore) Get(_ context.Context, key string) (*Token, error)

Get returns the member’s tokens, or nil.

func (s *FileTokenStore) Set(_ context.Context, key string, t *Token) error

Set stores t for the member.

type FinishedSignIn struct {
Token *Token
Identity *Identity
}

FinishedSignIn is a completed sign-in.

type Identity struct {
// Subject is the member's stable id for your app. Key your user record on
// it, not on the email.
Subject string
Email string
EmailVerified bool
// Claims holds every claim.
Claims map[string]any
}

Identity is the member, from the verified ID token or the userinfo endpoint.

type Introspection struct {
Active bool `json:"active"`
Scope string `json:"scope,omitempty"`
ClientID string `json:"client_id,omitempty"`
// Raw holds every field of the answer.
Raw map[string]any `json:"-"`
}

Introspection is an RFC 7662 answer.

type Locker interface {
WithLock(ctx context.Context, memberKey string, fn func(ctx context.Context) error) error
}

Locker is an optional TokenStore method. Implement it when several processes share the store, so only one refreshes a member at a time: a second, concurrent refresh with the same rotating refresh token trips reuse detection and revokes the grant. Within one process the package already refreshes each member once at a time.

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

MemoryPendingStore is an in-memory PendingStore for one process. The zero value is ready to use. Expired entries are dropped.

func (s *MemoryPendingStore) Len() int

Len returns the number of sign-ins in progress.

func (s *MemoryPendingStore) Put(_ context.Context, state string, p *PendingAuthorization) error

Put stores p under state.

func (s *MemoryPendingStore) Take(_ context.Context, state string) (*PendingAuthorization, error)

Take returns and removes the entry for state.

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

MemoryTokenStore is an in-memory TokenStore for scripts, demos and tests. The zero value is ready to use.

func (s *MemoryTokenStore) Delete(_ context.Context, key string) error

Delete forgets the member’s tokens.

func (s *MemoryTokenStore) Get(_ context.Context, key string) (*Token, error)

Get returns a copy of the member’s tokens, or nil.

func (s *MemoryTokenStore) Set(_ context.Context, key string, t *Token) error

Set stores a copy of t.

type OpenIDConfiguration struct {
Issuer string `json:"issuer"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
JWKSURI string `json:"jwks_uri"`
UserinfoEndpoint string `json:"userinfo_endpoint,omitempty"`
RevocationEndpoint string `json:"revocation_endpoint,omitempty"`
IDTokenSigningAlgValuesSupported []string `json:"id_token_signing_alg_values_supported,omitempty"`
}

OpenIDConfiguration is the exchange’s OpenID Connect discovery document, as far as SignIn uses it.

type PendingAuthorization struct {
// CodeVerifier is the PKCE verifier the code exchange presents.
CodeVerifier string `json:"code_verifier"`
// RedirectURL was sent to the authorize endpoint; the exchange repeats it.
RedirectURL string `json:"redirect_url"`
// Scope is the scope asked for, space-delimited.
Scope string `json:"scope,omitempty"`
// Expires is when the entry stops being valid.
Expires time.Time `json:"expires"`
// Data is yours, carried to the callback: a user id, an app id, a return URL.
Data map[string]string `json:"data,omitempty"`
}

PendingAuthorization is one sign-in in progress, kept server-side under its state between the authorize redirect and the callback.

type PendingStore interface {
Put(ctx context.Context, state string, p *PendingAuthorization) error
Take(ctx context.Context, state string) (*PendingAuthorization, error)
}

PendingStore keeps sign-ins in progress, keyed by state. Take returns and removes the entry in one step, so a replayed callback finds nothing; it returns (nil, nil) for an unknown or expired state. Implementations must be safe for concurrent use.

type ProtectedResourceMetadata struct {
Resource string `json:"resource"`
AuthorizationServers []string `json:"authorization_servers"`
ScopesSupported []string `json:"scopes_supported,omitempty"`
BearerMethodsSupported []string `json:"bearer_methods_supported,omitempty"`
ResourceName string `json:"resource_name,omitempty"`
}

ProtectedResourceMetadata is the exchange’s RFC 9728 document.

func DiscoverProtectedResource(ctx context.Context, baseURL string, hc *http.Client) (*ProtectedResourceMetadata, error)

DiscoverProtectedResource fetches baseURL/.well-known/oauth-protected-resource. hc may be nil.

type RedeemOptions struct {
Store TokenStore
// MemberKey is the key to store under. MemberKeyFunc, when set, derives
// it from the Data given to Begin instead.
MemberKey string
MemberKeyFunc func(data map[string]string) string
}

RedeemOptions say where Client.Complete and Client.Redeem keep the tokens. Leave Store nil to keep them yourself.

type RegisterOptions struct {
// Endpoint is the registration_endpoint from discovery, or a path.
// Default "/oauth/register".
Endpoint string
HTTPClient *http.Client
}

RegisterOptions tune Register.

type SavedSignIn struct {
State string `json:"state"`
CodeVerifier string `json:"code_verifier"`
Nonce string `json:"nonce"`
RedirectURL string `json:"redirect_url,omitempty"`
}

SavedSignIn is what to keep in your server session between SignIn.Start and SignIn.Finish. It marshals to JSON.

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

Session acts for one connected member, with tokens kept in a TokenStore. It implements stx.Auth: every request carries the member’s access token, refreshed before expiry and once on a 401, with the rotated refresh token stored each time. A revoked grant deletes the stored tokens and returns an error matching ErrGrantRevoked.

Refreshes are shared per store and member across every Session of one Client, so concurrent requests refresh once. Across processes, give the store a Locker.

func (s *Session) AuthHeaders(ctx context.Context, _, _ string) (http.Header, error)

AuthHeaders returns the Bearer header for one request.

func (s *Session) Kind() string

Kind returns “oauth”.

func (s *Session) MemberKey() string

MemberKey returns the key the member’s tokens are stored under.

func (s *Session) Reauthenticate(ctx context.Context) (bool, error)

Reauthenticate handles a 401: when another request has already replaced the token it retries with that one, otherwise it refreshes.

func (s *Session) Scopes(ctx context.Context) ([]string, error)

Scopes returns the granted scopes of the stored tokens.

func (s *Session) Token(ctx context.Context) (*Token, error)

Token returns the member’s tokens, refreshed first when they expire within the skew. If a refresh fails for a passing reason while the access token still works, the current tokens are returned.

func (s *Session) WebSocketHeaders(ctx context.Context, _ bool) (http.Header, error)

WebSocketHeaders returns the handshake header, refreshing first when the token is near expiry, so a reconnect after expiry gets a fresh one.

type SessionOptions struct {
// Skew is how long before expiry the access token is refreshed. Default
// 30 seconds.
Skew time.Duration
// OnRefresh runs after every refresh, once the new tokens are stored.
OnRefresh func(ctx context.Context, t *Token)
// OnGrantRevoked runs once when the grant is found revoked, after the
// stored tokens are deleted.
OnGrantRevoked func(ctx context.Context, err error)
// OnTermsRequired runs after a refresh that says the member has new STX
// terms to accept (the tokens are stored and work). Send the member to
// termsURL when they are next in your app.
OnTermsRequired func(ctx context.Context, termsURL string)
}

SessionOptions tune a member Session.

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

SignIn is sign in with STX: OpenID Connect on top of the authorization code flow, giving a server who the member is and, with member scopes, their grant, in one round trip. Server-side only: the secret and the tokens never belong in a browser. It is safe for concurrent use.

See https://docs.stxapp.io/oauth/sign-in-with-your-stx-account/.

Example

Sign in with STX: Start on your sign-in route, Finish on the callback.

signIn, err := oauth.NewSignIn(oauth.SignInConfig{
Issuer: "https://demo.stxapp.io",
ClientID: "stxapp_client_9f2c41d7",
ClientSecret: "stxapp_cs_your_secret",
RedirectURL: "https://your.app/auth/stx/callback",
})
if err != nil {
log.Fatal(err)
}
started, err := signIn.Start(context.Background(), oauth.StartParams{Connection: "google"})
if err != nil {
log.Fatal(err)
}
// Keep started.Saved in the user's session and redirect to started.URL.
// On the callback:
//
// done, err := signIn.Finish(ctx, r.URL.Query(), saved)
// userID := done.Identity.Subject
fmt.Println(started.URL != "")
func NewSignIn(cfg SignInConfig) (*SignIn, error)

NewSignIn returns a SignIn for cfg. It makes no request.

func (s *SignIn) Configuration(ctx context.Context) (*OpenIDConfiguration, error)

Configuration returns the discovery document, fetched once and cached. An exchange without sign in with STX returns an error matching stx.ErrNotAvailable (feature “connect”).

func (s *SignIn) Disconnect(ctx context.Context, t *Token) error

Disconnect ends the member’s connection by revoking the refresh token, or the access token when there is no refresh token.

func (s *SignIn) Finish(ctx context.Context, query url.Values, saved SavedSignIn) (*FinishedSignIn, error)

Finish completes a sign-in from the callback’s query and the saved state: it checks the state, exchanges the code, and verifies the ID token (signature, issuer, audience, expiry, nonce). Callback errors match ErrAccessDenied, ErrAccountPending or ErrTermsNotAccepted; a state that is not this sign-in’s matches ErrInvalidState.

func (s *SignIn) Refresh(ctx context.Context, refreshToken string) (*Token, error)

Refresh trades a refresh token for a new pair. Keep the refresh token that comes back: STX rotates it.

func (s *SignIn) Revoke(ctx context.Context, token, hint string) error

Revoke revokes one token. A refresh token ends the member’s connection.

func (s *SignIn) Start(ctx context.Context, p StartParams) (*StartedSignIn, error)

Start prepares a sign-in: PKCE, state and nonce, and the authorize URL with openid added to the scopes.

func (s *SignIn) UserInfo(ctx context.Context, accessToken, expectedSubject string) (*Identity, error)

UserInfo reads the member’s claims from the userinfo endpoint with their access token, which must carry openid. Pass the subject you stored for the member as expectedSubject and an answer about anyone else is refused; “” skips that check. A dead token, or one without openid, is an *Error with Code “invalid_token”.

func (s *SignIn) VerifyIDToken(ctx context.Context, idToken, nonce string) (*Identity, error)

VerifyIDToken verifies an ID token from this issuer for this app (the signature against the published keys, issuer, audience, expiry and nonce) and returns its claims. SignIn.Finish already does this; use it for an ID token obtained another way.

type SignInConfig struct {
// Issuer is the exchange's public URL, such as "https://demo.stxapp.io".
// It must equal the discovery document's issuer.
Issuer string
ClientID string
ClientSecret string
// RedirectURL is the redirect URI registered with STX.
RedirectURL string
// Scopes are asked for besides openid, which is always added.
Scopes []string
// ClockSkew is the leeway when checking exp and iat. Default 60 seconds.
ClockSkew time.Duration
HTTPClient *http.Client
}

SignInConfig describes one confidential app using sign in with STX.

type StartParams struct {
// Connection goes straight to a sign-in provider: "google", "apple" or "x".
Connection string
// LoginHint is the member's email, if known.
LoginHint string
// Scopes override SignInConfig.Scopes for this sign-in.
Scopes []string
// RedirectURL overrides SignInConfig.RedirectURL.
RedirectURL string
// Prompt is "none" for a silent reconnect, or "login" or "consent".
Prompt string
}

StartParams are the options of SignIn.Start.

type StartedSignIn struct {
// URL is where to send the member's browser.
URL string
// Saved goes in your server session for Finish.
Saved SavedSignIn
}

StartedSignIn is a prepared sign-in.

type StaticToken string

StaticToken is an access token used as is, with no refresh: it implements stx.Auth for a one-off script. Pass it to stx.WithAuth.

func (t StaticToken) AuthHeaders(context.Context, string, string) (http.Header, error)

AuthHeaders returns the Bearer header.

func (StaticToken) Kind() string

Kind returns “oauth”.

func (t StaticToken) WebSocketHeaders(context.Context, bool) (http.Header, error)

WebSocketHeaders returns the handshake header.

type Token struct {
// AccessToken goes in the Authorization header as a Bearer token.
AccessToken string `json:"access_token"`
// TokenType is "Bearer".
TokenType string `json:"token_type,omitempty"`
// RefreshToken renews the access token. STX rotates it on every refresh,
// so always keep the one that came back last. Empty on an app token.
RefreshToken string `json:"refresh_token,omitempty"`
// Expiry is when the access token expires, or zero when unknown.
Expiry time.Time `json:"expiry,omitzero"`
// Scope is the granted scope, space-delimited. It may be narrower than
// the scope asked for.
Scope string `json:"scope,omitempty"`
// IDToken is the OpenID Connect ID token, when openid was granted.
// [SignIn.Finish] verifies it; do not trust it otherwise.
IDToken string `json:"id_token,omitempty"`
// TermsRequired is true when a refresh said the member has not accepted
// the current STX terms. The tokens work, but orders are refused until
// the member accepts at TermsURL. See [TermsURLWithReturn].
TermsRequired bool `json:"terms_required,omitempty"`
// TermsURL is the STX page where the member accepts the terms.
TermsURL string `json:"terms_url,omitempty"`
}

Token is an OAuth token set: the answer of the token endpoint, and what a TokenStore keeps for a member. It marshals to JSON for storage.

func (t *Token) Scopes() []string

Scopes returns the granted scopes, canonical names.

func (t *Token) Valid() bool

Valid reports whether t has an access token that has not expired.

type TokenSource interface {
Token(ctx context.Context) (*Token, error)
}

TokenSource supplies a valid access token. *AppToken and *Session implement it.

type TokenStore interface {
Get(ctx context.Context, memberKey string) (*Token, error)
Set(ctx context.Context, memberKey string, t *Token) error
Delete(ctx context.Context, memberKey string) error
}

TokenStore keeps members’ tokens, keyed by any stable string you use for a member (your user id, for example). Get returns (nil, nil) when it holds nothing for the key. Implement it over your own database and encrypt the tokens at rest; MemoryTokenStore and FileTokenStore suit one process.

Implementations must be safe for concurrent use.

STX is operated by XV Exchange, LLC, a Designated Contract Market regulated by the U.S. Commodity Futures Trading Commission (CFTC). Contracts traded on STX are cleared by XV Clearing, LLC, a CFTC-registered Derivatives Clearing Organization. Trading involves substantial risk of loss and may not be appropriate for everyone. Members risk losing the cost to enter any transaction, including fees. Consider whether trading is appropriate for you in light of your experience and financial resources. Nothing on this site is investment advice or a recommendation to trade. Past performance is not indicative of future results.

© 2026 STX. All rights reserved.llms.txtllms-full.txtView as Markdown
Docs version v1.10.5