assinafy 2.3.0 → 2.4.1

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.
@@ -11,7 +11,7 @@ module Assinafy
11
11
  # client = Assinafy::Client.create(ENV['ASSINAFY_API_KEY'], ENV['ASSINAFY_ACCOUNT_ID'])
12
12
  #
13
13
  # @example Construct from a config Hash (e.g. parsed YAML/JSON)
14
- # client = Assinafy::Client.from_config(api_key: '...', account_id: '...')
14
+ # client = Assinafy::Client.from_hash(api_key: '...', account_id: '...')
15
15
  #
16
16
  # @example Act as a user through OAuth 2.1
17
17
  # tokens = Assinafy::Client.new.oauth.exchange_code(
@@ -23,8 +23,6 @@ module Assinafy
23
23
  # @see Assinafy::OAuth
24
24
  # @see https://api.assinafy.com.br/v1/docs
25
25
  class Client
26
- # @return [Resources::AuthResource]
27
- attr_reader :auth
28
26
  # @return [Resources::OAuthResource]
29
27
  attr_reader :oauth
30
28
  # @return [Resources::AccountResource]
@@ -56,16 +54,19 @@ module Assinafy
56
54
  # @return [Support::WebhookVerifier]
57
55
  attr_reader :webhook_verifier
58
56
 
57
+ ASSIGNMENT_SIGNER_KEYS = %w[verification_method notification_methods step sign_as embedded].freeze
58
+ private_constant :ASSIGNMENT_SIGNER_KEYS
59
+
59
60
  # @param api_key [String, nil] sent as `X-Api-Key`
60
- # @param token [String, nil] bearer token; sent as
61
- # `Authorization: Bearer ...` when no `api_key` is given. Pass either a
62
- # login session token or an OAuth access token from
63
- # {Resources::OAuthResource#exchange_code} here.
61
+ # @param token [String, nil] OAuth access token from
62
+ # {Resources::OAuthResource#exchange_code}; sent as
63
+ # `Authorization: Bearer ...` when no `api_key` is given
64
64
  # @param account_id [String, nil] default workspace ID for account-scoped
65
65
  # resources; those methods document their supported per-call overrides
66
66
  # @param base_url [String]
67
67
  # @param webhook_secret [String, nil] secret for {Support::WebhookVerifier}
68
- # @param timeout [Integer] Faraday read/open timeout in seconds
68
+ # @param timeout [Integer] Faraday read/open timeout in seconds; keep it above 30, because a
69
+ # certificated page or thumbnail render can hold the response that long before answering 503
69
70
  # @param logger [Logger, nil] receives info-level lifecycle messages
70
71
  #
71
72
  # @example Build a client and reach a resource accessor (no network call)
@@ -85,7 +86,6 @@ module Assinafy
85
86
  @connection = build_connection(config)
86
87
  @logger = config.logger || NullLogger.new
87
88
 
88
- @auth = Resources::AuthResource.new(@connection, nil, @logger)
89
89
  @oauth = Resources::OAuthResource.new(@connection, nil, @logger)
90
90
  @accounts = Resources::AccountResource.new(@connection, account_id, @logger)
91
91
  @users = Resources::UserResource.new(@connection, nil, @logger)
@@ -125,19 +125,7 @@ module Assinafy
125
125
  #
126
126
  # @example Build from a credentials Hash loaded from YAML/JSON (string or symbol keys both work)
127
127
  # creds = YAML.load_file('config/assinafy.yml') # { 'api_key' => '...', 'account_id' => '...' }
128
- # client = Assinafy::Client.from_config(creds)
129
- # client #=> #<Assinafy::Client ...>
130
- def self.from_config(config)
131
- from_hash(config)
132
- end
133
-
134
- # Alias of {.from_config} for symmetry with {Configuration.from_hash}.
135
- #
136
- # @param config [Hash]
137
- # @return [Client]
138
- #
139
- # @example Build from a symbol-keyed Hash
140
- # client = Assinafy::Client.from_hash(api_key: 'example_api_key', account_id: 'account_example')
128
+ # client = Assinafy::Client.from_hash(creds)
141
129
  # client #=> #<Assinafy::Client ...>
