oauth

package
v0.9.4 Latest Latest
Warning

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

Go to latest
Published: Aug 30, 2026 License: MIT Imports: 20 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package oauth implements the Claude Code OAuth login: PKCE, the dual-path authorization race, and the token endpoint.

Every constant here was read out of the Claude Code 2.1.238 binary. They ship INSIDE Claude Code and can change between its releases, so they live in one file: a drift check has exactly one place to look.

Index

Constants

View Source
const (
	// ClientID is Claude Code's own public OAuth client.
	ClientID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e"

	// ClaudeAIAuthorizeURL is the subscription surface: Pro, Max, Team,
	// Enterprise. This is the one that mints claude.ai credentials.
	ClaudeAIAuthorizeURL = "https://claude.com/cai/oauth/authorize"

	// ConsoleAuthorizeURL is the Console/API-billing surface. It does NOT mint
	// claude.ai credentials, so it is only right for a credit-billed account.
	ConsoleAuthorizeURL = "https://platform.claude.com/oauth/authorize"

	// TokenURL exchanges an authorization code and refreshes a token.
	TokenURL = "https://platform.claude.com/v1/oauth/token"

	// ManualRedirectURL is where the browser lands when the user is going to
	// copy the code by hand. The page shows `code#state` for pasting.
	ManualRedirectURL = "https://platform.claude.com/oauth/code/callback"

	// APIBaseURL serves the profile and usage endpoints.
	APIBaseURL = "https://api.anthropic.com"
)

Endpoints, verbatim from Claude Code 2.1.238.

View Source
const DefaultLoginTimeout = 300 * time.Second

DefaultLoginTimeout bounds a login attempt. Claude Code has no timeout at all; ccdad adds one so an abandoned `ccdad add` cannot hold a terminal forever.

View Source
const RefreshScopeString = "user:profile user:inference " +
	"user:sessions:claude_code user:mcp_servers user:file_upload"

RefreshScopeString is the scope parameter Claude Code sends on the REFRESH grant, and it is deliberately not ScopeString: it drops org:create_api_key.

In the 2.1.238 bundle the authorize builder joins `Jjs`, the deduped union of both scope lists, while the refresh call joins `UYe` alone. Omitting the parameter is not equivalent — RFC 6749 §6 reads an absent scope as "the same as originally granted", which would keep all six. A live ~/.claude/.credentials.json holds exactly these five, so sending anything else would write a scope set Claude Code never produces into the file ccdad swaps.

View Source
const ScopeInference = "user:inference"

ScopeInference is the scope that marks a credential as a claude.ai login. Claude Code tests for it by name in several places, so it is named here once.

View Source
const ScopeString = "org:create_api_key user:profile user:inference " +
	"user:sessions:claude_code user:mcp_servers user:file_upload"

ScopeString is the scope parameter exactly as Claude Code sends it, in Claude Code's own order. Order is cosmetic to the authorization server but kept identical so a stored scope string compares equal to one Claude Code wrote.

The authorize builder reads this const and not the Scopes slice: a caller who reorders or truncates an exported slice must not be able to corrupt every subsequent request process-wide.

Variables

View Source
var (
	// ErrLoginTimeout means neither path delivered a code in time.
	ErrLoginTimeout = errors.New("timed out waiting for the login to complete")
	// ErrLoginInterrupted means the caller cancelled. It is deliberately NOT
	// used for a context deadline: the exit contract reserves exit 130 for
	// SIGINT, and a supervisor keys on it to mean a human pressed Ctrl-C.
	ErrLoginInterrupted = errors.New("login canceled")
)
View Source
var PreservableExpansionScopes = strings.Split(preservableExpansionScopes, " ")

PreservableExpansionScopes lists the same set for callers that need to inspect it. Mutating it cannot affect a request.

View Source
var RefreshScopes = strings.Split(RefreshScopeString, " ")

RefreshScopes is RefreshScopeString split out, mirroring Scopes.

View Source
var Scopes = strings.Split(ScopeString, " ")

Scopes is the same set split out, for callers that need the individual tokens rather than the wire string.

