jwk.go

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