auth

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 3, 2026 License: MIT Imports: 29 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 auth implements the freshbooks CLI's login flow on top of the freshbooks library's auth package: a loopback PKCE authorization-code exchange over an ephemeral self-signed TLS certificate, a --no-browser paste fallback, and the status/logout/token commands' shared plumbing. Credentials live in a lib auth.FileStore, one JSON file per context (see paths.go); config.yaml never carries a secret.

Index

Constants

View Source
const DefaultLoginTimeout = 5 * time.Minute

DefaultLoginTimeout bounds how long the loopback listener waits for the browser to complete the redirect before Login gives up and the listener closes.

View Source
const DefaultPort = 8765

DefaultPort is the loopback port `auth login` listens on when --callback-port is not given, matching the app's registered redirect URI https://localhost:8765/callback.

Variables

View Source
var DefaultScopes = buildDefaultScopes()

DefaultScopes is the user:<object>:<read|write> scope set the CLI requests on `auth login` when the caller does not pass --scopes: every scope the FreshBooks developer portal actually offers a normal app, one entry per object and action.

It is deliberately NOT the cross product of the object list published at https://www.freshbooks.com/api/scopes. That page is incomplete in both directions (Phase 7, live, 2026-09-02): three of its objects have no write scope at all, and it omits objects the portal does offer. Requesting a scope that does not exist fails the whole consent with "The requested scope is invalid, unknown, or malformed", so the default set has to match the portal, not the docs page.

user:profile:read is always granted by FreshBooks regardless of what is requested, but it is listed explicitly so the authorization screen shows the CLI's full intent. Every scope requested must ALSO be enabled on the app in the developer portal, or consent fails the same way.

Functions

func CredentialsDir

func CredentialsDir() (string, error)

CredentialsDir is $XDG_CONFIG_HOME/freshbooks/credentials (falling back to ~/.config), where one FileStore-backed JSON file lives per context (D5: "one lib FileStore per context").

func CredentialsPath

func CredentialsPath(context string) (string, error)

CredentialsPath is the credentials file for one named context. It rejects an invalid context name (see ValidContextName) rather than letting it reach filepath.Join, where a name like "../../etc/passwd" would resolve outside the credentials directory entirely.

func Login

func Login(ctx context.Context, o LoginOptions) (*fbauth.Token, error)

Login runs the full loopback PKCE flow: it starts an HTTPS listener on 127.0.0.1:port with an ephemeral self-signed certificate, prints the authorization URL, opens the browser, waits for the single callback request, validates state, exchanges the code, and (when Store is set) persists the token. It returns an error without persisting anything on a state mismatch, a browser-reported denial, or a timeout.

func LoginNoBrowser

func LoginNoBrowser(ctx context.Context, o LoginOptions, stdin io.Reader) (*fbauth.Token, error)

LoginNoBrowser prints the authorization URL and reads one line from stdin: either the full URL the browser was redirected to (state is validated against it) or a bare authorization code (no listener runs, so there is nothing to validate state against).

func Logout

func Logout(ctx context.Context, cfg fbauth.Config, credentialsPath string, store fbauth.TokenStore) error

Logout best-effort revokes both the stored refresh token and the stored access token (a revocation failure is not fatal -- the credentials file is removed regardless) and then removes the credentials file. A missing file is not an error.

Both tokens are revoked, not just the refresh token: a copy of the access token surviving elsewhere (a shell scrollback from `auth token`, a backup, a synced dotfile) would otherwise keep working until its natural expiry even after `logout`. Revoke-then-delete is the correct order and stays that way even though the revocation result is ignored: deleting first would mean a revoke failure leaves a live credential with nothing on disk to retry against, and making the delete unconditional means a network-down logout still clears local state.

func NewState

func NewState() (string, error)

NewState returns a fresh, unguessable OAuth state value: 32 bytes from crypto/rand, base64url-encoded without padding.

func Token

func Token(ctx context.Context, cfg fbauth.Config, store fbauth.TokenStore, refresh bool, now func() time.Time) (string, error)

