turbodocx-sdk 0.9.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.
@@ -0,0 +1,325 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require_relative "http_client"
5
+
6
+ module TurboDocxSdk
7
+ # The fixed name used for the single SDK-managed webhook per org.
8
+ # Mirrors the convention enforced by the UI's Signature Webhooks settings.
9
+ SIGNATURE_WEBHOOK_NAME = "signature"
10
+
11
+ # TurboWebhooks module -- org-scoped signature webhook subscription.
12
+ #
13
+ # The SDK is intentionally locked to a single webhook per org, identified by
14
+ # the fixed name +signature+. This matches the UI's "Signature Webhooks"
15
+ # settings page so SDK-created webhooks show up where users expect to manage
16
+ # them. To manage multiple webhooks per org, call the REST API directly.
17
+ #
18
+ # All routes require an administrator TDX- API key. Webhook management does
19
+ # not send signature emails, so +skip_sender_validation: true+ is hardcoded
20
+ # inside +configure+ and +get_client+.
21
+ #
22
+ # POST/PATCH responses come back as +{ data, message }+ envelopes which
23
+ # +smart_unwrap+ leaves intact (it only unwraps single-key +{ data }+).
24
+ # Methods that hit non-GET routes extract +["data"]+ explicitly. GET routes
25
+ # are auto-unwrapped by the HttpClient.
26
+ #
27
+ # TurboDocxSdk::TurboWebhooks.configure(api_key: "...", org_id: "...")
28
+ # created = TurboDocxSdk::TurboWebhooks.create_webhook(
29
+ # urls: ["https://example.com/hook"],
30
+ # events: [TurboDocxSdk::WebhookEvent::RECIPIENT_SIGNED,
31
+ # TurboDocxSdk::WebhookEvent::COMPLETED]
32
+ # )
33
+ #
34
+ class TurboWebhooks
35
+ class << self
36
+ # Configure the TurboWebhooks module with API credentials.
37
+ #
38
+ # Hardcodes +skip_sender_validation: true+ -- webhook management never
39
+ # sends signature emails.
40
+ #
41
+ # @param api_key [String, nil]
42
+ # @param access_token [String, nil]
43
+ # @param org_id [String, nil]
44
+ # @param base_url [String, nil]
45
+ # @raise [AuthenticationError] if no API key or access token is provided
46
+ def configure(api_key: nil, access_token: nil, org_id: nil, base_url: nil)
47
+ @client = HttpClient.new(
48
+ api_key: api_key,
49
+ access_token: access_token,
50
+ org_id: org_id,
51
+ base_url: base_url,
52
+ skip_sender_validation: true
53
+ )
54
+ end
55
+
56
+ # Create the org's signature webhook. The returned +secret+ is shown
57
+ # ONCE; store it on receipt -- it cannot be retrieved later.
58
+ #
59
+ # If a webhook named +signature+ already exists, the backend returns 409
60
+ # ConflictError. Update the existing webhook with +update_webhook+ or
61
+ # delete it first.
62
+ #
63
+ # @param urls [Array<String>] HTTPS-only endpoint URLs, 1-10 (HTTP returns 400)
64
+ # @param events [Array<String>] subscribed event types (at least 1). Prefer
65
+ # the +TurboDocxSdk::WebhookEvent+ constants (+WebhookEvent::COMPLETED+, or
66
+ # +WebhookEvent::ALL+ for every event) over raw strings. Raw strings still
67
+ # work, so new backend events need no gem bump.
68
+ # @return [Hash] { "id" => ..., "secret" => ... }
69
+ # @raise [ConflictError] if the signature webhook already exists
70
+ # @raise [ValidationError] on invalid request data (e.g. non-HTTPS url)
71
+ def create_webhook(urls:, events:)
72
+ client = get_client
73
+ envelope = client.post(
74
+ "/api/webhooks",
75
+ { "name" => SIGNATURE_WEBHOOK_NAME, "urls" => urls, "events" => events }
76
+ )
77
+ envelope["data"]
78
+ end
79
+
80
+ # Get the org's signature webhook with delivery stats + available events.
81
+ #
82
+ # @return [Hash] the webhook with "deliveryStats" and "availableEvents"
83
+ # @raise [NotFoundError] if the signature webhook does not exist
84
+ def get_webhook
85
+ get_client.get("/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}")
86
+ end
87
+
88
+ # Patch one or more fields on the signature webhook. Only fields the
89
+ # caller explicitly provides are sent; untouched fields are omitted.
90
+ #
91
+ # +urls+ and +events+ stay +min(1)+ on the backend even though they are
92
+ # optional on PATCH, so an empty/nil array is a 400 rather than a "clear
93
+ # this field" instruction. Both are rejected client-side instead: to leave
94
+ # a field untouched, omit the keyword entirely.
95
+ #
96
+ # @param urls [Array<String>] HTTPS-only endpoint URLs (1-10)
97
+ # @param events [Array<String>] subscribed event types (at least 1)
98
+ # @param is_active [Boolean] enable/disable delivery
99
+ # @return [Hash] the updated webhook
100
+ # @raise [NotFoundError] if the signature webhook does not exist
101
+ # @raise [ValidationError] if urls or events is provided but empty/nil, or
102
+ # on invalid request data (e.g. non-HTTPS url)
103
+ def update_webhook(urls: :__unset, events: :__unset, is_active: :__unset)
104
+ patch = {}
105
+
106
+ unless urls == :__unset
107
+ if urls.nil? || urls.empty?
108
+ raise ValidationError,
109
+ "urls must contain at least one URL. Omit the urls: argument to leave it unchanged."
110
+ end
111
+
112
+ patch["urls"] = urls
113
+ end
114
+
115
+ unless events == :__unset
116
+ if events.nil? || events.empty?
117
+ raise ValidationError,
118
+ "events must contain at least one event type. Omit the events: argument to leave it unchanged."
119
+ end
120
+
121
+ patch["events"] = events
122
+ end
123
+
124
+ patch["isActive"] = is_active unless is_active == :__unset
125
+
126
+ envelope = get_client.patch("/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}", patch)
127
+ envelope["data"]
128
+ end
129
+
130
+ # Soft-delete the signature webhook and its delivery history.
131
+ #
132
+ # @return [Hash] { "message" => ... }
133
+ # @raise [NotFoundError] if the signature webhook does not exist
134
+ def delete_webhook
135
+ get_client.delete("/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}")
136
+ end
137
+
138
+ # Send a test delivery to all URLs configured on the signature webhook.
139
+ #
140
+ # @param event_type [String] the event type to simulate
141
+ # @param payload [Hash] the event payload
142
+ # @return [Hash] { "deliveries" => [...], "summary" => {...} }
143
+ def test_webhook(event_type:, payload:)
144
+ envelope = get_client.post(
145
+ "/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}/test",
146
+ { "eventType" => event_type, "payload" => payload }
147
+ )
148
+ envelope["data"]
149
+ end
150
+
151
+ # Send a manual notification to all URLs configured on the signature
152
+ # webhook. Routes through the same backend handler as +test_webhook+ --
153
+ # only the response/error message strings differ.
154
+ #
155
+ # @param event_type [String] the event type to send
156
+ # @param payload [Hash] the event payload
157
+ # @return [Hash] { "deliveries" => [...], "summary" => {...} }
158
+ def notify_webhook(event_type:, payload:)
159
+ envelope = get_client.post(
160
+ "/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}/notify",
161
+ { "eventType" => event_type, "payload" => payload }
162
+ )
163
+ envelope["data"]
164
+ end
165
+
166
+ # Rotate the webhook's HMAC secret. The new secret is shown ONCE; old
167
+ # signatures will fail immediately.
168
+ #
169
+ # @return [Hash] { "id" => ..., "secret" => ..., "regeneratedAt" => ... }
170
+ def regenerate_webhook_secret
171
+ envelope = get_client.post("/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}/regenerate")
172
+ envelope["data"]
173
+ end
174
+
175
+ # List historical delivery attempts for the signature webhook.
176
+ #
177
+ # @param limit [Integer, nil]
178
+ # @param offset [Integer, nil]
179
+ # @param event_type [String, nil]
180
+ # @param is_delivered [Boolean, nil]
181
+ # @param http_status [Integer, nil]
182
+ # @return [Hash] { "results" => [...], "totalRecords" => N, "limit" => ..., "offset" => ... }
183
+ def list_webhook_deliveries(limit: nil, offset: nil, event_type: nil, is_delivered: nil, http_status: nil)
184
+ params = {}
185
+ params["limit"] = limit unless limit.nil?
186
+ params["offset"] = offset unless offset.nil?
187
+ params["eventType"] = event_type unless event_type.nil?
188
+ params["isDelivered"] = is_delivered unless is_delivered.nil?
189
+ params["httpStatus"] = http_status unless http_status.nil?
190
+
191
+ get_client.get("/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}/deliveries", params)
192
+ end
193
+
194
+ # Manually retry a specific past delivery by ID.
195
+ #
196
+ # @param delivery_id [String]
197
+ # @return [Hash] the freshly-created delivery row
198
+ def replay_webhook_delivery(delivery_id)
199
+ envelope = get_client.post(
200
+ "/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}/replay",
201
+ { "deliveryId" => delivery_id }
202
+ )
203
+ envelope["data"]
204
+ end
205
+
206
+ # Aggregate delivery stats over a sliding window (days).
207
+ #
208
+ # @param days [Integer, nil] 1-365, default 30 (server-side default)
209
+ # @return [Hash] { "webhook" => {...}, "period" => {...}, "summary" => {...}, "eventBreakdown" => [...] }
210
+ def get_webhook_stats(days: nil)
211
+ params = {}
212
+ params["days"] = days unless days.nil?
213
+ get_client.get("/api/webhooks/#{SIGNATURE_WEBHOOK_NAME}/stats", params)
214
+ end
215
+
216
+ private
217
+
218
+ # Lazy fallback to env-driven config. Mirrors the explicit env-var check
219
+ # used by the JS module -- descriptive error rather than a silent
220
+ # auto-configure.
221
+ def get_client
222
+ return @client if @client
223
+
224
+ api_key = ENV["TURBODOCX_API_KEY"]
225
+ org_id = ENV["TURBODOCX_ORG_ID"]
226
+ unless api_key && org_id
227
+ raise TurboDocxError.new(
228
+ "TurboWebhooks must be configured before use. Call TurboWebhooks.configure() " \
229
+ "or set TURBODOCX_API_KEY and TURBODOCX_ORG_ID environment variables."
230
+ )
231
+ end
232
+
233
+ configure(api_key: api_key, org_id: org_id)
234
+ @client
235
+ end
236
+ end
237
+ end
238
+
239
+ # Verify a TurboDocx webhook delivery signature.
240
+ #
241
+ # Verifies the +X-TurboDocx-Signature+ header on an incoming webhook
242
+ # delivery. Format matches how TurboDocx signs each delivery:
243
+ # - Header: X-TurboDocx-Signature: sha256=<hex>
244
+ # - Timestamp: X-TurboDocx-Timestamp: <unix-seconds>
245
+ # - String signed: "<timestamp>.<raw_body>"
246
+ # - Algorithm: HMAC-SHA256
247
+ #
248
+ # Enforces a configurable timestamp tolerance (default 300s) to prevent
249
+ # replay attacks. Uses a constant-time comparison and never raises on bad
250
+ # input -- always returns a boolean.
251
+ #
252
+ # @param payload [String] the raw request body, AS RECEIVED. Do NOT parse
253
+ # then re-serialize; whitespace must match exactly.
254
+ # @param signature_header [String] value of the +X-TurboDocx-Signature+
255
+ # header (format: "sha256=<hex>").
256
+ # @param timestamp_header [String] value of the +X-TurboDocx-Timestamp+
257
+ # header (Unix epoch seconds, as string).
258
+ # @param secret [String] webhook secret returned by +create_webhook+ or
259
+ # +regenerate_webhook_secret+.
260
+ # @param tolerance_seconds [Integer] max acceptable age of the timestamp,
261
+ # in seconds. Defaults to 300. Set to 0 to disable the timestamp check
262
+ # (NOT recommended in production). A negative, non-numeric or non-finite
263
+ # (NaN, Infinity) value fails closed: every delivery is rejected.
264
+ # @param now [Proc, nil] override the "current time" function for
265
+ # deterministic testing. Returns Unix epoch seconds. Defaults to
266
+ # +Time.now.to_i+.
267
+ # @return [Boolean] true iff the signature is valid AND the timestamp is
268
+ # within tolerance.
269
+ def self.verify_webhook_signature(payload:, signature_header:, timestamp_header:, secret:, tolerance_seconds: 300, now: nil)
270
+ # Non-String / nil / empty headers and secret fail closed here; the rescue
271
+ # below covers what these guards can't see (Integer() parse failures and
272
+ # encoding clashes, a NaN now result).
273
+ return false unless signature_header.is_a?(String) && !signature_header.empty?
274
+ return false unless timestamp_header.is_a?(String) && !timestamp_header.empty?
275
+ return false unless secret.is_a?(String) && !secret.empty?
276
+ # A non-numeric tolerance raised NoMethodError, and so did a Complex one (no negative?).
277
+ return false unless tolerance_seconds.is_a?(Numeric) && tolerance_seconds.real?
278
+ # NaN made the window check always pass, and Infinity is a window that never expires.
279
+ return false if tolerance_seconds.respond_to?(:finite?) && !tolerance_seconds.finite?
280
+
281
+ # tolerance_seconds == 0 disables the replay window. A negative value fails
282
+ # closed (rejects everything) rather than silently disabling the check.
283
+ return false if tolerance_seconds.negative?
284
+
285
+ unless tolerance_seconds.zero?
286
+ # Digits only (an optional leading "-"), as in the JS and PHP helpers: Integer() alone would
287
+ # also accept surrounding whitespace, underscores and a "+".
288
+ return false unless timestamp_header.match?(/\A-?\d+\z/)
289
+
290
+ ts = Integer(timestamp_header, 10)
291
+ # now may return a Time or an Integer; coerce both to epoch seconds.
292
+ current_time = now ? now.call.to_i : Time.now.to_i
293
+ return false if (current_time - ts).abs > tolerance_seconds
294
+ end
295
+
296
+ body = payload.is_a?(String) ? payload : payload.to_s
297
+ digest = OpenSSL::HMAC.hexdigest("SHA256", secret, "#{timestamp_header}.#{body}")
298
+ expected = "sha256=#{digest}"
299
+
300
+ secure_compare(expected, signature_header)
301
+ rescue ArgumentError, TypeError, EncodingError, FloatDomainError
302
+ # Integer() raises ArgumentError on a non-numeric timestamp and Encoding::CompatibilityError
303
+ # (an EncodingError) on a UTF-16 one; building "#{timestamp}.#{body}" raises
304
+ # Encoding::CompatibilityError when the two encodings can't be combined; a NaN or infinite
305
+ # now result raises FloatDomainError on to_i.
306
+ false
307
+ end
308
+
309
+ # Constant-time string comparison. Prefers Rack::Utils.secure_compare when
310
+ # Rack is available; otherwise falls back to a manual constant-time compare
311
+ # so the SDK never takes on Rack as a runtime dependency.
312
+ def self.secure_compare(a, b)
313
+ if defined?(Rack::Utils) && Rack::Utils.respond_to?(:secure_compare)
314
+ return Rack::Utils.secure_compare(a, b)
315
+ end
316
+
317
+ return false unless a.bytesize == b.bytesize
318
+
319
+ l = a.unpack("C*")
320
+ res = 0
321
+ b.each_byte { |byte| res |= byte ^ l.shift }
322
+ res.zero?
323
+ end
324
+ private_class_method :secure_compare
325
+ end
@@ -0,0 +1,15 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "turbodocx_sdk/constants"
4
+ require_relative "turbodocx_sdk/errors"
5
+ require_relative "turbodocx_sdk/response_normalizer"
6
+ require_relative "turbodocx_sdk/http_client"
7
+ require_relative "turbodocx_sdk/turbo_sign"
8
+ require_relative "turbodocx_sdk/turbo_partner"
9
+ require_relative "turbodocx_sdk/turbo_quote"
10
+ require_relative "turbodocx_sdk/deliverable"
11
+ require_relative "turbodocx_sdk/turbo_webhooks"
12
+
13
+ module TurboDocxSdk
14
+ VERSION = "0.9.0"
15
+ end
metadata ADDED
@@ -0,0 +1,76 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: turbodocx-sdk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.9.0
5
+ platform: ruby
6
+ authors:
7
+ - TurboDocx
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-10-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: rspec
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.13'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3.13'
27
+ description: Official Ruby SDK for TurboDocx — digital signatures (TurboSign), partner
28
+ management (TurboPartner), quoting/CPQ (TurboQuote), document generation (Deliverable),
29
+ and signature webhooks (TurboWebhooks).
30
+ email:
31
+ - team@turbodocx.com
32
+ executables: []
33
+ extensions: []
34
+ extra_rdoc_files: []
35
+ files:
36
+ - LICENSE
37
+ - README.md
38
+ - lib/turbodocx_sdk.rb
39
+ - lib/turbodocx_sdk/client_context.rb
40
+ - lib/turbodocx_sdk/constants.rb
41
+ - lib/turbodocx_sdk/deliverable.rb
42
+ - lib/turbodocx_sdk/errors.rb
43
+ - lib/turbodocx_sdk/http_client.rb
44
+ - lib/turbodocx_sdk/response_normalizer.rb
45
+ - lib/turbodocx_sdk/turbo_partner.rb
46
+ - lib/turbodocx_sdk/turbo_quote.rb
47
+ - lib/turbodocx_sdk/turbo_sign.rb
48
+ - lib/turbodocx_sdk/turbo_webhooks.rb
49
+ homepage: https://github.com/TurboDocx/SDK
50
+ licenses:
51
+ - MIT
52
+ metadata:
53
+ homepage_uri: https://github.com/TurboDocx/SDK
54
+ source_code_uri: https://github.com/TurboDocx/SDK/tree/main/packages/ruby-sdk
55
+ documentation_uri: https://docs.turbodocx.com/docs/SDKs/ruby
56
+ rubygems_mfa_required: 'true'
57
+ post_install_message:
58
+ rdoc_options: []
59
+ require_paths:
60
+ - lib
61
+ required_ruby_version: !ruby/object:Gem::Requirement
62
+ requirements:
63
+ - - ">="
64
+ - !ruby/object:Gem::Version
65
+ version: 2.7.0
66
+ required_rubygems_version: !ruby/object:Gem::Requirement
67
+ requirements:
68
+ - - ">="
69
+ - !ruby/object:Gem::Version
70
+ version: '0'
71
+ requirements: []
72
+ rubygems_version: 3.3.5
73
+ signing_key:
74
+ specification_version: 4
75
+ summary: Ruby SDK for the TurboDocx API
76
+ test_files: []