Class: Privy::JwtExchangeService

Inherits:
Object
  • Object
show all
Defined in:
lib/privy/authorization/jwt_exchange.rb

Constant Summary collapse

DEFAULT_CACHE_MAX_CAPACITY =
1000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(wallets_resource:, cache_max_capacity: DEFAULT_CACHE_MAX_CAPACITY) ⇒ JwtExchangeService

Returns a new instance of JwtExchangeService.



11
12
13
14
15
16
17
# File 'lib/privy/authorization/jwt_exchange.rb', line 11

def initialize(wallets_resource:, cache_max_capacity: DEFAULT_CACHE_MAX_CAPACITY)
  @wallets = wallets_resource
  @hpke_recipient = Privy::Cryptography::HpkeRecipient.new
  @cache = {}
  @cache_max_capacity = cache_max_capacity
  @mutex = Mutex.new
end

Instance Attribute Details

#cache_max_capacityObject (readonly)

Returns the value of attribute cache_max_capacity.



9
10
11
# File 'lib/privy/authorization/jwt_exchange.rb', line 9

def cache_max_capacity
  @cache_max_capacity
end

Instance Method Details

#exchange_jwt_for_authorization_key(jwt) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/privy/authorization/jwt_exchange.rb', line 19

def exchange_jwt_for_authorization_key(jwt)
  cached = get_cached(jwt)
  return cached if cached

  response = @wallets.authenticate_with_jwt(
    user_jwt: jwt,
    encryption_type: :HPKE,
    recipient_public_key: Base64.strict_encode64(@hpke_recipient.public_key_spki)
  )

  encrypted = response.encrypted_authorization_key
  unless encrypted && encrypted.encryption_type.to_s == "HPKE"
    raise Privy::Errors::Error, "JWT exchange failed: unsupported encryption type"
  end

  decrypted_key = @hpke_recipient.decrypt(
    Base64.strict_decode64(encrypted.encapsulated_key),
    Base64.strict_decode64(encrypted.ciphertext)
  )

  authorization_key = decrypted_key.force_encoding("UTF-8")
  cache_put(jwt, authorization_key, response.expires_at)
  authorization_key
end