package web
import (
"fmt"
"github.com/dolthub/dolt/go/libraries/doltcore/creds"
)
// ed25519PubKeyLen is the raw length of an Ed25519 public key. dolt encodes it
// as 52 base32 characters (creds.B32EncodedPubKeyLen) in its custom alphabet.
const ed25519PubKeyLen = 32
// decodeDoltPubKey decodes the base32 public-key string that the dolt CLI emits.
// It is exactly the string `dolt login` appends to the login URL as a fragment
// (creds.DoltCreds.PubKeyBase32Str: creds.B32CredsEncoding over the raw 32-byte
// key, custom alphabet "0123456789abcdefghijklmnopqrstuv", no padding). It
// returns the raw 32-byte key and its derived key id (kid =
// base32(SHA-512/224(pubkey)) via creds.PubKeyToKIDStr), matching exactly what
// the Bearer-JWT verifier in authn expects to look up.
//
// It validates the decoded length is exactly 32 bytes; a wrong length is a
// malformed key and is rejected loudly rather than stored.
func decodeDoltPubKey(s string) (pubkey []byte, kid string, err error) {
if s == "" {
return nil, "", fmt.Errorf("empty public key")
}
pubkey, err = creds.B32CredsEncoding.DecodeString(s)
if err != nil {
return nil, "", fmt.Errorf("invalid base32 public key: %w", err)
}
if len(pubkey) != ed25519PubKeyLen {
return nil, "", fmt.Errorf("public key must be %d bytes, got %d", ed25519PubKeyLen, len(pubkey))
}
kid = creds.PubKeyToKIDStr(pubkey)
return pubkey, kid, nil
}