142
130
  def self.from_hash(config)
143
131
  cfg = Configuration.from_hash(config)
@@ -152,20 +140,42 @@ module Assinafy
152
140
  )
153
141
  end
154
142
 
143
+ class << self
144
+ # Same as {.from_hash}.
145
+ #
146
+ # @param config [Hash]
147
+ # @return [Client]
148
+ #
149
+ # @example Build from a symbol-keyed Hash
150
+ # client = Assinafy::Client.from_config(api_key: 'example_api_key', account_id: 'account_example')
151
+ # client #=> #<Assinafy::Client ...>
152
+ alias from_config from_hash
153
+ end
154
+
155
155
  # High-level helper that bundles the most common workflow:
156
156
  # upload PDF → (optionally wait for metadata) → create signers → create a
157
157
  # virtual assignment for them.
158
158
  #
159
+ # Each signer Hash carries the contact fields of {Resources::SignerResource#create} and may also
160
+ # carry the assignment's per-signer keys: `verification_method`, `notification_methods`, `step`,
161
+ # `sign_as` and `embedded`. The contact fields create the signer; the assignment keys go on the
162
+ # assignment. Everything is validated before the upload, including that each signer has the
163
+ # contact its notification needs: `email` for Email (the default), `whatsapp_phone_number` for Whatsapp.
164
+ #
159
165
  # @param source [String, Hash] see {Resources::DocumentResource#upload}
160
- # @param signers [Array<Hash>] see {Resources::SignerResource#create}
166
+ # @param signers [Array<Hash>] contact fields plus optional per-signer assignment keys
161
167
  # @param message [String, nil]
162
168
  # @param wait_for_ready [Boolean] poll until the document is metadata-ready (default true)
163
169
  # @param expires_at [String, nil] ISO 8601 expiration for the assignment
164
170
  # @param copy_receivers [Array<String>, nil] signer IDs that only receive copies
165
171
  # @param account_id [String, nil] override the client default
172
+ # @param max_total_credits [Numeric, String, nil] refuse the assignment when it would cost more credits
166
173
  # @return [Hash{Symbol=>Object}] `{ document: {Hash}, assignment: {Hash}, signer_ids: [String, ...] }`
167
174
  # where `document` is the (unwrapped) document payload, `assignment` is the (unwrapped) virtual
168
175
  # assignment, and `signer_ids` lists the IDs of the signers created during the workflow.
176
+ # @raise [Assinafy::ValidationError] on invalid input, before anything is uploaded or created
177
+ # @raise [Assinafy::ApiError] on an unsuccessful API response
178
+ # @raise [Assinafy::NetworkError] on transport or TLS failure
169
179
  # @note This helper is not transactional. If a later API call fails, an uploaded
170
180
  # document or newly created signer may remain and should be cleaned up by the caller.
171
181
  # After an upload succeeds, SDK errors include the latest `document` and the
@@ -211,31 +221,41 @@ module Assinafy
211
221
  # # },
212
222
  # # signer_ids: ["signer-id"]
213
223
  # # }