Functions

func AuthorizeURL

func AuthorizeURL(p AuthorizeParams) string

AuthorizeURL builds the URL to send the user to.

One login attempt builds this TWICE — once with ManualRedirectURL and once with LoopbackRedirectURI — sharing a single verifier, challenge, and state. The two differ only in redirect_uri. Whichever path returns the code first determines which redirect_uri the token exchange must send; sending the other one fails with 400.

Parameter ORDER differs from Claude Code's: url.Values.Encode sorts keys, Claude Code appends them. No authorization server is order-sensitive, and the percent-encoding is identical, so only the set and the values matter — but a reader diffing the two against a browser trace should not read the reordering as a defect.

func LoopbackRedirectURI

func LoopbackRedirectURI(port int) string

LoopbackRedirectURI is the redirect for the browser path. RFC 8252 wants a loopback IP, and Claude Code spells it "localhost", so ccdad does too — the string has to match what the authorization server saw.

port must come from a bound listener. A zero port means the bind failed and the loopback path is disabled, in which case the caller must not build this URL at all: sending http://localhost:0/callback would turn a local bug into an opaque 400 from the authorization server.

func NewState

func NewState() (string, error)

NewState returns a CSRF state value for one login attempt.

func PreservableScopesFrom

func PreservableScopesFrom(stored []string) []string

PreservableScopesFrom returns the members of stored that survive a refresh, in the order stored lists them. It is Claude Code's preservableScopesFrom: `e.filter(r => PRESERVABLE_EXPANSION_SCOPES.includes(r))`.

func SplitPaste

func SplitPaste(s string) (code, state string, err error)

SplitPaste parses a pasted `code#state` value.

Verified against the 2.1.238 bundle rather than inferred. Claude Code's own paste handler is `let[ie,fe]=re.split("#"); if(!ie||!fe){...error...}; handleManualAuthCodeInput({authorizationCode:ie,state:fe})`, sitting next to the `tengu_oauth_manual_entry` event and in the class whose config carries CLIENT_ID 9d1c250a-e61b-44d9-88ed-5944d1962f5e — so it is Claude Code's own login, not the MCP OAuth client and not msal, both of which also split on '#' elsewhere in the binary and have misled this check before.

Both halves are required, exactly as there. The pasted state is where the two deliberately differ: handleManualAuthCodeInput takes it and forwards only e.authorizationCode to its resolver, so Claude Code requires the state syntactically and then drops it. ccdad validates it against the attempt instead, which costs nothing and catches a code pasted from a different login window. Stricter than the original, not divergent from it.

The leading TrimSpace matches Claude Code's headless `claude login` reader (`m.trim().split("#")`), which is the path ccdad is the analogue of. Its interactive Ink prompt does not trim, and would forward a space-prefixed code to the token exchange; there is no reason to reproduce that.

Types

type Account

type Account struct {
	UUID         string `json:"uuid"`
	EmailAddress string `json:"email_address"`
}

Account identifies the logged-in user. It rides along on the exchange, which is why a browser login can label the account without a second request.

type AuthorizeParams

type AuthorizeParams struct {
	Surface     Surface
	Challenge   string
	State       string
	RedirectURI string
}

AuthorizeParams is one authorize request.

type AuthorizeRejection

type AuthorizeRejection int

AuthorizeRejection is the reason an authorize callback came back without a code, parsed into RFC 6749 §4.1.2.1's closed set.

The callback's error and error_description parameters are uncapped upstream text. Parsing into a closed set at the boundary and discarding the bytes is what keeps them out of stderr, out of the log, and off the served page.

const (
	// RejectionDeclined is access_denied — the operator said no. The one arm
	// that is a choice rather than a failure.
	RejectionDeclined AuthorizeRejection = iota
	// RejectionUpstream is Anthropic's side; a retry can clear it.
	RejectionUpstream
	// RejectionRefused means the authorize REQUEST was refused, so a retry
	// sends the same thing again and fails the same way.
	RejectionRefused
	// RejectionUnrecognized is an error value outside RFC 6749's set — the case
	// where the bytes are least trustworthy, so none are kept.
	RejectionUnrecognized
)

