assinafy 2.1.1 → 2.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d98e9a7dcc345cedc9196fe2356abde16e37ba098253ee66892fd62522d7eb92
4
- data.tar.gz: 63ea42ed9f2f171f111f174766a29e2df588fbc832bcee3ff57747ee539a7b34
3
+ metadata.gz: 073433eee6179fd50ee1c3d99d4bff3e2f04f4129ad3275fc04f846e39b7d517
4
+ data.tar.gz: e2af09f0adb1e6617b899edd87f8ade5d0b9cea2cf5dd3390042c6c03593e215
5
5
  SHA512:
6
- metadata.gz: 1e6c49c00aa499cc06db92281c54f41a58afbe5431d03e319153057f417a1490b65b128873d6201845d95e69b1ac90283dc8fbbaf5cc83517a8dc430b5b460a1
7
- data.tar.gz: ee0b354da27acc2bf7faa70e5416eec3e98fad6f72b822697d13d0dd7ff3938907848b772426157e5270f91f5f22d3b8c213390e8b114ef0a5adfb68ae3167b9
6
+ metadata.gz: a177feaf3de3dd3ee8c61709e3dc18e9116cceafd78a99bf2d713f858291f7b6ae5c3dd27d32469a470ecfc09604bd02ac17aa68205a4c00707e7f93a3ce73dc
7
+ data.tar.gz: ac13456281928324c7b80bee3c061648d3da5d5dcb67ba339383a561e794cffa0f07dbda8a94ee2ae9213efaaa653e9c7b2e35cb3803eeba6ef6c63aad078025
data/CHANGELOG.md CHANGED
@@ -2,6 +2,26 @@
2
2
 
3
3
  All notable changes to the `assinafy` Ruby gem are documented here.
4
4
 
5
+ ## [2.2.0] - 2026-11-11
6
+
7
+ ### Added
8
+
9
+ - Envelope creation, estimates, document management, reminders, activities and ZIP downloads through `client.envelopes`.
10
+ - Embedded signing origins and sessions, signer branding, and token-based certified-copy delivery and downloads.
11
+ - Account usage and notification policies, user push preferences, and webhook test deliveries.
12
+ - Credit ceilings for assignments, templates and envelopes; idempotency keys for template and envelope creation.
13
+ - Document and contract expansions, signed page renders, and `documents.activities_page` pagination metadata.
14
+ - Webhook secret rotation with a 24-hour overlap through `keep_previous: true`.
15
+
16
+ ### Fixed
17
+
18
+ - Signer downloads require the signer access code and default to the original artifact.
19
+ - Template creation supports email-based signer references and returns its asynchronous processing state.
20
+ - Template copy receivers no longer interfere with signing-step validation.
21
+ - Collect fields, credit ceilings, OAuth revocation secrets and contract inputs reject invalid values locally.
22
+ - OAuth assignment listing can use the token's workspace without a separate account ID.
23
+ - Signer confirmation and verification return the documented response shapes.
24
+
5
25
  ## [2.1.1] - 2026-11-02
6
26
 
7
27
  ### Fixed
data/README.en.md CHANGED
@@ -7,6 +7,9 @@
7
7
 
