Module: RubyCoded::Auth::JWTDecoder

Defined in:
lib/ruby_coded/auth/jwt_decoder.rb

Overview

Decodes JWT tokens without external dependencies. Used to extract the ChatGPT account ID from OAuth access tokens.

Constant Summary collapse

JWT_CLAIM_PATH =
"https://api.openai.com/auth"
PLAN_CLAIM_KEYS =
%w[chatgpt_plan_type planType plan_type].freeze

Class Method Summary collapse

Class Method Details

.decode(token) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/ruby_coded/auth/jwt_decoder.rb', line 13

def self.decode(token)
  parts = token.to_s.split(".")
  return nil unless parts.size == 3

  padded = parts[1] + ("=" * ((4 - (parts[1].length % 4)) % 4))
  JSON.parse(Base64.urlsafe_decode64(padded))
rescue StandardError
  nil
end

.extract_account_id(token) ⇒ Object



23
24
25
26
# File 'lib/ruby_coded/auth/jwt_decoder.rb', line 23

def self.(token)
  payload = decode(token)
  payload&.dig(JWT_CLAIM_PATH, "chatgpt_account_id")
end

.extract_plan_type(token) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/ruby_coded/auth/jwt_decoder.rb', line 30

def self.extract_plan_type(token)
  payload = decode(token)
  return nil unless payload

  auth_claims = payload[JWT_CLAIM_PATH].is_a?(Hash) ? payload[JWT_CLAIM_PATH] : {}
  PLAN_CLAIM_KEYS.each do |key|
    value = auth_claims[key] || payload[key]
    return value.to_s.downcase if value
  end
  nil
end