func (AuthorizeRejection) LogDetail

func (r AuthorizeRejection) LogDetail() string

LogDetail is the OAuth error code for an operator log — always one of our own literals, never the browser's bytes.

func (AuthorizeRejection) UserMessage

func (r AuthorizeRejection) UserMessage() string

UserMessage is the canned, upstream-free description.

type CallbackResult

type CallbackResult struct {
	Code string
	Err  error
}

CallbackResult is one delivery from the loopback listener. Exactly one of Code and Err is set.

type Client

type Client struct {
	HTTP          *http.Client
	TokenEndpoint string
}

Client talks to the token endpoint.

func NewClient

func NewClient() *Client

NewClient returns a Client with Claude Code's 30s timeout on this endpoint.

Unlike Claude Code's axios call it refuses to FOLLOW a redirect. The token endpoint never legitimately sends one, and following it hands the credentials to whoever the redirect names: 307 and 308 replay the POST body — refresh token and PKCE verifier included — and every 3xx would let the redirect target supply the tokens ccdad writes to disk. Against a well-behaved server this deviation is unobservable.

func (*Client) ExchangeCode

func (c *Client) ExchangeCode(ctx context.Context, code, verifier, redirectURI, state string) (*TokenResponse, error)

ExchangeCode trades an authorization code for tokens.

redirectURI MUST be the one used in the authorize request that produced this code. A login races a loopback redirect against a manual paste, and the two use different redirect URIs; echoing the wrong one back is a 400.

func (*Client) Refresh

func (c *Client) Refresh(ctx context.Context, p RefreshParams) (*TokenResponse, error)

Refresh trades a refresh token for a new pair, deriving the request from the stored credential the way Claude Code does.

On a 400 invalid_scope it retries ONCE with the credential's own scopes, which is Claude Code's `tengu_oauth_refresh_invalid_scope_fallback`. That is not a general retry — refreshing is not idempotent — but a 400 issued no token, so re-sending is safe, and without it an account whose stored scopes the endpoint no longer honours could never refresh at all.

It does NOT port the caller-side `not_refreshable` guard Claude Code applies before taking its refresh lock (`if(!IZ(i.scopes)&&!i.subscriptionType)`). That is a policy about which accounts are worth refreshing, and it belongs to whoever decides to refresh, not to the client that performs one.

type Listener

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

Listener is the loopback HTTP server that catches the browser redirect.

func Listen

func Listen(expectedState string) (*Listener, error)

Listen binds an ephemeral loopback port and starts serving.

Binding to 127.0.0.1 specifically, not 0.0.0.0, keeps the callback unreachable from the network; only this machine can deliver a code.

The redirect URI advertises "localhost" to match Claude Code, so a resolver that prefers IPv6 tries [::1] first and falls back to 127.0.0.1 once that is refused. If IPv6-only loopback ever needs supporting, bind a second listener on [::1] — never widen this one to every interface.

func (*Listener) Close

func (l *Listener) Close() error

Close stops the listener. It is idempotent.

closeOnce is not redundant with net/http, though a test cannot show it: Server.Close tolerates a second call in today's implementation, so removing the guard leaves the suite green. That tolerance is not a documented guarantee, and this type promises idempotence in its own right — the guard stays, and the surviving mutation is disclosed rather than papered over.

This severs live connections instead of draining them, so a browser can lose the success page mid-transfer. That is the right trade here: the caller closes only once the exchange is done, and a tab that never finished loading must not hold up the CLI. Reach for Shutdown only if that ordering ever changes.

func (*Listener) Port

func (l *Listener) Port() int

Port is the bound port, for building the loopback redirect URI.

func (*Listener) Results

func (l *Listener) Results() <-chan CallbackResult

Results delivers at most one CallbackResult.

type LoginOptions