224
+ # @example A WhatsApp signer with a spending ceiling
225
+ # client.upload_and_request_signatures(
226
+ # source: '/path/to/contract.pdf',
227
+ # signers: [{ full_name: 'Example Signer', whatsapp_phone_number: '+5511999999999',
228
+ # verification_method: 'Whatsapp', notification_methods: ['Whatsapp'] }],
229
+ # max_total_credits: 1
230
+ # )
231
+ # # POST /accounts/{account_id}/signers body:
232
+ # # { "full_name": "Example Signer", "whatsapp_phone_number": "+5511999999999" }
233
+ # # POST /documents/{document_id}/assignments body:
234
+ # # { "method": "virtual", "max_total_credits": 1,
235
+ # # "signers": [{ "id": "signer-id", "verification_method": "Whatsapp",
236
+ # # "notification_methods": ["Whatsapp"] }] }
237
+ # # => the same { document:, assignment:, signer_ids: } Hash as above
214
238
  def upload_and_request_signatures(source:, signers:, message: nil,
215
239
  wait_for_ready: true, expires_at: nil,
216
- copy_receivers: nil, account_id: nil)
217
- validate_signature_workflow!(signers, wait_for_ready)
218
-
219
- # Placeholder IDs stand in for the signers created below, so the whole
220
- # assignment body is validated before anything is uploaded or created.
221
- assignment_payload = { method: 'virtual', signers: Array.new(signers.length, 'preflight'),
222
- message: message, expires_at: expires_at,
223
- copy_receivers: copy_receivers }
224
- Resources::AssignmentResource.build_payload(assignment_payload)
240
+ copy_receivers: nil, account_id: nil, max_total_credits: nil)
241
+ Validation.require_boolean(wait_for_ready, 'wait_for_ready')
242
+ assignment_payload = { method: 'virtual', message: message, expires_at: expires_at,
243
+ copy_receivers: copy_receivers, max_total_credits: max_total_credits }
244
+ contacts, options = preflight_workflow(signers, assignment_payload)
225
245
 
226
246
  @logger.info("Starting upload and signature workflow for #{signers.length} signer(s)")
227
247
 
228
- upload_opts = account_id.nil? ? {} : { account_id: account_id }
229
- document = @documents.upload(source, upload_opts)
248
+ document = @documents.upload(source, { account_id: account_id }.compact)
230
249
  signer_ids = []
231
250
 
232
251
  begin
233
252
  document = @documents.wait_until_ready(document['id']) if wait_for_ready
234
- signers.each do |signer|
235
- signer_ids << signer_id!(@signers.create(signer, account_id))
253
+ contacts.each do |contact|
254
+ signer_ids << created_resource_id!(@signers.create(contact, account_id), 'Signer')
236
255
  end
237
256
 
238
- assignment = @assignments.create(document['id'], assignment_payload.merge(signers: signer_ids))
257
+ assignment_signers = signer_ids.zip(options).map { |id, option| { id: id, **option } }
258
+ assignment = @assignments.create(document['id'], assignment_payload.merge(signers: assignment_signers))
239
259
  created_resource_id!(assignment, 'Assignment')
240
260
 
241
261
  @logger.info("Upload and signature workflow completed for document #{document['id']}")
@@ -281,24 +301,38 @@ module Assinafy
281
301
  end
282
302
  end
283
303
 
284
- def validate_signature_workflow!(signers, wait_for_ready)
304
+ # Placeholder IDs stand in for the signers created later, so the whole
305
+ # assignment body is validated before anything is uploaded or created.
306
+ def preflight_workflow(signers, assignment_payload)
285
307
  unless signers.is_a?(Array) && !signers.empty? && signers.all?(Hash)
286
308
  raise ValidationError.new('Signers must be a non-empty Array of Hashes')
287
309
  end
288
- unless [true, false].include?(wait_for_ready)
289
- raise ValidationError.new('wait_for_ready must be true or false')
290
- end
291
310
 
292
- signers.each { |signer| @signers.validate_create!(signer) }
311
+ contacts, options = signers.map do |signer|
312
+ option, contact = signer.partition { |key, _| ASSIGNMENT_SIGNER_KEYS.include?(key.to_s) }.map(&:to_h)
313
+ [@signers.validate_create!(contact), option.transform_keys(&:to_sym)]
314
+ end.transpose
315
+ placeholders = options.each_with_index.map { |option, index| { id: "preflight-#{index}", **option } }
316
+ preflight = Resources::AssignmentResource.build_payload(assignment_payload.merge(signers: placeholders))
317
+ require_notification_contacts!(contacts, preflight['signers'])
318
+ [contacts, options]
293
319
  end
294
320
 
