xdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/README.md +123 -0
  4. data/lib/xdk/client.rb +410 -0
  5. data/lib/xdk/clients/account_activity_client.rb +109 -0
  6. data/lib/xdk/clients/account_client.rb +53 -0
  7. data/lib/xdk/clients/activity_client.rb +119 -0
  8. data/lib/xdk/clients/articles_client.rb +54 -0
  9. data/lib/xdk/clients/bots_client.rb +138 -0
  10. data/lib/xdk/clients/broadcasts_client.rb +854 -0
  11. data/lib/xdk/clients/calls_client.rb +255 -0
  12. data/lib/xdk/clients/chat_client.rb +1017 -0
  13. data/lib/xdk/clients/communities_client.rb +69 -0
  14. data/lib/xdk/clients/community_notes_client.rb +147 -0
  15. data/lib/xdk/clients/compliance_client.rb +157 -0
  16. data/lib/xdk/clients/connections_client.rb +102 -0
  17. data/lib/xdk/clients/direct_messages_client.rb +269 -0
  18. data/lib/xdk/clients/general_client.rb +34 -0
  19. data/lib/xdk/clients/lists_client.rb +245 -0
  20. data/lib/xdk/clients/media_client.rb +400 -0
  21. data/lib/xdk/clients/news_client.rb +67 -0
  22. data/lib/xdk/clients/posts_client.rb +596 -0
  23. data/lib/xdk/clients/spaces_client.rb +222 -0
  24. data/lib/xdk/clients/stream_client.rb +690 -0
  25. data/lib/xdk/clients/trends_client.rb +81 -0
  26. data/lib/xdk/clients/usage_client.rb +57 -0
  27. data/lib/xdk/clients/users_client.rb +1280 -0
  28. data/lib/xdk/clients/webhooks_client.rb +164 -0
  29. data/lib/xdk/errors.rb +69 -0
  30. data/lib/xdk/http_client.rb +126 -0
  31. data/lib/xdk/oauth1.rb +183 -0
  32. data/lib/xdk/oauth2_pkce.rb +156 -0
  33. data/lib/xdk/paginator.rb +41 -0
  34. data/lib/xdk/streaming.rb +294 -0
  35. data/lib/xdk/version.rb +9 -0
  36. data/lib/xdk.rb +62 -0
  37. metadata +84 -0
