feat: add atproto OAuth login and token commands

New internal/atproto package implements the atproto OAuth profile as a
public client: handle/DID resolution with bidirectional verification,
PDS and authorization-server metadata discovery, PAR + PKCE, ES256
DPoP proofs with server-nonce retry, and token exchange/refresh with
sub verification. Sessions (tokens + DPoP key) are saved 0600.
'latha-auth atproto' collects the code via the existing deploy relay;
'latha-auth atproto-token' prints a refreshed access token.
This commit is contained in:
nandi committed 2026-11-18 06:19:36 +00:00
1 parent 653da47753
commit fb79db4e21
9 files changed
+1531 -6

No files matched your search

+251
View File
@@ -0,0 +1,251 @@
package atproto
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"slices"
"strings"
)
const (
// DefaultClientID is where the latha-auth client metadata JSON is
// expected to be hosted. Host the output of
// `latha-auth atproto --print-client-metadata` at this URL (or pass
// --client-id / LATHA_ATPROTO_CLIENT_ID).
DefaultClientID = "https://deploy.site.latha.org/oauth/atproto-client-metadata.json"
// DefaultScope covers full repo writes and blob uploads (the old
// app-password capability level), which publishing tiles needs.
DefaultScope = "atproto transition:generic"
)
// ClientMetadata is the OAuth Client ID Metadata Document. latha-auth
// is a public client: no client secret, no assertion key.
type ClientMetadata struct {
ClientID string `json:"client_id"`
ClientName string `json:"client_name,omitempty"`
GrantTypes []string `json:"grant_types"`
ResponseTypes []string `json:"response_types"`
RedirectURIs []string `json:"redirect_uris"`
Scope string `json:"scope"`
TokenEndpointAuthMethod string `json:"token_endpoint_auth_method"`
DPoPBoundAccessTokens bool `json:"dpop_bound_access_tokens"`
}
func BuildClientMetadata(clientID, redirectURI, scope string) ClientMetadata {
return ClientMetadata{
ClientID: clientID,
ClientName: "latha-auth",
GrantTypes: []string{"authorization_code", "refresh_token"},
ResponseTypes: []string{"code"},
RedirectURIs: []string{redirectURI},
Scope: scope,
TokenEndpointAuthMethod: "none",
DPoPBoundAccessTokens: true,
}
}
// FetchClientMetadata preflights the hosted client metadata document so
// a missing/misconfigured one fails locally with a clear message
// instead of as an opaque PAR rejection by the authorization server.
func FetchClientMetadata(ctx context.Context, client *http.Client, clientID string) (*ClientMetadata, error) {
client = httpClientOrDefault(client)
var out ClientMetadata
if err := getJSON(ctx, client, clientID, &out); err != nil {
return nil, err
}
if out.ClientID != clientID {
return nil, fmt.Errorf("client metadata client_id %q does not match %q", out.ClientID, clientID)
}
return &out, nil
}
func (m *ClientMetadata) ValidateFor(redirectURI, scope string) error {
if !slices.Contains(m.RedirectURIs, redirectURI) {
return fmt.Errorf("client metadata does not declare redirect_uri %q", redirectURI)
}
declared := strings.Fields(m.Scope)
for _, want := range strings.Fields(scope) {
if !slices.Contains(declared, want) {
return fmt.Errorf("client metadata scope %q does not include requested %q", m.Scope, want)
}
}
if !m.DPoPBoundAccessTokens {
return fmt.Errorf("client metadata must set dpop_bound_access_tokens: true")
}
return nil
}
type TokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token,omitempty"`
Scope string `json:"scope,omitempty"`
Sub string `json:"sub,omitempty"`
Error string `json:"error,omitempty"`
ErrorDescription string `json:"error_description,omitempty"`
}
type oauthError struct {
Error string `json:"error"`
ErrorDescription string `json:"error_description"`
}
// OAuthClient performs DPoP-bound requests against one authorization
// server. Nonce holds the latest server-issued DPoP nonce and is
// updated from every response.
type OAuthClient struct {
HTTP *http.Client
Metadata *AuthServerMetadata
ClientID string
Key *DPoPKey
Nonce string
}
// postForm posts a form with a DPoP proof, retrying when the server
// demands a (fresh) DPoP nonce via a use_dpop_nonce error.
func (c *OAuthClient) postForm(ctx context.Context, endpoint string, form url.Values) (int, []byte, error) {
client := httpClientOrDefault(c.HTTP)
for attempt := 0; attempt < 3; attempt++ {
proof, err := c.Key.Proof(http.MethodPost, endpoint, c.Nonce, "")
if err != nil {
return 0, nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, strings.NewReader(form.Encode()))
if err != nil {
return 0, nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
req.Header.Set("DPoP", proof)
resp, err := client.Do(req)
if err != nil {
return 0, nil, err
}
body, readErr := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
resp.Body.Close()
if readErr != nil {
return 0, nil, readErr
}
if nonce := resp.Header.Get("DPoP-Nonce"); nonce != "" {
c.Nonce = nonce
}
var oerr oauthError
_ = json.Unmarshal(body, &oerr)
if resp.StatusCode == http.StatusBadRequest && oerr.Error == "use_dpop_nonce" {
continue
}
return resp.StatusCode, body, nil
}
return 0, nil, fmt.Errorf("DPoP nonce negotiation with %s did not converge", endpoint)
}
func errorFrom(status int, body []byte, what string) error {
var oerr oauthError
_ = json.Unmarshal(body, &oerr)
msg := oerr.ErrorDescription
if msg == "" {
msg = oerr.Error
}
if msg == "" {
msg = strings.TrimSpace(string(body))
}
return fmt.Errorf("%s failed (%d): %s", what, status, msg)
}
type PARResponse struct {
RequestURI string `json:"request_uri"`
ExpiresIn int `json:"expires_in"`
}
// PushAuthorizationRequest performs PAR (RFC 9126), which the atproto
// OAuth profile requires for all clients.
func (c *OAuthClient) PushAuthorizationRequest(ctx context.Context, redirectURI, scope, state, codeChallenge, loginHint string) (*PARResponse, error) {
form := url.Values{}
form.Set("client_id", c.ClientID)
form.Set("response_type", "code")
form.Set("redirect_uri", redirectURI)
form.Set("scope", scope)
form.Set("state", state)
form.Set("code_challenge", codeChallenge)
form.Set("code_challenge_method", "S256")
if loginHint != "" {
form.Set("login_hint", loginHint)
}
status, body, err := c.postForm(ctx, c.Metadata.PushedAuthorizationRequestEndpoint, form)
if err != nil {
return nil, err
}
var out PARResponse
if err := json.Unmarshal(body, &out); err != nil {
return nil, fmt.Errorf("decode PAR response (%d): %w", status, err)
}
if status < 200 || status >= 300 {
return nil, errorFrom(status, body, "pushed authorization request")
}
if out.RequestURI == "" {
return nil, fmt.Errorf("pushed authorization request returned empty request_uri")
}
return &out, nil
}
func BuildAuthorizeURL(meta *AuthServerMetadata, clientID, requestURI string) string {
u, _ := url.Parse(meta.AuthorizationEndpoint)
q := u.Query()
q.Set("client_id", clientID)
q.Set("request_uri", requestURI)
u.RawQuery = q.Encode()
return u.String()
}
func (c *OAuthClient) tokenRequest(ctx context.Context, form url.Values, expectedDID, what string) (*TokenResponse, error) {
form.Set("client_id", c.ClientID)
status, body, err := c.postForm(ctx, c.Metadata.TokenEndpoint, form)
if err != nil {
return nil, err
}
var tok TokenResponse
if err := json.Unmarshal(body, &tok); err != nil {
return nil, fmt.Errorf("decode token response (%d): %w", status, err)
}
if status < 200 || status >= 300 || tok.Error != "" {
return nil, errorFrom(status, body, what)
}
if tok.AccessToken == "" {
return nil, fmt.Errorf("%s returned empty access_token", what)
}
if !slices.Contains(strings.Fields(tok.Scope), "atproto") {
return nil, fmt.Errorf("%s granted scope %q without atproto", what, tok.Scope)
}
if expectedDID != "" && tok.Sub != expectedDID {
return nil, fmt.Errorf("%s authorized %q, expected account %q", what, tok.Sub, expectedDID)
}
return &tok, nil
}
// ExchangeCode trades the authorization code for tokens, verifying the
// returned sub is the account the flow started from.
func (c *OAuthClient) ExchangeCode(ctx context.Context, code, redirectURI, codeVerifier, expectedDID string) (*TokenResponse, error) {
form := url.Values{}
form.Set("grant_type", "authorization_code")
form.Set("code", code)
form.Set("redirect_uri", redirectURI)
form.Set("code_verifier", codeVerifier)
return c.tokenRequest(ctx, form, expectedDID, "token exchange")
}
// Refresh trades a refresh token for new tokens. Refresh tokens are
// single-use: the caller must persist the replacement immediately.
func (c *OAuthClient) Refresh(ctx context.Context, refreshToken, expectedDID string) (*TokenResponse, error) {
form := url.Values{}
form.Set("grant_type", "refresh_token")
form.Set("refresh_token", refreshToken)
return c.tokenRequest(ctx, form, expectedDID, "token refresh")
}