assinafy 2.2.0 → 2.4.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.
data/docs/GUIDE.md ADDED
@@ -0,0 +1,1079 @@
1
+ # Assinafy Ruby SDK integration guide
2
+
3
+ This guide walks an integration end to end and lists the Ruby call for every resource. The
4
+ [README](../README.en.md) has the short version; the [API reference](API_REFERENCE.md) maps every operation to
5
+ its Ruby method with exact authentication, parameters, request bodies and responses.
6
+
7
+ ## Authentication
8
+
9
+ | Credential | Who acts | Use for |
10
+ | --- | --- | --- |
11
+ | **API key** (`api_key:`) | the workspace | back-end integrations. Permanent. Sent as `X-Api-Key`; generate it in the Assinafy app. |
12
+ | **OAuth 2.1** (`token:`) | an app, **on behalf of** a user | marketplace apps, third-party integrations, AI assistants. See [OAuth 2.1](#oauth-21). |
13
+
14
+ Configure exactly one credential per client; if both are supplied, the SDK sends only `X-Api-Key`. A client with
15
+ no credentials serves OAuth and the public or signer endpoints — the SDK strips `X-Api-Key`/`Authorization` from
16
+ those calls regardless. User login, passwords, two-factor setup and API-key management happen in the Assinafy app;
17
+ the SDK does not wrap them.
18
+
19
+ ## OAuth 2.1
20
+
21
+ Use OAuth when an application acts **on behalf of a user**, with that user's permission. Unlike an API key, the
22
+ token is scoped to one workspace and carries only the scopes the user approved. Third-party OAuth tokens cannot
23
+ reach billing, account lifecycle, credential management, webhook-secret reads, embed-session creation,
24
+ biometric review images/decisions, or admin surfaces, whatever scopes they hold.
25
+
26
+ The flow is authorization-code with **mandatory PKCE**; the authorization server accepts `S256` only.
27
+
28
+ | Scope | Grants |
29
+ | --- | --- |
30
+ | `documents:read` | Read documents, pages, tags, signers, assignments, activity, webhook deliveries |
31
+ | `documents:write` | Create, update, delete documents and manage their signers and assignments |
32
+ | `templates:read` | Read templates, pages, roles, fields, tags |
33
+ | `templates:write` | Create, update, delete templates |
34
+ | `account:read` | Read the workspace profile, theme, logo, webhook endpoints |
35
+ | `webhooks:write` | Create, change, deactivate, and delete the workspace's webhook endpoints |
36
+ | `openid` | Identify the user (`sub` claim) and enable `/oauth/userinfo` |
37
+ | `profile` | Include the user's name in the claims |
38
+ | `email` | Include the user's email and verification status in the claims |
39
+ | `offline_access` | Be issued a refresh token (never echoed in the returned `scope`) |
40
+
41
+ **1. Register a callback and redirect the user.** Register an HTTPS callback URL in the Assinafy application.
42
+ For each authorization attempt, store the verifier, the state, and the expected issuer:
43
+
44
+ ```ruby
45
+ verifier = Assinafy::OAuth.generate_code_verifier
46
+ state = Assinafy::OAuth.generate_state
47
+
48
+ session[:assinafy_code_verifier] = verifier
49
+ session[:assinafy_state] = state
50
+ session[:assinafy_issuer] = Assinafy::OAuth::AUTHORIZATION_SERVER # issuer of the server this attempt uses
51
+
52
+ redirect_to Assinafy::OAuth.authorization_url(
53
+ client_id: ENV.fetch('ASSINAFY_CLIENT_ID'),
54
+ redirect_uri: 'https://app.example.com/oauth/callback',
55
+ code_verifier: verifier,
56
+ state: state,
57
+ scope: %w[documents:read documents:write openid profile email offline_access]
58
+ )
59
+ ```
60
+
61
+ The `code_challenge` is derived from the verifier; the verifier itself never appears in the URL.
62
+ `Assinafy::OAuth::AUTHORIZATION_SERVER` is the production issuer. For another environment, pass the
63
+ `authorization_endpoint:` its discovery metadata publishes and store that server's issuer instead.
64
+
65
+ **2. Validate the callback and exchange the code.** Check `state` and `iss` against the values stored for this
66
+ attempt before anything else, including on an `error=` return — that is the CSRF check, and it rejects responses
67
+ that are not yours. The code is single-use and expires 60 seconds after approval: exchange it at once, with the
68
+ same `redirect_uri`, and never retry.
69
+
70
+ ```ruby
71
+ expected_state = session.delete(:assinafy_state)
72
+ expected_issuer = session.delete(:assinafy_issuer)
73
+ unless expected_state.is_a?(String) && !expected_state.empty? &&
74
+ expected_issuer.is_a?(String) && !expected_issuer.empty? &&
75
+ params[:state] == expected_state && params[:iss] == expected_issuer
76
+ raise 'authorization response is not ours'
77
+ end
78
+ raise "authorization not granted: #{params[:error]}" if params[:error] # access_denied, invalid_scope, ...
79
+
80
+ tokens = Assinafy::Client.new.oauth.exchange_code(
81
+ code: params.fetch(:code),
82
+ client_id: ENV.fetch('ASSINAFY_CLIENT_ID'),
83
+ code_verifier: session.delete(:assinafy_code_verifier),
84
+ redirect_uri: 'https://app.example.com/oauth/callback'
85
+ )
86
+ # => { 'access_token' => ..., 'token_type' => 'Bearer', 'expires_in' => 3600,
87
+ # 'refresh_token' => ..., 'scope' => 'documents:read documents:write openid profile email' }
88
+ ```
89
+
90
+ The SDK checks the `code_verifier` grammar locally, because the server reports a malformed verifier as
91
+ `invalid_grant` — indistinguishable from an expired code.
92
+
93
+ **3. Persist the connection and act as the user.** The token works only in the workspace the user picked.
94
+
95
+ ```ruby
96
+ access_token = tokens.fetch('access_token')
97
+ workspace_id = Assinafy::Client.new(token: access_token).accounts.list[:data].first.fetch('id')
98
+
99
+ connection = Connection.create!(
100
+ workspace_id: workspace_id,
101
+ scope: tokens.fetch('scope'),
102
+ access_token: access_token, # store encrypted
103
+ refresh_token: tokens['refresh_token'], # store encrypted
104
+ expires_at: Time.now + tokens.fetch('expires_in')
105
+ )
106
+
107
+ user_client = Assinafy::Client.new(token: connection.access_token, account_id: connection.workspace_id)
108
+ user_client.documents.list
109
+ user_client.oauth.userinfo # => { 'sub' => ..., 'name' => ..., 'email' => ... } (openid scope)
110
+ ```
111
+
112
+ **4. Refresh with rotation, one at a time per connection.** Every refresh returns a **new** refresh token, valid
113
+ for another 30 days, and retires the old one, so a connection only expires after 30 days without a refresh.
114
+ Reusing a retired refresh token ends the whole connection, so refresh under a per-connection lock and store the
115
+ new tokens atomically before using them:
116
+
117
+ ```ruby
118
+ connection.with_lock do # row lock: one refresh at a time per connection
119
+ next if connection.expires_at > Time.now + 60 # another worker already refreshed
120
+
121
+ tokens = Assinafy::Client.new.oauth.refresh(
122
+ refresh_token: connection.refresh_token,
123
+ client_id: ENV.fetch('ASSINAFY_CLIENT_ID')
124
+ )
125
+
126
+ connection.update!(
127
+ refresh_token: tokens.fetch('refresh_token'),
128
+ access_token: tokens.fetch('access_token'),
129
+ expires_at: Time.now + tokens.fetch('expires_in')
130
+ )
131
+ end
132
+ user_client = Assinafy::Client.new(token: connection.access_token, account_id: connection.workspace_id)
133
+ ```
134
+
135
+ > The SDK does **not** refresh automatically and sends each token request once — never add retry middleware to
136
+ > the connection. `refresh` raises `Assinafy::Error` rather than return a success without a new refresh token;
137
+ > handle it like `invalid_grant`.
138
+ >
139
+ > If a refresh fails without a clear answer — a timeout, a reset connection, a `5xx` — the server may have rotated
140
+ > the token without the response reaching you. Re-read the stored refresh token: if it is still the one you sent,
141
+ > **never send it again**; ask the user to connect again. Carry on only if another worker has since stored a
142
+ > different one. Only a failure that provably happened before the request was sent — DNS resolution, a refused
143
+ > connection, a failed TLS handshake — is safe to retry. On an API `401`, refresh once; if that fails, or on
144
+ > `invalid_grant`, ask the user to connect again.
145
+
146
+ A refresh token exists only when `offline_access` was requested *and* consented.
147
+
148
+ **5. Revoke on disconnect.** Revoke the refresh token in storage **now** — the latest one — then delete the stored
149
+ tokens:
150
+
151
+ ```ruby
152
+ Assinafy::Client.new.oauth.revoke(
153
+ token: connection.reload.refresh_token,
154
+ client_id: ENV.fetch('ASSINAFY_CLIENT_ID'),
155
+ token_type_hint: 'refresh_token'
156
+ )
157
+ connection.destroy!
158
+ ```
159
+
160
+ Revoking a refresh token also invalidates the access tokens issued from it. Every revoke outcome returns `200` —
161
+ including an unknown, already-revoked, or rotated token — so revoking a stale copy can look successful while the
162
+ connection stays active.
163
+
164
+ **Discovery**, instead of hardcoding endpoints:
165
+
166
+ ```ruby
167
+ client.oauth.protected_resource_metadata['authorization_servers']
168
+ # => ["https://auth.assinafy.com.br"]
169
+
170
+ client.oauth.authorization_server_metadata['code_challenge_methods_supported']
171
+ # => ["S256"]
172
+ ```
173
+
174
+ `authorization_server_metadata` reaches a different host, so — like `/oauth/token` and `/oauth/revoke` — the SDK
175
+ sends it with no workspace credentials attached. An override URL must be an absolute HTTPS URL; anything else
176
+ raises `ValidationError`.
177
+
178
+ **Internal service clients.** The advertised RFC 8693 token-exchange grant is restricted to
179
+ Assinafy-provisioned confidential service clients. Marketplace apps use PKCE authorization code
180
+ and refresh. `client.oauth.token` accepts token exchange with `client_secret`, `subject_token`,
181
+ `subject_token_type`, and `resource`; it issues no refresh token.
182
+
183
+ **Errors.** OAuth routes answer with the flat RFC 6749 object rather than this API's envelope, so the SDK raises
184
+ `Assinafy::OAuthError` (a subclass of `Assinafy::ApiError`):
185
+
186
+ ```ruby
187
+ rescue Assinafy::OAuthError => e
188
+ e.error # => "invalid_grant"
189
+ e.error_description # => "The authorization code is invalid or has expired."
190
+ e.context[:www_authenticate] # on a 403, names the missing scope
191
+ ```
192
+
193
+ Any resource, not only these routes, puts that challenge in `context[:www_authenticate]`. Treat it as a prompt to
194
+ reconnect with that scope added, not as a retry; a `403` without it means another workspace, the user's role, or
195
+ an area OAuth tokens never reach.
196
+
197
+ ## Complete document workflow
198
+
199
+ Every call below returns the SDK value after response-envelope handling. Use the
200
+ [API operation table](API_REFERENCE.md#api-operations) for each method's exact HTTP authentication,
201
+ parameters, request body, and success wire response.
202
+
203
+ ### 1. Upload a document and wait for its metadata
204
+
205
+ ```ruby
206
+ document = client.documents.upload({ file_path: './customer-agreement.pdf' })
207
+ document['name'] # => "customer-agreement.pdf"
208
+
209
+ document = client.documents.wait_until_ready(
210
+ document.fetch('id'),
211
+ max_wait_seconds: 60,
212
+ poll_interval_seconds: 2
213
+ )
214
+ # => Document with a ready status and populated pages
215
+ ```
216
+
217
+ The document is named after the uploaded file; rename it with `client.documents.rename(id, 'New name')`. For
218
+ in-memory data, pass `{ buffer: pdf_bytes, file_name: 'contract.pdf' }`. PDF, DOC, DOCX or ODT (Word and OpenDocument files
219
+ are converted to PDF), at most 25 MB: the SDK checks the extension and size, and a PDF's `%PDF-` header, before
220
+ sending. `wait_until_ready` raises `Assinafy::ValidationError` for
221
+ invalid interval values and `Assinafy::Error` for a failed terminal status or a timeout.
222
+ The high-level `upload_and_request_signatures` helper waits up to 30 seconds by default. For asynchronous
223
+ processing, pass `wait_for_ready: false` and poll separately with the required timeout. Its errors retain
224
+ the uploaded document and any created signer IDs in `error.context` for recovery without uploading again.
225
+
226
+ **Or select a template.** A template upload initially contains an `Editor` role. Configure at least one `Signer`
227
+ role and its fields in the Assinafy application before generating a document. Template uploads have the same
228
+ 25 MB limit as documents.
229
+
230
+ ```ruby
231
+ template = client.templates.get('template-id')
232
+ ```
233
+
234
+ ### 2. Create or reuse signers
235
+
236
+ ```ruby
237
+ signer = client.signers.find_by_email('signer@example.com') ||
238
+ client.signers.create(full_name: 'Example Signer', email: 'signer@example.com')
239
+
240
+ # A DigitalCertificate signer needs a CPF or CNPJ in government_id — set it at creation:
241
+ cert_signer = client.signers.create(
242
+ full_name: 'Certificate Signer',
243
+ email: 'cert-signer@example.com',
244
+ government_id: ENV.fetch('ASSINAFY_SIGNER_GOVERNMENT_ID')
245
+ )
246
+ # ...or later: client.signers.update(signer['id'], government_id: '...')
247
+ ```
248
+
249
+ ### 3. Choose verification and notification methods
250
+
251
+ Each assignment signer has a **verification method** (how they prove identity before signing) and a
252
+ **notification method** (how they receive the invitation). The two are **coupled**: send one, both, or neither —
253
+ the missing side is inferred from the other, and when both are omitted both default to `Email`.
254
+
255
+ | Verification | How it works | Allowed notification | Cost per signer |
256
+ | --- | --- | --- | --- |
257
+ | `Email` *(default)* | One-time code (OTP) by email before signing | `Email` | 0 credits |
258
+ | `Whatsapp` | One-time code (OTP) over WhatsApp; needs `whatsapp_phone_number` and a paid plan | `Whatsapp` | The WhatsApp notification: 0.4 credits on Pro, 0.45 on other plans |
259
+ | `DigitalCertificate` | Signs with their own ICP-Brasil certificate (A1/A3), producing a qualified PAdES signature | `Email` **or** `Whatsapp` | The plan's certificate price + its notification |
260
+ | `IdDocumentFaceMatchBasic` | Government ID photos, a photo holding the ID and liveness; requires its account feature and a valid CPF in `government_id` | `Email` **or** `Whatsapp` | Free 1.5, Standard 1, Pro 0.5, other plans 0.25 credits + its notification |
261
+
262
+ - Send exactly one channel in `notification_methods` (a one-element array).
263
+ - The certificate charge appears in the cost breakdown under `SignatureDigitalCertificate` and the biometric one
264
+ under `VerificationIdDocumentFaceMatchBasic`. In an envelope the certificate is charged on every document the
265
+ signer signs and the biometric check once per signer. Resending a notification charges it again. Prices
266
+ depend on the plan; `estimate_cost` returns the exact total.
267
+ - `DigitalCertificate` needs the Digital Certificate account feature (Standard and Pro plans), a CPF or CNPJ in the
268
+ signer's `government_id`, a `method: 'virtual'` assignment, and the signer alone in its signing step. A collect
269
+ assignment, including one inferred from a template with positioned signer fields, cannot use certificate
270
+ signing. Direct assignment creation and estimation reject it with `ValidationError` code
271
+ `digital_certificate_requires_virtual`. A CPF requires that person's certificate (an e-CPF, or an e-CNPJ naming
272
+ them as legal representative); a CNPJ requires an e-CNPJ for that company, from any of its representatives.
273
+ - `AssignmentResource::VERIFICATION_METHODS` and `::NOTIFICATION_METHODS` publish the enums. `build_payload`
274
+ validates values, pairings, and `step` locally, so a typo fails before the request is sent.
275
+
276
+ ### 4. Estimate the cost
277
+
278
+ ```ruby
279
+ estimate = client.assignments.estimate_cost(
280
+ document.fetch('id'),
281
+ signers: [
282
+ { verification_method: 'Email' },
283
+ { verification_method: 'DigitalCertificate', notification_methods: ['Whatsapp'] }
284
+ ]
285
+ )
286
+ estimate['total_credits'] # => 0.95
287
+ estimate['breakdown'] # [{ 'code' => ..., 'quantity' => ..., 'unit_cost' => ..., 'cost' => ... }]
288
+ estimate['has_sufficient_resources'] # => true
289
+ ```
290
+
291
+ Estimates accept signers described by method alone, without an `id`.
292
+
293
+ ### 5. Create the assignment
294
+
295
+ ```ruby
296
+ assignment = client.assignments.create(
297
+ document.fetch('id'),
298
+ method: 'virtual',
299
+ signers: [
300
+ { id: signer.fetch('id'), verification_method: 'Email', notification_methods: ['Email'], step: 1 },
301
+ { id: cert_signer.fetch('id'), verification_method: 'DigitalCertificate', notification_methods: ['Email'], step: 2 }
302
+ ],
303
+ message: 'Please review and sign.',
304
+ expires_at: '2099-12-31T23:59:00Z'
305
+ )
306
+ assignment['signing_urls'] # => [{ 'signer_id' => 'signer-id', 'url' => 'https://.../sign/...' }, ...]
307
+ ```
308
+
309
+ `virtual` has no positioned fields and is required for `DigitalCertificate`; `collect` adds `entries` of
310
+ positioned fields (see [Assignments](#assignments)). Both require a non-empty `signers` array. Steps are
311
+ all-or-none, positive, and contiguous from 1; equal steps sign in parallel, and each step is notified when the
312
+ previous one finishes. A certificate signer is alone in its step. Deadlines are zoned ISO 8601 and at least one
313
+ hour ahead.
314
+
315
+ For a template, bind one distinct signer to each role; processing creates the document's assignment:
316
+
317
+ ```ruby
318
+ role_signer = {
319
+ role_id: template.fetch('roles').find { |role| role['assignment_type'] == 'Signer' }.fetch('id'),
320
+ id: signer.fetch('id'),
321
+ verification_method: 'Email',
322
+ notification_methods: ['Email']
323
+ }
324
+
325
+ client.documents.estimate_cost_from_template(template.fetch('id'), [role_signer])
326
+ template_document = client.documents.create_from_template(
327
+ template.fetch('id'), [role_signer],
328
+ name: 'customer-agreement.pdf', message: 'Please review and sign.',
329
+ idempotency_key: 'template-request-id'
330
+ )
331
+ # Initial response: status "uploaded", assignment nil; processing creates the assignment afterward.
332
+ # Follow document status/webhooks until pending_signature or failed.
333
+ # wait_until_ready waits for metadata and can return before the template assignment exists.
334
+ ```
335
+
336
+ Template creation also accepts `email` and `name` for a role instead of an existing signer `id`; the server reuses
337
+ or creates the signer. Keep the same `idempotency_key` after a lost response to avoid duplicate documents and
338
+ charges. `max_total_credits` can cap creation costs; a higher actual price returns `409` with
339
+ `error_code == 'CreditCeilingExceeded'`, creating and charging nothing.
340
+
341
+ **Shortcut.** `Client#upload_and_request_signatures` bundles upload, waiting, signer creation (including
342
+ `government_id`), and a virtual assignment. Each signer Hash may also carry its `verification_method`,
343
+ `notification_methods`, `step`, `sign_as` and `embedded`. The whole request is validated before anything is
344
+ uploaded, including that each signer has the email or WhatsApp number its notification needs:
345
+
346
+ ```ruby
347
+ result = client.upload_and_request_signatures(
348
+ source: { file_path: './contract.pdf' },
349
+ signers: [{ full_name: 'Alice Silva', email: 'alice@example.com', step: 1 },
350
+ { full_name: 'Bruno Lima', email: 'bruno@example.com', government_id: '000.000.000-00',
351
+ verification_method: 'DigitalCertificate', notification_methods: ['Email'], step: 2 }],
352
+ message: 'Please sign.',
353
+ expires_at: '2099-12-31T23:59:00Z',
354
+ max_total_credits: 5
355
+ )
356
+ result[:document]['id'] # => "document-id"
357
+ result[:signer_ids] # => ["signer-id"]
358
+ ```
359
+
360
+ It is not transactional: on a later failure, `e.context[:document]` and `e.context[:signer_ids]` list what was
361
+ created so you can clean up.
362
+
363
+ ### 6. The signer experience
364
+
365
+ The signer receives an access link through the notification channel. Signer-facing calls use
366
+ `signer-access-code` as a query parameter, with workspace credentials removed. The code remains usable during
367
+ signing and closes 30 minutes after that signer is done; an envelope code closes after all their documents are
368
+ done. After closure, document reads return only signer status, theme/logo and certified-copy delivery remain
369
+ available, and other signer calls return `410`.
370
+
371
+ ```ruby
372
+ signing = Assinafy::Client.new(base_url: ENV.fetch('ASSINAFY_BASE_URL'))
373
+ access_code = ENV.fetch('ASSINAFY_SIGNER_ACCESS_CODE')
374
+
375
+ signer_data = signing.signers.self_data(signer_access_code: access_code)
376
+ signing.signers.accept_terms(signer_access_code: access_code) unless signer_data['has_accepted_terms']
377
+
378
+ signing_document = signing.assignments.signer_document(signer_access_code: access_code, has_accepted_terms: true)
379
+ signing.signers.confirm_data(
380
+ signing_document.fetch('id'), { email: 'signer@example.com', has_accepted_terms: true },
381
+ signer_access_code: access_code
382
+ )
383
+ signing.signers.verify_email( # the OTP from email or WhatsApp
384
+ verification_code: ENV.fetch('ASSINAFY_VERIFICATION_CODE'),
385
+ signer_access_code: access_code
386
+ )
387
+ signing.signers.upload_signature(File.binread('signature.png'), signer_access_code: access_code, type: 'signature')
388
+
389
+ signing.assignments.sign(
390
+ signing_document.fetch('id'), signing_document.dig('assignment', 'id'), [], signer_access_code: access_code
391
+ )
392
+ # sign_multiple is also available for batches of virtual documents.
393
+ ```
394
+
395
+ That signs a virtual assignment. For a collect assignment, upload both the signature and initial images, then
396
+ submit required item values through `assignments.sign`. This example places only signature fields; add values
397
+ matching each field's type for other editable fields. Omit read-only dates, which the server fills:
398
+
399
+ ```ruby
400
+ signing.signers.upload_signature(File.binread('initial.png'), signer_access_code: access_code, type: 'initial')
401
+ items = signing_document.fetch('assignment').fetch('items')
402
+ collect_items = items.select { |item| item.dig('field', 'type') == 'signature' }.map do |item|
403
+ { item_id: item.fetch('id'), field_id: item.dig('field', 'id'), page_id: item.dig('page', 'id'), value: 'Accepted' }
404
+ end
405
+
406
+ signing.assignments.sign(
407
+ signing_document.fetch('id'), signing_document.dig('assignment', 'id'), collect_items,
408
+ signer_access_code: access_code
409
+ )
410
+
411
+ # To decline instead:
412
+ signing.assignments.decline(
413
+ signing_document.fetch('id'), signing_document.dig('assignment', 'id'),
414
+ decline_reason: 'Terms differ from the proposal', signer_access_code: access_code
415
+ )
416
+ ```
417
+
418
+ **Biometric signers** use `verification_method: 'IdDocumentFaceMatchBasic'` with exactly one Email or Whatsapp
419
+ notification in virtual/collect assignments or template generation. Store a valid CPF in the signer's
420
+ `government_id` first and call `estimate_cost` or `estimate_cost_from_template` for the current price.
421
+ The OTP example above applies to Email/Whatsapp. For biometrics, read the verification state and collect explicit
422
+ biometric-processing consent before starting:
423
+
424
+ ```ruby
425
+ state = signing.signers.identity_verification(signer_access_code: access_code)
426
+ # => { 'can_start' => true, 'status' => nil, 'url' => nil, 'expires_at' => nil, 'completed_at' => nil }
427
+
428
+ # After the signer explicitly consents to biometric processing:
429
+ session = signing.signers.start_identity_verification(consent: true, signer_access_code: access_code)
430
+ # => { 'id' => 'verification-id', 'url' => 'https://verify.assinafy.com.br/c/session#t=token-placeholder',
431
+ # 'expires_at' => '2026-10-16T13:00:00Z' }
432
+ ```
433
+
434
+ Open the capture URL unchanged, including its `#t=` fragment. It is a bearer link: keep it out of logs and browser
435
+ storage. For an existing Pending session, use the URL from `identity_verification`. `can_start` is true only
436
+ before any session or after Expired; restarting an Expired session costs nothing extra. Declined or Abandoned
437
+ requires a new document and assignment.
438
+
439
+ InReview lets the signer view, confirm data and sign while account review holds certification. After all signers
440
+ sign, the document can be `pending_identity_review`. The account reviewer uses an API key:
441
+
442
+ ```ruby
443
+ review = client.assignments.identity_review(document.fetch('id'), assignment.fetch('id'), signer.fetch('id'))
444
+ # => SignerIdentityReview: status, reason_codes, evidence_available, expected, document, matches,
445
+ # checks, images, ruleset_version, evidence_sha256 and decision metadata
446
+ image = client.assignments.identity_review_image(document.fetch('id'), assignment.fetch('id'), signer.fetch('id'), 'face')
447
+ # => JPEG, PNG or PDF bytes, depending on the name listed in review['images']; do not cache
448
+
449
+ # After the reviewer checks the evidence:
450
+ client.assignments.decide_identity_review(
451
+ document.fetch('id'), assignment.fetch('id'), signer.fetch('id'), decision: 'Approved', note: 'Identity checked'
452
+ )
453
+ ```
454
+
455
+ `decision: 'Rejected'` cancels the document and notifies signers and copy receivers. The optional note accepts at
456
+ most 2000 characters, goes to activities and the provider, and is never shown to the signer. Images exist only
457
+ during InReview. Observe signer_identity_review_required, signer_identity_review_approved,
458
+ signer_identity_review_rejected, signer_identity_verified and signer_identity_verification_failed events.
459
+ Third-party OAuth apps can read the review summary with `documents:read`; they cannot fetch evidence images or
460
+ submit the human review decision. For envelopes, one biometric check covers the signer's documents; rejection
461
+ cancels the whole envelope and notifies each recipient once.
462
+
463
+ **A1/A3 certificate signers** complete their signature in Assinafy's hosted signing flow, opened from
464
+ `assignment['signing_urls']`: they accept the terms, confirm their data, and sign with their A1 or A3 certificate
465
+ through the Web PKI browser extension. The ordinary signing endpoint rejects certificate signers, and the SDK does
466
+ not wrap the Web PKI handshake (`/signers/certificate/start`, `/signers/certificate/complete`), whose schemas are
467
+ not part of the OpenAPI contract. Once it completes, the `pades` artifact returns the qualified signature.
468
+
469
+ ### 7. Receive webhooks
470
+
471
+ An account can have 1 webhook endpoint, or up to 3 on paid plans. Each has its own distinct URL, event list, and
472
+ signing setting, and every active endpoint subscribed to an event receives it.
473
+
474
+ ```ruby
475
+ client.webhooks.list_event_types # => [{ 'id' => 'document_ready', 'description' => '...' }, ...]
476
+
477
+ endpoint = client.webhooks.create_endpoint(
478
+ url: 'https://app.example.com/webhooks/assinafy',
479
+ email: 'ops@example.com', # delivery-failure notices
480
+ events: %w[document_ready signer_signed_document signer_rejected_document],
481
+ name: 'ERP',
482
+ signing_enabled: true
483
+ )
484
+ secret = endpoint.fetch('secret') # returned once on creation; store it immediately, including for OAuth apps
485
+ ```
486
+
487
+ - `create_endpoint` requires `url`, `email`, and `events`; `name`, `is_active` (default `true`), and
488
+ `signing_enabled` (default `false`) are optional. Unknown keys raise `ValidationError` locally.
489
+ - Creating one past the plan limit answers `403`; a URL another endpoint already uses answers `400`.
490
+ - `update_endpoint(id, payload)` changes only the fields sent. `signing_enabled: true` creates a secret when the
491
+ endpoint has none and keeps the current one otherwise; `false` discards it.
492
+ - `rotate_endpoint_secret(id)` returns a new secret; the old one stops working immediately. Pass
493
+ `keep_previous: true` for 24 hours of signatures from both secrets while receivers switch.
494
+ - Reading a secret requires an API key. Rotation is available to OAuth apps with
495
+ `webhooks:write`, including recovery of a lost secret. Both methods answer `400` when signing is disabled.
496
+ - Enabling signing with `update_endpoint` returns the new secret once. Store it before using the endpoint.
497
+ - `list_endpoints(url: registered_url)` filters by exact URL; `delete_endpoint_by_url(registered_url)` removes
498
+ that endpoint and returns `nil` (`404` when no endpoint matches).
499
+
500
+ **Delivery contract.** Each delivery is a `POST` with an `application/json` body and the headers `webhook-id`
501
+ (identical on every attempt of the same event to the same endpoint — deduplicate on it), `webhook-timestamp`
502
+ (Unix seconds), and, when signing is enabled, `webhook-signature`. Any `2xx` is success. Network failures,
503
+ timeouts, `408`, `429` and `5xx` get up to six attempts about ten minutes apart; other statuses are final.
504
+ After ten failed deliveries in a row the endpoint pauses. Probes follow after 3, 15 and 60 minutes, then every
505
+ six hours; success releases queued events oldest first. Updating its URL or setting `is_active: true` also lifts
506
+ the pause. `retry_dispatch` sends now; `test_endpoint` sends a separate `webhook_test` without changing the pause.
507
+ Delivery history is retained for seven days and captures the first 2000 response-body characters.
508
+
509
+ **Verifying signatures.** Signatures follow [Standard Webhooks](https://www.standardwebhooks.com): space-separated
510
+ `v1,<base64 HMAC-SHA256>` entries over `"{webhook-id}.{webhook-timestamp}.{raw body}"`, keyed with the
511
+ base64-decoded part of the secret after `whsec_`. `verify_delivery` checks them in constant time and rejects
512
+ timestamps more than 5 minutes from the local clock (`tolerance:` changes the window):
513
+
514
+ ```ruby
515
+ class AssinafyWebhooksController < ActionController::API
516
+ VERIFIER = Assinafy::Support::WebhookVerifier.new(ENV.fetch('ASSINAFY_WEBHOOK_SECRET'))
517
+
518
+ def create
519
+ raw_body = request.raw_post
520
+ return head(:unauthorized) unless VERIFIER.verify_delivery(raw_body, request.headers)
521
+
522
+ webhook_id = request.headers['webhook-id']
523
+ return head(:ok) if AssinafyEvent.exists?(webhook_id: webhook_id) # already processed
524
+
525
+ event = VERIFIER.extract_event(raw_body)
526
+ AssinafyEvent.create!(webhook_id: webhook_id, kind: VERIFIER.event_type(event), body: raw_body)
527
+ ProcessAssinafyEventJob.perform_later(webhook_id)
528
+ head :ok
529
+ end
530
+ end
531
+ ```
532
+
533
+ In plain Rack (Sinatra, Roda), pass the env: `VERIFIER.verify_delivery(request.body.read, request.env)` — the
534
+ `HTTP_WEBHOOK_ID` form is accepted, as is a plain Hash. `verify_delivery` returns `false` — never raises — for a
535
+ missing or malformed secret, a missing header, a wrong signature, or a stale timestamp. Always pass the **raw**
536
+ body exactly as received. `client.webhook_verifier` is a verifier built from the client's `webhook_secret`.
537
+
538
+ `extract_event` parses the body (or returns `nil`); `event_type`, `event_payload`, `event_object` (the entity acted
539
+ on), and `event_subject` (the actor) read the envelope `{ id, event, message, payload, origin, created_at,
540
+ subject, object, account_id }`. `subject` and `object` carry a `type` (`User`, `Signer`, `Account`, `Document`, or
541
+ `Template`); body timestamps are Unix seconds.
542
+
543
+ `verify(raw_body, hex_signature)` remains only for receivers whose own gateway signs bodies with a hex
544
+ HMAC-SHA256 shared secret.
545
+
546
+ Give the webhook event table a unique index on `webhook_id`, process events idempotently, and arrange durable
547
+ job delivery before acknowledging the request so concurrent retries or a failed enqueue cannot lose an event.
548
+
549
+ ### 8. Track progress, download, and verify
550
+
551
+ ```ruby
552
+ document_id = document.fetch('id')
553
+
554
+ client.documents.signing_progress(document_id) # => { signed: 1, total: 2, pending: 1, percentage: 50.0 }
555
+ client.documents.fully_signed?(document_id)
556
+ client.documents.activities(document_id) # => one page of Array<DocumentActivity>
557
+ client.documents.activities_page(document_id, page: 1, per_page: 20) # => { data:, meta: }
558
+
559
+ signed_pdf = client.documents.download(document_id, 'certificated')
560
+ # also 'original', 'certificate-page', 'bundle' (zip), and 'pades' for certificate-signed documents
561
+
562
+ verification = client.documents.verify('signature-hash-from-assinafy')
563
+ verification['is_valid'] # => true
564
+ verification['agreement_code'] # printed on the document certificate
565
+ ```
566
+
567
+ `verify` returns Assinafy's verification result. It does not independently validate the PDF signature or its
568
+ certificate chain; see [Authentication and safety](API_REFERENCE.md#authentication-and-safety).
569
+
570
+ ### 9. Cancel or clean up
571
+
572
+ ```ruby
573
+ client.documents.cancel(document_id) # pending_signature/pending_identity_review -> rejected_by_user, kept
574
+ client.documents.delete(document_id) # removes it; a pending document is cancelled first
575
+ client.signers.delete(signer.fetch('id'))
576
+ client.webhooks.delete_endpoint(endpoint.fetch('id'))
577
+ ```
578
+
579
+ `cancel` notifies the signers and owner and keeps the document, its files and history. A fully signed document
580
+ answers `409` (`DocumentClosed`); a document of an open envelope answers `409` (`EnvelopeOpen`) — cancel the
581
+ envelope or remove the document from it instead. Delete only resources your application owns, after downstream
582
+ work is complete; keep shared signer and template data. Some resources return `409` while processing or while
583
+ still referenced.
584
+
585
+ ### 10. Handle errors
586
+
587
+ ```ruby
588
+ begin
589
+ client.documents.details(document_id)
590
+ rescue Assinafy::ValidationError => e
591
+ warn e.errors.inspect
592
+ rescue Assinafy::ApiError => e
593
+ warn "Assinafy returned #{e.status_code}: #{e.message}"
594
+ sleep(e.retry_after) if e.status_code == 429 && e.retry_after # also e.rate_limit => { limit:, remaining:, reset: }
595
+ rescue Assinafy::NetworkError => e
596
+ warn "Network failure: #{e.message}"
597
+ end
598
+ ```
599
+
600
+ See [Errors](#errors) for the full hierarchy.
601
+
602
+ ## Resource reference
603
+
604
+ `Assinafy::Client` exposes the API resources below plus the local `webhook_verifier` helper:
605
+
606
+ | Accessor | What it covers |
607
+ | --------------------------- | ------------------------------------------------------------------ |
608
+ | `client.oauth` | OAuth 2.1 token exchange, refresh, revocation, userinfo, discovery |
609
+ | `client.accounts` | Account CRUD, theme, KPI stats, brand logo |
610
+ | `client.users` | User profile, notification preferences, cross-account KPIs |
611
+ | `client.documents` | Upload, list, search, rename, download, delete, verify, tags |
612
+ | `client.envelopes` | Send several documents together, estimate, reorder, cancel and download |
613
+ | `client.contracts` | Contract terms, amendments, renewals, terminations |
614
+ | `client.signers` | Workspace signer CRUD + signer self-service endpoints |
615
+ | `client.signer_documents` | Signer-authenticated multi-document operations + search |
616
+ | `client.assignments` | List/create/sign/decline/resend/estimate assignments |
617
+ | `client.templates` | Template creation (file upload), get, list, update, delete |
618
+ | `client.tags` | Workspace tags |
619
+ | `client.fields` | Field definitions + validation + type catalog |
620
+ | `client.webhooks` | Webhook endpoints, signing secrets, event catalog, deliveries, retries |
621
+ | `client.webhook_verifier` | Standard Webhooks signature verification for received deliveries |
622
+
623
+ ### Accounts
624
+
625
+ ```ruby
626
+ client.accounts.list # { data: [...] } — no pagination meta
627
+ client.accounts.get # the current account (or pass an id)
628
+ client.accounts.get(expand: 'signing_features') # includes available signing features
629
+ client.accounts.create(name: 'Acme Inc.')
630
+ client.accounts.update({ name: 'Acme Renamed' })
631
+ client.accounts.delete(force: true, account_id_override: 'account-id')
632
+ client.accounts.theme # { account_name, primary_color, secondary_color, logo }
633
+ client.accounts.stats(granularity: 'monthly', month: '2026-06') # account KPI rows
634
+ client.accounts.upload_logo({ file_path: './logo.png' })
635
+ client.accounts.download_logo # raw bytes; raises ApiError on HTTP 404 when unset
636
+ client.accounts.delete_logo
637
+ client.accounts.usage # { 'plan' => ..., 'documents_renewal_date' => ..., 'balances' => { ... } }
638
+ client.accounts.notification_policy # { 'editable' => true, 'owners_receive_all' => false, 'events' => { ... } }
639
+ client.accounts.update_notification_policy(events: { SignerViewed: false }, owners_receive_all: true)
640
+ ```
641
+
642
+ Usage and notification policy are unavailable to third-party OAuth applications. Policy writes require an owner;
643
+ they merge only supplied event flags. A disabled workspace event suppresses it across channels even when a
644
+ member enables it. `SignerIdentityReviewRequired: false` disables only push; its email is always sent.
645
+
646
+ ### Users
647
+
648
+ ```ruby
649
+ client.users.me
650
+ client.users.stats(granularity: 'daily', month: '2026-06') # cross-account KPI rows
651
+ client.users.notification_preferences # returns all thirteen owner-email preferences
652
+ client.users.update_notification_preferences(SignerDeclined: false) # partial request; returns all thirteen
653
+ client.users.push_preferences # eight phone-push preferences; separate from email
654
+ client.users.update_push_preferences(SignerViewed: false) # partial request; returns the full push map
655
+ ```
656
+
657
+ Email and push preferences apply to the user across workspaces. They accept boolean values and reject unknown
658
+ keys or an empty update. These personal settings are unavailable to third-party OAuth applications.
659
+
660
+ Both stats methods validate `granularity` (`monthly` or `daily`) and `month` (`YYYY-MM`) locally; daily statistics
661
+ require `month`. They return rows
662
+ with `period`, `documents_uploaded`, `documents_sent`, `signature_requests`,
663
+ `signature_requests_notification_email`, `signature_requests_notification_whatsapp`,
664
+ `signature_requests_notification_bypass`, `signature_requests_verification_email`,
665
+ `signature_requests_verification_whatsapp`, `signature_requests_verification_bypass`,
666
+ `signature_requests_verification_digital_certificate`, `signature_requests_viewed`,
667
+ `signature_requests_completed`, and `documents_certified`.
668
+
669
+ ### Documents
670
+
671
+ ```ruby
672
+ client.documents.statuses # GET /documents/statuses
673
+ client.documents.list(page: 1, per_page: 20, status: 'pending_signature')
674
+ client.documents.list(tags: ['tag-id-1', 'tag-id-2']) # documents carrying every listed tag
675
+ client.documents.list(envelope_id: 'envelope-id') # documents in an envelope
676
+ client.documents.search('contract') # lightweight GET .../documents/search
677
+ client.documents.upload({ file_path: './contract.pdf' }) # named after the file
678
+ client.documents.upload({ buffer: pdf_bytes, file_name: 'contract.pdf' })
679
+ client.documents.rename('document-id', 'renamed.pdf') # PATCH /documents/{id}
680
+ client.documents.get('document-id') # alias of .details
681
+ client.documents.details('document-id', expand: ['envelope_id', 'envelope'])
682
+ client.documents.wait_until_ready('document-id', max_wait_seconds: 60)
683
+ client.documents.activities('document-id')
684
+ client.documents.activities_page('document-id', sort: '-id', page: 1, per_page: 20)
685
+ client.documents.thumbnail('document-id') # binary PNG/JPEG
686
+ client.documents.thumbnail('document-id', artifact: 'certificated') # rendered signed content
687
+ client.documents.download('document-id', 'certificated') # binary PDF
688
+ client.documents.download('document-id', 'pades') # signed PAdES artifact
689
+ client.documents.download_page('document-id', 'page-id')
690
+ client.documents.download_page('document-id', 'page-id', artifact: 'certificated')
691
+ client.documents.cancel('document-id') # stop signing and keep the document
692
+ client.documents.delete('document-id') # cancels a pending document first
693
+ client.documents.verify('signature-hash')
694
+ client.documents.public_info('document-id')
695
+ client.documents.send_token('document-id', recipient: 'signer@example.com')
696
+ client.documents.list_tags('document-id')
697
+ client.documents.replace_tags('document-id', ['tag-id-1', 'tag-id-2'])
698
+ client.documents.append_tags('document-id', ['tag-id-3'])
699
+ client.documents.detach_tag('document-id', 'tag-id')
700
+
701
+ client.documents.create_from_template(
702
+ 'template-id',
703
+ [{ role_id: 'role-id', id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'] }],
704
+ { name: 'Contract', message: 'Please sign', expires_at: '2099-12-31T23:59:00Z' }
705
+ )
706
+ client.documents.estimate_cost_from_template('template-id', [{ role_id: 'role-id', verification_method: 'Whatsapp' }])
707
+
708
+ client.documents.fully_signed?('document-id')
709
+ client.documents.signing_progress('document-id') # => { signed: 1, total: 2, pending: 1, percentage: 50.0 }
710
+ ```
711
+
712
+ An Array `tags` filter is sent as comma-separated tag IDs. The tag arrays of `replace_tags`/`append_tags` take tag
713
+ IDs.
714
+
715
+ Activities default to twenty per page. `activities` preserves the Array return; `activities_page` exposes the
716
+ pagination headers so callers can traverse every event. Signed thumbnails/pages use `artifact: 'certificated'`
717
+ with workspace credentials. The first render can wait up to thirty seconds, then return `503` with `Retry-After`;
718
+ the SDK does not retry. These renders carry `Cache-Control: no-store`. Certificate pages have no document page
719
+ IDs, and the qualified certificate seal is available in the `pades` artifact.
720
+
721
+ ### Envelopes
722
+
723
+ Send up to 20 prepared documents to up to 20 existing signers in one invitation. Each document retains its own
724
+ assignment, status and artifacts. All envelope signers sign in parallel; no `step` is accepted.
725
+
726
+ ```ruby
727
+ request = {
728
+ name: 'Agreement and annex',
729
+ signers: [{ id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'] }],
730
+ documents: [
731
+ { id: 'agreement-id', signer_ids: ['signer-id'] },
732
+ { id: 'annex-id', signer_ids: ['signer-id'] }
733
+ ]
734
+ }
735
+ estimate = client.envelopes.estimate_cost(request)
736
+ envelope = client.envelopes.create(
737
+ request.merge(max_total_credits: estimate.fetch('total_credits')), idempotency_key: 'envelope-request-id'
738
+ )
739
+ # => { 'id' => 'envelope-id', 'name' => 'Agreement and annex', 'message' => nil,
740
+ # 'documents' => [...], 'counts' => { 'pending_signature' => 2 },
741
+ # 'signing_urls' => [...], 'created_at' => '2026-11-11T12:00:00Z' }
742
+
743
+ client.envelopes.list(status: 'open') # { data: [...], meta: { ... } }
744
+ client.envelopes.get(envelope.fetch('id'))
745
+ client.envelopes.update(envelope.fetch('id'), document_ids: %w[annex-id agreement-id], message: nil)
746
+ client.envelopes.activities(envelope.fetch('id')) # paginated events with document_id/document_name
747
+ client.envelopes.resend_notification(envelope.fetch('id'), 'signer-id') # { 'is_sent' => true, ... }
748
+ client.envelopes.add_document(envelope.fetch('id'), id: 'extra-document-id', signer_ids: ['signer-id'])
749
+ client.envelopes.remove_document(envelope.fetch('id'), 'extra-document-id') # cancels and removes that open document
750
+ archive = client.envelopes.download(envelope.fetch('id'), 'original') # ZIP bytes in envelope order
751
+ client.envelopes.cancel(envelope.fetch('id')) # [{ 'id' => ..., 'status' => ..., 'cancelled' => true }]
752
+ client.envelopes.delete(envelope.fetch('id')) # nil; closed envelopes only, documents remain
753
+ ```
754
+
755
+ `collect` documents add positioned `entries` whose field signers exactly match `signer_ids`. Every envelope
756
+ signer must appear on a document. A certificate signer signs alone on each virtual document and is charged per
757
+ document; a biometric signer verifies once for the envelope. Preserve the creation idempotency key after an
758
+ ambiguous response. `max_total_credits` prevents creating or charging an envelope above the approved cost.
759
+
760
+ ### Scheduled sends and document recipients
761
+
762
+ ```ruby
763
+ scheduled = client.assignments.schedule(
764
+ 'document-id', { signers: [{ id: 'signer-id', sign_as: 'Witness' }], max_total_credits: 1 },
765
+ send_at: (Time.now + 7200).iso8601
766
+ )
767
+ # => { 'id' => 'send-id', 'type' => 'assignment', 'document_ids' => ['document-id'],
768
+ # 'status' => 'pending', 'send_at' => '2026-12-01T12:00:00Z', 'assignment_id' => nil,
769
+ # 'envelope_id' => nil, 'failure_reason' => nil, 'created_at' => '2026-12-01T10:00:00Z',
770
+ # 'processed_at' => nil }
771
+ client.scheduled_sends.list(document_id: 'document-id', per_page: 20) # { data:, meta: }
772
+ client.scheduled_sends.cancel(scheduled.fetch('id')) # status: cancelled; no charge
773
+ # Or send a pending request immediately:
774
+ # client.scheduled_sends.send_now(scheduled.fetch('id')) # status: sent; assignment_id/envelope_id populated
775
+
776
+ client.envelopes.schedule(
777
+ { name: 'Contract', signers: [{ id: 'signer-id' }],
778
+ documents: [{ id: 'another-document-id', signer_ids: ['signer-id'] }] },
779
+ send_at: (Time.now + 7200).to_i
780
+ ) # ScheduledSend with type: envelope
781
+
782
+ client.documents.signer_capacities('document-id') # [{ 'signer_id' => 'signer-id', 'sign_as' => 'Witness' }]
783
+ client.documents.set_watchers('document-id', ['contact-id']) # Array<Signer>; [] clears all
784
+ client.documents.watchers('document-id') # Array<Signer>
785
+ client.documents.notification_history('document-id') # signer_id plus records with delivered_at/opened_at
786
+ client.envelopes.estimate_resend_cost('envelope-id', 'signer-id') # total, breakdown, credit_balance, has_sufficient_credits
787
+ ```
788
+
789
+ Scheduling creates no assignment, invitation or charge until delivery. `send_at` accepts Unix seconds or
790
+ ISO 8601 (no offset means UTC), one hour to 90 days ahead. Each document's deadline must be at least two hours
791
+ later. All schedule operations, including listing, need OAuth `documents:write`. Delivery uses the original
792
+ member's permissions and then-current balance, plan and price; preserve `max_total_credits` to bound charges.
793
+ The worker checks about every five minutes. A failed send records a reason and notifies the original member
794
+ (or active owners if they left). Send-now failures leave the request pending; cancel it to prevent a later attempt.
795
+ Only pending sends can be cancelled or sent now. Scheduling does not accept idempotency keys.
796
+
797
+ `sign_as` defaults to `Sign`; other exact values are in `AssignmentResource::SIGNER_CAPACITIES`. It records
798
+ the sender's statement on the certificate and is read separately, not from ordinary assignments or webhooks.
799
+ Watchers are up to ten workspace contacts with email, editable until the document ends. They receive a terminal
800
+ status email without a document link/file, independently of workspace notification policy. Delivery/open times
801
+ are nullable; an open is a hint, not proof a human read the invitation. Reminder estimates do not check eligibility;
802
+ reminders are limited to one per two minutes and ten per 24 hours, shared across an envelope's documents.
803
+
804
+ ### Embedded signing
805
+
806
+ Requires the account's Embed feature and an API key; third-party OAuth cannot create sessions.
807
+ Register exact allowed origins, then mark the signer `embedded: true` with Email or Whatsapp verification:
808
+
809
+ ```ruby
810
+ origin = client.accounts.create_embed_origin('https://app.example.com')
811
+ # => { 'id' => 'origin-id', 'origin' => 'https://app.example.com', 'created_at' => '2026-11-11T12:00:00Z' }
812
+ client.accounts.list_embed_origins
813
+ client.accounts.update_embed_origin(origin.fetch('id'), 'https://sign.example.com')
814
+
815
+ assignment = client.assignments.create(
816
+ 'document-id', method: 'virtual',
817
+ signers: [{ id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'], embedded: true }]
818
+ )
819
+ session = client.assignments.create_embed_session('document-id', assignment.fetch('id'), 'signer-id')
820
+ # => { 'url' => 'https://app.assinafy.com.br/embed/session-token', 'expires_at' => '2026-11-11T12:05:00Z' }
821
+ # Pass session['url'] only to the intended signer's page and load it in an iframe.
822
+ client.accounts.delete_embed_origin(origin.fetch('id')) # nil; removes that embedding permission
823
+ ```
824
+
825
+ Origins have no path, query, fragment or wildcard; HTTPS is required except HTTP localhost/127.0.0.1.
826
+ At most ten origins are allowed. Mint a fresh single-use URL for each frame display; it expires after five
827
+ minutes. `signing_urls` contains `url: nil, embedded: true` for embedded signers; invitations still deliver their
828
+ code. Follow the live [Embedded Signing Guide](https://api.assinafy.com.br/v1/docs) for the `assinafy:hello`
829
+ handshake and validate both `postMessage` origin and iframe window. Confirm completion through a webhook or
830
+ document read; frame events alone do not authorize application actions.
831
+
832
+ `assignments.exchange_embed_session(token, parent_origin:)` is the token-only operation used by the Assinafy
833
+ embed page. An ordinary integration loads the session URL; it does not exchange the token itself or expose the
834
+ returned signer access code. Resend the code through `assignments.resend_notification` from your backend.
835
+
836
+ ### Contracts
837
+
838
+ ```ruby
839
+ contract = client.contracts.update(
840
+ 'document-id',
841
+ status: 'active', counterparty_name: 'Example Ltda', value: 120_000, currency: 'BRL',
842
+ start_date: '2026-11-01', end_date: '2027-10-31', auto_renew: true,
843
+ renewal_term_months: 12, notice_period_days: 30
844
+ )
845
+
846
+ client.contracts.get('document-id')
847
+ client.contracts.list(status: ['active'], ending_within_days: 30)
848
+ client.contracts.related('document-id')
849
+ client.contracts.related('document-id', expand: 'document') # also includes the parent document
850
+ client.contracts.renew('document-id', term: contract['term'], updated_at: contract['updated_at'])
851
+ client.contracts.terminate('document-id', reason: 'Ended by the parties')
852
+ ```
853
+
854
+ `update` is partial and preserves explicit `nil` values as JSON `null`. Link an amendment document with
855
+ `parent_document_id` and `relation_type`. Reads require OAuth scope `documents:read`; writes require
856
+ `documents:write` and a plan with contract tracking. `get` and `related` return `nil` when no tracked terms exist.
857
+
858
+ ### Signers (workspace CRUD)
859
+
860
+ ```ruby
861
+ client.signers.create(full_name: 'Alice Silva', email: 'alice@example.com')
862
+ client.signers.create(full_name: 'Bob Costa', phone: '+5500000000000') # phone -> whatsapp_phone_number
863
+ client.signers.create(full_name: 'Carla Lima', email: 'carla@example.com', government_id: '00000000000')
864
+ client.signers.validate_create!(full_name: 'Alice Silva', email: 'alice@example.com') # no request
865
+ client.signers.get('signer-id')
866
+ client.signers.list(search: 'alice', per_page: 50) # returns { data:, meta: }
867
+ client.signers.update('signer-id', full_name: 'Alice S.', government_id: '00000000000')
868
+ client.signers.delete('signer-id')
869
+ client.signers.find_by_email('alice@example.com') # case-insensitive; nil when no match
870
+ ```
871
+
872
+ `signers.update` changes only supplied fields. Explicit `nil` or `''` clears email, WhatsApp number or
873
+ government ID; full_name cannot be cleared. Verified channels on unfinished requests cannot change, and changing
874
+ an unverified channel invalidates old invitation links. `confirm_data` only reads email, WhatsApp number and terms;
875
+ name/government-ID changes belong in workspace signer updates.
876
+
877
+ ### Signers (self-service, signer-access-code)
878
+
879
+ ```ruby
880
+ client.signers.self_data(signer_access_code: 'code') # includes has_signature, has_initial, is_signature_reusable
881
+ client.signers.accept_terms(signer_access_code: 'code')
882
+ client.signers.verify_email(verification_code: '123456', signer_access_code: 'code')
883
+ client.signers.confirm_data('document-id', { email: 'alice@example.com', has_accepted_terms: true }, signer_access_code: 'code')
884
+ client.signers.upload_signature(png_bytes, signer_access_code: 'code', type: 'signature', content_type: 'image/png')
885
+ client.signers.upload_signature(jpeg_bytes, signer_access_code: 'code', type: 'initial', content_type: 'image/jpeg')
886
+ client.signers.download_signature(signer_access_code: 'code', type: 'signature')
887
+ client.signers.theme(signer_access_code: 'code') # account_name, primary_color, secondary_color, logo
888
+ client.signers.download_logo(signer_access_code: 'code') # binary image; 404 when unset
889
+ ```
890
+
891
+ ### Assignments
892
+
893
+ ```ruby
894
+ # Virtual (no positioned fields)
895
+ client.assignments.create(
896
+ 'document-id',
897
+ method: 'virtual',
898
+ signers: [{ id: 'signer-1', verification_method: 'Email', notification_methods: ['Email'], step: 1 }],
899
+ message: 'Please sign',
900
+ expires_at: '2099-12-31T23:59:00Z',
901
+ copy_receivers: ['cc-signer-id']
902
+ )
903
+
904
+ # Collect (positioned fields)
905
+ client.assignments.create(
906
+ 'document-id',
907
+ method: 'collect',
908
+ signers: [{ id: 'signer-1' }],
909
+ entries: [{ page_id: 'page-id', fields: [{ signer_id: 'signer-1', field_id: 'field-id',
910
+ display_settings: { left: 100, top: 100, width: 240,
911
+ height: 48, fontSize: 16 } }] }]
912
+ )
913
+
914
+ client.assignments.list # GET /assignments (scoped to the account)
915
+ client.assignments.estimate_cost('document-id', signers: [{ verification_method: 'Whatsapp' }])
916
+ client.assignments.reset_expiration('document-id', 'assignment-id', '2099-12-31T23:59:00Z')
917
+ client.assignments.reset_expiration('document-id', 'assignment-id', nil) # clears the expiry
918
+ client.assignments.resend_notification('document-id', 'assignment-id', 'signer-id')
919
+ client.assignments.estimate_resend_cost('document-id', 'assignment-id', 'signer-id')
920
+ client.assignments.whatsapp_notifications('document-id', 'assignment-id')
921
+
922
+ # Signer perspective (signer-access-code authentication)
923
+ client.assignments.signer_document(signer_access_code: 'code', has_accepted_terms: true)
924
+ client.assignments.sign('document-id', 'assignment-id',
925
+ [{ item_id: 'i1', field_id: 'f1', page_id: 'p1', value: 'Alice' }],
926
+ signer_access_code: 'code')
927
+ client.assignments.decline('document-id', 'assignment-id', decline_reason: 'Clause 2', signer_access_code: 'code')
928
+ ```
929
+
930
+ The `sign` body is the API's camelCase exception: the SDK maps `item_id`/`field_id`/`page_id` to
931
+ `itemId`/`fieldId`/`pageId` (camelCase input passes through). Assignment listing sends the camelCase `accountId`
932
+ query parameter.
933
+
934
+ ### Signer documents (multi-document workflows)
935
+
936
+ ```ruby
937
+ client.signer_documents.current('signer-id', signer_access_code: 'code')
938
+ client.signer_documents.list('signer-id', { status: 'pending_signature' }, signer_access_code: 'code')
939
+ client.signer_documents.search('signer-id', 'contract', signer_access_code: 'code')
940
+ client.signer_documents.list_as_workspace('signer-id') # same route with your API key
941
+ client.signer_documents.search_as_workspace('signer-id', 'contract')
942
+ client.signer_documents.sign_multiple(%w[document-id-1 document-id-2], signer_access_code: 'code')
943
+ client.signer_documents.decline_multiple(%w[document-id-1 document-id-2], decline_reason: 'No', signer_access_code: 'code')
944
+ client.signer_documents.download('signer-id', 'document-id', signer_access_code: 'code') # original PDF only
945
+ client.signer_documents.send_certified_copy(signer_access_code: 'code', document_id: 'document-id')
946
+ # => { 'available' => true, 'notification_method' => 'Email', 'resends_left' => 2, 'sent_to' => 'a***@example.com' }
947
+ client.signer_documents.download_certified_copy('download-token', pades: false) # binary PDF, token only
948
+ client.signer_documents.resend_certified_copy('download-token') # delivery metadata as above
949
+ ```
950
+
951
+ Signer downloads require the access code and serve only `original`; use the workspace download API for other
952
+ artifacts. Certified copies are delivered by email or WhatsApp with their own download token. An expired token's
953
+ `302` is exposed as `ApiError`; the SDK does not follow it. For an envelope, pass `document_id` when selecting a
954
+ document or requesting its copy; `assignments.signer_document(expand: 'envelope', signer_access_code: 'code')`
955
+ includes the envelope's remaining documents.
956
+
957
+ ### Templates
958
+
959
+ ```ruby
960
+ client.templates.list(search: 'contract', per_page: 25)
961
+ client.templates.get('template-id')
962
+ client.templates.create({ file_path: './contract.pdf' }) # multipart upload, up to 25 MB
963
+ client.templates.create({ buffer: pdf_bytes, file_name: 'contract.pdf' })
964
+ client.templates.update('template-id', name: 'Renamed template')
965
+ client.templates.delete('template-id')
966
+ client.templates.download_page('template-id', 'page-id') # binary image bytes
967
+ ```
968
+
969
+ `get`, `create`, `update`, `delete`, and `download_page` are supported by the deployed API beyond the OpenAPI
970
+ document. `create` requires a source file; the template name defaults to the file's name. Template generation
971
+ needs one entry per role, using a distinct existing signer ID or an `email`/`name` pair;
972
+ `role_id` comes from the template's `roles`. Cost estimation requires `role_id` but can omit the signer ID.
973
+
974
+ ### Tags
975
+
976
+ ```ruby
977
+ client.tags.list(search: 'contract')
978
+ client.tags.create(name: 'Contracts', color: 'ff8800') # a leading # is stripped before sending
979
+ client.tags.update('tag-id', name: 'Sales Contracts', color: nil) # nil clears the color
980
+ client.tags.delete('tag-id') # fails with 409 if the tag is in use
981
+ client.tags.delete('tag-id', force: true) # detaches from documents/templates first
982
+ ```
983
+
984
+ ### Fields
985
+
986
+ ```ruby
987
+ client.fields.types # GET /field-types
988
+ client.fields.list(include_inactive: true, include_standard: false)
989
+ client.fields.create(type: 'text', name: 'Internal code', regex: '/[A-Z]{3}-[0-9]{4}/')
990
+ client.fields.get('field-id')
991
+ client.fields.update('field-id', name: 'Renamed')
992
+ client.fields.delete('field-id')
993
+
994
+ client.fields.validate('field-id', 'ABC-1234') # workspace user
995
+ client.fields.validate('field-id', 'ABC-1234', signer_access_code: 'code') # signer
996
+ client.fields.validate_multiple(
997
+ [{ field_id: 'field-id-1', value: '1' }, { field_id: 'field-id-2', value: 'value@example.com' }],
998
+ signer_access_code: 'code'
999
+ )
1000
+ ```
1001
+
1002
+ Single and batch field validation preserve explicit `nil` as JSON null. The API decides whether an empty value
1003
+ is allowed by that field; a batch item must still contain its `value` key. Zero is a value.
1004
+
1005
+ ### Webhooks
1006
+
1007
+ ```ruby
1008
+ client.webhooks.list_event_types # GET /webhooks/event-types
1009
+ client.webhooks.list_endpoints # oldest first
1010
+ client.webhooks.create_endpoint(url: 'https://example.com/webhooks/assinafy', email: 'ops@example.com',
1011
+ events: %w[document_ready], signing_enabled: true)
1012
+ client.webhooks.get_endpoint('webhook-endpoint-id')
1013
+ client.webhooks.update_endpoint('webhook-endpoint-id', is_active: false)
1014
+ client.webhooks.delete_endpoint('webhook-endpoint-id') # => nil
1015
+ client.webhooks.endpoint_secret('webhook-endpoint-id') # => { 'secret' => 'whsec_...' }
1016
+ client.webhooks.rotate_endpoint_secret('webhook-endpoint-id')
1017
+ client.webhooks.rotate_endpoint_secret('webhook-endpoint-id', keep_previous: true) # 24-hour overlap
1018
+ client.webhooks.test_endpoint('webhook-endpoint-id') # one manual delivery; returns its dispatch entry
1019
+
1020
+ client.webhooks.list_dispatches(endpoint_id: 'webhook-endpoint-id', delivered: false, per_page: 50)
1021
+ client.webhooks.retry_dispatch('dispatch-id')
1022
+
1023
+ # Subscription operations act on the account's oldest endpoint:
1024
+ client.webhooks.get # nil on 404
1025
+ client.webhooks.register(url: 'https://example.com/webhooks/assinafy', email: 'ops@example.com',
1026
+ events: %w[document_ready signer_signed_document])
1027
+ client.webhooks.inactivate # stop deliveries, keep the event set
1028
+ ```
1029
+
1030
+ `register` accepts only `url`, `email`, `events`, and `is_active`; other keys raise `ValidationError`. Use the
1031
+ endpoint operations for names, signing, and several endpoints.
1032
+
1033
+ ## Responses
1034
+
1035
+ Most JSON successes use a `{ "status": ..., "message": ..., "data": ... }` envelope. The SDK
1036
+ returns the `data` payload (a Hash for single resources, an Array for collection bodies). For
1037
+ documented no-data envelopes containing only `status`/`message`, it returns `nil`; deployed API
1038
+ versions that add `data` are passed through. Binary endpoints (`download`, `thumbnail`,
1039
+ `download_page`, `download_signature`) return raw bytes as an ASCII-8BIT `String`, and
1040
+ delete-style endpoints return `nil`.
1041
+
1042
+ OAuth endpoints are the exception: `/oauth/token`, `/oauth/revoke`, `/oauth/userinfo`, and the `.well-known`
1043
+ metadata documents answer with flat RFC 6749 / OIDC / RFC 8615 objects rather than the envelope, and the SDK
1044
+ returns those bodies unchanged.
1045
+
1046
+ The [SDK API reference](API_REFERENCE.md) maps every API operation to its Ruby method and documents exact
1047
+ authentication, parameters, request bodies, success responses, and every published schema property.
1048
+
1049
+ ## Pagination
1050
+
1051
+ Most `*.list*` methods return `{ data: [...], meta: { ... } }` when the API includes pagination
1052
+ headers. Ruby-style `per_page:` is transparently converted to the documented `per-page` query
1053
+ parameter (values above the API's maximum are clamped server-side). Endpoints that send no pagination headers
1054
+ (e.g. `accounts.list`) return `{ data: [...] }` without `meta`.
1055
+
1056
+ ```ruby
1057
+ result = client.documents.list(page: 2, per_page: 25)
1058
+ result[:data] # => Array<Hash>
1059
+ result[:meta] # => { current_page: 2, per_page: 25, total: 138, last_page: 6 }
1060
+ ```
1061
+
1062
+ ## Errors
1063
+
1064
+ The SDK raises one of:
1065
+
1066
+ - `Assinafy::ValidationError` — caller-side input invalid (missing IDs, bad email, etc.), raised before any request.
1067
+ - `Assinafy::ApiError` — the API returned a non-2xx status. Includes `status_code`, `message`, `error_name`,
1068
+ `error_code`, and `response_data`; on a `403`, `context[:www_authenticate]` names the scope an OAuth token is
1069
+ missing.
1070
+ - `Assinafy::OAuthError` — an OAuth endpoint failed. Subclasses `ApiError`, and adds `error` and
1071
+ `error_description` from the flat RFC 6749 body.
1072
+ - `Assinafy::NetworkError` — Faraday connection error, timeout, or TLS failure.
1073
+ - `Assinafy::Error` — base class; other unexpected errors get wrapped here with the operation label.
1074
+
1075
+ All inherit a `#context` Hash with debugging metadata.
1076
+
1077
+ Use `ApiError#error_code` for actionable refusals such as `PlanRestricted`, `InsufficientScope`,
1078
+ `ContractChanged`, or `CreditCeilingExceeded`. Field validation details remain in `response_data['errors']`,
1079
+ an array of `{ 'field' => ..., 'code' => ..., 'message' => ... }`; localized messages are for display, not branching.