Token returns the stored access token, refreshing (and persisting the rotated pair) first when refresh is true OR when the stored access token has already expired.

The expiry check is not a convenience. Without it `auth token` printed a dead token and exited 0 (observed live, 2026-09-03: `auth status` reported valid: false while `auth token` still printed the stale value), so every caller of the documented `TOKEN=$(freshbooks auth token)` idiom got a silent 401 on its next call instead of a working credential. A token that is about to expire inside the lib's DefaultExpirySkew counts as expired here, matching what `auth status` calls valid.

now supplies the clock; nil means time.Now.

func ValidContextName

func ValidContextName(name string) bool

ValidContextName reports whether name is safe to use as the filesystem component CredentialsPath builds a path from. A context name reaches filepath.Join from several places -- a --context flag, $FRESHBOOKS_CONTEXT, and config.yaml's current-context (which a config.yaml the operator did not author, e.g. one checked into a repo or shipped in a container image, can also set) -- so this is validated centrally here rather than trusted at each call site.

Types

type LoginOptions

type LoginOptions struct {
	// ClientID and ClientSecret are the registered application's OAuth
	// credentials.
	ClientID, ClientSecret string
	// Scopes are the scopes to request. Nil means DefaultScopes.
	Scopes []string
	// Port is the loopback port for the browser flow. Zero means
	// DefaultPort. Unused by LoginNoBrowser.
	Port int
	// Timeout bounds how long the browser flow waits for the callback.
	// Zero means DefaultLoginTimeout. Unused by LoginNoBrowser.
	Timeout time.Duration
	// Endpoints selects the OAuth endpoint set. Zero means the lib
	// default (MetadataEndpoints).
	Endpoints fbauth.Endpoints
	// HTTPClient performs the token exchange. Nil means the lib default.
	HTTPClient *http.Client
	// Store persists the resulting token. Required for the token to be
	// saved; a nil Store means "exchange only, do not persist" (used by
	// tests that want the token without a filesystem side effect).
	Store fbauth.TokenStore
	// Stdout receives the authorization URL and progress messages. Nil
	// means io.Discard.
	Stdout io.Writer
	// OpenBrowser opens url in the user's browser. Nil means the
	// platform-appropriate program (xdg-open/open/rundll32). Tests
	// inject a no-op here so a live browser never launches.
	OpenBrowser func(rawURL string) error
	// Now supplies the current time, for deterministic certificate
	// validity windows in tests. Nil means time.Now.
	Now func() time.Time
}

LoginOptions configures Login and LoginNoBrowser.

type StatusInfo

type StatusInfo struct {
	// Context is the context this status was checked for.
	Context string `json:"context"`
	// CredentialsPath is the file the context's credentials live in,
	// whether or not it exists yet.
	CredentialsPath string `json:"credentials_path"`
	// LoggedIn reports whether a token is stored at all.
	LoggedIn bool `json:"logged_in"`
	// Valid reports whether the stored access token is present and not
	// expiring within the lib's DefaultExpirySkew. False when
	// LoggedIn is false.
	Valid bool `json:"valid"`
	// Expiry is the stored access token's expiry, zero if unknown or
	// non-expiring.
	Expiry time.Time `json:"expiry"`
	// Scopes are the scopes the stored token actually carries.
	Scopes []string `json:"scopes"`
}

StatusInfo is what `auth status` reports. It never carries the token itself -- see Token for the one command that prints it.

G5/QA Q10: snake_case json tags, matching the D8 fold's Page[T]/User/ Membership -- without them `auth status -o json` printed Go-cased field names (Context, LoggedIn, ...) instead of the wire-shape convention every other command's -o json output follows.

func Status

func Status(ctx context.Context, contextName, credentialsPath string, store fbauth.TokenStore, now func() time.Time) (*StatusInfo, error)

Status reports a context's credential state without ever touching the network or printing the token.

Jump to

Keyboard shortcuts

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