jwk.go

 1package jwk
 2
 3import (
 4	"crypto"
 5	"crypto/sha256"
 6	"fmt"
 7
 8	"github.com/charmbracelet/soft-serve/pkg/config"
 9	"github.com/go-jose/go-jose/v3"
10	jwt "github.com/golang-jwt/jwt/v5"
11)
12
13// SigningMethod is a JSON Web Token signing method. It uses Ed25519 keys to
14// sign and verify tokens.
15var SigningMethod = &jwt.SigningMethodEd25519{}
16
17// Pair is a JSON Web Key pair.
18type Pair struct {
19	privateKey crypto.PrivateKey
20	jwk        jose.JSONWebKey
21}
22
23// PrivateKey returns the private key.
24func (p Pair) PrivateKey() crypto.PrivateKey {
25	return p.privateKey
26}
27
28// JWK returns the JSON Web Key.
29func (p Pair) JWK() jose.JSONWebKey {
30	return p.jwk
31}
32
33// NewPair creates a new JSON Web Key pair.
34func NewPair(cfg *config.Config) (Pair, error) {
35	kp, err := config.KeyPair(cfg)
36	if err != nil {
37		return Pair{}, err
38	}
39
40	sum := sha256.Sum256(kp.RawPrivateKey())
41	kid := fmt.Sprintf("%x", sum)
42	jwk := jose.JSONWebKey{
43		Key:       kp.CryptoPublicKey(),
44		KeyID:     kid,
45		Algorithm: SigningMethod.Alg(),
46	}
47
48	return Pair{privateKey: kp.PrivateKey(), jwk: jwk}, nil
49}