package atproto import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/json" "fmt" "math/big" "net/url" "strings" "time" ) // JWK is an EC P-256 key in JSON Web Key form. D is only set for the // private key stored in the session file; the DPoP proof header carries // the public subset (kty/crv/x/y). type JWK struct { Kty string `json:"kty"` Crv string `json:"crv"` X string `json:"x"` Y string `json:"y"` D string `json:"d,omitempty"` Kid string `json:"kid,omitempty"` } // DPoPKey is the per-session ES256 key all tokens in a session are bound // to (RFC 9449). It must be persisted with the tokens: without it the // access token cannot be used. type DPoPKey struct { priv *ecdsa.PrivateKey pub JWK } func pad32(b []byte) []byte { out := make([]byte, 32) copy(out[32-len(b):], b) return out } func publicJWK(pub *ecdsa.PublicKey) JWK { return JWK{ Kty: "EC", Crv: "P-256", X: base64.RawURLEncoding.EncodeToString(pad32(pub.X.Bytes())), Y: base64.RawURLEncoding.EncodeToString(pad32(pub.Y.Bytes())), } } // Thumbprint returns the RFC 7638 JWK thumbprint of the public key, // which servers use as the DPoP key binding (jkt) for the session. func (k *DPoPKey) Thumbprint() string { canonical := fmt.Sprintf(`{"crv":%q,"kty":%q,"x":%q,"y":%q}`, k.pub.Crv, k.pub.Kty, k.pub.X, k.pub.Y) sum := sha256.Sum256([]byte(canonical)) return base64.RawURLEncoding.EncodeToString(sum[:]) } // PrivateJWK returns the full key (including the private scalar) for // storage in the 0600 session file. func (k *DPoPKey) PrivateJWK() JWK { jwk := k.pub jwk.D = base64.RawURLEncoding.EncodeToString(pad32(k.priv.D.Bytes())) jwk.Kid = k.Thumbprint() return jwk } func GenerateDPoPKey() (*DPoPKey, error) { priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { return nil, fmt.Errorf("generate DPoP key: %w", err) } return &DPoPKey{priv: priv, pub: publicJWK(&priv.PublicKey)}, nil } func ParseDPoPKey(jwk JWK) (*DPoPKey, error) { if jwk.Kty != "EC" || jwk.Crv != "P-256" { return nil, fmt.Errorf("unsupported DPoP key type %q/%q", jwk.Kty, jwk.Crv) } x, err := base64.RawURLEncoding.DecodeString(jwk.X) if err != nil { return nil, fmt.Errorf("decode DPoP key x: %w", err) } y, err := base64.RawURLEncoding.DecodeString(jwk.Y) if err != nil { return nil, fmt.Errorf("decode DPoP key y: %w", err) } d, err := base64.RawURLEncoding.DecodeString(jwk.D) if err != nil { return nil, fmt.Errorf("decode DPoP key d: %w", err) } priv := &ecdsa.PrivateKey{ PublicKey: ecdsa.PublicKey{ Curve: elliptic.P256(), X: new(big.Int).SetBytes(x), Y: new(big.Int).SetBytes(y), }, D: new(big.Int).SetBytes(d), } if !elliptic.P256().IsOnCurve(priv.X, priv.Y) { return nil, fmt.Errorf("DPoP public key is not on P-256") } pub := jwk pub.D = "" pub.Kid = "" return &DPoPKey{priv: priv, pub: pub}, nil } // Proof builds a signed DPoP JWT for one HTTP request. A fresh proof is // required per request. accessToken, when non-empty, adds the ath claim // (required when presenting an access token to a resource server). func (k *DPoPKey) Proof(method, rawURL, nonce, accessToken string) (string, error) { u, err := url.Parse(rawURL) if err != nil { return "", fmt.Errorf("parse DPoP target URL: %w", err) } u.RawQuery = "" u.Fragment = "" jti := make([]byte, 16) if _, err := rand.Read(jti); err != nil { return "", fmt.Errorf("generate DPoP jti: %w", err) } header := map[string]any{ "typ": "dpop+jwt", "alg": "ES256", "jwk": k.pub, } claims := map[string]any{ "jti": base64.RawURLEncoding.EncodeToString(jti), "htm": strings.ToUpper(method), "htu": u.String(), "iat": time.Now().Unix(), } if nonce != "" { claims["nonce"] = nonce } if accessToken != "" { sum := sha256.Sum256([]byte(accessToken)) claims["ath"] = base64.RawURLEncoding.EncodeToString(sum[:]) } headerJSON, err := json.Marshal(header) if err != nil { return "", err } claimsJSON, err := json.Marshal(claims) if err != nil { return "", err } signingInput := base64.RawURLEncoding.EncodeToString(headerJSON) + "." + base64.RawURLEncoding.EncodeToString(claimsJSON) digest := sha256.Sum256([]byte(signingInput)) r, s, err := ecdsa.Sign(rand.Reader, k.priv, digest[:]) if err != nil { return "", fmt.Errorf("sign DPoP proof: %w", err) } sig := append(pad32(r.Bytes()), pad32(s.Bytes())...) return signingInput + "." + base64.RawURLEncoding.EncodeToString(sig), nil }