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:
1 parent
653da47753
commit
fb79db4e21
9 files changed
+1531
-6
No files matched your search
+173
-5
@@ -11,12 +11,13 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"git.site.latha.org/experiments/latha-auth/internal/atproto"
|
||||
"git.site.latha.org/experiments/latha-auth/internal/gitea"
|
||||
"git.site.latha.org/experiments/latha-auth/internal/oidc"
|
||||
"git.site.latha.org/experiments/latha-auth/internal/pkce"
|
||||
)
|
||||
|
||||
const version = "0.1.0"
|
||||
const version = "0.2.0"
|
||||
|
||||
func main() {
|
||||
if len(os.Args) < 2 {
|
||||
@@ -35,6 +36,10 @@ func main() {
|
||||
err = runK3s(ctx, os.Args[2:])
|
||||
case "oidc":
|
||||
err = runOIDC(ctx, os.Args[2:])
|
||||
case "atproto":
|
||||
err = runAtproto(ctx, os.Args[2:])
|
||||
case "atproto-token":
|
||||
err = runAtprotoToken(ctx, os.Args[2:])
|
||||
case "version", "--version", "-v":
|
||||
fmt.Printf("latha-auth %s\n", version)
|
||||
return
|
||||
@@ -60,10 +65,12 @@ Usage:
|
||||
latha-auth <command> [flags]
|
||||
|
||||
Commands:
|
||||
gitea Authenticate with Gitea (git.site.latha.org) via PKCE + relay
|
||||
k3s Authenticate with K3s Headlamp (dash.latha.org) via Zitadel Device Code
|
||||
oidc Authenticate with any Zitadel service (auth.site.latha.org) via Device Code
|
||||
version Print version
|
||||
gitea Authenticate with Gitea (git.site.latha.org) via PKCE + relay
|
||||
k3s Authenticate with K3s Headlamp (dash.latha.org) via Zitadel Device Code
|
||||
oidc Authenticate with any Zitadel service (auth.site.latha.org) via Device Code
|
||||
atproto Authenticate with AT Protocol via OAuth (PAR + PKCE + DPoP) + relay
|
||||
atproto-token Print a valid atproto access token, refreshing the saved session if needed
|
||||
version Print version
|
||||
|
||||
Run 'latha-auth <command> --help' for command-specific flags.
|
||||
`)
|
||||
@@ -207,3 +214,164 @@ func runDeviceFlow(ctx context.Context, authURL, clientID, scope, outPath string
|
||||
fmt.Printf("Saved token to %s (0600).\n", resolved)
|
||||
return nil
|
||||
}
|
||||
|
||||
func runAtproto(ctx context.Context, args []string) error {
|
||||
defaultClientID := os.Getenv("LATHA_ATPROTO_CLIENT_ID")
|
||||
if defaultClientID == "" {
|
||||
defaultClientID = atproto.DefaultClientID
|
||||
}
|
||||
|
||||
fs := flag.NewFlagSet("atproto", flag.ContinueOnError)
|
||||
identifier := fs.String("identifier", "", "Account handle or DID (required unless --print-client-metadata)")
|
||||
clientID := fs.String("client-id", defaultClientID, "OAuth client_id URL serving the client metadata JSON (or LATHA_ATPROTO_CLIENT_ID)")
|
||||
scope := fs.String("scope", atproto.DefaultScope, "OAuth scope")
|
||||
relayURL := fs.String("relay-url", gitea.DefaultRelayURL, "OAuth callback relay base URL")
|
||||
redirectURI := fs.String("redirect-uri", "", "OAuth redirect URI (defaults to <relay-url>/oauth/callback)")
|
||||
outPath := fs.String("out", atproto.DefaultSessionPath, "Output session JSON path")
|
||||
plcURL := fs.String("plc-url", atproto.DefaultPLCURL, "PLC directory base URL")
|
||||
timeout := fs.Duration("timeout", 5*time.Minute, "Authorization timeout")
|
||||
printMetadata := fs.Bool("print-client-metadata", false, "Print the client metadata JSON to host at --client-id and exit")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if *redirectURI == "" {
|
||||
*redirectURI = gitea.RedirectURI(*relayURL)
|
||||
}
|
||||
|
||||
if *printMetadata {
|
||||
b, err := json.MarshalIndent(atproto.BuildClientMetadata(*clientID, *redirectURI, *scope), "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(string(b))
|
||||
return nil
|
||||
}
|
||||
if *identifier == "" {
|
||||
return fmt.Errorf("--identifier is required")
|
||||
}
|
||||
|
||||
httpClient := &http.Client{Timeout: 15 * time.Second}
|
||||
|
||||
meta, err := atproto.FetchClientMetadata(ctx, httpClient, *clientID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("fetch client metadata: %w\nhost the output of 'latha-auth atproto --print-client-metadata' at %s first", err, *clientID)
|
||||
}
|
||||
if err := meta.ValidateFor(*redirectURI, *scope); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
resolved, err := atproto.ResolveAuthServer(ctx, httpClient, *plcURL, *identifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
verifier, err := pkce.GenerateVerifier()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
state, err := pkce.GenerateState()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
key, err := atproto.GenerateDPoPKey()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
oauthClient := &atproto.OAuthClient{
|
||||
HTTP: httpClient,
|
||||
Metadata: resolved.AuthServer,
|
||||
ClientID: *clientID,
|
||||
Key: key,
|
||||
}
|
||||
par, err := oauthClient.PushAuthorizationRequest(ctx, *redirectURI, *scope, state, pkce.ChallengeS256(verifier), *identifier)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println("Open this URL in your browser to authorize AT Protocol access:")
|
||||
fmt.Println()
|
||||
fmt.Printf(" %s\n\n", atproto.BuildAuthorizeURL(resolved.AuthServer, *clientID, par.RequestURI))
|
||||
fmt.Println("Waiting for authorization callback...")
|
||||
|
||||
pollCtx, cancel := context.WithTimeout(ctx, *timeout)
|
||||
defer cancel()
|
||||
|
||||
code, err := gitea.PollRelay(pollCtx, httpClient, *relayURL, state, 2*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
tok, err := oauthClient.ExchangeCode(pollCtx, code, *redirectURI, verifier, resolved.DID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sess := atproto.NewSession(resolved, *clientID, tok, key)
|
||||
if err := atproto.SaveSessionFile(*outPath, sess); err != nil {
|
||||
return err
|
||||
}
|
||||
savedTo, _ := atproto.ExpandPath(*outPath)
|
||||
who := resolved.DID
|
||||
if resolved.Handle != "" {
|
||||
who = "@" + resolved.Handle + " (" + resolved.DID + ")"
|
||||
}
|
||||
fmt.Printf("Saved atproto session for %s to %s (0600), scope %q.\n", who, savedTo, sess.Scope)
|
||||
return nil
|
||||
}
|
||||
|
||||
func runAtprotoToken(ctx context.Context, args []string) error {
|
||||
fs := flag.NewFlagSet("atproto-token", flag.ContinueOnError)
|
||||
sessionPath := fs.String("session", atproto.DefaultSessionPath, "Session JSON path (updated in place on refresh)")
|
||||
forceRefresh := fs.Bool("refresh", false, "Refresh even if the access token is still valid")
|
||||
asJSON := fs.Bool("json", false, "Print token info as JSON instead of just the access token")
|
||||
if err := fs.Parse(args); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
sess, err := atproto.LoadSessionFile(*sessionPath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if *forceRefresh || sess.ExpiresWithin(time.Minute) {
|
||||
if sess.RefreshToken == "" {
|
||||
return fmt.Errorf("session has no refresh_token; run 'latha-auth atproto' again")
|
||||
}
|
||||
key, err := sess.DPoP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
httpClient := &http.Client{Timeout: 15 * time.Second}
|
||||
meta, err := atproto.FetchAuthServerMetadata(ctx, httpClient, sess.Issuer)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
oauthClient := &atproto.OAuthClient{
|
||||
HTTP: httpClient,
|
||||
Metadata: meta,
|
||||
ClientID: sess.ClientID,
|
||||
Key: key,
|
||||
}
|
||||
tok, err := oauthClient.Refresh(ctx, sess.RefreshToken, sess.DID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sess.ApplyToken(tok)
|
||||
if err := atproto.SaveSessionFile(*sessionPath, sess); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if *asJSON {
|
||||
b, err := json.MarshalIndent(sess.Info(), "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fmt.Println(string(b))
|
||||
return nil
|
||||
}
|
||||
fmt.Println(sess.AccessToken)
|
||||
return nil
|
||||
}
|
||||
Reference in new issue
Block a user