@assinafy/sdk 3.0.2 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/docs/README.en.md CHANGED
@@ -4,9 +4,9 @@
4
4
 
5
5
  TypeScript SDK for the [Assinafy API](https://api.assinafy.com.br/v1/docs) — a Brazilian digital signature platform.
6
6
 
7
- Maps all 147 operations in the current official OpenAPI document (146 with SDK
8
- methods; the embed session exchange is reserved for Assinafy's embed page): accounts,
9
- authentication, OAuth 2.1 applications, users, documents, assignments,
7
+ Maps all 158 operations in the current official OpenAPI document (142 with SDK
8
+ methods; the embed session exchange and the login, password, two-factor and API
9
+ key routes belong to the Assinafy app): accounts, OAuth 2.1 applications, users, documents, assignments,
10
10
  envelopes, embedded signing, signers, signer-side flows, contract lifecycle
11
11
  management (CLM), templates, tags, fields, webhooks, branding, plan usage,
12
12
  notification policy, statistics, and
@@ -15,8 +15,8 @@ template-management routes used by existing integrations and two legacy browser
15
15
  URL helpers are retained for compatibility.
16
16
 
17
17
  See [API coverage](API_COVERAGE.md) for the operation map and
18
- [compatibility notes](COMPATIBILITY.md) for deployment-specific request
19
- and response variants.
18
+ [compatibility notes](COMPATIBILITY.md) for the request and response variants
19
+ the SDK accepts.
20
20
 
21
21
  ## Contents
22
22
 
@@ -45,13 +45,12 @@ afterwards.
45
45
  [embedded signing](#embedded-signing) · [templates](#templates) ·
46
46
  [tags](#tags) · [workspaces](#workspaces) ·
47
47
  [field definitions](#field-definitions) ·
48
- [auth and API keys](#authentication--api-key-management) ·
49
48
  [the current user](#authenticated-user) · [webhooks](#webhooks)
50
49
  ([verification](#webhook-verification)) ·
51
50
  [signer-side endpoints](#signer-side-endpoints)
52
51
 
53
52
  **Everything else** — [High-level helper](#high-level-helper) ·
54
- [Errors](#errors) · [Environments](#environments) ·
53
+ [Errors](#errors) · [API host](#api-host) ·
55
54
  [Development](#development) · [License](#license)
56
55
 
57
56
  ## Requirements
@@ -109,14 +108,16 @@ and ICP-Brasil certificate signing have separate prerequisites and costs; see
109
108
 
110
109
  ## Authentication
111
110
 
112
- The API supports three credentials. Which one you need depends on *whose*
113
- workspace you are acting in.
111
+ The SDK authenticates with an API key or an OAuth access token. Which one you
112
+ need depends on *whose* workspace you are acting in.
114
113
 
115
114
  | Credential | Acts on | Choose it when |
116
115
  | --- | --- | --- |
117
- | `apiKey` (`X-Api-Key`) | **Your own** workspace | You automate your own account. Recommended for back-end services. |
118
- | `token` (`Authorization: Bearer`) | The logged-in user | You bootstrapped a session with `auth.login()`. |
119
- | OAuth access token (`Authorization: Bearer`) | **Someone else's** workspace, with their permission | You build an app other people connect. See [OAuth applications](#oauth-applications). |
116
+ | `apiKey` (`X-Api-Key`) | **Your own** workspace | You automate your own account. Recommended for back-end services. The user creates the key logged in to the Assinafy app. |
117
+ | `token` (`Authorization: Bearer`) | **Someone else's** workspace, with their permission | You build an app other people connect: an OAuth access token. See [OAuth applications](#oauth-applications). |
118
+
119
+ Login, password, two-factor and API key management belong to the Assinafy app;
120
+ the SDK does not expose them.
120
121
 
121
122
  Prefer `apiKey` for a server-to-server integration — it maps to the `X-Api-Key`
122
123
  header recommended by Assinafy for backend services.
@@ -125,12 +126,12 @@ header recommended by Assinafy for backend services.
125
126
  // Preferred: X-Api-Key header
126
127
  new AssinafyClient({ apiKey: 'k_xxx', accountId: 'acc_xxx' });
127
128
 
128
- // Access token: Authorization: Bearer <token>
129
- new AssinafyClient({ token: 'jwt_xxx', accountId: 'acc_xxx' });
129
+ // OAuth access token: Authorization: Bearer <token>
130
+ new AssinafyClient({ token: oauthAccessToken, accountId: 'acc_xxx' });
130
131
  ```
131
132
 
132
133
  Credentials are optional at construction time. A credentialless client uses a
133
- separate, auth-free transport for public authentication and signer-access-code
134
+ separate, auth-free transport for public, OAuth and signer-access-code
134
135
  operations, so an API key or Bearer token is never attached accidentally:
135
136
 
136
137
  ```ts
@@ -138,7 +139,6 @@ const publicClient = new AssinafyClient({
138
139
  baseUrl: 'https://api.assinafy.com.br/v1',
139
140
  });
140
141
 
141
- await publicClient.auth.login('me@example.com', 'password');
142
142
  await publicClient.documents.getPublic(documentId);
143
143
  await publicClient.signerDocuments.self(signerAccessCode);
144
144
  ```
@@ -321,8 +321,11 @@ On an HTTP `429`, the client automatically retries up to `maxRetries` times,
321
321
  waiting for the server-provided `Retry-After` (or `X-Rate-Limit-Reset`) delay
322
322
  before each attempt. Automatic replay is limited to read-safe `GET`, `HEAD`,
323
323
  `OPTIONS`, and `DELETE` requests. `GET /sign` is excluded because it records
324
- that the signer viewed the assignment. Writes are not replayed by default.
325
- A non-empty `Idempotency-Key` opts a request into SDK replay. Envelope creation
324
+ that the signer viewed the assignment. Writes are not replayed by default, and
325
+ `PUT` and `PATCH` never are. A non-empty `Idempotency-Key` opts a `POST` into SDK replay. When
326
+ the server asks to wait longer than the retry cap (30 s) — the free plan's daily
327
+ signer e-mail limit answers `429 FreePlanEmailLimit` with a wait of hours — the
328
+ `ApiError` is thrown at once instead. Envelope creation
326
329
  and template document creation deduplicate it server-side, so
327
330
  `envelopes.create(…, { idempotencyKey })` and `documents.createFromTemplate(…,
328
331
  { idempotencyKey })` are safe to retry; other routes ignore the header. No
@@ -344,20 +347,117 @@ const client = AssinafyClient.fromConfig({
344
347
  The configuration object accepted by `fromConfig` has the exported type
345
348
  `ClientConfigInput`.
346
349
 
350
+ ## Scheduled sends and document notifications
351
+
352
+ ```ts
353
+ const scheduled = await client.scheduledSends.createAssignment(document.id, {
354
+ method: 'virtual',
355
+ signers: [{ id: signer.id, sign_as: 'Witness', verification_method: 'Email',
356
+ notification_methods: ['Email'] }],
357
+ send_at: new Date(Date.now() + 86_400_000).toISOString(),
358
+ expires_at: null,
359
+ max_total_credits: 0,
360
+ });
361
+ ```
362
+
363
+ The request is the ordinary assignment body plus `send_at`. Its response is:
364
+
365
+ ```json
366
+ {
367
+ "resource": "scheduled_send", "id": "send-1", "type": "assignment",
368
+ "document_ids": ["doc-1"], "status": "pending",
369
+ "send_at": "2026-12-01T12:00:00Z", "next_attempt_at": null,
370
+ "assignment_id": null, "envelope_id": null, "failure_reason": null,
371
+ "created_at": "2026-11-30T12:00:00Z", "processed_at": null
372
+ }
373
+ ```
374
+
375
+ `send_at` accepts ISO date-time or Unix seconds, one hour to 90 days ahead.
376
+ An offset-free value means UTC. An expiration must be at least two hours after
377
+ the send time. Scheduling sends and charges nothing; execution rechecks the
378
+ request, plan and balance. The server checks due requests every five minutes.
379
+ `sign_as` records the sender's stated capacity on the certificate page only;
380
+ omitting it or sending `null` means `Sign`. It does not change verification.
381
+
382
+ `next_attempt_at` (ISO date-time or `null`) is set while a `pending` send is
383
+ postponed by the free plan's daily signer e-mail limit; `send_at` keeps the
384
+ original time. A send held back for 7 days past `send_at` fails with
385
+ `failure_reason`.
386
+
387
+ ```ts
388
+ const page = await client.scheduledSends.list({ document_id: document.id });
389
+ await client.scheduledSends.cancel(scheduled.id); // pending → cancelled
390
+ // Alternatively: await client.scheduledSends.sendNow(scheduled.id);
391
+ const envelopeSend = await client.scheduledSends.createEnvelope({
392
+ name: 'Agreement', signers: [{ id: signer.id }],
393
+ documents: [{ id: otherDocument.id, signer_ids: [signer.id] }],
394
+ send_at: new Date(Date.now() + 86_400_000).toISOString(),
395
+ max_total_credits: 0,
396
+ });
397
+ ```
398
+
399
+ All five methods, including listing, require OAuth `documents:write`.
400
+ `list()` returns `{ data: IScheduledSend[], meta }`. Cancellation and immediate
401
+ dispatch return the same state object, with `processed_at` and the created
402
+ `assignment_id` or `envelope_id` when sent. A refused immediate dispatch leaves
403
+ the request pending; cancel it to stop its future attempt. On a free plan,
404
+ `sendNow()` answers `429` with `ApiError.code` `FreePlanEmailLimit` and
405
+ `Retry-After` once the daily signer e-mail limit is reached: nothing is charged
406
+ and the send stays pending. A failed scheduled execution records
407
+ `failure_reason`. Mutations have no automatic retry or idempotency key; read
408
+ the state after a lost response before acting again.
409
+
410
+ ```ts
411
+ await client.documents.setWatchers(document.id, [contact.id]);
412
+ const watchers = await client.documents.listWatchers(document.id);
413
+ await client.documents.setWatchers(document.id, []); // clear
414
+ const capacities = await client.assignments.getSignerCapacities(document.id);
415
+ const history = await client.assignments.getNotificationHistory(document.id);
416
+ const reminder = await client.envelopes.estimateResendCost(envelope.id, signer.id);
417
+ ```
418
+
419
+ Watcher writes send `{ "watcher_ids": ["contact-1"] }`; reads and writes return
420
+ `ISigner[]`. At most ten entries (duplicates count toward the limit and are
421
+ stored once) of workspace contacts with email receive terminal
422
+ notifications without a document link or attachment. Configure them before
423
+ sending or while the document is open. These routes require an API key or user
424
+ token; OAuth application tokens cannot manage watchers.
425
+
426
+ Capacities return `[{ "signer_id": "signer-1", "sign_as": "Witness" }]`.
427
+ Notification history returns one `{ signer_id, notification_history }` per
428
+ signer; each history entry contains `event`, `status`, nullable `error_code`,
429
+ `error_message`, `sent_at`, `failed_at`, `delivered_at` and `opened_at`. Times
430
+ are ISO strings or null. Opens may be mail scanners, not human reading.
431
+ Both reads require `documents:read` and return `[]` for an unsent document.
432
+ Reminder estimates require `documents:write` and return
433
+ `{ total, breakdown, credit_balance, has_sufficient_credits }` without sending
434
+ or checking the cooldown. See each method's JSDoc for full typed examples and
435
+ HTTP errors. Signature images may be PNG or JPEG: send JPEG bytes with
436
+ `uploadSignature(code, bytes, { contentType: 'image/jpeg' })`; PNG remains the default.
437
+
438
+ Signer refusals expose `ApiError.code`: `SignerDataUnconfirmed`,
439
+ `EmailVerificationRequired`, `WhatsappVerificationRequired`,
440
+ `DigitalCertificateRequired`, `IdentityVerificationRequired` and
441
+ `TermsNotAccepted` identify the missing signing step. Complete that step
442
+ through the appropriate signer flow.
443
+ Email token requests can return `429` during a two-minute cooldown; inspect
444
+ `error.rateLimit.retryAfter` and do not loop on the send operation.
445
+
347
446
  ## Endpoint coverage
348
447
 
349
- All 147 operations documented at https://api.assinafy.com.br/v1/docs are
350
- mapped: 146 have SDK methods, and the embed session exchange is reserved for
351
- Assinafy's embed page. The table below is the resource-level summary; the detailed operation
448
+ All 158 operations documented at https://api.assinafy.com.br/v1/docs are
449
+ mapped: 142 have SDK methods; the embed session exchange and the login,
450
+ password, two-factor and API key routes belong to the Assinafy app. The table below is the resource-level summary; the detailed operation
352
451
  ledger is in [API_COVERAGE.md](API_COVERAGE.md).
353
452
 
354
453
  | Resource | Endpoints |
355
454
  | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
356
- | `client.documents` | list, **search**, upload, details, get, **rename**, activities, listActivities, waitUntilReady, download, thumbnail, downloadPage, statuses, delete, verify, createFromTemplate, estimateCostFromTemplate, getPublic, sendToken, listTags, replaceTags, addTags, detachTag, isFullySigned, getSigningProgress |
455
+ | `client.documents` | list, **search**, upload, details, get, **rename**, activities, listActivities, waitUntilReady, download, thumbnail, downloadPage, statuses, cancel, delete, verify, createFromTemplate, estimateCostFromTemplate, getPublic, sendToken, listTags, replaceTags, addTags, detachTag, isFullySigned, getSigningProgress, listWatchers, setWatchers |
357
456
  | `client.signers` | create, get, list, update, delete, findByEmail |
358
- | `client.assignments` | list, create, estimateCost, resetExpiration, resendNotification, estimateResendCost, listWhatsAppNotifications, getIdentityVerification, downloadIdentityVerificationImage, reviewIdentityVerification |
457
+ | `client.assignments` | list, create, estimateCost, resetExpiration, resendNotification, estimateResendCost, listWhatsAppNotifications, getIdentityVerification, downloadIdentityVerificationImage, reviewIdentityVerification, getSignerCapacities, getNotificationHistory |
458
+ | `client.scheduledSends` | createAssignment, createEnvelope, list, cancel, sendNow |
359
459
  | `client.contracts` | list, get, set, listRelated, renew, terminate |
360
- | `client.envelopes` | list, get, create, estimateCost, update, delete, cancel, listActivities, download, addDocument, removeDocument, resendNotification |
460
+ | `client.envelopes` | list, get, create, estimateCost, update, delete, cancel, listActivities, download, addDocument, removeDocument, resendNotification, estimateResendCost |
361
461
  | `client.embed` | listOrigins, addOrigin, updateOrigin, deleteOrigin, createSession |
362
462
  | `client.templates` | create, list, get, update, delete, downloadPage |
363
463
  | `client.tags` | list, create, update, delete |
@@ -365,8 +465,7 @@ ledger is in [API_COVERAGE.md](API_COVERAGE.md).
365
465
  | `client.webhooks` | listEndpoints, createEndpoint, getEndpoint, updateEndpoint, deleteEndpoint, deleteEndpointByUrl, getEndpointSecret, rotateEndpointSecret, testEndpoint, register, get, inactivate, listEventTypes, listDispatches, retryDispatch |
366
466
  | `client.fields` | create, list, get, update, delete, validate, validateMultiple, listTypes |
367
467
  | `client.oauth` | **getProtectedResourceMetadata**, **getAuthorizationServerMetadata**, **createAuthorizationUrl**, **readAuthorizationCallback**, **exchangeCode**, **refreshToken**, **revokeToken**, **getUserInfo** |
368
- | `client.auth` | getSocialLoginUrl, getSocialLoginCallbackUrl, login, verifyMfa, socialLogin, linkSocialLogin, createApiKey, getApiKey, deleteApiKey, changePassword, requestPasswordReset, resetPassword |
369
- | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences, getPushPreferences, updatePushPreferences, getMfa, startTotpEnrollment, confirmTotpEnrollment, regenerateRecoveryCodes, deleteMfaMethod |
468
+ | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences, getPushPreferences, updatePushPreferences |
370
469
  | `client.signerDocuments` | getCurrent, list, search, listAsWorkspace, searchAsWorkspace, download, signMultiple, declineMultiple, self, getIdentityVerification, startIdentityVerification, acceptTerms, verifyEmail, confirmData, uploadSignature, downloadSignature, getAssignment, getTheme, downloadLogo, resendCertifiedCopy, downloadCertifiedCopy, resendCertifiedCopyFromLink, sign, decline |
371
470
  | `client.webhookVerifier` | verifySignature, extractEvent, getEventType, getEventData |
372
471
 
@@ -407,8 +506,7 @@ const uploaded = await client.documents.upload({ filePath: './contract.pdf' });
407
506
  ```
408
507
 
409
508
  The official multipart body contains the `file` part. The SDK also supports a
410
- display-name override (used as that file part's filename) and an optional JSON
411
- `metadata` part for deployments that accept it. A successful response is
509
+ display-name override (used as that file part's filename). A successful response is
412
510
  `IDocumentUploadResponse`:
413
511
 
414
512
  ```ts
@@ -443,9 +541,10 @@ type DocumentUploadShape = {
443
541
  `metadata_ready`, `pending_signature`, `pending_identity_review`, `expired`, `certificating`,
444
542
  `certificated`, `rejected_by_signer`, `rejected_by_user`, and `failed`.
445
543
 
446
- Uploads must be PDFs, at most 25 MB and at most 2,000 pages (the byte limit is
447
- exported as `MAX_UPLOAD_BYTES`). The SDK checks the
448
- extension, size, and `%PDF-` header before sending. A new upload can have an
544
+ Uploads may be PDF, DOC, DOCX or ODT, at most 25 MB and at most 2,000 pages
545
+ (the byte limit is exported as `MAX_UPLOAD_BYTES`); the API converts Word and
546
+ ODT files to PDF. The SDK checks the extension, size and the format's leading
547
+ bytes before sending, and keeps the file's real extension in the part name. A new upload can have an
449
548
  empty `pages` array until metadata processing finishes. Wait before creating a
450
549
  `collect` assignment because its fields refer to rendered page IDs; a
451
550
  `virtual` assignment may be created immediately.
@@ -484,7 +583,6 @@ type SignerShape = {
484
583
  has_signature?: boolean; // signer-self response only
485
584
  has_initial?: boolean; // signer-self response only
486
585
  is_signature_reusable?: boolean; // signer-self response only
487
- metadata?: Record<string, unknown>;
488
586
  };
489
587
  ```
490
588
 
@@ -594,7 +692,7 @@ await signerClient.signerDocuments.confirmData(
594
692
  uploaded.id,
595
693
  accessCode,
596
694
  { ...(self.email === null ? {} : { email: self.email }), has_accepted_terms: true },
597
- ); // null on production (data: [])
695
+ ); // null (the API answers data: [])
598
696
 
599
697
  const signable = await signerClient.signerDocuments.getAssignment(accessCode, {
600
698
  hasAcceptedTerms: true,
@@ -615,8 +713,8 @@ can sign in parallel.
615
713
 
616
714
  `signMultiple` is only for `virtual` assignments. For `collect`, read
617
715
  `signable.assignment.items`, then call `sign(documentId, assignmentId,
618
- accessCode, entries)` with a non-empty array of
619
- `{ itemId, fieldId, pageId, value }`. A virtual signer must confirm their data
716
+ accessCode, entries)` with an array of `{ itemId, fieldId, pageId, value }`
717
+ (`[]` for a virtual assignment, whose entries the API ignores). A virtual signer must confirm their data
620
718
  before signing. A `DigitalCertificate` signer cannot call `sign`; that branch
621
719
  uses Assinafy's certificate flow, described in
622
720
  [ICP-Brasil digital certificate](#icp-brasil-digital-certificate).
@@ -705,19 +803,18 @@ methods always require an explicit account ID.
705
803
  // Upload from a file path (recommended)
706
804
  const doc = await client.documents.upload(
707
805
  { filePath: './contract.pdf' },
708
- { name: 'Service agreement', metadata: { type: 'service' } },
806
+ { name: 'Service agreement' },
709
807
  );
710
- // `metadata` is a compatibility multipart part outside the published schema.
711
808
  // `name` sets the filename of the file part; it is not sent as a separate field.
712
809
  // When omitted, it defaults to the original filename. The API appends `.pdf`
713
810
  // when absent, so
714
811
  // the document above is stored as 'Service agreement.pdf'. Accents are
715
812
  // transliterated by the API ('Contrato de Serviço' → 'Contrato de Servico.pdf').
716
813
  // → {
717
- // resource: 'document', id: '1031…', account_id: '102d…', template_id: null,
814
+ // resource: 'document', id: '1000…', account_id: 'acc_example', template_id: null,
718
815
  // name: 'Service agreement.pdf', status: 'uploaded',
719
816
  // artifacts: { original: 'https://…/download/original' },
720
- // signing_url: 'https://app…/sign/1031…',
817
+ // signing_url: 'https://app…/sign/1000…',
721
818
  // pages: [], // populated once status reaches `metadata_ready`
722
819
  // tags: [], is_closed: false, created_at: '2026-…', updated_at: '2026-…'
723
820
  // }
@@ -733,10 +830,10 @@ const { data, meta } = await client.documents.list({ page: 1, 'per-page': 20, so
733
830
  const hits = await client.documents.search({ search: 'agreement', status: 'pending_signature', 'per-page': 20 });
734
831
 
735
832
  await client.documents.details(doc.id);
736
- // Production: page 2 of activities, oldest first; returns an array.
737
- await client.documents.activities(doc.id, { page: 2, 'per-page': 100, sort: 'id' });
833
+ // Page 2 of activities, oldest first; returns an array.
834
+ await client.documents.activities(doc.id, { page: 2, 'per-page': 50, sort: 'id' });
738
835
  // Use listActivities for { data, meta }, including total and last_page.
739
- await client.documents.listActivities(doc.id, { page: 2, 'per-page': 100, sort: 'id' });
836
+ await client.documents.listActivities(doc.id, { page: 2, 'per-page': 50, sort: 'id' });
740
837
  await client.documents.waitUntilReady(doc.id, { maxWaitMs: 30_000 });
741
838
 
742
839
  // Rename. The API rejects this with 400 while the document is still in
@@ -755,10 +852,12 @@ await client.documents.downloadPage(doc.id, pageId);
755
852
  await client.documents.statuses(); // list every status code + deletable flag
756
853
  await client.documents.isFullySigned(doc.id);
757
854
  await client.documents.getSigningProgress(doc.id);
855
+ // Cancel a pending document and keep it → the document, now `rejected_by_user`
856
+ await client.documents.cancel(doc.id);
758
857
  await client.documents.delete(doc.id);
759
858
 
760
859
  // Verify a signed document by its Assinafy signature hash
761
- await client.documents.verify('FE32EDDADE7CBDDCBB934E7402047450B0E59C02');
860
+ await client.documents.verify('0123456789ABCDEF0123456789ABCDEF01234567');
762
861
 
763
862
  // Public endpoints (no auth)
764
863
  await client.documents.getPublic(doc.id);
@@ -775,9 +874,20 @@ await client.documents.addTags(doc.id, [urgentTag.id]);
775
874
  await client.documents.detachTag(doc.id, urgentTag.id); // → { detached: true }
776
875
  ```
777
876
 
778
- Uploads are validated locally: only `.pdf` files up to 25 MB whose bytes begin
779
- with the PDF magic header (`%PDF-`) are accepted. The API also limits documents
780
- to 2,000 pages.
877
+ Uploads are validated locally: `.pdf`, `.doc`, `.docx` and `.odt` files up to
878
+ 25 MB whose bytes begin with that format's signature (`%PDF-`, the ZIP header
879
+ for DOCX/ODT, the OLE header for DOC) are accepted. The API also limits
880
+ documents to 2,000 pages.
881
+
882
+ `documents.cancel(documentId)` (`PUT /v1/documents/{documentId}/cancel`)
883
+ cancels a `pending_signature` or `pending_identity_review` document and keeps
884
+ it: it moves to `rejected_by_user`, its signers and owner are told, the
885
+ cancellation is recorded, and its files and history stay. It returns the
886
+ document. A document that is not pending answers `400`; one of an open
887
+ envelope answers `409` with `ApiError.code` `EnvelopeOpen` (cancel the envelope
888
+ or take the document out of it); once every signer has signed it answers `409`
889
+ `DocumentClosed`. `documents.delete()` runs the same cancel first for a pending
890
+ document, then deletes it.
781
891
 
782
892
  Page and artifact URLs embedded in JSON responses still require the same
783
893
  account authentication as their download operations. Prefer
@@ -792,19 +902,17 @@ both are silent rather than errors:
792
902
  - Only the hyphenated `per-page` is read. `per_page` is accepted and ignored,
793
903
  falling back to 20 rows — so the SDK rewrites `per_page` to `per-page` on
794
904
  every list method, and an explicit `per-page` wins when both are given.
795
- - Document and signer lists have been observed to clamp `per-page` to **50**.
796
- Asking for 100 returns 50 rows with a `200` on those deployments.
797
- The exported `MAX_LIST_PAGE_SIZE` constant is that observed ceiling; page through with
905
+ - Lists clamp `per-page` to **50**: asking for 100 returns 50 rows with a `200`.
906
+ The exported `MAX_LIST_PAGE_SIZE` constant is that ceiling; page through with
798
907
  `page` rather than requesting a larger page, and trust `meta.per_page` over
799
908
  the value you asked for.
800
909
 
801
910
  `documents.activities(documentId, params?)` keeps its array return type and does
802
911
  not expose pagination metadata; use `documents.listActivities()` for `{ data, meta }`.
803
- In production, these methods return **20 entries per page**
804
- by default and documents a maximum `per-page` of **100**. Use `page` to fetch later
912
+ These methods return **20 entries per page**
913
+ by default, with a maximum `per-page` of **50**. Use `page` to fetch later
805
914
  entries; an empty array marks the end. `sort: 'id'` returns oldest first, and
806
- `sort: '-id'` (the default) returns newest first. Sandbox still returns the full,
807
- unpaged log and may ignore these parameters, so do not loop through pages there.
915
+ `sort: '-id'` (the default) returns newest first.
808
916
  Existing integrations that read the entire history in one request must now
809
917
  request subsequent pages. See the [migration example](COMPATIBILITY.md#document-activities).
810
918
 
@@ -812,9 +920,8 @@ request subsequent pages. See the [migration example](COMPATIBILITY.md#document-
812
920
 
813
921
  Contract lifecycle management tracks the business terms attached to an existing
814
922
  document without changing how that document is uploaded, sent, or signed. The
815
- production API supports the complete flow below; a sandbox can lag a newly
816
- released CLM route or plan entitlement (see
817
- [compatibility notes](COMPATIBILITY.md#contract-lifecycle-management-clm)).
923
+ complete flow is below; plan and OAuth-scope requirements are in the
924
+ [compatibility notes](COMPATIBILITY.md#contract-lifecycle-management-clm).
818
925
 
819
926
  ```ts
820
927
  // 1. Upload or select the contract document, then attach its terms.
@@ -918,7 +1025,7 @@ await client.signers.create({
918
1025
  email: 'signer@example.com',
919
1026
  cpf: '123.456.789-00', // legacy compatibility input; non-digits are stripped
920
1027
  });
921
- // → { id: '19e6…', full_name: 'Example Signer', email: 'signer@example.com',
1028
+ // → { id: '1000…', full_name: 'Example Signer', email: 'signer@example.com',
922
1029
  // whatsapp_phone_number: null, has_accepted_terms: false }
923
1030
  // (note: `cpf` is accepted on input but never echoed back by the API)
924
1031
 
@@ -935,7 +1042,7 @@ await client.signers.get(signerId);
935
1042
  await client.signers.list({ page: 1, 'per-page': 50, search: 'signer' });
936
1043
  await client.signers.update(signerId, {
937
1044
  full_name: 'Updated Signer',
938
- government_id: '390.533.447-05', // official update field; sent as digits
1045
+ government_id: '390.533.447-05', // sent unchanged; the API normalizes formatting
939
1046
  });
940
1047
  await client.signers.delete(signerId);
941
1048
 
@@ -1012,8 +1119,7 @@ await client.assignments.resendNotification(documentId, assignmentId, signerId);
1012
1119
  // → { is_sent: true, document_id: '…', signer_id: '…' }
1013
1120
 
1014
1121
  const resendCost = await client.assignments.estimateResendCost(documentId, assignmentId, signerId);
1015
- // Production: { total, breakdown, credit_balance, has_sufficient_credits }. Older
1016
- // deployments return a full ICostEstimate; narrow with `'total_credits' in resendCost`.
1122
+ // → { total, breakdown, credit_balance, has_sufficient_credits }
1017
1123
  ```
1018
1124
 
1019
1125
  The `create` response is an `IAssignment`: `{ id, method, signers: [...],
@@ -1021,10 +1127,11 @@ items: [{ display_settings, ... }], signing_urls: [{ signer_id, url, embedded }]
1021
1127
 
1022
1128
  For backwards compatibility, the SDK also accepts legacy `signer_ids` and `signerIds` payloads and rewrites them to the current `signers: [{ id }]` format expected by the API.
1023
1129
 
1024
- **Cancelling a signature request.** Assinafy has no workspace-side "cancel" endpoint. To stop a pending request either delete the document (when its status is deletable) or have the signer decline:
1130
+ **Cancelling a signature request.** Cancel the document to stop a pending request and keep it, delete it to remove it as well, or have the signer decline:
1025
1131
 
1026
1132
  ```ts
1027
- await client.documents.delete(documentId); // workspace-side (an envelope: envelopes.cancel)
1133
+ await client.documents.cancel(documentId); // workspace-side, keeps the document (an envelope: envelopes.cancel)
1134
+ await client.documents.delete(documentId); // cancels a pending document, then deletes it
1028
1135
  await client.signerDocuments.decline(documentId, assignmentId, accessCode, 'No longer needed'); // signer-side
1029
1136
  ```
1030
1137
 
@@ -1042,7 +1149,7 @@ to `Email`.
1042
1149
  | --- | --- | --- | --- |
1043
1150
  | `Email` *(default)* | One-time code (OTP) by email | `Email` | Free |
1044
1151
  | `Whatsapp` | One-time code (OTP) by WhatsApp | `Whatsapp` | 0.45 credit (the notification), paid plans only |
1045
- | `DigitalCertificate` | The signer signs with their **own ICP-Brasil certificate — A1 or A3 —** through the Web PKI extension, producing a **qualified PAdES signature**; requires `method: 'virtual'` | `Email` **or** `Whatsapp` (or `Bypass`) | 0.5 credits + the notification |
1152
+ | `DigitalCertificate` | The signer signs with their **own ICP-Brasil certificate — A1 or A3 —** through the Web PKI extension, producing a **qualified PAdES signature**; requires `method: 'virtual'` | `Email` **or** `Whatsapp` (or `Bypass`) | Use the current estimate |
1046
1153
  | `IdDocumentFaceMatchBasic` | Hosted identity-document, face and liveness verification | `Email` **or** `Whatsapp` (or `Bypass`) | Use `estimateCost()` |
1047
1154
  | `Bypass` | No code: your app has already authenticated the signer. Enabled per account by Assinafy | `Email`, `Whatsapp` **or** `Bypass` (sends no invitation) | The notification |
1048
1155
 
@@ -1098,8 +1205,8 @@ forward them outside the signing flow.
1098
1205
  `DigitalCertificate` requires `method: 'virtual'`, the account feature, a CPF
1099
1206
  or CNPJ in the signer's `government_id`, and exactly one certificate signer in
1100
1207
  that signing step. Estimates take the same `step` as creation: with two or
1101
- more certificate signers, give each its own step in both calls. It costs 0.5
1102
- credits per certificate signer in addition to the selected notification cost. A certificate flow completes the signer's
1208
+ more certificate signers, give each its own step in both calls. The price depends on the workspace; call `estimateCost()`
1209
+ and use its `total_credits` as `max_total_credits` when creating the request. A certificate flow completes the signer's
1103
1210
  virtual item; it cannot submit placed fields through the ordinary `collect`
1104
1211
  signing endpoint.
1105
1212
 
@@ -1115,8 +1222,7 @@ signing time: A1 lives in software (a file on the machine) and A3 in hardware
1115
1222
  (a token or smartcard). The API models both with the single
1116
1223
  `DigitalCertificate` value — there is no `A1`/`A3` field to send, and the
1117
1224
  resulting PAdES signature is qualified in either case. Certificate signers
1118
- complete a Web PKI handshake on two production-only routes that are not part
1119
- of this SDK.
1225
+ complete a Web PKI handshake on two routes that are not part of this SDK.
1120
1226
 
1121
1227
  ```ts
1122
1228
  const certificateSigner = await client.signers.update(signerId, {
@@ -1230,7 +1336,7 @@ const { url, expires_at } = await client.embed.createSession(documentId, assignm
1230
1336
  integrations can also use five template-management routes—`create`, `get`,
1231
1337
  `update`, `delete`, and `downloadPage`—that are absent from that document. See
1232
1338
  [compatibility notes](COMPATIBILITY.md#template-management-extensions).
1233
- Template status casing can vary by deployment; normalize with
1339
+ Template status casing can vary; normalize with
1234
1340
  `template.status.toLowerCase()` when branching on it.
1235
1341
 
1236
1342
  ```ts
@@ -1314,15 +1420,14 @@ await client.tags.delete(tag.id, { force: true }); // detach everywhere,
1314
1420
 
1315
1421
  Attach/detach tags on a specific document via `client.documents.listTags / replaceTags / addTags / detachTag` (see [Documents](#documents)).
1316
1422
 
1317
- The published attachment contract takes tag IDs. Older sandbox deployments
1318
- instead interpret strings as names and create ID-named tags for ID inputs;
1319
- pass existing names intentionally there. See [document tag compatibility](COMPATIBILITY.md#document-tags).
1423
+ The published attachment contract takes tag IDs: create or list the tag first
1424
+ and send its ID. See [document tag compatibility](COMPATIBILITY.md#document-tags).
1320
1425
 
1321
1426
  ### Workspaces
1322
1427
 
1323
1428
  The official create/update request schemas define `name` and
1324
- `notification_sender_type`. The sandbox also accepts the color fields shown
1325
- below; they are retained as a documented compatibility extension.
1429
+ `notification_sender_type`. The color fields shown below are retained as a
1430
+ documented compatibility extension.
1326
1431
 
1327
1432
  ```ts
1328
1433
  // Colours are 6-char hex WITHOUT a leading '#' (unlike tags, which strip it).
@@ -1404,37 +1509,6 @@ await client.fields.validateMultiple(
1404
1509
  await client.fields.listTypes();
1405
1510
  ```
1406
1511
 
1407
- ### Authentication / API key management
1408
-
1409
- Most server-side integrations should just use `X-Api-Key` directly. Use these endpoints when you need to bootstrap a session for a human user.
1410
-
1411
- ```ts
1412
- // Browser OAuth: redirect the user to this URL. The callback helper returns the
1413
- // Assinafy callback URL for provider configuration; neither follows a redirect.
1414
- const oauthStart = client.auth.getSocialLoginUrl('google');
1415
- const oauthCallback = client.auth.getSocialLoginCallbackUrl();
1416
-
1417
- let session = await client.auth.login('me@example.com', 'pw');
1418
- // With two-factor authentication on, login returns `mfa_token`; exchange it
1419
- // within 5 minutes for an authenticator code or a recovery code.
1420
- if (session.mfa_token) {
1421
- session = await client.auth.verifyMfa(session.mfa_token, '123456');
1422
- }
1423
- const { access_token, user, accounts } = session;
1424
- await client.auth.socialLogin({ provider: 'google', token: 'google-id-token', has_accepted_terms: true });
1425
- await client.auth.linkSocialLogin({ provider: 'google', token: 'google-id-token' });
1426
-
1427
- // Personal API key
1428
- await client.auth.createApiKey('current-password');
1429
- await client.auth.getApiKey(); // → { api_key: '****...nBNr' } or null
1430
- await client.auth.deleteApiKey();
1431
-
1432
- // Password lifecycle
1433
- await client.auth.changePassword({ email, password: 'current', new_password: 'next' });
1434
- await client.auth.requestPasswordReset('me@example.com');
1435
- await client.auth.resetPassword({ email, token: 'tk', new_password: 'next' });
1436
- ```
1437
-
1438
1512
  ### Authenticated user
1439
1513
 
1440
1514
  ```ts
@@ -1466,27 +1540,6 @@ const push = await client.users.getPushPreferences(); // every key, default true
1466
1540
  await client.users.updatePushPreferences({ SignerViewed: false });
1467
1541
  ```
1468
1542
 
1469
- #### Two-factor authentication
1470
-
1471
- Available in production. The TOTP secret and the recovery codes are shown once.
1472
-
1473
- ```ts
1474
- const enrollment = await client.users.startTotpEnrollment('My phone');
1475
- // → { id, secret, provisioning_uri } — render provisioning_uri as a QR code
1476
- const { recovery_codes } = await client.users.confirmTotpEnrollment({
1477
- id: enrollment.id,
1478
- code: '123456', // current code from the new device
1479
- });
1480
- // From now on every login needs the second factor.
1481
-
1482
- const { methods, recovery_codes_remaining } = await client.users.getMfa();
1483
- await client.users.regenerateRecoveryCodes({ password: 'current-password' }); // or { code }
1484
- await client.users.deleteMfaMethod(methods[0]!.id, { code: '123456' }); // → { is_mfa_enabled }
1485
- ```
1486
-
1487
- Replacing an already confirmed authenticator also needs `password` or
1488
- `reauth_code` in `confirmTotpEnrollment()`; first-time enrollment does not.
1489
-
1490
1543
  ### Webhooks
1491
1544
 
1492
1545
  An account has 1 webhook endpoint, or up to 3 on paid plans. Every active
@@ -1609,6 +1662,8 @@ Event-specific values are:
1609
1662
  | `document_ready` | `Account` | `Document` | — |
1610
1663
  | `document_processing_failed` | `Account` | `Document` | `error_message` |
1611
1664
  | `signature_requested` | `User` | `Document` | `signer_email`, `signer_full_name`, or `signer_whatsapp_phone_number`, according to channel |
1665
+ | `signature_reminder_sent` | `Document` | `Document` | `signer_full_name`, `signer_email`, `signer_whatsapp_phone_number`, `notification_method` |
1666
+ | `signature_request_delivery_failed` | `Signer` | `Document` | `signer_full_name`, `signer_email`, `signer_whatsapp_phone_number`, `notification_method` (`whatsapp`) |
1612
1667
  | `signer_created` | `User` | `Signer` | `signer_full_name` |
1613
1668
  | `signer_email_verified` | `Signer` | `Document` | `signer_email` |
1614
1669
  | `signer_whatsapp_verified` | `Signer` | `Document` | `signer_whatsapp_phone_number` |
@@ -1622,6 +1677,8 @@ Event-specific values are:
1622
1677
  | `signer_signed_document` | `Signer` | `Document` | `signer_full_name` |
1623
1678
  | `signer_rejected_document` | `Signer` | `Document` | `signer_full_name` |
1624
1679
  | `user_rejected_document` | `User` | `Document` | `user_name` |
1680
+ | `document_expiring` | `Document` | `Document` | — |
1681
+ | `document_expired` | `Document` | `Document` | — |
1625
1682
  | `template_created` | `User` | `Template` | — |
1626
1683
  | `template_processed` | `User` | `Template` | — |
1627
1684
  | `template_processing_failed` | `Account` | `Template` | `error_message` |
@@ -1633,6 +1690,15 @@ failed deliveries. `assignment_created` and `document_metadata_ready` have no
1633
1690
  guaranteed ordering. For account entities, Assinafy removes the `integration`
1634
1691
  property before delivery.
1635
1692
 
1693
+ `signature_reminder_sent` accompanies `signature_requested` for each reminder
1694
+ that went out. `signature_request_delivery_failed` reports a WhatsApp
1695
+ invitation or reminder that could not be delivered. `document_expiring` fires
1696
+ once per deadline when it is less than 24 hours away and the remaining signers
1697
+ were warned; `document_expired` fires when the deadline passed and the status
1698
+ became `expired`. Reminders and both deadline events carry the document itself
1699
+ as `subject`. Subscribe to these events explicitly; the default set does not
1700
+ include them.
1701
+
1636
1702
  ### Webhook verification
1637
1703
 
1638
1704
  With `signing_enabled: true`, every delivery is signed following
@@ -1697,7 +1763,7 @@ await client.signerDocuments.download(signerId, documentId, 'original', accessCo
1697
1763
  await client.signerDocuments.confirmData(documentId, accessCode, {
1698
1764
  email: 'me@example.com',
1699
1765
  has_accepted_terms: true,
1700
- }); // null on production
1766
+ }); // null (the API answers data: [])
1701
1767
  // Alternatively, accept terms separately before getAssignment():
1702
1768
  // await client.signerDocuments.acceptTerms(accessCode); // { full_name, email, has_accepted_terms }
1703
1769
 
@@ -1732,6 +1798,9 @@ await client.signerDocuments.declineMultiple(['doc-1'], 'Unfavorable terms', acc
1732
1798
  `sign()` also requires virtual signers to have confirmed their data first, but
1733
1799
  virtual assignments should normally use `signMultiple()`. Certificate signers
1734
1800
  cannot use `sign()`; see [Paid signing branches](#paid-signing-branches).
1801
+ A signer who already signed and calls `sign()` again gets `200` with the
1802
+ current assignment, even after that signature closed the document, so it is
1803
+ safe to repeat after a lost response.
1735
1804
 
1736
1805
  ## High-level helper
1737
1806
 
@@ -1746,7 +1815,6 @@ const result = await client.uploadAndRequestSignatures({
1746
1815
  { name: 'Example Signer B', email: 'signer-b@example.com' },
1747
1816
  ],
1748
1817
  message: 'Please sign',
1749
- metadata: { year: 2026 }, // compatibility upload part; omit for file-only wire format
1750
1818
  waitForReady: true,
1751
1819
  waitOptions: { maxWaitMs: 30_000, pollIntervalMs: 1_000 },
1752
1820
  expiresAt: '2027-12-31T00:00:00Z',
@@ -1761,13 +1829,12 @@ result.signer_ids; // string[]
1761
1829
 
1762
1830
  `waitForReady: false` skips post-assignment polling and returns the initial
1763
1831
  upload response. With the default `true`, the helper creates the assignment first and
1764
- then waits for the current document details. Both production and sandbox allow
1765
- virtual assignments in `uploaded` and `metadata_processing` and promote them
1832
+ then waits for the current document details. The API allows
1833
+ virtual assignments in `uploaded` and `metadata_processing` and promotes them
1766
1834
  automatically; only `collect` assignments require rendered pages.
1767
1835
  Every signer above uses the default email channel. A phone-only signer selects
1768
1836
  the paid WhatsApp branch described earlier. `copyReceivers` accepts existing
1769
- signer IDs, not email addresses; check the returned assignment before treating
1770
- a copy receiver as registered.
1837
+ signer IDs, not email addresses; they receive a copy of the signed document.
1771
1838
 
1772
1839
  The helper is not transactional. A post-assignment polling error includes the
1773
1840
  created `documentId`, `assignmentId`, and `signerIds` in its `context` (and in
@@ -1777,8 +1844,8 @@ whether to retry the workflow.
1777
1844
  ## Errors
1778
1845
 
1779
1846
  HTTP methods reject with an `AssinafyError` subclass. Synchronous helpers such
1780
- as `getSocialLoginUrl()` and `readAuthorizationCallback()` can throw
1781
- `ValidationError` before any request.
1847
+ as `oauth.readAuthorizationCallback()` can throw `ValidationError` before any
1848
+ request.
1782
1849
 
1783
1850
  ```ts
1784
1851
  import { ApiError, OAuthError, ValidationError, NetworkError, AssinafyError } from '@assinafy/sdk';
@@ -1809,20 +1876,31 @@ try {
1809
1876
  internally is exported as `parseWwwAuthenticate()`, for reading the
1810
1877
  `WWW-Authenticate` header of responses received outside the SDK.
1811
1878
 
1812
- ## Environments
1879
+ Besides the codes named in each section, these refusals carry an
1880
+ `ApiError.code`:
1813
1881
 
1814
- | | |
1815
- | --- | --- |
1816
- | Production | `https://api.assinafy.com.br/v1` |
1817
- | Sandbox | `https://sandbox.assinafy.com.br/v1` |
1818
-
1819
- The sandbox runs its own authorization server at
1820
- `https://auth-sandbox.assinafy.com.br`, with the consent screen at
1821
- `/oauth/authorize`. Discovery is available and selects that server from the
1822
- configured `baseUrl`:
1882
+ | `err.code` | Status | When |
1883
+ | --- | --- | --- |
1884
+ | `FreePlanSignerLimit` | `403` | A free workspace asks for more than three signers when creating or estimating an assignment, envelope, template document or scheduled send |
1885
+ | `DocumentClosed` | `409` | The document closed and will not reopen; do not retry |
1886
+ | `EmailVerificationRequired`, `WhatsappVerificationRequired`, `IdentityVerificationRequired`, `TermsNotAccepted` | `400` | A signer route needs that step first |
1887
+ | `SignatureImageInvalid`, `SignatureImageBlank` | `400` | Signature upload: the file is not PNG or JPEG, or the image is blank |
1888
+ | `InvalidEmail` | `400` | Signer create/update or `confirmData()`: the address cannot receive messages |
1889
+ | `FreeWorkspaceLimit` | `403` | Creating an additional workspace without a paid plan |
1890
+ | `FreePlanEmailLimit` | `429` | `scheduledSends.sendNow()` reached the free plan's daily signer e-mail limit; read `Retry-After`. Nothing is charged, the send stays pending, and the SDK never retries it automatically |
1891
+
1892
+ ## API host
1893
+
1894
+ The API is at `https://api.assinafy.com.br/v1`, the `baseUrl` default. OAuth
1895
+ discovery starts from the configured `baseUrl`: the protected-resource
1896
+ document (`https://api.assinafy.com.br/.well-known/oauth-protected-resource`)
1897
+ names the issuer, whose metadata is at
1898
+ `https://auth.assinafy.com.br/.well-known/oauth-authorization-server`, with the
1899
+ consent screen at `/oauth/authorize`. Discover the issuer from the API origin
1900
+ rather than hardcoding it:
1823
1901
 
1824
1902
  ```ts
1825
- const client = new AssinafyClient({ baseUrl: 'https://sandbox.assinafy.com.br/v1' });
1903
+ const client = new AssinafyClient({ baseUrl: 'https://api.assinafy.com.br/v1' });
1826
1904
  const metadata = await client.oauth.getAuthorizationServerMetadata();
1827
1905
  const request = await client.oauth.createAuthorizationUrl({
1828
1906
  clientId: process.env.ASSINAFY_CLIENT_ID!,
@@ -1831,9 +1909,8 @@ const request = await client.oauth.createAuthorizationUrl({
1831
1909
  });
1832
1910
  ```
1833
1911
 
1834
- Register the application in the matching environment. Production and sandbox
1835
- have separate issuers, client IDs, credentials and workspaces; keep each
1836
- connection entirely in one environment. Token, revocation and userinfo requests
1912
+ Keep each connection's issuer, client ID, credentials, workspace and `baseUrl`
1913
+ together. Token, revocation and userinfo requests
1837
1914
  use the configured `baseUrl`. For local testing, expose only the callback
1838
1915
  through an HTTPS tunnel, register its exact URL and revoke tokens afterward.
1839
1916
  See [COMPATIBILITY.md](COMPATIBILITY.md).
@@ -1855,7 +1932,7 @@ bun run verify # complete local release gate
1855
1932
 
1856
1933
  - **[README.md](README.md)** — the same complete reference in Portuguese
1857
1934
  - [API_COVERAGE.md](API_COVERAGE.md) — operation map
1858
- - [COMPATIBILITY.md](COMPATIBILITY.md) — per-deployment request and response variants
1935
+ - [COMPATIBILITY.md](COMPATIBILITY.md) — request and response variants
1859
1936
  - [RELEASING.md](RELEASING.md) — publishing process
1860
1937
  - [API documentation](https://api.assinafy.com.br/v1/docs)
1861
1938