Module: BetterAuth::Plugins::JWT

Defined in:
lib/better_auth/plugins/jwt.rb

Constant Summary collapse

SUPPORTED_ALGORITHMS =
%w[EdDSA RS256 PS256 ES256 ES512].freeze

Class Method Summary collapse

Class Method Details

.public_key(jwk) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/better_auth/plugins/jwt.rb', line 14

def public_key(jwk)
  data = stringify_jwk(jwk)
  return OpenSSL::PKey.read(data["pem"] || data["publicKey"]) if data["pem"] || data["publicKey"]

  if data["kty"] == "RSA" && data["n"] && data["e"]
    rsa_from_components(data["n"], data["e"])
  elsif data["kty"] == "OKP" && data["crv"] == "Ed25519" && data["x"]
    OpenSSL::PKey.new_raw_public_key("ED25519", Crypto.base64url_decode(data["x"]))
  else
    raise OpenSSL::PKey::PKeyError, "Unsupported JWK"
  end
end

.rsa_from_components(n, e) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/better_auth/plugins/jwt.rb', line 27

def rsa_from_components(n, e)
  sequence = OpenSSL::ASN1::Sequence([
    OpenSSL::ASN1::Integer(OpenSSL::BN.new(Crypto.base64url_decode(n).unpack1("H*"), 16)),
    OpenSSL::ASN1::Integer(OpenSSL::BN.new(Crypto.base64url_decode(e).unpack1("H*"), 16))
  ])
  OpenSSL::PKey::RSA.new(sequence.to_der)
end

.stringify_jwk(value) ⇒ Object



35
36
37
# File 'lib/better_auth/plugins/jwt.rb', line 35

def stringify_jwk(value)
  value.each_with_object({}) { |(key, object_value), result| result[key.to_s] = object_value } if value.is_a?(Hash)
end