295
- def signer_id!(response)
296
- created_resource_id!(response, 'Signer')
321
+ # A signer without the contact its notification uses makes the API refuse
322
+ # the assignment only after the document and signers already exist.
323
+ def require_notification_contacts!(contacts, assignment_signers)
324
+ contacts.zip(assignment_signers) do |contact, signer|
325
+ whatsapp = (signer['notification_methods']&.first || signer['verification_method']) == 'Whatsapp'
326
+ field = whatsapp ? 'whatsapp_phone_number' : 'email'
327
+ next unless contact[field].to_s.strip.empty?
328
+
329
+ raise ValidationError.new("Signer #{field} is required for #{whatsapp ? 'Whatsapp' : 'Email'} notification")
330
+ end
297
331
  end
298
332
 
299
333
  def created_resource_id!(response, resource_name)
300
334
  id = response['id'] if response.is_a?(Hash)
301
- return id if id.is_a?(String) && Resources::BaseResource::PATH_SEGMENT.match?(id) && !%w[. ..].include?(id)
335
+ return id if Validation.path_segment?(id)
302
336
 
303
337
  raise Error.new(
304
338
  "#{resource_name} created but the API returned no usable ID",
@@ -24,8 +24,9 @@ module Assinafy
24
24
  class Configuration
25
25
  # Default base URL (production v1 API).
26
26
  DEFAULT_BASE_URL = 'https://api.assinafy.com.br/v1'
27
- # Default Faraday open/read timeout, in seconds.
28
- DEFAULT_TIMEOUT = 30
27
+ # Default Faraday open/read timeout, in seconds. It exceeds the 30 seconds a certificated
28
+ # page or thumbnail render may hold a response before answering 503 with Retry-After.
29
+ DEFAULT_TIMEOUT = 60
29
30
  # Schemes accepted for {#base_url}. Credentials are attached to every request
30
31
  # sent to this host, so anything that is not absolute HTTP(S) is rejected.
31
32
  BASE_URL_SCHEMES = %w[http https].freeze
@@ -33,7 +34,7 @@ module Assinafy
33
34
  # @!attribute [rw] api_key
34
35
  # @return [String, nil] sent as `X-Api-Key`
35
36
  # @!attribute [rw] token
36
- # @return [String, nil] session or OAuth bearer token (used when `api_key` is blank)
37
+ # @return [String, nil] OAuth access token (used when `api_key` is blank)
37
38
  # @!attribute [rw] account_id
38
39
  # @return [String, nil] default workspace ID
39
40
  # @!attribute [rw] base_url
@@ -48,11 +49,11 @@ module Assinafy
48
49
  attr_reader :base_url, :timeout
49
50
 
50
51
  # Build a configuration directly from keyword arguments. Prefer passing
51
- # `api_key` (the documented `X-Api-Key` mechanism); `token` is the session/OAuth
52
+ # `api_key` (the documented `X-Api-Key` mechanism); `token` is the OAuth
52
53
  # bearer fallback. `base_url` has its trailing slash stripped on assignment.
53
54
  #
54
55
  # @param api_key [String, nil] sent as the `X-Api-Key` header
55
- # @param token [String, nil] session or OAuth bearer token (used only when `api_key` is blank)
56
+ # @param token [String, nil] OAuth access token (used only when `api_key` is blank)
56
57
  # @param account_id [String, nil] default workspace account ID
57
58
  # @param base_url [String] API base URL (trailing slash is stripped)
58
59
  # @param webhook_secret [String, nil] secret for {Support::WebhookVerifier}
@@ -65,7 +66,7 @@ module Assinafy
65
66
  # account_id: 'account_example'
66
67
  # )
67
68
  # config.base_url # => "https://api.assinafy.com.br/v1"
68
- # config.timeout # => 30
69
+ # config.timeout # => 60
69
70
  # config.auth_headers # => { "X-Api-Key" => "example_api_key" }
70
71
  #
71
72
  # @example Trailing slash on base_url is stripped
@@ -117,7 +118,7 @@ module Assinafy
117
118
  account_id: h['account_id'],
118
119
  base_url: h.key?('base_url') ? h['base_url'] : DEFAULT_BASE_URL,
119
120
  webhook_secret: h['webhook_secret'],
120
- timeout: h.key?('timeout') ? h['timeout'] : DEFAULT_TIMEOUT,
121
+ timeout: h['timeout'],
121
122
  logger: h['logger']
122
123
  )
