Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251// Package session stores the signed-in account and turns it into an// authenticated client for the account's PDS.//// Two sign-in methods are supported: atproto OAuth through the browser, using// a loopback client, and app passwords for headless machines. Both produce an// [atclient.APIClient] that talks to the user's PDS.package session
import ( "context" "encoding/json" "errors" "fmt" "net/http" "os" "path/filepath" "time"
"github.com/bluesky-social/indigo/atproto/atclient" "github.com/bluesky-social/indigo/atproto/auth/oauth" "github.com/bluesky-social/indigo/atproto/syntax"
"tangled.org/rockorager.dev/knit/internal/config")
// ErrNotLoggedIn is returned when no account is signed in.var ErrNotLoggedIn = errors.New("not logged in; run `knit auth login`")
// UserAgent is sent with every request knit makes.var UserAgent = "knit"
const ( MethodOAuth = "oauth" MethodAppPassword = "app-password")
// Scopes are the OAuth scopes knit requests. Records knit writes to the user's// PDS need a repo scope; calls to knots and to the API need a service-auth// token, which needs an rpc scope for the method the token is bound to.var Scopes = []string{ "atproto", "repo:org.tangled.graph.attestation", "repo:org.tangled.repo.declaration", "repo:org.tangled.key.sshKey", "rpc?lxm=com.atproto.repo.createRecord" + "&lxm=com.atproto.repo.putRecord" + "&lxm=com.atproto.repo.deleteRecord" + "&lxm=org.tangled.repo.createRepo" + "&lxm=org.tangled.repo.deleteRepo" + "&lxm=org.tangled.review.submitPatch" + "&lxm=org.tangled.git.receivePack" + "&lxm=org.tangled.repo.mintToken" + "&lxm=org.tangled.ci.approvePipeline" + "&lxm=org.tangled.ci.cancelPipeline" + "&lxm=org.tangled.ci.retryPipeline" + "&lxm=org.tangled.event.notifyEvent" + "&aud=*",}
// Session is the persisted state of the signed-in account.type Session struct { Method string `json:"method"` DID string `json:"did"` Handle string `json:"handle"`
// OAuth sessions are bound to the client ID they were created with, // which for a loopback client embeds the redirect URI. OAuthClientID string `json:"oauth_client_id,omitempty"` OAuthCallbackURL string `json:"oauth_callback_url,omitempty"` OAuth *oauth.ClientSessionData `json:"oauth,omitempty"` Password *atclient.PasswordSessionData `json:"password,omitempty"`}
func path() (string, error) { dir, err := config.Dir() if err != nil { return "", err } return filepath.Join(dir, "auth.json"), nil}
// Load reads the stored session, returning ErrNotLoggedIn when there is none.func Load() (*Session, error) { p, err := path() if err != nil { return nil, err } data, err := os.ReadFile(p) if errors.Is(err, os.ErrNotExist) { return nil, ErrNotLoggedIn } if err != nil { return nil, err } var s Session if err := json.Unmarshal(data, &s); err != nil { return nil, fmt.Errorf("reading %s: %w", p, err) } return &s, nil}
// Save writes the session with owner-only permissions.func (s *Session) Save() error { p, err := path() if err != nil { return err } if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil { return err } data, err := json.MarshalIndent(s, "", " ") if err != nil { return err } tmp := p + ".tmp" if err := os.WriteFile(tmp, data, 0o600); err != nil { return err } return os.Rename(tmp, p)}
// Delete removes the stored session.func Delete() error { p, err := path() if err != nil { return err } err = os.Remove(p) if errors.Is(err, os.ErrNotExist) { return nil } return err}
// Client returns an API client for the account's PDS. Refreshed tokens are// written back to disk.func (s *Session) Client(ctx context.Context) (*atclient.APIClient, error) { var c *atclient.APIClient switch s.Method { case MethodOAuth: if s.OAuth == nil { return nil, ErrNotLoggedIn } app := s.oauthApp() sess, err := app.ResumeSession(ctx, s.OAuth.AccountDID, s.OAuth.SessionID) if err != nil { return nil, err } c = sess.APIClient() case MethodAppPassword: if s.Password == nil { return nil, ErrNotLoggedIn } c = atclient.ResumePasswordSession(*s.Password, func(_ context.Context, data atclient.PasswordSessionData) { s.Password = &data _ = s.Save() }) default: return nil, ErrNotLoggedIn } c.Client = &http.Client{Timeout: 60 * time.Second} if c.Headers == nil { c.Headers = http.Header{} } c.Headers.Set("User-Agent", UserAgent) return c, nil}
// Logout revokes the session where the server supports it and deletes it// from disk.func (s *Session) Logout(ctx context.Context) error { var revokeErr error switch s.Method { case MethodOAuth: if s.OAuth != nil { revokeErr = s.oauthApp().Logout(ctx, s.OAuth.AccountDID, s.OAuth.SessionID) } case MethodAppPassword: if s.Password != nil { c := atclient.ResumePasswordSession(*s.Password, nil) if pa, ok := c.Auth.(*atclient.PasswordAuth); ok { revokeErr = pa.Logout(ctx, c.Client) } } } if err := Delete(); err != nil { return err } return revokeErr}
func (s *Session) oauthApp() *oauth.ClientApp { cfg := oauth.ClientConfig{ ClientID: s.OAuthClientID, CallbackURL: s.OAuthCallbackURL, Scopes: Scopes, UserAgent: UserAgent, } return oauth.NewClientApp(&cfg, &store{session: s})}
// store adapts a single on-disk Session to oauth.ClientAuthStore. Pending// auth requests only live for the duration of a login, so they stay in memory.type store struct { session *Session requests map[string]oauth.AuthRequestData}
func (st *store) GetSession(_ context.Context, did syntax.DID, sessionID string) (*oauth.ClientSessionData, error) { d := st.session.OAuth if d == nil || d.AccountDID != did || d.SessionID != sessionID { return nil, ErrNotLoggedIn } return d, nil}
func (st *store) SaveSession(_ context.Context, sess oauth.ClientSessionData) error { st.session.OAuth = &sess if st.session.Method == "" { // a login in progress; the caller saves once it has the handle return nil } return st.session.Save()}
func (st *store) DeleteSession(context.Context, syntax.DID, string) error { st.session.OAuth = nil return nil}
func (st *store) GetAuthRequestInfo(_ context.Context, state string) (*oauth.AuthRequestData, error) { info, ok := st.requests[state] if !ok { return nil, errors.New("unknown OAuth state") } return &info, nil}
func (st *store) SaveAuthRequestInfo(_ context.Context, info oauth.AuthRequestData) error { if st.requests == nil { st.requests = map[string]oauth.AuthRequestData{} } st.requests[info.State] = info return nil}
func (st *store) DeleteAuthRequestInfo(_ context.Context, state string) error { delete(st.requests, state) return nil}