8
8
  Ruby SDK for the [Assinafy API v1](https://api.assinafy.com.br/v1/docs).
9
9
 
10
+ Run this SDK on your server. Mobile and browser clients call your backend; keep API keys, OAuth client secrets,
11
+ refresh tokens and signer access codes out of application bundles, logs and browser storage.
12
+
10
13
  The SDK exposes every Assinafy API v1 operation — including OAuth 2.1, two-factor authentication, webhook
11
14
  endpoints with native signatures, and the complete supported template lifecycle. The checked-in
12
15
  [`spec/api_coverage_spec.rb`](spec/api_coverage_spec.rb) validates that each route maps uniquely to a public SDK
@@ -157,8 +160,9 @@ client.auth.reset_password(email: 'user@example.com', new_password: 'new', token
157
160
  ## OAuth 2.1
158
161
 
159
162
  Use OAuth when an application acts **on behalf of a user**, with that user's permission. Unlike an API key, the
160
- token is scoped to one workspace and carries only the scopes the user approved. It never reaches billing, account
161
- lifecycle, credential management, webhook signing secrets, or admin surfaces, whatever scopes it holds.
163
+ token is scoped to one workspace and carries only the scopes the user approved. Third-party OAuth tokens cannot
164
+ reach billing, account lifecycle, credential management, webhook-secret reads, embed-session creation,
165
+ biometric review images/decisions, or admin surfaces, whatever scopes they hold.
162
166
 
163
167
  The flow is authorization-code with **mandatory PKCE**; the authorization server accepts `S256` only.
164
168
 
@@ -191,7 +195,7 @@ redirect_to Assinafy::OAuth.authorization_url(
191
195
  redirect_uri: 'https://app.example.com/oauth/callback',
192
196
  code_verifier: verifier,
193
197
  state: state,
194
- scope: %w[documents:read documents:write offline_access]
198
+ scope: %w[documents:read documents:write openid profile email offline_access]
195
199
  )
196
200
  ```
197
201
 
@@ -206,8 +210,11 @@ that are not yours. The code is single-use and expires 60 seconds after approval
206
210
  same `redirect_uri`, and never retry.
207
211
 
208
212
  ```ruby
209
- unless params[:state] == session.delete(:assinafy_state) &&
210
- params[:iss] == session.delete(:assinafy_issuer)
213
+ expected_state = session.delete(:assinafy_state)
214
+ expected_issuer = session.delete(:assinafy_issuer)
215
+ unless expected_state.is_a?(String) && !expected_state.empty? &&
216
+ expected_issuer.is_a?(String) && !expected_issuer.empty? &&
217
+ params[:state] == expected_state && params[:iss] == expected_issuer
211
218
  raise 'authorization response is not ours'
212
219
  end
213
220
  raise "authorization not granted: #{params[:error]}" if params[:error] # access_denied, invalid_scope, ...
@@ -219,7 +226,7 @@ tokens = Assinafy::Client.new.oauth.exchange_code(
219
226
  redirect_uri: 'https://app.example.com/oauth/callback'
220
227
  )
221
228
  # => { 'access_token' => ..., 'token_type' => 'Bearer', 'expires_in' => 3600,
222
- # 'refresh_token' => ..., 'scope' => 'documents:read documents:write' }
229
+ # 'refresh_token' => ..., 'scope' => 'documents:read documents:write openid profile email' }
223
230
  ```
224
231
 
225
232
  The SDK checks the `code_verifier` grammar locally, because the server reports a malformed verifier as
@@ -441,7 +448,7 @@ all-or-none, positive, and contiguous from 1; equal steps sign in parallel, and
441
448
  previous one finishes. A certificate signer is alone in its step. Deadlines are zoned ISO 8601 and at least one
442
449
  hour ahead.
443
450
 
444
- For a template, bind one distinct existing signer to each role and create the document and assignment together:
451
+ For a template, bind one distinct signer to each role; processing creates the document's assignment:
445
452
 
446
453
  ```ruby
447
454
  role_signer = {
@@ -454,10 +461,19 @@ role_signer = {
454
461
  client.documents.estimate_cost_from_template(template.fetch('id'), [role_signer])
455
462
  template_document = client.documents.create_from_template(
456
463
  template.fetch('id'), [role_signer],
457
- name: 'customer-agreement.pdf', message: 'Please review and sign.'
464
+ name: 'customer-agreement.pdf', message: 'Please review and sign.',
465
+ idempotency_key: 'template-request-id'
458
466
  )
467
+ # Initial response: status "uploaded", assignment nil; processing creates the assignment afterward.
468
+ # Follow document status/webhooks until pending_signature or failed.
469
+ # wait_until_ready waits for metadata and can return before the template assignment exists.
459
470
  ```
460
471
 
472
+ Template creation also accepts `email` and `name` for a role instead of an existing signer `id`; the server reuses
473
+ or creates the signer. Keep the same `idempotency_key` after a lost response to avoid duplicate documents and
474
+ charges. `max_total_credits` can cap creation costs; a higher actual price returns `409` with
475
+ `error_code == 'CreditCeilingExceeded'`, creating and charging nothing.
476
+
461
477
  **Shortcut.** `Client#upload_and_request_signatures` bundles upload, waiting, signer creation (including
462
478
  `government_id`), and a virtual assignment, validating the whole payload before anything is uploaded:
463
479
 
@@ -477,8 +493,11 @@ created so you can clean up.
477
493
 
478
494
  ### 6. The signer experience
479
495
 
480
- The signer receives an access link through the notification channel. Signer-facing calls use the one-time
481
- `signer-access-code` (a query parameter), not workspace credentials.
496
+ The signer receives an access link through the notification channel. Signer-facing calls use
497
+ `signer-access-code` as a query parameter, with workspace credentials removed. The code remains usable during
498
+ signing and closes 30 minutes after that signer is done; an envelope code closes after all their documents are
499
+ done. After closure, document reads return only signer status, theme/logo and certified-copy delivery remain
500
+ available, and other signer calls return `410`.
482
501
 
483
502
  ```ruby
484
503
  signing = Assinafy::Client.new(base_url: ENV.fetch('ASSINAFY_BASE_URL'))
@@ -489,7 +508,7 @@ signing.signers.accept_terms(signer_access_code: access_code) unless signer_data
489
508
 
490
509
  signing_document = signing.assignments.signer_document(signer_access_code: access_code, has_accepted_terms: true)
491
510
  signing.signers.confirm_data(
492
- signing_document.fetch('id'), { full_name: 'Example Signer', government_id: '00000000000' },
511
+ signing_document.fetch('id'), { email: 'signer@example.com', has_accepted_terms: true },
493
512
  signer_access_code: access_code
494
513
  )
495
514
  signing.signers.verify_email( # the OTP from email or WhatsApp
@@ -543,7 +562,7 @@ before any session or after Expired; restarting an Expired session costs nothing
543
562
  requires a new document and assignment.
544
563
 
545
564
  InReview lets the signer view, confirm data and sign while account review holds certification. After all signers
546
- sign, the document can be `pending_identity_review`. The account reviewer uses workspace credentials:
565
+ sign, the document can be `pending_identity_review`. The account reviewer uses an API key or user session:
547
566
 
548
567
  ```ruby
549
568
  review = client.assignments.identity_review(document.fetch('id'), assignment.fetch('id'), signer.fetch('id'))
@@ -562,6 +581,9 @@ client.assignments.decide_identity_review(
562
581
  most 2000 characters, goes to activities and the provider, and is never shown to the signer. Images exist only
563
582
  during InReview. Observe signer_identity_review_required, signer_identity_review_approved,
564
583
  signer_identity_review_rejected, signer_identity_verified and signer_identity_verification_failed events.
584
+ Third-party OAuth apps can read the review summary with `documents:read`; they cannot fetch evidence images or
585
+ submit the human review decision. For envelopes, one biometric check covers the signer's documents; rejection
586
+ cancels the whole envelope and notifies each recipient once.
565
587
 
566
588
  **A1/A3 certificate signers** complete their signature in Assinafy's hosted signing flow, opened from
567
589
  `assignment['signing_urls']`: they accept the terms, confirm their data, and sign with their A1 or A3 certificate
@@ -592,17 +614,22 @@ secret = endpoint.fetch('secret') # returned once on creation; store it immediat
592
614
  - Creating one past the plan limit answers `403`; a URL another endpoint already uses answers `400`.
593
615
  - `update_endpoint(id, payload)` changes only the fields sent. `signing_enabled: true` creates a secret when the
594
616
  endpoint has none and keeps the current one otherwise; `false` discards it.
595
- - `rotate_endpoint_secret(id)` returns a new secret; the old one stops working immediately.
596
- - Reading and rotating secrets is not available to OAuth applications — use an API key or a user session token.
597
- Both answer `400` when signing is disabled. An OAuth app that loses its secret must delete and recreate the endpoint.
617
+ - `rotate_endpoint_secret(id)` returns a new secret; the old one stops working immediately. Pass
618
+ `keep_previous: true` for 24 hours of signatures from both secrets while receivers switch.
619
+ - Reading a secret requires an API key or user session. Rotation is available to OAuth apps with
620
+ `webhooks:write`, including recovery of a lost secret. Both methods answer `400` when signing is disabled.
621
+ - Enabling signing with `update_endpoint` returns the new secret once. Store it before using the endpoint.
598
622
  - `list_endpoints(url: registered_url)` filters by exact URL; `delete_endpoint_by_url(registered_url)` removes
599
623
  that endpoint and returns `nil` (`404` when no endpoint matches).
600
624
 
601
625
  **Delivery contract.** Each delivery is a `POST` with an `application/json` body and the headers `webhook-id`
602
626
  (identical on every attempt of the same event to the same endpoint — deduplicate on it), `webhook-timestamp`
603
- (Unix seconds), and, when signing is enabled, `webhook-signature`. Any `2xx` is success. Each event gets up to 2
604
- attempts, 3 seconds apart; after 10 consecutive failed events the endpoint's deliveries pause and only a sample is
605
- probed until one succeeds. Force a redelivery with `retry_dispatch`.
627
+ (Unix seconds), and, when signing is enabled, `webhook-signature`. Any `2xx` is success. Network failures,
628
+ timeouts, `408`, `429` and `5xx` get up to six attempts about ten minutes apart; other statuses are final.
629
+ After ten failed deliveries in a row the endpoint pauses. Probes follow after 3, 15 and 60 minutes, then every
630
+ six hours; success releases queued events oldest first. Updating its URL or setting `is_active: true` also lifts
631
+ the pause. `retry_dispatch` sends now; `test_endpoint` sends a separate `webhook_test` without changing the pause.
632
+ Delivery history is retained for seven days and captures the first 2000 response-body characters.
606
633
 
607
634
  **Verifying signatures.** Signatures follow [Standard Webhooks](https://www.standardwebhooks.com): space-separated
608
635
  `v1,<base64 HMAC-SHA256>` entries over `"{webhook-id}.{webhook-timestamp}.{raw body}"`, keyed with the
@@ -641,6 +668,9 @@ subject, object, account_id }`. `subject` and `object` carry a `type` (`User`, `
641
668
  `verify(raw_body, hex_signature)` remains only for receivers whose own gateway signs bodies with a hex
642
669
  HMAC-SHA256 shared secret.
643
670
 
671
+ Give the webhook event table a unique index on `webhook_id`, process events idempotently, and arrange durable
672
+ job delivery before acknowledging the request so concurrent retries or a failed enqueue cannot lose an event.
673
+
644
674
  ### 8. Track progress, download, and verify
645
675
 
646
676
  ```ruby
@@ -648,7 +678,8 @@ document_id = document.fetch('id')
648
678
 
649
679
  client.documents.signing_progress(document_id) # => { signed: 1, total: 2, pending: 1, percentage: 50.0 }
650
680
  client.documents.fully_signed?(document_id)
651
- client.documents.activities(document_id) # => Array<DocumentActivity>
681
+ client.documents.activities(document_id) # => one page of Array<DocumentActivity>
682
+ client.documents.activities_page(document_id, page: 1, per_page: 20) # => { data:, meta: }
652
683
 
653
684
  signed_pdf = client.documents.download(document_id, 'certificated')
654
685
  # also 'original', 'certificate-page', 'bundle' (zip), and 'pades' for certificate-signed documents
@@ -691,7 +722,7 @@ See [Errors](#errors) for the full hierarchy.
691
722
 
692
723
  ## Resource reference
693
724
 
694
- `Assinafy::Client` exposes fourteen accessors — thirteen API resources plus the local `webhook_verifier` helper:
725
+ `Assinafy::Client` exposes the API resources below plus the local `webhook_verifier` helper:
695
726
 
696
727
  | Accessor | What it covers |
697
728
  | --------------------------- | ------------------------------------------------------------------ |
@@ -700,6 +731,7 @@ See [Errors](#errors) for the full hierarchy.
700
731
  | `client.accounts` | Account CRUD, theme, KPI stats, brand logo |
701
732
  | `client.users` | User profile, notification preferences, cross-account KPIs |
702
733
  | `client.documents` | Upload, list, search, rename, download, delete, verify, tags |
734
+ | `client.envelopes` | Send several documents together, estimate, reorder, cancel and download |
703
735
  | `client.contracts` | Contract terms, amendments, renewals, terminations |
704
736
  | `client.signers` | Workspace signer CRUD + signer self-service endpoints |
705
737
  | `client.signer_documents` | Signer-authenticated multi-document operations + search |
@@ -715,6 +747,7 @@ See [Errors](#errors) for the full hierarchy.
715
747
  ```ruby
716
748
  client.accounts.list # { data: [...] } — no pagination meta
717
749
  client.accounts.get # the current account (or pass an id)
750
+ client.accounts.get(expand: 'signing_features') # includes available signing features
718
751
  client.accounts.create(name: 'Acme Inc.')
719
752
  client.accounts.update({ name: 'Acme Renamed' })
720
753
  client.accounts.delete(force: true, account_id_override: 'account-id')
@@ -723,8 +756,15 @@ client.accounts.stats(granularity: 'monthly', month: '2026-06') # account KPI r
723
756
  client.accounts.upload_logo({ file_path: './logo.png' })
724
757
  client.accounts.download_logo # raw bytes; raises ApiError on HTTP 404 when unset
725
758
  client.accounts.delete_logo
759
+ client.accounts.usage # { 'plan' => ..., 'documents_renewal_date' => ..., 'balances' => { ... } }
760
+ client.accounts.notification_policy # { 'editable' => true, 'owners_receive_all' => false, 'events' => { ... } }
761
+ client.accounts.update_notification_policy(events: { SignerViewed: false }, owners_receive_all: true)
726
762
  ```
727
763
 
764
+ Usage and notification policy are unavailable to third-party OAuth applications. Policy writes require an owner;
765
+ they merge only supplied event flags. A disabled workspace event suppresses it across channels even when a
766
+ member enables it. `SignerIdentityReviewRequired: false` disables only push; its email is always sent.
767
+
728
768
  ### Users
729
769
 
730
770
  ```ruby
@@ -732,8 +772,13 @@ client.users.me
732
772
  client.users.stats(granularity: 'daily', month: '2026-06') # cross-account KPI rows
733
773
  client.users.notification_preferences # returns all thirteen owner-email preferences
734
774
  client.users.update_notification_preferences(SignerDeclined: false) # partial request; returns all thirteen
775
+ client.users.push_preferences # eight phone-push preferences; separate from email
776
+ client.users.update_push_preferences(SignerViewed: false) # partial request; returns the full push map
735
777
  ```
736
778
 
779
+ Email and push preferences apply to the user across workspaces. They accept boolean values and reject unknown
780
+ keys or an empty update. These personal settings are unavailable to third-party OAuth applications.
781
+
737
782
  Both stats methods validate `granularity` (`monthly` or `daily`) and `month` (`YYYY-MM`) locally; daily statistics
738
783
  require `month`. They return rows
739
784
  with `period`, `documents_uploaded`, `documents_sent`, `signature_requests`,
@@ -749,17 +794,22 @@ with `period`, `documents_uploaded`, `documents_sent`, `signature_requests`,
749
794
  client.documents.statuses # GET /documents/statuses
750
795
  client.documents.list(page: 1, per_page: 20, status: 'pending_signature')
751
796
  client.documents.list(tags: ['tag-id-1', 'tag-id-2']) # documents carrying every listed tag
797
+ client.documents.list(envelope_id: 'envelope-id') # documents in an envelope
752
798
  client.documents.search('contract') # lightweight GET .../documents/search
753
799
  client.documents.upload({ file_path: './contract.pdf' }) # named after the file
754
800
  client.documents.upload({ buffer: pdf_bytes, file_name: 'contract.pdf' })
755
801
  client.documents.rename('document-id', 'renamed.pdf') # PATCH /documents/{id}
756
802
  client.documents.get('document-id') # alias of .details
803
+ client.documents.details('document-id', expand: ['envelope_id', 'envelope'])
757
804
  client.documents.wait_until_ready('document-id', max_wait_seconds: 60)
758
805
  client.documents.activities('document-id')
806
+ client.documents.activities_page('document-id', sort: '-id', page: 1, per_page: 20)
759
807
  client.documents.thumbnail('document-id') # binary PNG/JPEG
808
+ client.documents.thumbnail('document-id', artifact: 'certificated') # rendered signed content
760
809
  client.documents.download('document-id', 'certificated') # binary PDF
761
810
  client.documents.download('document-id', 'pades') # signed PAdES artifact
762
811
  client.documents.download_page('document-id', 'page-id')
812
+ client.documents.download_page('document-id', 'page-id', artifact: 'certificated')
763
813
  client.documents.delete('document-id')
764
814
  client.documents.verify('signature-hash')
765
815
  client.documents.public_info('document-id')
@@ -783,6 +833,83 @@ client.documents.signing_progress('document-id') # => { signed: 1, total: 2, p
783
833
  An Array `tags` filter is sent as comma-separated tag IDs. The tag arrays of `replace_tags`/`append_tags` take tag
784
834
  IDs.
785
835
 
836
+ Activities default to twenty per page. `activities` preserves the Array return; `activities_page` exposes the
837
+ pagination headers so callers can traverse every event. Signed thumbnails/pages use `artifact: 'certificated'`
838
+ with workspace credentials. The first render can wait up to thirty seconds, then return `503` with `Retry-After`;
839
+ the SDK does not retry. These renders carry `Cache-Control: no-store`. Certificate pages have no document page
840
+ IDs, and the qualified certificate seal is available in the `pades` artifact.
841
+
842
+ ### Envelopes
843
+
844
+ Send up to 20 prepared documents to up to 20 existing signers in one invitation. Each document retains its own
845
+ assignment, status and artifacts. All envelope signers sign in parallel; no `step` is accepted.
846
+
847
+ ```ruby
848
+ request = {
849
+ name: 'Agreement and annex',
850
+ signers: [{ id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'] }],
851
+ documents: [
852
+ { id: 'agreement-id', signer_ids: ['signer-id'] },
853
+ { id: 'annex-id', signer_ids: ['signer-id'] }
854
+ ]
855
+ }
856
+ estimate = client.envelopes.estimate_cost(request)
857
+ envelope = client.envelopes.create(
858
+ request.merge(max_total_credits: estimate.fetch('total_credits')), idempotency_key: 'envelope-request-id'
859
+ )
860
+ # => { 'id' => 'envelope-id', 'name' => 'Agreement and annex', 'message' => nil,
861
+ # 'documents' => [...], 'counts' => { 'pending_signature' => 2 },
862
+ # 'signing_urls' => [...], 'created_at' => '2026-11-11T12:00:00Z' }
863
+
864
+ client.envelopes.list(status: 'open') # { data: [...], meta: { ... } }
865
+ client.envelopes.get(envelope.fetch('id'))
866
+ client.envelopes.update(envelope.fetch('id'), document_ids: %w[annex-id agreement-id], message: nil)
867
+ client.envelopes.activities(envelope.fetch('id')) # paginated events with document_id/document_name
868
+ client.envelopes.resend_notification(envelope.fetch('id'), 'signer-id') # { 'is_sent' => true, ... }
869
+ client.envelopes.add_document(envelope.fetch('id'), id: 'extra-document-id', signer_ids: ['signer-id'])
870
+ client.envelopes.remove_document(envelope.fetch('id'), 'extra-document-id') # cancels and removes that open document
871
+ archive = client.envelopes.download(envelope.fetch('id'), 'original') # ZIP bytes in envelope order
872
+ client.envelopes.cancel(envelope.fetch('id')) # [{ 'id' => ..., 'status' => ..., 'cancelled' => true }]
873
+ client.envelopes.delete(envelope.fetch('id')) # nil; closed envelopes only, documents remain
874
+ ```
875
+
876
+ `collect` documents add positioned `entries` whose field signers exactly match `signer_ids`. Every envelope
877
+ signer must appear on a document. A certificate signer signs alone on each virtual document and is charged per
878
+ document; a biometric signer verifies once for the envelope. Preserve the creation idempotency key after an
879
+ ambiguous response. `max_total_credits` prevents creating or charging an envelope above the approved cost.
880
+
881
+ ### Embedded signing
882
+
883
+ Requires the account's Embed feature and an API key or user session; third-party OAuth cannot create sessions.
884
+ Register exact allowed origins, then mark the signer `embedded: true` with Email or Whatsapp verification:
885
+
886
+ ```ruby
887
+ origin = client.accounts.create_embed_origin('https://app.example.com')
888
+ # => { 'id' => 'origin-id', 'origin' => 'https://app.example.com', 'created_at' => '2026-11-11T12:00:00Z' }
889
+ client.accounts.list_embed_origins
890
+ client.accounts.update_embed_origin(origin.fetch('id'), 'https://sign.example.com')
891
+
892
+ assignment = client.assignments.create(
893
+ 'document-id', method: 'virtual',
894
+ signers: [{ id: 'signer-id', verification_method: 'Email', notification_methods: ['Email'], embedded: true }]
895
+ )
896
+ session = client.assignments.create_embed_session('document-id', assignment.fetch('id'), 'signer-id')
897
+ # => { 'url' => 'https://app.assinafy.com.br/embed/session-token', 'expires_at' => '2026-11-11T12:05:00Z' }
898
+ # Pass session['url'] only to the intended signer's page and load it in an iframe.
899
+ client.accounts.delete_embed_origin(origin.fetch('id')) # nil; removes that embedding permission
900
+ ```
901
+
902
+ Origins have no path, query, fragment or wildcard; HTTPS is required except HTTP localhost/127.0.0.1.
903
+ At most ten origins are allowed. Mint a fresh single-use URL for each frame display; it expires after five
904
+ minutes. `signing_urls` contains `url: nil, embedded: true` for embedded signers; invitations still deliver their
905
+ code. Follow the live [Embedded Signing Guide](https://api.assinafy.com.br/v1/docs) for the `assinafy:hello`
906
+ handshake and validate both `postMessage` origin and iframe window. Confirm completion through a webhook or
907
+ document read; frame events alone do not authorize application actions.
908
+
909
+ `assignments.exchange_embed_session(token, parent_origin:)` is the token-only operation used by the Assinafy
910
+ embed page. An ordinary integration loads the session URL; it does not exchange the token itself or expose the
911
+ returned signer access code. Resend the code through `assignments.resend_notification` from your backend.
912
+
786
913
  ### Contracts
787
914
 
788
915
  ```ruby
@@ -796,6 +923,7 @@ contract = client.contracts.update(
796
923
  client.contracts.get('document-id')
797
924
  client.contracts.list(status: ['active'], ending_within_days: 30)
798
925
  client.contracts.related('document-id')
926
+ client.contracts.related('document-id', expand: 'document') # also includes the parent document
799
927
  client.contracts.renew('document-id', term: contract['term'], updated_at: contract['updated_at'])
800
928
  client.contracts.terminate('document-id', reason: 'Ended by the parties')
801
929
  ```
@@ -824,9 +952,11 @@ client.signers.find_by_email('alice@example.com') # case-insensitive; nil when
824
952
  client.signers.self_data(signer_access_code: 'code') # includes has_signature, has_initial, is_signature_reusable
825
953
  client.signers.accept_terms(signer_access_code: 'code')
826
954
  client.signers.verify_email(verification_code: '123456', signer_access_code: 'code')
827
- client.signers.confirm_data('document-id', { full_name: 'Alice Silva', email: 'alice@example.com', government_id: '00000000000' }, signer_access_code: 'code')
955
+ client.signers.confirm_data('document-id', { email: 'alice@example.com', has_accepted_terms: true }, signer_access_code: 'code')
828
956
  client.signers.upload_signature(png_bytes, signer_access_code: 'code', type: 'signature', content_type: 'image/png')
829
957
  client.signers.download_signature(signer_access_code: 'code', type: 'signature')
958
+ client.signers.theme(signer_access_code: 'code') # account_name, primary_color, secondary_color, logo
959
+ client.signers.download_logo(signer_access_code: 'code') # binary image; 404 when unset
830
960
  ```
831
961
 
832
962
  ### Assignments
@@ -882,9 +1012,19 @@ client.signer_documents.list_as_workspace('signer-id') # same ro
882
1012
  client.signer_documents.search_as_workspace('signer-id', 'contract')
883
1013
  client.signer_documents.sign_multiple(%w[document-id-1 document-id-2], signer_access_code: 'code')
884
1014
  client.signer_documents.decline_multiple(%w[document-id-1 document-id-2], decline_reason: 'No', signer_access_code: 'code')
885
- client.signer_documents.download('signer-id', 'document-id', 'pades') # public: no access code needed
1015
+ client.signer_documents.download('signer-id', 'document-id', signer_access_code: 'code') # original PDF only
1016
+ client.signer_documents.send_certified_copy(signer_access_code: 'code', document_id: 'document-id')
1017
+ # => { 'available' => true, 'notification_method' => 'Email', 'resends_left' => 2, 'sent_to' => 'a***@example.com' }
1018
+ client.signer_documents.download_certified_copy('download-token', pades: false) # binary PDF, token only
1019
+ client.signer_documents.resend_certified_copy('download-token') # delivery metadata as above
886
1020
  ```
887
1021
 
1022
+ Signer downloads require the access code and serve only `original`; use the workspace download API for other
1023
+ artifacts. Certified copies are delivered by email or WhatsApp with their own download token. An expired token's
1024
+ `302` is exposed as `ApiError`; the SDK does not follow it. For an envelope, pass `document_id` when selecting a
1025
+ document or requesting its copy; `assignments.signer_document(expand: 'envelope', signer_access_code: 'code')`
1026
+ includes the envelope's remaining documents.
1027
+
888
1028
  ### Templates
889
1029
 
890
1030
  ```ruby
@@ -899,8 +1039,8 @@ client.templates.download_page('template-id', 'page-id') # binary image bytes
899
1039
 
900
1040
  `get`, `create`, `update`, `delete`, and `download_page` are supported by the deployed API beyond the OpenAPI
901
1041
  document. `create` requires a source file; the template name defaults to the file's name. Template generation
902
- needs one entry per role, each with a distinct existing signer ID; `role_id` comes from the template's `roles`.
903
- Cost estimation requires `role_id` but can omit the signer ID.
1042
+ needs one entry per role, using a distinct existing signer ID or an `email`/`name` pair;
1043
+ `role_id` comes from the template's `roles`. Cost estimation requires `role_id` but can omit the signer ID.
904
1044
 
905
1045
  ### Tags
906
1046
 
@@ -942,6 +1082,8 @@ client.webhooks.update_endpoint('webhook-endpoint-id', is_active: false)
942
1082
  client.webhooks.delete_endpoint('webhook-endpoint-id') # => nil
943
1083
  client.webhooks.endpoint_secret('webhook-endpoint-id') # => { 'secret' => 'whsec_...' }
944
1084
  client.webhooks.rotate_endpoint_secret('webhook-endpoint-id')
1085
+ client.webhooks.rotate_endpoint_secret('webhook-endpoint-id', keep_previous: true) # 24-hour overlap
1086
+ client.webhooks.test_endpoint('webhook-endpoint-id') # one manual delivery; returns its dispatch entry
945
1087
 
946
1088
  client.webhooks.list_dispatches(endpoint_id: 'webhook-endpoint-id', delivered: false, per_page: 50)
947
1089
  client.webhooks.retry_dispatch('dispatch-id')
@@ -1000,12 +1142,17 @@ The SDK raises one of:
1000
1142
 
1001
1143
  All inherit a `#context` Hash with debugging metadata.
1002
1144
 
1145
+ Use `ApiError#error_code` for actionable refusals such as `PlanRestricted`, `InsufficientScope`,
1146
+ `ContractChanged`, or `CreditCeilingExceeded`. Field validation details remain in `response_data['errors']`,
1147
+ an array of `{ 'field' => ..., 'code' => ..., 'message' => ... }`; localized messages are for display, not branching.
1148
+
1003
1149
  ## Tests
1004
1150
 
1005
1151
  ```bash
1006
1152
  bundle exec rake spec # RSpec, including a coverage matrix
1007
- bundle exec rubocop # Linting
1008
- bundle exec bundler-audit check # Dependency CVEs
1153
+ bundle exec rubocop --cache false # Linting
1154
+ bundle exec bundler-audit check --update # Dependency CVEs
1155
+ rbs -I sig validate # Published signatures (install rbs outside the bundle)
1009
1156
  ruby scripts/check_api_contract.rb --file path/to/openapi.json # validate a local contract document
1010
1157
  ```
1011
1158
 
data/README.md CHANGED
@@ -29,8 +29,9 @@ client = Assinafy::Client.new(
29
29
  )
30
30
  ```
31
31
 
32
- Use `https://sandbox.assinafy.com.br/v1` no sandbox. O SDK exige URL absoluta, usa TLS 1.2+ e aceita exatamente
33
- uma credencial por cliente: `api_key:` para a workspace ou `token:` para sessão/OAuth. Endpoints públicos e de
32
+ Use `https://sandbox.assinafy.com.br/v1` no sandbox. O SDK exige URL absoluta, usa TLS 1.2+ e aceita
33
+ credenciais por cliente: prefira `api_key:` para a workspace ou `token:` para sessão/OAuth; se ambas forem
34
+ configuradas, a chave não vazia tem precedência. Endpoints públicos e de
34
35
  signatário removem essas credenciais e enviam apenas o código próprio da operação.
35
36
 
36
37
  ## OAuth 2.1 para marketplace
@@ -47,7 +48,7 @@ url = Assinafy::OAuth.authorization_url(
47
48
  redirect_uri: 'https://app.example.com/oauth/callback',
48
49
  code_verifier: verifier,
49
50
  state: state,
50
- scope: %w[documents:read documents:write offline_access]
51
+ scope: %w[openid profile email documents:read documents:write offline_access]
51
52
  )
52
53
  ```
53
54
 
@@ -104,7 +105,13 @@ assignment = client.assignments.create(document.fetch('id'), request)
104
105
  ```
105
106
 
106
107
  `Client#upload_and_request_signatures` executa upload, signatários e assignment numa chamada e valida todo o
107
- pedido antes da rede. Templates configurados usam `client.documents.create_from_template`.
108
+ pedido antes da rede. Templates configurados usam `client.documents.create_from_template`; aguarde o estado
109
+ `pending_signature` para ler o assignment gerado. `idempotency_key:` evita duplicar a criação após perda de resposta.
110
+
111
+ Para vários documentos na mesma solicitação, use `client.envelopes.estimate_cost` e `create` com `name`,
112
+ `signers` e `documents: [{ id: 'document-id', signer_ids: ['signer-id'] }]`. Cada documento mantém sua assinatura
113
+ e artefatos; a criação aceita `idempotency_key:` e `max_total_credits` limita o gasto. A mesma proteção de custo
114
+ existe em assignments e templates. Consulte uso e recursos do plano em `accounts.usage` e `accounts.get`.
108
115
 
109
116
  ### Verificação e notificação
110
117
 
@@ -122,13 +129,18 @@ sozinho na etapa. `expires_at` deve ter fuso e ficar pelo menos uma hora no futu
122
129
  Na biometria, `signers.start_identity_verification(consent: true, signer_access_code:)` devolve uma URL bearer:
123
130
  preserve o fragmento e não a armazene em logs ou browser storage. O revisor usa `assignments.identity_review`,
124
131
  `identity_review_image` e `decide_identity_review`. Evidências existem apenas durante `InReview` e não devem ser
125
- cacheadas. Uma rejeição cancela o documento. Certificados A1/A3 são concluídos no fluxo hospedado; o SDK não
132
+ cacheadas; imagens e decisões exigem chave/sessão. OAuth pode ler o resumo com `documents:read`. Uma rejeição
133
+ cancela o documento. Certificados A1/A3 são concluídos no fluxo hospedado; o SDK não
126
134
  inventa os endpoints de handshake ainda não publicados.
127
135
 
128
136
  Operações do signatário usam `signer_access_code:` sem chave/token da workspace. O fluxo inclui termos,
129
137
  confirmação de dados, OTP, identidade, imagem de assinatura, `assignments.sign`/`decline` e operações em lote em
130
138
  `signer_documents`.
131
139
 
140
+ Assinatura embutida usa `embedded: true` em signatários Email/Whatsapp, origens cadastradas em `accounts` e
141
+ `assignments.create_embed_session` no servidor. Exige recurso Embed e chave/sessão, sem OAuth de terceiros.
142
+ Downloads de original exigem código do signatário; cópias certificadas usam links temporários autenticados.
143
+
132
144
  ## Webhooks e artefatos
133
145
 
134
146
  Crie o endpoint com `signing_enabled: true`, guarde o segredo `whsec_...` retornado uma vez e verifique o corpo
@@ -149,7 +161,8 @@ event = verifier.extract_event(raw_body)
149
161
  ```
150
162
 
151
163
  Deduplicate por `webhook-id`. O timestamp tem tolerância padrão de 300 segundos. Aplicações OAuth precisam guardar
152
- o segredo da criação: leitura e rotação exigem chave de API ou sessão de usuário. Depois da certificação, use
164
+ o segredo da criação: a leitura exige chave/sessão; OAuth com `webhooks:write` pode rotacionar e guardar o novo
165
+ segredo. `keep_previous: true` mantém ambos por 24 horas. Depois da certificação, use
153
166
  `documents.download`, `thumbnail`, `download_page`, `activities` e `verify` conforme o artefato.
154
167
 
155
168
  ## Contratos, erros e recursos
@@ -164,7 +177,7 @@ Falhas da API levantam `Assinafy::ApiError`; OAuth usa `OAuthError < ApiError`;
164
177
  `{ data:, meta: }`, listas simples devolvem `Array`, binários devolvem `String` e respostas vazias devolvem `nil`.
165
178
 
166
179
  Recursos: `accounts`, `auth`, `oauth`, `users`, `documents`, `contracts`, `signers`, `signer_documents`,
167
- `assignments`, `templates`, `tags`, `fields`, `webhooks` e `webhook_verifier`. As assinaturas RBS publicadas ficam em
180
+ `assignments`, `envelopes`, `templates`, `tags`, `fields`, `webhooks` e `webhook_verifier`. As assinaturas RBS ficam em
168
181
  [`sig/assinafy.rbs`](sig/assinafy.rbs).
169
182
 
170
183
  ## Desenvolvimento