123
124
  end
@@ -45,8 +45,8 @@ module Assinafy
45
45
  module OAuth
46
46
  # Production authorization server, which owns the browser-facing flow.
47
47
  # Published by `GET /.well-known/oauth-protected-resource` as
48
- # `authorization_servers[0]`, and the `iss` its callbacks carry. The
49
- # sandbox publishes its own, `https://auth-sandbox.assinafy.com.br`.
48
+ # `authorization_servers[0]`, and the `iss` its callbacks carry. Another
49
+ # environment publishes its own issuer there; store and check that one.
50
50
  AUTHORIZATION_SERVER = 'https://auth.assinafy.com.br'
51
51
 
52
52
  # RFC 8414 discovery document for {AUTHORIZATION_SERVER}.
@@ -143,8 +143,8 @@ module Assinafy
143
143
  # @param redirect_uri [String] must match the URI registered for the client
144
144
  # @param code_verifier [String, nil] PKCE verifier; the S256 challenge is derived from it
145
145
  # @param code_challenge [String, nil] pre-computed S256 challenge, if the verifier lives elsewhere
146
- # @param scope [Array<String>, String, nil] requested scopes; include
147
- # `offline_access` to be issued a refresh token
146
+ # @param scope [Array<String>, String] requested scopes, at least one (the server
147
+ # answers `invalid_scope` for none); include `offline_access` to be issued a refresh token
148
148
  # @param state [String, nil] CSRF token echoed back on the callback
149
149
  # @param resource [String, nil] RFC 8707 resource indicator; when sent
150
150
  # here it must also be sent to the token endpoint, and must be the
@@ -153,7 +153,7 @@ module Assinafy
153
153
  # server; store that server's issuer for the callback's `iss` check
154
154
  # @param extra_params [Hash] additional query parameters (e.g. nonce); protocol fields cannot be overridden
155
155
  # @return [String] the absolute URL to redirect to
156
- # @raise [ValidationError] on a missing client_id/redirect_uri, an invalid
156
+ # @raise [ValidationError] on a missing client_id/redirect_uri/scope, an invalid
157
157
  # verifier, or when neither (or both) of verifier/challenge are given
158
158
  #
159
159
  # @example Minimal read-only request
@@ -169,11 +169,14 @@ module Assinafy
169
169
  authorization_endpoint: AUTHORIZATION_ENDPOINT, **extra_params)
170
170
  challenge = resolve_code_challenge(code_verifier, code_challenge)
171
171
 