@@ -0,0 +1,164 @@
1
+ # AUTO-GENERATED FILE - DO NOT EDIT
2
+ # This file was automatically generated by the XDK build tool.
3
+ # Any manual changes will be overwritten on the next generation.
4
+ # frozen_string_literal: true
5
+
6
+ require "uri"
7
+
8
+ module Xdk
9
+ module Clients
10
+ # Auto-generated webhooks client for the X API v2.
11
+ class WebhooksClient
12
+ def initialize(client)
13
+ @client = client
14
+ end
15
+
16
+ # Create Replay Job for Webhook
17
+ def create_webhook_replay_job(body:)
18
+ path = +"/2/webhooks/replay"
19
+
20
+ query = {}
21
+
22
+ headers = {}
23
+ @client.execute_request(
24
+ method: "POST",
25
+ path: path,
26
+ schemes: ["BearerToken"],
27
+ query: query,
28
+ headers: headers,
29
+ body: body,
30
+ binary_request: false,
31
+ binary_response: false
32
+ )
33
+ end
34
+
35
+ # Create Stream Link
36
+ def create_stream_link(webhook_id:)
37
+ path = +"/2/tweets/search/webhooks/{webhook_id}"
38
+ path.gsub!("{webhook_id}", URI.encode_www_form_component(webhook_id.to_s))
39
+
40
+ query = {}
41
+
42
+ headers = {}
43
+ @client.execute_request(
44
+ method: "POST",
45
+ path: path,
46
+ schemes: ["BearerToken"],
47
+ query: query,
48
+ headers: headers,
49
+ binary_response: false
50
+ )
51
+ end
52
+
53
+ # Delete Stream Link
54
+ def delete_stream_link(webhook_id:)
55
+ path = +"/2/tweets/search/webhooks/{webhook_id}"
56
+ path.gsub!("{webhook_id}", URI.encode_www_form_component(webhook_id.to_s))
57
+
58
+ query = {}
59
+
60
+ headers = {}
61
+ @client.execute_request(
62
+ method: "DELETE",
63
+ path: path,
64
+ schemes: ["BearerToken"],
65
+ query: query,
66
+ headers: headers,
67
+ binary_response: false
68
+ )
69
+ end
70
+
71
+ # Validate Webhook
72
+ def validate(webhook_id:)
73
+ path = +"/2/webhooks/{webhook_id}"
74
+ path.gsub!("{webhook_id}", URI.encode_www_form_component(webhook_id.to_s))
75
+
76
+ query = {}
77
+
78
+ headers = {}
79
+ @client.execute_request(
80
+ method: "PUT",
81
+ path: path,
82
+ schemes: ["BearerToken", "OAuth2UserToken", "UserToken"],
83
+ query: query,
84
+ headers: headers,
85
+ binary_response: false
86
+ )
87
+ end
88
+
89
+ # Delete Webhook
90
+ def delete(webhook_id:)
91
+ path = +"/2/webhooks/{webhook_id}"
92
+ path.gsub!("{webhook_id}", URI.encode_www_form_component(webhook_id.to_s))
93
+
94
+ query = {}
95
+
96
+ headers = {}
97
+ @client.execute_request(
98
+ method: "DELETE",
99
+ path: path,
100
+ schemes: ["BearerToken", "OAuth2UserToken", "UserToken"],
101
+ query: query,
102
+ headers: headers,
103
+ binary_response: false
104
+ )
105
+ end
106
+
107
+ # Get Stream Links
108
+ def get_stream_links()
109
+ path = +"/2/tweets/search/webhooks"
110
+
111
+ query = {}
112
+
113
+ headers = {}
114
+ @client.execute_request(
115
+ method: "GET",
116
+ path: path,
117
+ schemes: ["BearerToken"],
118
+ query: query,
119
+ headers: headers,
120
+ binary_response: false
121
+ )
122
+ end
123
+
124
+ # Get Webhook
125
+ def get(webhook_config_fields: nil)
126
+ path = +"/2/webhooks"
127
+
128
+ query = {}
129
+ unless webhook_config_fields.nil?
130
+ query["webhook_config.fields"] = webhook_config_fields.is_a?(Array) ? webhook_config_fields.map(&:to_s).join(",") : webhook_config_fields.to_s
131
+ end
132
+
133
+ headers = {}
134
+ @client.execute_request(
135
+ method: "GET",
136
+ path: path,
137
+ schemes: ["BearerToken", "OAuth2UserToken", "UserToken"],
138
+ query: query,
139
+ headers: headers,
140
+ binary_response: false
141
+ )
142
+ end
143
+
144
+ # Create Webhook
145
+ def create(body:)
146
+ path = +"/2/webhooks"
147
+
148
+ query = {}
149
+
150
+ headers = {}
151
+ @client.execute_request(
152
+ method: "POST",
153
+ path: path,
154
+ schemes: ["BearerToken", "OAuth2UserToken", "UserToken"],
155
+ query: query,
156
+ headers: headers,
157
+ body: body,
158
+ binary_request: false,
159
+ binary_response: false
160
+ )
161
+ end
162
+ end
163
+ end
164
+ end
data/lib/xdk/errors.rb ADDED
@@ -0,0 +1,69 @@
1
+ # AUTO-GENERATED FILE - DO NOT EDIT
2
+ # This file was automatically generated by the XDK build tool.
3
+ # Any manual changes will be overwritten on the next generation.
4
+ # frozen_string_literal: true
5
+
6
+ require "json"
7
+
8
+ module Xdk
9
+ # Base exception for all XDK errors.
10
+ class Error < StandardError; end
11
+
12
+ # Raised when required authentication credentials are missing or invalid.
13
+ class AuthenticationError < Error; end
14
+
15
+ # Raised when pagination encounters an invalid configuration or state.
16
+ class PaginationError < Error; end
17
+
18
+ # Raised when the X API returns a non-2xx HTTP status code.
19
+ class ApiError < Error
20
+ attr_reader :status, :headers, :body, :json, :request_id, :retry_after
21
+
22
+ def initialize(status:, body: "", headers: {}, message: nil)
23
+ @status = status.to_i
24
+ @headers = normalize_headers(headers)
25
+ @body = body.to_s
26
+ @json = parse_json(@body)
27
+ @request_id = @headers["x-request-id"]
28
+ @retry_after = parse_retry_after(@headers["retry-after"])
29
+ super(message || build_message)
30
+ end
31
+
32
+ private
33
+
34
+ def normalize_headers(raw)
35
+ return {} unless raw
36
+
37
+ out = {}
38
+ raw.each { |k, v| out[k.to_s.downcase] = v.is_a?(Array) ? v.first : v }
39
+ out
40
+ end
41
+
42
+ def parse_json(text)
43
+ return nil if text.nil? || text.empty?
44
+
45
+ JSON.parse(text)
46
+ rescue JSON::ParserError
47
+ nil
48
+ end
49
+
50
+ def parse_retry_after(raw)
51
+ return nil if raw.nil? || raw.to_s.empty?
52
+
53
+ Float(raw)
54
+ rescue ArgumentError, TypeError
55
+ nil
56
+ end
57
+
58
+ def build_message
59
+ detail = if @json.is_a?(Hash)
60
+ @json["detail"] || @json["title"] || @json["error_description"] || @json["error"]
61
+ end
62
+ msg = +"HTTP #{@status}"
63
+ msg << ": #{detail}" if detail && !detail.to_s.empty?
64
+ msg << " (x-request-id: #{@request_id})" if @request_id && !@request_id.empty?
65
+ msg << ": #{@body[0, 300]}" if (!detail || detail.to_s.empty?) && !@body.empty?
66
+ msg
67
+ end
68
+ end
69
+ end
@@ -0,0 +1,126 @@
1
+ # AUTO-GENERATED FILE - DO NOT EDIT
2
+ # This file was automatically generated by the XDK build tool.
3
+ # Any manual changes will be overwritten on the next generation.
4
+ # frozen_string_literal: true
5
+
6
+ require "json"
7
+ require "net/http"
8
+ require "openssl"
9
+ require "uri"
10
+
11
+ module Xdk
12
+ # Response wrapper returned by {HttpClient#request}.
13
+ HttpResponse = Struct.new(:status, :headers, :body, keyword_init: true)
14
+
15
+ # Low-level Net::HTTP transport with timeout, User-Agent, and retry handling.
16
+ class HttpClient
17
+ RETRYABLE_STATUSES = [429, 500, 502, 503, 504].freeze
18
+ MAX_RETRY_AFTER = 5.0
19
+
20
+ attr_accessor :timeout, :max_retries, :retry_backoff, :http_adapter
21
+
22
+ def initialize(timeout: nil, max_retries: 0, retry_backoff: 0.5, http_adapter: nil)
23
+ @timeout = timeout
24
+ @max_retries = max_retries.to_i
25
+ @retry_backoff = retry_backoff.to_f
26
+ @http_adapter = http_adapter
27
+ end
28
+
29
+ # Execute an HTTP request, rebuilding headers on each attempt via
30
+ # headers_factory (so OAuth 1.0a nonces and OAuth 2.0 tokens stay fresh).
31
+ def request(method:, url:, query: nil, headers_factory: nil, headers: {}, body: nil)
32
+ full_url = append_query(url, query)
33
+ attempt = 0
34
+
35
+ loop do
36
+ req_headers = headers_factory ? headers_factory.call : headers.dup
37
+ req_headers = { "User-Agent" => Xdk::USER_AGENT }.merge(req_headers)
38
+
39
+ response = dispatch(method: method, url: full_url, headers: req_headers, body: body)
40
+ if @max_retries > 0 && attempt < @max_retries && RETRYABLE_STATUSES.include?(response.status)
41
+ delay = compute_delay(response.headers, attempt)
42
+ attempt += 1
43
+ sleep(delay) if delay > 0
44
+ next
45
+ end
46
+
47
+ return response
48
+ end
49
+ end
50
+
51
+ def append_query(url, query)
52
+ return url if query.nil? || query.empty?
53
+
54
+ qs = URI.encode_www_form(query)
55
+ return url if qs.empty?
56
+
57
+ url.include?("?") ? "#{url}&#{qs}" : "#{url}?#{qs}"
58
+ end
59
+
60
+ private
61
+
62
+ def dispatch(method:, url:, headers:, body:)
63
+ if @http_adapter
64
+ res = @http_adapter.call(method: method, url: url, headers: headers, body: body, timeout: @timeout)
65
+ return res if res.is_a?(HttpResponse)
66
+
67
+ return HttpResponse.new(
68
+ status: res[:status] || res["status"],
69
+ headers: res[:headers] || res["headers"] || {},
70
+ body: res[:body] || res["body"] || ""
71
+ )
72
+ end
73
+
74
+ uri = URI.parse(url)
75
+ http = Net::HTTP.new(uri.host, uri.port)
76
+ http.use_ssl = uri.scheme == "https"
77
+ if @timeout
78
+ http.open_timeout = @timeout
79
+ http.read_timeout = @timeout
80
+ end
81
+
82
+ req_class = net_http_class(method)
83
+ request_target = uri.request_uri
84
+ req = req_class.new(request_target)
85
+ headers.each { |k, v| req[k] = v.to_s unless v.nil? }
86
+ req.body = body unless body.nil?
87
+
88
+ res = http.request(req)
89
+ resp_headers = {}
90
+ res.each_header { |k, v| resp_headers[k.downcase] = v }
91
+ HttpResponse.new(
92
+ status: res.code.to_i,
93
+ headers: resp_headers,
94
+ body: res.body || "".b
95
+ )
96
+ end
97
+
98
+ def net_http_class(method)
99
+ case method.to_s.upcase
100
+ when "GET" then Net::HTTP::Get
101
+ when "POST" then Net::HTTP::Post
102
+ when "PUT" then Net::HTTP::Put
103
+ when "DELETE" then Net::HTTP::Delete
104
+ when "PATCH" then Net::HTTP::Patch
105
+ when "HEAD" then Net::HTTP::Head
106
+ when "OPTIONS" then Net::HTTP::Options
107
+ else
108
+ raise ArgumentError, "Unsupported HTTP method: #{method}"
109
+ end
110
+ end
111
+
112
+ def compute_delay(headers, attempt)
113
+ delay = @retry_backoff * (2**attempt)
114
+ retry_after = headers["retry-after"] || headers["Retry-After"]
115
+ if retry_after
116
+ begin
117
+ parsed = Float(retry_after)
118
+ delay = [parsed, MAX_RETRY_AFTER].min if parsed >= 0
119
+ rescue ArgumentError, TypeError
120
+ # Ignore unparseable Retry-After values
121
+ end
122
+ end
123
+ delay > 0 ? delay : 0.0
124
+ end
125
+ end
126
+ end
data/lib/xdk/oauth1.rb ADDED
@@ -0,0 +1,183 @@
1
+ # AUTO-GENERATED FILE - DO NOT EDIT
2
+ # This file was automatically generated by the XDK build tool.
3
+ # Any manual changes will be overwritten on the next generation.
4
+ # frozen_string_literal: true
5
+
6
+ require "net/http"
7
+ require "openssl"
8
+ require "securerandom"
9
+ require "uri"
10
+
11
+ module Xdk
12
+ OAuth1RequestToken = Struct.new(:oauth_token, :oauth_token_secret, keyword_init: true)
13
+ OAuth1AccessToken = Struct.new(:access_token, :access_token_secret, keyword_init: true)
14
+
15
+ # OAuth 1.0a (HMAC-SHA1) authentication handler for the X API.
16
+ class OAuth1
17
+ attr_reader :api_key, :api_secret, :callback, :base_url
18
+ attr_accessor :request_token, :access_token
19
+
20
+ def initialize(
21
+ api_key:,
22
+ api_secret:,
23
+ callback: "oob",
24
+ access_token: nil,
25
+ access_token_secret: nil,
26
+ base_url: "https://api.x.com"
27
+ )
28
+ @api_key = api_key
29
+ @api_secret = api_secret
30
+ @callback = callback
31
+ @base_url = base_url.chomp("/")
32
+ @request_token = nil
33
+ @access_token = if access_token && access_token_secret
34
+ OAuth1AccessToken.new(
35
+ access_token: access_token,
36
+ access_token_secret: access_token_secret
37
+ )
38
+ end
39
+ end
40
+
41
+ def get_authorization_url(login_with_x: false)
42
+ unless @request_token
43
+ raise AuthenticationError, "Request token not obtained. Call get_request_token first."
44
+ end
45
+
46
+ base = login_with_x ? "https://x.com/i/oauth/authenticate" : "https://x.com/oauth/authorize"
47
+ "#{base}?#{URI.encode_www_form('oauth_token' => @request_token.oauth_token)}"
48
+ end
49
+
50
+ def get_request_token
51
+ url = "#{@base_url}/oauth/request_token"
52
+ params = { "oauth_callback" => @callback }
53
+ @request_token = nil
54
+ @access_token = nil
55
+
56
+ full_url = "#{url}?#{URI.encode_www_form(params)}"
57
+ header = build_oauth_header(method: "POST", url: full_url, extra_oauth: { "oauth_callback" => @callback })
58
+ res = post_oauth(full_url, header)
59
+ parsed = URI.decode_www_form(res.body.to_s).to_h
60
+
61
+ token = parsed["oauth_token"]
62
+ secret = parsed["oauth_token_secret"]
63
+ raise AuthenticationError, "Invalid response from request token endpoint" unless token && secret
64
+
65
+ @request_token = OAuth1RequestToken.new(oauth_token: token, oauth_token_secret: secret)
66
+ end
67
+
68
+ def get_access_token(verifier)
69
+ unless @request_token
70
+ raise AuthenticationError, "Request token not obtained. Call get_request_token first."
71
+ end
72
+
73
+ url = "#{@base_url}/oauth/access_token"
74
+ params = {
75
+ "oauth_token" => @request_token.oauth_token,
76
+ "oauth_verifier" => verifier.to_s
77
+ }
78
+ full_url = "#{url}?#{URI.encode_www_form(params)}"
79
+ header = build_oauth_header(
80
+ method: "POST",
81
+ url: full_url,
82
+ token: @request_token.oauth_token,
83
+ token_secret: @request_token.oauth_token_secret,
84
+ extra_oauth: { "oauth_verifier" => verifier.to_s }
85
+ )
86
+ res = post_oauth(full_url, header)
87
+ parsed = URI.decode_www_form(res.body.to_s).to_h
88
+
89
+ token = parsed["oauth_token"]
90
+ secret = parsed["oauth_token_secret"]
91
+ raise AuthenticationError, "Invalid response from access token endpoint" unless token && secret
92
+
93
+ @access_token = OAuth1AccessToken.new(access_token: token, access_token_secret: secret)
94
+ end
95
+
96
+ # Build an RFC 5849 OAuth 1.0a Authorization header for an API request.
97
+ def build_request_header(method:, url:, body: "", timestamp: nil, nonce: nil)
98
+ build_oauth_header(
99
+ method: method,
100
+ url: url,
101
+ token: @access_token&.access_token,
102
+ token_secret: @access_token&.access_token_secret,
103
+ timestamp: timestamp,
104
+ nonce: nonce
105
+ )
106
+ end
107
+
108
+ # RFC 3986 percent encoding required by RFC 5849 section 3.6.
109
+ def self.percent_encode(value)
110
+ value.to_s.encode(Encoding::UTF_8).bytes.map do |b|
111
+ ch = b.chr
112
+ if (b >= 0x41 && b <= 0x5A) || (b >= 0x61 && b <= 0x7A) ||
113
+ (b >= 0x30 && b <= 0x39) || ch == "-" || ch == "." || ch == "_" || ch == "~"
114
+ ch
115
+ else
116
+ format("%%%02X", b)
117
+ end
118
+ end.join
119
+ end
120
+
121
+ private
122
+
123
+ def build_oauth_header(method:, url:, token: nil, token_secret: nil, extra_oauth: {}, timestamp: nil, nonce: nil)
124
+ uri = URI.parse(url)
125
+ base_url = "#{uri.scheme.downcase}://#{uri.host.downcase}"
126
+ default_port = uri.scheme.downcase == "https" ? 443 : 80
127
+ base_url = "#{base_url}:#{uri.port}" if uri.port && uri.port != default_port
128
+ base_url = "#{base_url}#{uri.path.nil? || uri.path.empty? ? '/' : uri.path}"
129
+
130
+ oauth_params = {
131
+ "oauth_consumer_key" => @api_key,
132
+ "oauth_nonce" => (nonce || SecureRandom.hex(16)).to_s,
133
+ "oauth_signature_method" => "HMAC-SHA1",
134
+ "oauth_timestamp" => (timestamp || Time.now.to_i).to_s,
135
+ "oauth_version" => "1.0"
136
+ }
137
+ oauth_params["oauth_token"] = token if token && !token.empty?
138
+ extra_oauth.each { |k, v| oauth_params[k] = v }
139
+
140
+ all_params = []
141
+ if uri.query && !uri.query.empty?
142
+ URI.decode_www_form(uri.query).each do |k, v|
143
+ all_params << [self.class.percent_encode(k), self.class.percent_encode(v)]
144
+ end
145
+ end
146
+ oauth_params.each do |k, v|
147
+ all_params << [self.class.percent_encode(k), self.class.percent_encode(v)]
148
+ end
149
+ all_params.sort!
150
+
151
+ param_string = all_params.map { |k, v| "#{k}=#{v}" }.join("&")
152
+ signature_base = [
153
+ method.to_s.upcase,
154
+ self.class.percent_encode(base_url),
155
+ self.class.percent_encode(param_string)
156
+ ].join("&")
157
+
158
+ signing_key = "#{self.class.percent_encode(@api_secret)}&#{self.class.percent_encode(token_secret.to_s)}"
159
+ digest = OpenSSL::HMAC.digest("SHA1", signing_key, signature_base)
160
+ oauth_params["oauth_signature"] = [digest].pack("m0")
161
+
162
+ header_parts = oauth_params.keys.sort.map do |k|
163
+ "#{self.class.percent_encode(k)}=\"#{self.class.percent_encode(oauth_params[k])}\""
164
+ end
165
+ "OAuth #{header_parts.join(', ')}"
166
+ end
167
+
168
+ def post_oauth(url, auth_header)
169
+ uri = URI.parse(url)
170
+ http = Net::HTTP.new(uri.host, uri.port)
171
+ http.use_ssl = uri.scheme == "https"
172
+ req = Net::HTTP::Post.new(uri.request_uri)
173
+ req["Authorization"] = auth_header
174
+ req["User-Agent"] = Xdk::USER_AGENT
175
+ res = http.request(req)
176
+ unless res.code.to_i.between?(200, 299)
177
+ raise ApiError.new(status: res.code.to_i, body: res.body.to_s, headers: res.to_hash)
178
+ end
179
+
180
+ res
181
+ end
182
+ end
183
+ end
@@ -0,0 +1,156 @@
1
+ # AUTO-GENERATED FILE - DO NOT EDIT
2
+ # This file was automatically generated by the XDK build tool.
3
+ # Any manual changes will be overwritten on the next generation.
4
+ # frozen_string_literal: true
5
+
6
+ require "digest"
7
+ require "json"
8
+ require "net/http"
9
+ require "securerandom"
10
+ require "uri"
11
+
12
+ module Xdk
13
+ # OAuth 2.0 PKCE (S256) authentication handler for the X API.
14
+ class OAuth2PKCEAuth
15
+ attr_reader :base_url, :authorization_base_url, :client_id, :client_secret,
16
+ :redirect_uri, :scope, :code_verifier, :code_challenge
17
+ attr_accessor :token
18
+
19
+ def initialize(
20
+ base_url: "https://api.x.com",
21
+ authorization_base_url: "https://x.com/i",
22
+ client_id: nil,
23
+ client_secret: nil,
24
+ redirect_uri: nil,
25
+ token: nil,
26
+ scope: nil
27
+ )
28
+ @base_url = base_url.chomp("/")
29
+ @authorization_base_url = authorization_base_url.chomp("/")
30
+ @client_id = client_id
31
+ @client_secret = client_secret
32
+ @redirect_uri = redirect_uri
33
+ @token = token ? stringify_keys(token) : nil
34
+ @scope = scope.is_a?(Array) ? scope.join(" ") : scope
35
+ @code_verifier = nil
36
+ @code_challenge = nil
37
+
38
+ if @token && @token["expires_in"] && !@token.key?("expires_at")
39
+ @token["expires_at"] = Time.now.to_f + @token["expires_in"].to_f
40
+ end
41
+ end
42
+
43
+ def access_token
44
+ @token ? @token["access_token"] : nil
45
+ end
46
+
47
+ def set_pkce_parameters(code_verifier, code_challenge = nil)
48
+ @code_verifier = code_verifier
49
+ @code_challenge = code_challenge || generate_code_challenge(code_verifier)
50
+ end
51
+
52
+ def get_authorization_url(state: nil)
53
+ if @code_verifier.nil? || @code_challenge.nil?
54
+ @code_verifier = generate_code_verifier
55
+ @code_challenge = generate_code_challenge(@code_verifier)
56
+ end
57
+
58
+ params = {
59
+ "response_type" => "code",
60
+ "client_id" => @client_id,
61
+ "redirect_uri" => @redirect_uri,
62
+ "code_challenge" => @code_challenge,
63
+ "code_challenge_method" => "S256"
64
+ }
65
+ params["scope"] = @scope if @scope && !@scope.empty?
66
+ params["state"] = state if state && !state.empty?
67
+
68
+ "#{@authorization_base_url}/oauth2/authorize?#{URI.encode_www_form(params)}"
69
+ end
70
+
71
+ def exchange_code(code, code_verifier: nil)
72
+ verifier = code_verifier || @code_verifier
73
+ unless verifier && !verifier.empty?
74
+ raise AuthenticationError, "Code verifier is required. Call get_authorization_url or set_pkce_parameters first."
75
+ end
76
+
77
+ params = {
78
+ "grant_type" => "authorization_code",
79
+ "code" => code,
80
+ "redirect_uri" => @redirect_uri,
81
+ "code_verifier" => verifier
82
+ }
83
+ post_token(params)
84
+ end
85
+
86
+ def fetch_token(authorization_response)
87
+ uri = URI.parse(authorization_response)
88
+ query = URI.decode_www_form(uri.query.to_s).to_h
89
+ code = query["code"]
90
+ raise AuthenticationError, "No authorization code found in callback URL" unless code && !code.empty?
91
+
92
+ exchange_code(code)
93
+ end
94
+
95
+ def refresh_token
96
+ refresh = @token && @token["refresh_token"]
97
+ raise AuthenticationError, "No refresh token available" unless refresh && !refresh.empty?
98
+
99
+ params = {
100
+ "grant_type" => "refresh_token",
101
+ "refresh_token" => refresh
102
+ }
103
+ post_token(params)
104
+ end
105
+
106
+ def token_expired?
107
+ return true unless @token && @token["access_token"]
108
+ return false unless @token["expires_at"]
109
+
110
+ Time.now.to_f >= (@token["expires_at"].to_f - 10.0)
111
+ end
112
+
113
+ private
114
+
115
+ def generate_code_verifier
116
+ SecureRandom.urlsafe_base64(96)[0, 128]
117
+ end
118
+
119
+ def generate_code_challenge(verifier)
120
+ digest = Digest::SHA256.digest(verifier.encode(Encoding::UTF_8))
121
+ [digest].pack("m0").tr("+/", "-_").delete("=")
122
+ end
123
+
124
+ def post_token(params)
125
+ uri = URI.parse("#{@base_url}/2/oauth2/token")
126
+ http = Net::HTTP.new(uri.host, uri.port)
127
+ http.use_ssl = uri.scheme == "https"
128
+ req = Net::HTTP::Post.new(uri.request_uri)
129
+ req["Content-Type"] = "application/x-www-form-urlencoded"
130
+ req["User-Agent"] = Xdk::USER_AGENT
131
+
132
+ if @client_secret && !@client_secret.empty?
133
+ creds = ["#{@client_id}:#{@client_secret}".b].pack("m0")
134
+ req["Authorization"] = "Basic #{creds}"
135
+ else
136
+ params["client_id"] = @client_id
137
+ end
138
+
139
+ req.body = URI.encode_www_form(params)
140
+ res = http.request(req)
141
+ unless res.code.to_i.between?(200, 299)
142
+ raise ApiError.new(status: res.code.to_i, body: res.body.to_s, headers: res.to_hash)
143
+ end
144
+
145
+ parsed = JSON.parse(res.body)
146
+ if parsed["expires_in"]
147
+ parsed["expires_at"] = Time.now.to_f + parsed["expires_in"].to_f
148
+ end
149
+ @token = parsed
150
+ end
151
+
152
+ def stringify_keys(hash)
153
+ hash.each_with_object({}) { |(k, v), out| out[k.to_s] = v }
154
+ end
155
+ end
156
+ end