An unofficial terminal client for Tangled, optimized for humans and agents. tgcli.wisp.place
cli atproto go tangled
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527package atproto
import ( "context" "errors" "fmt" "net/http" "net/url" "slices" "strings"
"github.com/bluesky-social/indigo/atproto/atclient" "github.com/bluesky-social/indigo/atproto/auth/oauth" "github.com/bluesky-social/indigo/atproto/identity" "github.com/bluesky-social/indigo/atproto/syntax" "github.com/zalando/go-keyring")
var ErrNotAuthenticated = errors.New("not authenticated")
const ( SessionStatusActive = "active" SessionStatusExpired = "expired" SessionStatusUnknown = "unknown")
// DefaultScopes are requested for a CLI session. The rpc scopes are needed for// the PDS to mint service-auth JWTs for knot procedures. The blob scope is// required for uploading strings and attachments.var DefaultScopes = []string{ "atproto", "blob:text/plain", "blob:image/*", "blob:video/*", "repo:org.tangled.repo.declaration", "repo:org.tangled.graph.attestation", "repo:org.tangled.key.sshKey", "repo:org.tangled.snippet.string", "rpc:com.atproto.repo.createRecord?aud=*", "rpc:com.atproto.repo.putRecord?aud=*", "rpc:com.atproto.repo.deleteRecord?aud=*", "rpc:com.atproto.repo.uploadBlob?aud=*", "rpc:org.tangled.repo.createRepo?aud=*", "rpc:org.tangled.repo.deleteRepo?aud=*", "rpc:org.tangled.repo.mintToken?aud=*", "rpc:org.tangled.review.submitPatch?aud=*", "rpc:org.tangled.git.receivePack?aud=*", "rpc:org.tangled.git.setDefaultBranch?aud=*", "rpc:org.tangled.event.notifyEvent?aud=*", "rpc:org.tangled.ci.cancelPipeline?aud=*", "rpc:org.tangled.ci.approvePipeline?aud=*", "rpc:org.tangled.ci.retryPipeline?aud=*",}
type AuthManager struct { app *oauth.ClientApp store *KeyringStore insecureStore *insecureFileStore client *http.Client selector string pendingIdentifier string}
// sessionSource identifies which credential store backs the active session.type sessionSource int
const ( sessionSourceKeyring sessionSource = iota sessionSourceInsecureFile)
func (m *AuthManager) SetAccount(selector string) { m.selector = selector}
// Accounts lists stored accounts from both credential stores. A file account// lets this succeed when the keyring is unavailable; otherwise keyring errors// are returned.func (m *AuthManager) Accounts() ([]Account, string, error) { accounts, activeDID, keyringErr := m.store.Accounts() fileAccount, hasFileAccount, err := m.findInsecureFileAccount() if err != nil { return nil, "", err } if hasFileAccount { accounts = append(accounts, fileAccount) if activeDID == "" { activeDID = fileAccount.DID } } if keyringErr != nil && !errors.Is(keyringErr, keyring.ErrNotFound) && !hasFileAccount { return nil, "", keyringErr } return accounts, activeDID, nil}
func (m *AuthManager) SelectAccount(selector string) (Account, error) { account, err := m.store.SelectAccount(selector) if err == nil { return account, nil } fileAccount, hasFileAccount, fileErr := m.findInsecureFileAccount() if fileErr != nil { return Account{}, fileErr } if hasFileAccount && selectorMatches(selector, fileAccount) { m.selector = selector return fileAccount, nil } return Account{}, err}
func (m *AuthManager) activeAccount() (Account, sessionSource, error) { // Prefer the keyring when an account exists in both stores. account, err := m.store.Account(m.selector) if err == nil { return account, sessionSourceKeyring, nil } fileAccount, hasFileAccount, fileErr := m.findInsecureFileAccount() if fileErr != nil { return Account{}, sessionSourceKeyring, fileErr } if hasFileAccount && selectorMatches(m.selector, fileAccount) { return fileAccount, sessionSourceInsecureFile, nil } if !errors.Is(err, keyring.ErrNotFound) { return Account{}, sessionSourceKeyring, err } return Account{}, sessionSourceKeyring, ErrNotAuthenticated}
// findInsecureFileAccount returns the sole account stored in the insecure credential file.func (m *AuthManager) findInsecureFileAccount() (Account, bool, error) { if m.insecureStore == nil { return Account{}, false, nil } return m.insecureStore.FindAccount()}
func NewAuthManager() *AuthManager { return NewAuthManagerWithClient(http.DefaultClient)}
// NewAuthManagerWithClient creates an AuthManager using httpClient for OAuth// and authenticated API requests. The OAuth loopback redirect URI is not known// until a callback server is bound, so it is configured per login via// SetCallbackURL before StartLogin.func NewAuthManagerWithClient(httpClient *http.Client) *AuthManager { config := oauth.NewLocalhostConfig("", DefaultScopes) config.UserAgent = "tg" store := NewKeyringStore() app := oauth.NewClientApp(&config, store) app.Client = httpClient app.Resolver.Client = httpClient // Best-effort: if the credentials directory cannot be created (e.g. no home // directory), --insecure login will surface a clear error instead. insecureStore, _ := newInsecureFileStore() return &AuthManager{ app: app, store: store, insecureStore: insecureStore, client: httpClient, }}
// SetCallbackURL configures the loopback redirect URI (including a dynamically// allocated port) for the next OAuth login. Per RFC 8252, tg binds an// ephemeral port per login, so this must be called with the bound listener's// address before StartLogin.func (m *AuthManager) SetCallbackURL(callbackURL string) { updated := oauth.NewLocalhostConfig(callbackURL, DefaultScopes) updated.UserAgent = m.app.Config.UserAgent *m.app.Config = updated}
// LoginWithPassword authenticates with an atproto app password and stores the// resulting session. When useInsecureFileStore is true the session is written to// plaintext instead of the keyring; this is intended// for headless systems without a Secret Service provider. Keyring-backed logins// replace any existing OAuth session for the account.func (m *AuthManager) LoginWithPassword(ctx context.Context, identifier, password string, useInsecureFileStore bool) error { if useInsecureFileStore && m.insecureStore == nil { return errors.New("insecure credential storage is unavailable") } parsedIdentifier, err := syntax.ParseAtIdentifier(identifier) if err != nil { return err } ctx, cancel := m.requestContext(ctx) defer cancel() savePasswordSession := func(data atclient.PasswordSessionData) error { if useInsecureFileStore { return m.insecureStore.SavePasswordSession(identifier, data) } return m.store.SavePasswordSession(context.Background(), data) } persist := func(_ context.Context, data atclient.PasswordSessionData) { _ = savePasswordSession(data) } client, err := atclient.LoginWithPassword(ctx, identity.DefaultDirectory(), parsedIdentifier, password, "", persist) if err != nil { return err } passwordAuth, ok := client.Auth.(*atclient.PasswordAuth) if !ok { return errors.New("password login returned an unexpected auth type") } client.Client = m.client if useInsecureFileStore { if err := savePasswordSession(passwordAuth.Session); err != nil { return err } m.selector = passwordAuth.Session.AccountDID.String() return nil } if err := savePasswordSession(passwordAuth.Session); err != nil { return err } did := passwordAuth.Session.AccountDID.String() if err := m.store.SetAccountHandle(did, identifier); err != nil { return err } _, err = m.store.SelectAccount(did) return err}
func (m *AuthManager) StartLogin(ctx context.Context, identifier string) (string, error) { loginURL, err := m.app.StartAuthFlow(ctx, identifier) if err == nil { m.pendingIdentifier = identifier } return loginURL, err}
func (m *AuthManager) FinishLogin(ctx context.Context, query url.Values) error { session, err := m.app.ProcessCallback(ctx, query) if err != nil { return err } handle := m.pendingIdentifier if handle == "" { handle = session.AccountDID.String() } m.pendingIdentifier = "" did := session.AccountDID.String() if err := m.store.SetAccountHandle(did, handle); err != nil { return err } if err := m.store.SetAccountOAuthClient(did, m.app.Config.CallbackURL, m.app.Config.ClientID); err != nil { return err } _, err = m.store.SelectAccount(did) return err}
// CancelLogin cleans up any pending auth request written by StartLogin when the// login flow is abandoned (e.g. the user closes the browser before the// callback). It is safe to call after a completed login.func (m *AuthManager) CancelLogin() { m.pendingIdentifier = "" _ = m.store.DeletePendingAuthRequest()}
func (m *AuthManager) CurrentDID(ctx context.Context) (syntax.DID, error) { account, source, err := m.activeAccount() if err != nil { return "", err } did, err := syntax.ParseDID(account.DID) if err != nil { return "", err } if source == sessionSourceInsecureFile { return did, nil } if account.Method == AuthMethodOAuth { session, err := m.resumeOAuthSession(ctx, account) if err != nil { return "", err } return session.Data.AccountDID, nil } passwordSession, err := m.store.GetPasswordSession(ctx, did) if err != nil { if errors.Is(err, keyring.ErrNotFound) { return "", ErrNotAuthenticated } return "", err } return passwordSession.AccountDID, nil}
func (m *AuthManager) CurrentSession(ctx context.Context) (*oauth.ClientSession, error) { account, source, err := m.activeAccount() if err != nil { return nil, err } // The file store only holds app-password sessions, so there is no OAuth // ClientSession to return. Callers fall back to APIClient for token access. if source == sessionSourceInsecureFile || account.Method != AuthMethodOAuth { return nil, ErrNotAuthenticated } return m.resumeOAuthSession(ctx, account)}
// OAuthSessionHasScope reports whether the active OAuth session grants scope.// isOAuth is false for app-password and missing sessions.func (m *AuthManager) OAuthSessionHasScope(ctx context.Context, scope string) (hasScope, isOAuth bool, err error) { session, err := m.CurrentSession(ctx) if errors.Is(err, ErrNotAuthenticated) { return false, false, nil } if err != nil { return false, false, err } return slices.Contains(session.Data.Scopes, scope), true, nil}
// APIClient returns an API client and the account DID for the active session,// whether OAuth or app-password and whether backed by the keyring or the// insecure file store. Token refreshes are persisted back to whichever store// backs the session.func (m *AuthManager) APIClient(ctx context.Context) (*atclient.APIClient, syntax.DID, error) { account, source, err := m.activeAccount() if err != nil { return nil, "", err } if source == sessionSourceInsecureFile { session, _, err := m.insecureStore.GetPasswordSession() if err != nil { if errors.Is(err, keyring.ErrNotFound) { return nil, "", ErrNotAuthenticated } return nil, "", err } persist := func(_ context.Context, data atclient.PasswordSessionData) { _ = m.insecureStore.SavePasswordSession(account.Handle, data) } client := atclient.ResumePasswordSession(*session, persist) client.Client = m.client return client, session.AccountDID, nil } did, err := syntax.ParseDID(account.DID) if err != nil { return nil, "", err } if account.Method == AuthMethodOAuth { session, err := m.resumeOAuthSession(ctx, account) if err != nil { return nil, "", err } return session.APIClient(), session.Data.AccountDID, nil } passwordSession, err := m.store.GetPasswordSession(ctx, did) if err != nil { if errors.Is(err, keyring.ErrNotFound) { return nil, "", ErrNotAuthenticated } return nil, "", err } persist := func(_ context.Context, data atclient.PasswordSessionData) { _ = m.store.SavePasswordSession(context.Background(), data) } client := atclient.ResumePasswordSession(*passwordSession, persist) client.Client = m.client return client, passwordSession.AccountDID, nil}
func (m *AuthManager) restoreOAuthClient(account Account) error { if account.ClientID != "" { m.app.Config.ClientID = account.ClientID if account.CallbackURL != "" { m.app.Config.CallbackURL = account.CallbackURL } return nil } if account.CallbackURL != "" { m.SetCallbackURL(account.CallbackURL) return nil } if m.app.Config.CallbackURL != "" && m.app.Config.ClientID != "" { return nil } return fmt.Errorf("OAuth session is missing the login client identity; run \"tg auth login\" once to persist it")}
func (m *AuthManager) resumeOAuthSession(ctx context.Context, account Account) (*oauth.ClientSession, error) { if err := m.restoreOAuthClient(account); err != nil { return nil, err } did, err := syntax.ParseDID(account.DID) if err != nil { return nil, err } session, err := m.app.ResumeSession(ctx, did, "") if err != nil { if errors.Is(err, keyring.ErrNotFound) { return nil, ErrNotAuthenticated } return nil, err } return session, nil}
func (m *AuthManager) requestContext(ctx context.Context) (context.Context, context.CancelFunc) { if m.client == nil || m.client.Timeout <= 0 { return ctx, func() {} } return context.WithTimeout(ctx, m.client.Timeout)}
// SessionStatus probes the server to verify the active session. The probe// refreshes the access token if needed. Returns ErrNotAuthenticated when// there is no active account.func (m *AuthManager) SessionStatus(ctx context.Context) (string, syntax.DID, error) { client, did, err := m.APIClient(ctx) if err != nil { return "", "", err } err = client.Get(ctx, syntax.NSID("com.atproto.server.getSession"), nil, nil) if err == nil { return SessionStatusActive, did, nil } var apiError *atclient.APIError if errors.As(err, &apiError) && apiError.StatusCode == http.StatusUnauthorized { return SessionStatusExpired, did, nil } // OAuth wraps refresh failures in fmt.Errorf, not APIError. A failed // refresh usually means the refresh token is dead. Client-metadata // mismatches are a local config bug, not an expired session. if strings.Contains(err.Error(), "failed to refresh OAuth tokens") { if strings.Contains(err.Error(), "invalid_client_metadata") { return "", did, fmt.Errorf("OAuth client identity does not match the stored session; run \"tg auth login\" once to persist it: %w", err) } return SessionStatusExpired, did, nil } return SessionStatusUnknown, did, nil}
// Logout removes the active account's credentials from whichever store backs// it (keyring or insecure file). Server-side revocation is best-effort; the// local entry is removed even if the PDS rejects the revoke request. Returns// ErrNotAuthenticated when there is no active account.func (m *AuthManager) Logout(ctx context.Context) error { account, source, err := m.activeAccount() if err != nil { return err } if source == sessionSourceInsecureFile { return m.logoutFile(ctx) } did, err := syntax.ParseDID(account.DID) if err != nil { return err } switch account.Method { case AuthMethodOAuth: _ = m.restoreOAuthClient(account) _ = m.app.Logout(ctx, did, "") if err := m.store.DeleteSession(ctx, did, ""); err != nil { return fmt.Errorf("clear local session: %w", err) } case AuthMethodPassword: passwordSession, err := m.store.GetPasswordSession(ctx, did) if err != nil && !errors.Is(err, keyring.ErrNotFound) { return err } if passwordSession != nil { client := atclient.ResumePasswordSession(*passwordSession, nil) client.Client = m.client if passwordAuth, ok := client.Auth.(*atclient.PasswordAuth); ok { _ = passwordAuth.Logout(ctx, client.Client) } } if err := m.store.DeletePasswordSession(ctx, did); err != nil { return fmt.Errorf("clear local session: %w", err) } default: return fmt.Errorf("unsupported auth method %q", account.Method) } return nil}
// logoutFile revokes the file-backed session server-side (best-effort) and// deletes the credentials file.func (m *AuthManager) logoutFile(ctx context.Context) error { session, _, _ := m.insecureStore.GetPasswordSession() if session != nil { client := atclient.ResumePasswordSession(*session, nil) client.Client = m.client if passwordAuth, ok := client.Auth.(*atclient.PasswordAuth); ok { _ = passwordAuth.Logout(ctx, client.Client) } } if err := m.insecureStore.DeletePasswordSession(); err != nil { return fmt.Errorf("clear local session: %w", err) } return nil}
func (m *AuthManager) LogoutAll(ctx context.Context) error { accounts, _, keyringErr := m.store.Accounts() _, hasFileAccount, err := m.findInsecureFileAccount() if err != nil { return err } if keyringErr != nil && !errors.Is(keyringErr, keyring.ErrNotFound) { if !hasFileAccount { return keyringErr } accounts = nil } if len(accounts) == 0 && !hasFileAccount { return ErrNotAuthenticated } originalSelector := m.selector defer func() { m.selector = originalSelector }() var errs []error for _, account := range accounts { m.selector = account.DID if err := m.Logout(ctx); err != nil { errs = append(errs, fmt.Errorf("logout %s: %w", account.DID, err)) } } if hasFileAccount { if err := m.logoutFile(ctx); err != nil { errs = append(errs, fmt.Errorf("logout file session: %w", err)) } } return errors.Join(errs...)}
// selectorMatches reports whether selector (empty, DID, or handle) identifies// the given account, mirroring findAccount's matching for the single-account// file store.func selectorMatches(selector string, account Account) bool { if selector == "" { return true } return account.DID == selector || strings.EqualFold(account.Handle, selector)}