@assinafy/sdk 3.1.0 → 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,10 +347,7 @@ const client = AssinafyClient.fromConfig({
344
347
  The configuration object accepted by `fromConfig` has the exported type
345
348
  `ClientConfigInput`.
346
349
 
347
- ## Scheduled sends and document notifications (staging)
348
-
349
- These operations require a deployment that publishes them. Configure its API
350
- URL through `baseUrl`; the SDK never changes environments on a refusal.
350
+ ## Scheduled sends and document notifications
351
351
 
352
352
  ```ts
353
353
  const scheduled = await client.scheduledSends.createAssignment(document.id, {
@@ -366,8 +366,8 @@ The request is the ordinary assignment body plus `send_at`. Its response is:
366
366
  {
367
367
  "resource": "scheduled_send", "id": "send-1", "type": "assignment",
368
368
  "document_ids": ["doc-1"], "status": "pending",
369
- "send_at": "2026-12-01T12:00:00Z", "assignment_id": null,
370
- "envelope_id": null, "failure_reason": null,
369
+ "send_at": "2026-12-01T12:00:00Z", "next_attempt_at": null,
370
+ "assignment_id": null, "envelope_id": null, "failure_reason": null,
371
371
  "created_at": "2026-11-30T12:00:00Z", "processed_at": null
372
372
  }
373
373
  ```
@@ -379,6 +379,11 @@ request, plan and balance. The server checks due requests every five minutes.
379
379
  `sign_as` records the sender's stated capacity on the certificate page only;
380
380
  omitting it or sending `null` means `Sign`. It does not change verification.
381
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
+
382
387
  ```ts
383
388
  const page = await client.scheduledSends.list({ document_id: document.id });
384
389
  await client.scheduledSends.cancel(scheduled.id); // pending → cancelled
@@ -395,9 +400,12 @@ All five methods, including listing, require OAuth `documents:write`.
395
400
  `list()` returns `{ data: IScheduledSend[], meta }`. Cancellation and immediate
396
401
  dispatch return the same state object, with `processed_at` and the created
397
402
  `assignment_id` or `envelope_id` when sent. A refused immediate dispatch leaves
398
- the request pending; cancel it to stop its future attempt. A failed scheduled
399
- execution records `failure_reason`. Mutations have no automatic retry or
400
- idempotency key; read the state after a lost response before acting again.
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.
401
409
 
402
410
  ```ts
403
411
  await client.documents.setWatchers(document.id, [contact.id]);
@@ -409,7 +417,8 @@ const reminder = await client.envelopes.estimateResendCost(envelope.id, signer.i
409
417
  ```
410
418
 
411
419
  Watcher writes send `{ "watcher_ids": ["contact-1"] }`; reads and writes return
412
- `ISigner[]`. Up to ten distinct workspace contacts with email receive terminal
420
+ `ISigner[]`. At most ten entries (duplicates count toward the limit and are
421
+ stored once) of workspace contacts with email receive terminal
413
422
  notifications without a document link or attachment. Configure them before
414
423
  sending or while the document is open. These routes require an API key or user
415
424
  token; OAuth application tokens cannot manage watchers.
@@ -423,26 +432,27 @@ Both reads require `documents:read` and return `[]` for an unsent document.
423
432
  Reminder estimates require `documents:write` and return
424
433
  `{ total, breakdown, credit_balance, has_sufficient_credits }` without sending
425
434
  or checking the cooldown. See each method's JSDoc for full typed examples and
426
- HTTP errors. Staging also accepts raw JPEG signature images using
435
+ HTTP errors. Signature images may be PNG or JPEG: send JPEG bytes with
427
436
  `uploadSignature(code, bytes, { contentType: 'image/jpeg' })`; PNG remains the default.
428
437
 
429
438
  Signer refusals expose `ApiError.code`: `SignerDataUnconfirmed`,
430
439
  `EmailVerificationRequired`, `WhatsappVerificationRequired`,
431
- `DigitalCertificateRequired` and `IdentityVerificationRequired` identify the
432
- missing signing step. Complete that step through the appropriate signer flow.
440
+ `DigitalCertificateRequired`, `IdentityVerificationRequired` and
441
+ `TermsNotAccepted` identify the missing signing step. Complete that step
442
+ through the appropriate signer flow.
433
443
  Email token requests can return `429` during a two-minute cooldown; inspect
434
444
  `error.rateLimit.retryAfter` and do not loop on the send operation.
435
445
 
436
446
  ## Endpoint coverage
437
447
 
438
- All 147 operations documented at https://api.assinafy.com.br/v1/docs are
439
- mapped: 146 have SDK methods, and the embed session exchange is reserved for
440
- 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
441
451
  ledger is in [API_COVERAGE.md](API_COVERAGE.md).
442
452
 
443
453
  | Resource | Endpoints |
444
454
  | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
445
- | `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, listWatchers, setWatchers |
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 |
446
456
  | `client.signers` | create, get, list, update, delete, findByEmail |
447
457
  | `client.assignments` | list, create, estimateCost, resetExpiration, resendNotification, estimateResendCost, listWhatsAppNotifications, getIdentityVerification, downloadIdentityVerificationImage, reviewIdentityVerification, getSignerCapacities, getNotificationHistory |
448
458
  | `client.scheduledSends` | createAssignment, createEnvelope, list, cancel, sendNow |
@@ -455,8 +465,7 @@ ledger is in [API_COVERAGE.md](API_COVERAGE.md).
455
465
  | `client.webhooks` | listEndpoints, createEndpoint, getEndpoint, updateEndpoint, deleteEndpoint, deleteEndpointByUrl, getEndpointSecret, rotateEndpointSecret, testEndpoint, register, get, inactivate, listEventTypes, listDispatches, retryDispatch |
456
466
  | `client.fields` | create, list, get, update, delete, validate, validateMultiple, listTypes |
457
467
  | `client.oauth` | **getProtectedResourceMetadata**, **getAuthorizationServerMetadata**, **createAuthorizationUrl**, **readAuthorizationCallback**, **exchangeCode**, **refreshToken**, **revokeToken**, **getUserInfo** |
458
- | `client.auth` | getSocialLoginUrl, getSocialLoginCallbackUrl, login, verifyMfa, socialLogin, linkSocialLogin, createApiKey, getApiKey, deleteApiKey, changePassword, requestPasswordReset, resetPassword |
459
- | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences, getPushPreferences, updatePushPreferences, getMfa, startTotpEnrollment, confirmTotpEnrollment, regenerateRecoveryCodes, deleteMfaMethod |
468
+ | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences, getPushPreferences, updatePushPreferences |
460
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 |
461
470
  | `client.webhookVerifier` | verifySignature, extractEvent, getEventType, getEventData |
462
471
 
@@ -497,8 +506,7 @@ const uploaded = await client.documents.upload({ filePath: './contract.pdf' });
497
506
  ```
498
507
 
499
508
  The official multipart body contains the `file` part. The SDK also supports a
500
- display-name override (used as that file part's filename) and an optional JSON
501
- `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
502
510
  `IDocumentUploadResponse`:
503
511
 
504
512
  ```ts
@@ -533,9 +541,10 @@ type DocumentUploadShape = {
533
541
  `metadata_ready`, `pending_signature`, `pending_identity_review`, `expired`, `certificating`,
534
542
  `certificated`, `rejected_by_signer`, `rejected_by_user`, and `failed`.
535
543
 
536
- Uploads must be PDFs, at most 25 MB and at most 2,000 pages (the byte limit is
537
- exported as `MAX_UPLOAD_BYTES`). The SDK checks the
538
- 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
539
548
  empty `pages` array until metadata processing finishes. Wait before creating a
540
549
  `collect` assignment because its fields refer to rendered page IDs; a
541
550
  `virtual` assignment may be created immediately.
@@ -574,7 +583,6 @@ type SignerShape = {
574
583
  has_signature?: boolean; // signer-self response only
575
584
  has_initial?: boolean; // signer-self response only
576
585
  is_signature_reusable?: boolean; // signer-self response only
577
- metadata?: Record<string, unknown>;
578
586
  };
579
587
  ```
580
588
 
@@ -684,7 +692,7 @@ await signerClient.signerDocuments.confirmData(
684
692
  uploaded.id,
685
693
  accessCode,
686
694
  { ...(self.email === null ? {} : { email: self.email }), has_accepted_terms: true },
687
- ); // null on production (data: [])
695
+ ); // null (the API answers data: [])
688
696
 
689
697
  const signable = await signerClient.signerDocuments.getAssignment(accessCode, {
690
698
  hasAcceptedTerms: true,
@@ -705,8 +713,8 @@ can sign in parallel.
705
713
 
706
714
  `signMultiple` is only for `virtual` assignments. For `collect`, read
707
715
  `signable.assignment.items`, then call `sign(documentId, assignmentId,
708
- accessCode, entries)` with a non-empty array of
709
- `{ 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
710
718
  before signing. A `DigitalCertificate` signer cannot call `sign`; that branch
711
719
  uses Assinafy's certificate flow, described in
712
720
  [ICP-Brasil digital certificate](#icp-brasil-digital-certificate).
@@ -795,19 +803,18 @@ methods always require an explicit account ID.
795
803
  // Upload from a file path (recommended)
796
804
  const doc = await client.documents.upload(
797
805
  { filePath: './contract.pdf' },
798
- { name: 'Service agreement', metadata: { type: 'service' } },
806
+ { name: 'Service agreement' },
799
807
  );
800
- // `metadata` is a compatibility multipart part outside the published schema.
801
808
  // `name` sets the filename of the file part; it is not sent as a separate field.
802
809
  // When omitted, it defaults to the original filename. The API appends `.pdf`
803
810
  // when absent, so
804
811
  // the document above is stored as 'Service agreement.pdf'. Accents are
805
812
  // transliterated by the API ('Contrato de Serviço' → 'Contrato de Servico.pdf').
806
813
  // → {
807
- // resource: 'document', id: '1031…', account_id: '102d…', template_id: null,
814
+ // resource: 'document', id: '1000…', account_id: 'acc_example', template_id: null,
808
815
  // name: 'Service agreement.pdf', status: 'uploaded',
809
816
  // artifacts: { original: 'https://…/download/original' },
810
- // signing_url: 'https://app…/sign/1031…',
817
+ // signing_url: 'https://app…/sign/1000…',
811
818
  // pages: [], // populated once status reaches `metadata_ready`
812
819
  // tags: [], is_closed: false, created_at: '2026-…', updated_at: '2026-…'
813
820
  // }
@@ -823,10 +830,10 @@ const { data, meta } = await client.documents.list({ page: 1, 'per-page': 20, so
823
830
  const hits = await client.documents.search({ search: 'agreement', status: 'pending_signature', 'per-page': 20 });
824
831
 
825
832
  await client.documents.details(doc.id);
826
- // Production: page 2 of activities, oldest first; returns an array.
827
- 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' });
828
835
  // Use listActivities for { data, meta }, including total and last_page.
829
- 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' });
830
837
  await client.documents.waitUntilReady(doc.id, { maxWaitMs: 30_000 });
831
838
 
832
839
  // Rename. The API rejects this with 400 while the document is still in
@@ -845,10 +852,12 @@ await client.documents.downloadPage(doc.id, pageId);
845
852
  await client.documents.statuses(); // list every status code + deletable flag
846
853
  await client.documents.isFullySigned(doc.id);
847
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);
848
857
  await client.documents.delete(doc.id);
849
858
 
850
859
  // Verify a signed document by its Assinafy signature hash
851
- await client.documents.verify('FE32EDDADE7CBDDCBB934E7402047450B0E59C02');
860
+ await client.documents.verify('0123456789ABCDEF0123456789ABCDEF01234567');
852
861
 
853
862
  // Public endpoints (no auth)
854
863
  await client.documents.getPublic(doc.id);
@@ -865,9 +874,20 @@ await client.documents.addTags(doc.id, [urgentTag.id]);
865
874
  await client.documents.detachTag(doc.id, urgentTag.id); // → { detached: true }
866
875
  ```
867
876
 
868
- Uploads are validated locally: only `.pdf` files up to 25 MB whose bytes begin
869
- with the PDF magic header (`%PDF-`) are accepted. The API also limits documents
870
- 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.
871
891
 
872
892
  Page and artifact URLs embedded in JSON responses still require the same
873
893
  account authentication as their download operations. Prefer
@@ -882,19 +902,17 @@ both are silent rather than errors:
882
902
  - Only the hyphenated `per-page` is read. `per_page` is accepted and ignored,
883
903
  falling back to 20 rows — so the SDK rewrites `per_page` to `per-page` on
884
904
  every list method, and an explicit `per-page` wins when both are given.
885
- - Document and signer lists have been observed to clamp `per-page` to **50**.
886
- Asking for 100 returns 50 rows with a `200` on those deployments.
887
- 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
888
907
  `page` rather than requesting a larger page, and trust `meta.per_page` over
889
908
  the value you asked for.
890
909
 
891
910
  `documents.activities(documentId, params?)` keeps its array return type and does
892
911
  not expose pagination metadata; use `documents.listActivities()` for `{ data, meta }`.
893
- In production, these methods return **20 entries per page**
894
- 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
895
914
  entries; an empty array marks the end. `sort: 'id'` returns oldest first, and
896
- `sort: '-id'` (the default) returns newest first. Sandbox still returns the full,
897
- unpaged log and may ignore these parameters, so do not loop through pages there.
915
+ `sort: '-id'` (the default) returns newest first.
898
916
  Existing integrations that read the entire history in one request must now
899
917
  request subsequent pages. See the [migration example](COMPATIBILITY.md#document-activities).
900
918
 
@@ -902,9 +920,8 @@ request subsequent pages. See the [migration example](COMPATIBILITY.md#document-
902
920
 
903
921
  Contract lifecycle management tracks the business terms attached to an existing
904
922
  document without changing how that document is uploaded, sent, or signed. The
905
- production API supports the complete flow below; a sandbox can lag a newly
906
- released CLM route or plan entitlement (see
907
- [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).
908
925
 
909
926
  ```ts
910
927
  // 1. Upload or select the contract document, then attach its terms.
@@ -1008,7 +1025,7 @@ await client.signers.create({
1008
1025
  email: 'signer@example.com',
1009
1026
  cpf: '123.456.789-00', // legacy compatibility input; non-digits are stripped
1010
1027
  });
1011
- // → { id: '19e6…', full_name: 'Example Signer', email: 'signer@example.com',
1028
+ // → { id: '1000…', full_name: 'Example Signer', email: 'signer@example.com',
1012
1029
  // whatsapp_phone_number: null, has_accepted_terms: false }
1013
1030
  // (note: `cpf` is accepted on input but never echoed back by the API)
1014
1031
 
@@ -1102,8 +1119,7 @@ await client.assignments.resendNotification(documentId, assignmentId, signerId);
1102
1119
  // → { is_sent: true, document_id: '…', signer_id: '…' }
1103
1120
 
1104
1121
  const resendCost = await client.assignments.estimateResendCost(documentId, assignmentId, signerId);
1105
- // Production: { total, breakdown, credit_balance, has_sufficient_credits }. Older
1106
- // deployments return a full ICostEstimate; narrow with `'total_credits' in resendCost`.
1122
+ // → { total, breakdown, credit_balance, has_sufficient_credits }
1107
1123
  ```
1108
1124
 
1109
1125
  The `create` response is an `IAssignment`: `{ id, method, signers: [...],
@@ -1111,10 +1127,11 @@ items: [{ display_settings, ... }], signing_urls: [{ signer_id, url, embedded }]
1111
1127
 
1112
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.
1113
1129
 
1114
- **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:
1115
1131
 
1116
1132
  ```ts
1117
- 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
1118
1135
  await client.signerDocuments.decline(documentId, assignmentId, accessCode, 'No longer needed'); // signer-side
1119
1136
  ```
1120
1137
 
@@ -1188,7 +1205,7 @@ forward them outside the signing flow.
1188
1205
  `DigitalCertificate` requires `method: 'virtual'`, the account feature, a CPF
1189
1206
  or CNPJ in the signer's `government_id`, and exactly one certificate signer in
1190
1207
  that signing step. Estimates take the same `step` as creation: with two or
1191
- more certificate signers, give each its own step in both calls. The price depends on the workspace and deployment; call `estimateCost()`
1208
+ more certificate signers, give each its own step in both calls. The price depends on the workspace; call `estimateCost()`
1192
1209
  and use its `total_credits` as `max_total_credits` when creating the request. A certificate flow completes the signer's
1193
1210
  virtual item; it cannot submit placed fields through the ordinary `collect`
1194
1211
  signing endpoint.
@@ -1205,8 +1222,7 @@ signing time: A1 lives in software (a file on the machine) and A3 in hardware
1205
1222
  (a token or smartcard). The API models both with the single
1206
1223
  `DigitalCertificate` value — there is no `A1`/`A3` field to send, and the
1207
1224
  resulting PAdES signature is qualified in either case. Certificate signers
1208
- complete a Web PKI handshake on two production-only routes that are not part
1209
- of this SDK.
1225
+ complete a Web PKI handshake on two routes that are not part of this SDK.
1210
1226
 
1211
1227
  ```ts
1212
1228
  const certificateSigner = await client.signers.update(signerId, {
@@ -1320,7 +1336,7 @@ const { url, expires_at } = await client.embed.createSession(documentId, assignm
1320
1336
  integrations can also use five template-management routes—`create`, `get`,
1321
1337
  `update`, `delete`, and `downloadPage`—that are absent from that document. See
1322
1338
  [compatibility notes](COMPATIBILITY.md#template-management-extensions).
1323
- Template status casing can vary by deployment; normalize with
1339
+ Template status casing can vary; normalize with
1324
1340
  `template.status.toLowerCase()` when branching on it.
1325
1341
 
1326
1342
  ```ts
@@ -1404,15 +1420,14 @@ await client.tags.delete(tag.id, { force: true }); // detach everywhere,
1404
1420
 
1405
1421
  Attach/detach tags on a specific document via `client.documents.listTags / replaceTags / addTags / detachTag` (see [Documents](#documents)).
1406
1422
 
1407
- The published attachment contract takes tag IDs. Older sandbox deployments
1408
- instead interpret strings as names and create ID-named tags for ID inputs;
1409
- 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).
1410
1425
 
1411
1426
  ### Workspaces
1412
1427
 
1413
1428
  The official create/update request schemas define `name` and
1414
- `notification_sender_type`. The sandbox also accepts the color fields shown
1415
- 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.
1416
1431
 
1417
1432
  ```ts
1418
1433
  // Colours are 6-char hex WITHOUT a leading '#' (unlike tags, which strip it).
@@ -1494,37 +1509,6 @@ await client.fields.validateMultiple(
1494
1509
  await client.fields.listTypes();
1495
1510
  ```
1496
1511
 
1497
- ### Authentication / API key management
1498
-
1499
- 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.
1500
-
1501
- ```ts
1502
- // Browser OAuth: redirect the user to this URL. The callback helper returns the
1503
- // Assinafy callback URL for provider configuration; neither follows a redirect.
1504
- const oauthStart = client.auth.getSocialLoginUrl('google');
1505
- const oauthCallback = client.auth.getSocialLoginCallbackUrl();
1506
-
1507
- let session = await client.auth.login('me@example.com', 'pw');
1508
- // With two-factor authentication on, login returns `mfa_token`; exchange it
1509
- // within 5 minutes for an authenticator code or a recovery code.
1510
- if (session.mfa_token) {
1511
- session = await client.auth.verifyMfa(session.mfa_token, '123456');
1512
- }
1513
- const { access_token, user, accounts } = session;
1514
- await client.auth.socialLogin({ provider: 'google', token: 'google-id-token', has_accepted_terms: true });
1515
- await client.auth.linkSocialLogin({ provider: 'google', token: 'google-id-token' });
1516
-
1517
- // Personal API key
1518
- await client.auth.createApiKey('current-password');
1519
- await client.auth.getApiKey(); // → { api_key: '****...nBNr' } or null
1520
- await client.auth.deleteApiKey();
1521
-
1522
- // Password lifecycle
1523
- await client.auth.changePassword({ email, password: 'current', new_password: 'next' });
1524
- await client.auth.requestPasswordReset('me@example.com');
1525
- await client.auth.resetPassword({ email, token: 'tk', new_password: 'next' });
1526
- ```
1527
-
1528
1512
  ### Authenticated user
1529
1513
 
1530
1514
  ```ts
@@ -1556,27 +1540,6 @@ const push = await client.users.getPushPreferences(); // every key, default true
1556
1540
  await client.users.updatePushPreferences({ SignerViewed: false });
1557
1541
  ```
1558
1542
 
1559
- #### Two-factor authentication
1560
-
1561
- Available in production. The TOTP secret and the recovery codes are shown once.
1562
-
1563
- ```ts
1564
- const enrollment = await client.users.startTotpEnrollment('My phone');
1565
- // → { id, secret, provisioning_uri } — render provisioning_uri as a QR code
1566
- const { recovery_codes } = await client.users.confirmTotpEnrollment({
1567
- id: enrollment.id,
1568
- code: '123456', // current code from the new device
1569
- });
1570
- // From now on every login needs the second factor.
1571
-
1572
- const { methods, recovery_codes_remaining } = await client.users.getMfa();
1573
- await client.users.regenerateRecoveryCodes({ password: 'current-password' }); // or { code }
1574
- await client.users.deleteMfaMethod(methods[0]!.id, { code: '123456' }); // → { is_mfa_enabled }
1575
- ```
1576
-
1577
- Replacing an already confirmed authenticator also needs `password` or
1578
- `reauth_code` in `confirmTotpEnrollment()`; first-time enrollment does not.
1579
-
1580
1543
  ### Webhooks
1581
1544
 
1582
1545
  An account has 1 webhook endpoint, or up to 3 on paid plans. Every active
@@ -1699,6 +1662,8 @@ Event-specific values are:
1699
1662
  | `document_ready` | `Account` | `Document` | — |
1700
1663
  | `document_processing_failed` | `Account` | `Document` | `error_message` |
1701
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`) |
1702
1667
  | `signer_created` | `User` | `Signer` | `signer_full_name` |
1703
1668
  | `signer_email_verified` | `Signer` | `Document` | `signer_email` |
1704
1669
  | `signer_whatsapp_verified` | `Signer` | `Document` | `signer_whatsapp_phone_number` |
@@ -1712,6 +1677,8 @@ Event-specific values are:
1712
1677
  | `signer_signed_document` | `Signer` | `Document` | `signer_full_name` |
1713
1678
  | `signer_rejected_document` | `Signer` | `Document` | `signer_full_name` |
1714
1679
  | `user_rejected_document` | `User` | `Document` | `user_name` |
1680
+ | `document_expiring` | `Document` | `Document` | — |
1681
+ | `document_expired` | `Document` | `Document` | — |
1715
1682
  | `template_created` | `User` | `Template` | — |
1716
1683
  | `template_processed` | `User` | `Template` | — |
1717
1684
  | `template_processing_failed` | `Account` | `Template` | `error_message` |
@@ -1723,6 +1690,15 @@ failed deliveries. `assignment_created` and `document_metadata_ready` have no
1723
1690
  guaranteed ordering. For account entities, Assinafy removes the `integration`
1724
1691
  property before delivery.
1725
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
+
1726
1702
  ### Webhook verification
1727
1703
 
1728
1704
  With `signing_enabled: true`, every delivery is signed following
@@ -1787,7 +1763,7 @@ await client.signerDocuments.download(signerId, documentId, 'original', accessCo
1787
1763
  await client.signerDocuments.confirmData(documentId, accessCode, {
1788
1764
  email: 'me@example.com',
1789
1765
  has_accepted_terms: true,
1790
- }); // null on production
1766
+ }); // null (the API answers data: [])
1791
1767
  // Alternatively, accept terms separately before getAssignment():
1792
1768
  // await client.signerDocuments.acceptTerms(accessCode); // { full_name, email, has_accepted_terms }
1793
1769
 
@@ -1822,6 +1798,9 @@ await client.signerDocuments.declineMultiple(['doc-1'], 'Unfavorable terms', acc
1822
1798
  `sign()` also requires virtual signers to have confirmed their data first, but
1823
1799
  virtual assignments should normally use `signMultiple()`. Certificate signers
1824
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.
1825
1804
 
1826
1805
  ## High-level helper
1827
1806
 
@@ -1836,7 +1815,6 @@ const result = await client.uploadAndRequestSignatures({
1836
1815
  { name: 'Example Signer B', email: 'signer-b@example.com' },
1837
1816
  ],
1838
1817
  message: 'Please sign',
1839
- metadata: { year: 2026 }, // compatibility upload part; omit for file-only wire format
1840
1818
  waitForReady: true,
1841
1819
  waitOptions: { maxWaitMs: 30_000, pollIntervalMs: 1_000 },
1842
1820
  expiresAt: '2027-12-31T00:00:00Z',
@@ -1851,13 +1829,12 @@ result.signer_ids; // string[]
1851
1829
 
1852
1830
  `waitForReady: false` skips post-assignment polling and returns the initial
1853
1831
  upload response. With the default `true`, the helper creates the assignment first and
1854
- then waits for the current document details. Both production and sandbox allow
1855
- 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
1856
1834
  automatically; only `collect` assignments require rendered pages.
1857
1835
  Every signer above uses the default email channel. A phone-only signer selects
1858
1836
  the paid WhatsApp branch described earlier. `copyReceivers` accepts existing
1859
- signer IDs, not email addresses; check the returned assignment before treating
1860
- a copy receiver as registered.
1837
+ signer IDs, not email addresses; they receive a copy of the signed document.
1861
1838
 
1862
1839
  The helper is not transactional. A post-assignment polling error includes the
1863
1840
  created `documentId`, `assignmentId`, and `signerIds` in its `context` (and in
@@ -1867,8 +1844,8 @@ whether to retry the workflow.
1867
1844
  ## Errors
1868
1845
 
1869
1846
  HTTP methods reject with an `AssinafyError` subclass. Synchronous helpers such
1870
- as `getSocialLoginUrl()` and `readAuthorizationCallback()` can throw
1871
- `ValidationError` before any request.
1847
+ as `oauth.readAuthorizationCallback()` can throw `ValidationError` before any
1848
+ request.
1872
1849
 
1873
1850
  ```ts
1874
1851
  import { ApiError, OAuthError, ValidationError, NetworkError, AssinafyError } from '@assinafy/sdk';
@@ -1899,20 +1876,31 @@ try {
1899
1876
  internally is exported as `parseWwwAuthenticate()`, for reading the
1900
1877
  `WWW-Authenticate` header of responses received outside the SDK.
1901
1878
 
1902
- ## Environments
1879
+ Besides the codes named in each section, these refusals carry an
1880
+ `ApiError.code`:
1903
1881
 
1904
- | | |
1905
- | --- | --- |
1906
- | Production | `https://api.assinafy.com.br/v1` |
1907
- | Sandbox | `https://sandbox.assinafy.com.br/v1` |
1908
-
1909
- The sandbox runs its own authorization server at
1910
- `https://auth-sandbox.assinafy.com.br`, with the consent screen at
1911
- `/oauth/authorize`. Discovery is available and selects that server from the
1912
- 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:
1913
1901
 
1914
1902
  ```ts
1915
- const client = new AssinafyClient({ baseUrl: 'https://sandbox.assinafy.com.br/v1' });
1903
+ const client = new AssinafyClient({ baseUrl: 'https://api.assinafy.com.br/v1' });
1916
1904
  const metadata = await client.oauth.getAuthorizationServerMetadata();
1917
1905
  const request = await client.oauth.createAuthorizationUrl({
1918
1906
  clientId: process.env.ASSINAFY_CLIENT_ID!,
@@ -1921,9 +1909,8 @@ const request = await client.oauth.createAuthorizationUrl({
1921
1909
  });
1922
1910
  ```
1923
1911
 
1924
- Register the application in the matching environment. Production and sandbox
1925
- have separate issuers, client IDs, credentials and workspaces; keep each
1926
- 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
1927
1914
  use the configured `baseUrl`. For local testing, expose only the callback
1928
1915
  through an HTTPS tunnel, register its exact URL and revoke tokens afterward.
1929
1916
  See [COMPATIBILITY.md](COMPATIBILITY.md).
@@ -1945,7 +1932,7 @@ bun run verify # complete local release gate
1945
1932
 
1946
1933
  - **[README.md](README.md)** — the same complete reference in Portuguese
1947
1934
  - [API_COVERAGE.md](API_COVERAGE.md) — operation map
1948
- - [COMPATIBILITY.md](COMPATIBILITY.md) — per-deployment request and response variants
1935
+ - [COMPATIBILITY.md](COMPATIBILITY.md) — request and response variants
1949
1936
  - [RELEASING.md](RELEASING.md) — publishing process
1950
1937
  - [API documentation](https://api.assinafy.com.br/v1/docs)
1951
1938