type LoginOptions struct {
	// Surface selects the subscription or console authorize endpoint.
	Surface Surface
	// Timeout bounds the attempt. Zero means DefaultLoginTimeout.
	Timeout time.Duration
	// OpenBrowser attempts a launch. Even when false the manual URL is announced.
	OpenBrowser bool
	// Paste supplies pasted lines. Nil disables the paste path, which is right
	// when stdin is not a terminal.
	Paste PasteSource
	// Announce receives the MANUAL authorize URL, before the browser opens.
	// Callers print it so the flow is visible and the URL can be used by hand.
	Announce func(manualURL string)
	// Rejected receives a message for a paste that could not be parsed. The
	// login keeps waiting: a malformed paste is a re-prompt rather than an
	// abort, because the loopback race may still be about to win.
	Rejected func(msg string)
	// Client is the token endpoint client. Nil means NewClient().
	Client *Client
	// OpenURL launches the LOOPBACK authorize URL when OpenBrowser is set. Nil
	// means browser.Open. It is a field rather than a direct call because it is
	// the only handle anything outside Login has on the loopback port — without
	// it no test can drive the loopback path at all.
	OpenURL func(loopbackURL string) error
	// contains filtered or unexported fields
}

LoginOptions configures one attempt.

type LoginResult

type LoginResult struct {
	Token *TokenResponse
	// ViaLoopback records which path won. It is frozen at delivery time, not
	// re-derived afterwards: Go serves each callback in its own goroutine, so a
	// post-hoc check would race the handler.
	ViaLoopback bool
}

LoginResult is a completed login.

func Login

func Login(ctx context.Context, opts LoginOptions) (*LoginResult, error)

Login runs the full attempt.

Both paths run at once, exactly as Claude Code does: a loopback listener is always started, the MANUAL url is shown to the user, and the browser is pointed at the LOOPBACK url. Whichever returns the code first wins, and the token exchange must echo back the redirect_uri belonging to that path. Sending the other one is a 400.

type Organization

type Organization struct {
	UUID string `json:"uuid"`
}

Organization is the org the account belongs to.

type PKCE

type PKCE struct {
	Verifier  string
	Challenge string
}

PKCE is one proof-key pair for a single login attempt.

The verifier never leaves this process until the token exchange, and it is never logged: holding it plus an intercepted authorization code is enough to mint a token. String and GoString below enforce that second half.

func NewPKCE

func NewPKCE() (PKCE, error)

NewPKCE generates a fresh pair. 32 random bytes encode to a 43-character verifier, inside RFC 7636's 43..128 range.

func (PKCE) GoString

func (p PKCE) GoString() string

GoString keeps %#v redacted too; without it fmt falls back to the raw struct.

func (PKCE) String

func (p PKCE) String() string

String redacts the verifier so that a PKCE printed with %v, %+v, %s or %#v — in an error, a debug line, or a struct that embeds it — cannot leak it. The verifier is only ever read through the field.

type PasteSource

type PasteSource func() (<-chan string, func())

PasteSource yields pasted `code#state` lines. It returns the channel and a stop function.

The stop function is best-effort by necessity: os.Stdin.Read is not cancellable in Go, so a reader already blocked on the terminal stays blocked until the process exits. What stop does reliably release is a reader blocked on handing its line over, which is why nothing ever waits for the goroutine.

func StdinPaste

func StdinPaste() PasteSource

StdinPaste reads lines from standard input.

type RefreshParams

type RefreshParams struct {
	RefreshToken string

	// StoredScopes is the scope set recorded WITH the credential (`scopes[]` in
	// .credentials.json) — not the set to request. What gets requested is
	// derived from it. Leaving it nil asks for the bare RefreshScopeString,
	// which is right only for a credential that has no scopes recorded.
	StoredScopes []string

	// SubscriptionType is the credential's subscriptionType, if any.
	//
	// It is one of the two things that mark a credential as the default
	// first-party client. Nothing Claude Code writes can carry a
	// subscriptionType without also carrying user:inference — both credential
	// writers gate on it — so this field only changes the outcome for a record
	// something else produced. It is kept because the bundle's predicate has
	// the disjunct and the cost of honouring it is one line.
	SubscriptionType string

	// ClientID is the credential's own clientId, for a credential that did not
	// come from Claude Code's public client. Setting it changes which scopes
	// are requested as well as which client is named.
	ClientID string
}