172
+ requested = normalize_scope(scope)
173
+ raise ValidationError.new('scope is required') if requested.nil?
174
+
172
175
  params = {
173
176
  'response_type' => 'code',
174
- 'client_id' => require_value!(client_id, 'client_id'),
175
- 'redirect_uri' => require_value!(redirect_uri, 'redirect_uri'),
176
- 'scope' => normalize_scope(scope),
177
+ 'client_id' => Validation.require_string(client_id, 'client_id'),
178
+ 'redirect_uri' => Validation.require_string(redirect_uri, 'redirect_uri'),
179
+ 'scope' => requested,
177
180
  'state' => state,
178
181
  'resource' => resource,
179
182
  'code_challenge' => challenge,
@@ -243,7 +246,7 @@ module Assinafy
243
246
  # @return [URI::HTTPS]
244
247
  # @raise [ValidationError] for anything else
245
248
  def https_uri!(value, name)
246
- uri = URI.parse(require_value!(value, name))
249
+ uri = URI.parse(Validation.require_string(value, name))
247
250
  return uri if uri.is_a?(URI::HTTPS) && !uri.host.to_s.empty? && uri.userinfo.nil? && uri.fragment.nil?
248
251
 
249
252
  raise ValidationError.new("#{name} must be an absolute HTTPS URL without userinfo or fragment")
@@ -263,12 +266,6 @@ module Assinafy
263
266
 
264
267
  raise ValidationError.new('code_challenge must be an unpadded S256 challenge')
265
268
  end
266
-
267
- def require_value!(value, name)
268
- return value if value.is_a?(String) && !value.strip.empty?
269
-
270
- raise ValidationError.new("#{name} is required")
271
- end
272
269
  end
273
270
  end
274
271
  end
@@ -131,6 +131,8 @@ module Assinafy
131
131
  def update(payload, account_id_override = nil)
132
132
  acc_id = account_id(account_id_override)
133
133
  body = body_params(require_payload(payload, 'Account payload'))
134
+ raise ValidationError.new('Account payload must change at least one field') if body.empty?
135
+
134
136
  require_string(body['name'], 'name') if body.key?('name')
135
137
  validate_sender_type!(body)
136
138
 
@@ -139,15 +141,15 @@ module Assinafy
139
141
  end
140
142
  end
141
143
 
142
- # Delete an account. Deletion is blocked while documents are pending.
143
- # For an active paid subscription, pass `force: true` to cancel the
144
- # subscription as part of deletion.
144
+ # Delete an account. An active paid subscription blocks deletion, together with any pending
145
+ # documents; pass `force: true` to cancel both as part of deletion.
145
146
  #
146
- # @param force [Boolean] cancel an active paid subscription and continue
147
- # deletion (default false); it does not bypass pending-document checks
147
+ # @param force [Boolean] cancel the blocking paid subscription and pending documents, then
148
+ # delete (default false)
148
149
  # @param account_id_override [String, nil]
149
150
  # @return [nil] the API returns `data: []`; the SDK normalizes this to `nil`
150
- # @raise [Assinafy::ApiError] on an unsuccessful API response
151
+ # @raise [Assinafy::ApiError] on an unsuccessful API response; a blocked deletion answers `400`
152
+ # with `response_data['restrictions']` codes `ActivePaidSubscription` and `PendingDocuments`
151
153
  # @raise [Assinafy::NetworkError] on transport or TLS failure
152
154
  # @raise [Assinafy::ValidationError] on invalid required input
153
155
  # @see DELETE /accounts/{account_id}
@@ -468,14 +470,16 @@ module Assinafy
468
470
  private
469
471
 
470
472
  def validate_notification_policy!(body)
471
- if body.empty? || (body.keys - %w[events owners_receive_all]).any?
473
+ events = body['events']
474
+ if (body.keys - %w[events owners_receive_all]).any? ||
475
+ (!body.key?('owners_receive_all') && (events.nil? || events == {}))
472
476
  raise ValidationError.new('Notification policy requires events and/or owners_receive_all')
473
477
  end
474
478
 
475
479
  require_boolean(body['owners_receive_all'], 'owners_receive_all') if body.key?('owners_receive_all')
476
480
  return unless body.key?('events')
477
481
 
478
- events = require_payload(body['events'], 'Notification policy events')
482
+ require_payload(events, 'Notification policy events')
479
483
  codes = UserResource::NOTIFICATION_PREFERENCE_CODES | UserResource::PUSH_PREFERENCE_CODES
480
484
  require_preferences(events, codes, 'Notification policy events') unless events.empty?
481
485
  end
@@ -495,9 +499,8 @@ module Assinafy
495
499
 
496
500
  def validate_sender_type!(body)
497
501
  return unless body.key?('notification_sender_type')
498
- return if %w[User Account].include?(body['notification_sender_type'])
499
502
 
500
- raise ValidationError.new('notification_sender_type must be User or Account')
503
+ require_one_of(body['notification_sender_type'], %w[User Account], 'notification_sender_type')
501
504
  end
502
505
  end
503
506
  end