RefreshParams describes one refresh against a stored credential.

Claude Code's refresh is a function of the whole stored record, not of the token alone: which scopes go on the wire depends on StoredScopes, SubscriptionType and ClientID together. There is deliberately no token-only form — all six refresh call sites in the 2.1.238 bundle pass an explicit scope array, so a token-only call is not a shape Claude Code has, and offering it as the shortest, best-named entry point would make silently stripping an account's expansion scopes the easiest thing to type.

type RejectionError

type RejectionError struct{ Rejection AuthorizeRejection }

RejectionError is the error a rejected authorize callback delivers.

Parsing into a closed set is only worth doing if the parsed value survives to the caller: this is what lets a login report WHY it failed without any upstream byte ever reaching a message. Error() is the canned user text; LogDetail() is the OAuth error code for an operator log.

func (*RejectionError) Error

func (e *RejectionError) Error() string

func (*RejectionError) LogDetail

func (e *RejectionError) LogDetail() string

type Surface

type Surface int

Surface selects which authorize endpoint a login goes to.

const (
	// SurfaceClaudeAI is the subscription login. This is the default and the
	// right answer for Pro, Max, Team, and Enterprise seats.
	SurfaceClaudeAI Surface = iota
	// SurfaceConsole is the Console/API-billing login, for a credit-billed
	// account. It does not mint claude.ai credentials.
	SurfaceConsole
)

func (Surface) String

func (s Surface) String() string

String names the surface, so a failure message reads "console" and not "1".

type TokenError

type TokenError struct {
	Kind   TokenErrorKind
	Status int
}

TokenError is a typed token-endpoint failure.

It carries the HTTP status and nothing else from the wire. The response body is upstream text of unbounded length with no newline stripping, so putting it in an error — which reaches stderr and the log — would let the endpoint forge log lines. The status is enough to act on.

func (*TokenError) Error

func (e *TokenError) Error() string

type TokenErrorKind

type TokenErrorKind int

TokenErrorKind classifies a token-endpoint failure.

const (
	// TokenErrorTransport means the request never got an HTTP answer. The kinds
	// start at 1 so a zero-value TokenError never reads as a classification
	// something actually made.
	TokenErrorTransport TokenErrorKind = iota + 1
	// TokenErrorInvalidCode is a 401, or any status carrying RFC 6749's
	// invalid_grant: the code or the refresh token was rejected.
	TokenErrorInvalidCode
	// TokenErrorInvalidScope is a 400 — and only a 400 — carrying RFC 6749's
	// invalid_scope: the endpoint refused the scope set, not the credential.
	// Refresh retries once with the credential's own scopes when it sees this.
	// Claude Code pins the status the same way: `e.response?.status !== 400`
	// short-circuits its check before the code is even read.
	TokenErrorInvalidScope
	// TokenErrorStatus is any other non-200.
	TokenErrorStatus
)

func (TokenErrorKind) String

func (k TokenErrorKind) String() string

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"`
	Scope        string `json:"scope"`

	// RefreshTokenExpiresIn is present on some responses. Keep it: a stored
	// credential that drops it loses the only signal that a refresh token is
	// near the end of its life.
	RefreshTokenExpiresIn int64 `json:"refresh_token_expires_in"`

	Account      Account      `json:"account"`
	Organization Organization `json:"organization"`
}

TokenResponse is the token endpoint's success body.

func (TokenResponse) GoString

func (r TokenResponse) GoString() string

GoString keeps %#v redacted too; without it fmt falls back to the raw struct.

func (TokenResponse) String

func (r TokenResponse) String() string

String redacts both tokens so a TokenResponse printed with %v, %+v, %s or %#v — in an error, a debug line, or a struct that embeds it — cannot leak them. This is the same guard PKCE carries, for the same reason and on a strictly more valuable secret: the credential writer in part 3 is handed this struct, and one %+v in a future log line is all it takes.

Jump to

Keyboard shortcuts

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