@assinafy/cli 2.7.1 → 2.9.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.
Files changed (61) hide show
  1. package/.env.example +2 -0
  2. package/README.en.md +75 -67
  3. package/README.md +39 -25
  4. package/THIRD_PARTY_NOTICES.md +8 -8
  5. package/dist/api.cjs +701 -93
  6. package/dist/api.cjs.map +1 -1
  7. package/dist/api.js +696 -93
  8. package/dist/api.js.map +1 -1
  9. package/dist/cli.cjs +2390 -694
  10. package/dist/types/api/client.d.ts +7 -0
  11. package/dist/types/api/client.d.ts.map +1 -1
  12. package/dist/types/api/envelope-types.d.ts +73 -0
  13. package/dist/types/api/envelope-types.d.ts.map +1 -0
  14. package/dist/types/api/index.d.ts +4 -0
  15. package/dist/types/api/index.d.ts.map +1 -1
  16. package/dist/types/api/resources/assignments.d.ts +7 -1
  17. package/dist/types/api/resources/assignments.d.ts.map +1 -1
  18. package/dist/types/api/resources/contracts.d.ts +3 -1
  19. package/dist/types/api/resources/contracts.d.ts.map +1 -1
  20. package/dist/types/api/resources/documents.d.ts +25 -6
  21. package/dist/types/api/resources/documents.d.ts.map +1 -1
  22. package/dist/types/api/resources/embed.d.ts +14 -0
  23. package/dist/types/api/resources/embed.d.ts.map +1 -0
  24. package/dist/types/api/resources/envelopes.d.ts +37 -0
  25. package/dist/types/api/resources/envelopes.d.ts.map +1 -0
  26. package/dist/types/api/resources/scheduled-sends.d.ts +11 -0
  27. package/dist/types/api/resources/scheduled-sends.d.ts.map +1 -0
  28. package/dist/types/api/resources/signer-documents.d.ts +23 -11
  29. package/dist/types/api/resources/signer-documents.d.ts.map +1 -1
  30. package/dist/types/api/resources/signers.d.ts +1 -1
  31. package/dist/types/api/resources/signers.d.ts.map +1 -1
  32. package/dist/types/api/resources/users.d.ts +3 -1
  33. package/dist/types/api/resources/users.d.ts.map +1 -1
  34. package/dist/types/api/resources/webhooks.d.ts +6 -2
  35. package/dist/types/api/resources/webhooks.d.ts.map +1 -1
  36. package/dist/types/api/resources/workspaces.d.ts +9 -2
  37. package/dist/types/api/resources/workspaces.d.ts.map +1 -1
  38. package/dist/types/api/types.d.ts +138 -8
  39. package/dist/types/api/types.d.ts.map +1 -1
  40. package/dist/types/api/utils.d.ts +9 -0
  41. package/dist/types/api/utils.d.ts.map +1 -1
  42. package/docs/README.md +5 -1
  43. package/docs/api-operations-staging.json +1262 -0
  44. package/docs/api-operations.json +234 -2
  45. package/docs/api-reference-staging.md +18466 -0
  46. package/docs/api-reference.md +11562 -3718
  47. package/docs/assignments.md +62 -14
  48. package/docs/contracts.md +4 -3
  49. package/docs/documents.md +75 -27
  50. package/docs/embed.md +119 -0
  51. package/docs/envelopes.md +239 -0
  52. package/docs/scheduled-sends.md +63 -0
  53. package/docs/sdk-reference.md +278 -30
  54. package/docs/send.md +15 -11
  55. package/docs/signer.md +84 -3
  56. package/docs/users.md +41 -0
  57. package/docs/webhooks.md +22 -6
  58. package/docs/workspaces.md +66 -3
  59. package/install.ps1 +1 -1
  60. package/install.sh +1 -1
  61. package/package.json +4 -4
@@ -0,0 +1,63 @@
1
+ # `assinafy scheduled-sends`
2
+
3
+ ## `assinafy scheduled-sends`
4
+
5
+ ```text
6
+ Usage: assinafy scheduled-sends [options] [command]
7
+
8
+ List, cancel or send queued requests (staging)
9
+
10
+ Options:
11
+ -h, --help display help for command
12
+
13
+ Commands:
14
+ list [options] List queued assignments and envelopes
15
+ cancel [options] <scheduledSendId> Cancel a pending request without sending
16
+ send [options] <scheduledSendId> Send now, charging the current cost and
17
+ notifying signers
18
+ help [command] display help for command
19
+ ```
20
+
21
+ ### `assinafy scheduled-sends list`
22
+
23
+ ```text
24
+ Usage: assinafy scheduled-sends list [options]
25
+
26
+ List queued assignments and envelopes
27
+
28
+ Options:
29
+ --page <n> Page number to fetch
30
+ --per-page <n> Items per page
31
+ --document <id> Filter by document ID
32
+ -h, --help display help for command
33
+ ```
34
+
35
+ ### `assinafy scheduled-sends cancel`
36
+
37
+ ```text
38
+ Usage: assinafy scheduled-sends cancel [options] <scheduledSendId>
39
+
40
+ Cancel a pending request without sending
41
+
42
+ Arguments:
43
+ scheduledSendId Scheduled send ID
44
+
45
+ Options:
46
+ -y, --yes Skip confirmation
47
+ -h, --help display help for command
48
+ ```
49
+
50
+ ### `assinafy scheduled-sends send`
51
+
52
+ ```text
53
+ Usage: assinafy scheduled-sends send [options] <scheduledSendId>
54
+
55
+ Send now, charging the current cost and notifying signers
56
+
57
+ Arguments:
58
+ scheduledSendId Scheduled send ID
59
+
60
+ Options:
61
+ -y, --yes Skip confirmation
62
+ -h, --help display help for command
63
+ ```
@@ -56,7 +56,7 @@ const publicClient = new AssinafyClient({ allowUnauthenticated: true });
56
56
 
57
57
  | API | Result |
58
58
  | --- | --- |
59
- | `new AssinafyClient(options: AssinafyClientOptions)` | Client with `documents`, `signers`, `workspaces`, `assignments`, `webhooks`, `templates`, `tags`, `auth`, `oauth`, `fields`, `users`, `signerDocuments`, and `webhookVerifier`. |
59
+ | `new AssinafyClient(options: AssinafyClientOptions)` | Client with `documents`, `signers`, `workspaces`, `assignments`, `webhooks`, `templates`, `tags`, `auth`, `oauth`, `fields`, `users`, `signerDocuments`, `contracts`, `envelopes`, `embed`, and `webhookVerifier`. |
60
60
  | `AssinafyClient.create(apiKey, accountId, options?)` | Convenience constructor. |
61
61
  | `AssinafyClient.fromConfig(config: ClientConfigInput)` | Accepts snake-case or camel-case configuration keys. |
62
62
  | `client.uploadAndRequestSignatures(options)` | Uploads a PDF, optionally waits for processing, creates/reuses signers, and creates a virtual assignment; returns `IUploadAndRequestSignaturesResult`. |
@@ -78,12 +78,14 @@ const publicClient = new AssinafyClient({ allowUnauthenticated: true });
78
78
  verification_method?: 'Email' | 'Whatsapp' | 'DigitalCertificate' | 'IdDocumentFaceMatchBasic';
79
79
  notification_methods?: Array<'Email' | 'Whatsapp'>;
80
80
  step?: number;
81
+ embedded?: boolean;
81
82
  }>;
82
83
  message?: string;
83
84
  metadata?: Record<string, unknown>;
84
85
  waitForReady?: boolean;
85
86
  expiresAt?: string;
86
87
  copyReceivers?: string[];
88
+ maxTotalCredits?: number;
87
89
  accountId?: string;
88
90
  }
89
91
  ```
@@ -111,16 +113,19 @@ try {
111
113
 
112
114
  | SDK method | HTTP operation | Resolves to |
113
115
  | --- | --- | --- |
116
+ | `listWatchers(documentId)` | `GET /documents/{documentId}/watchers` (staging) | `ISigner[]` |
117
+ | `setWatchers(documentId, watcherIds)` | `PUT /documents/{documentId}/watchers` (staging); `{ watcher_ids: string[] }` | `ISigner[]` |
114
118
  | `upload(source, options?)` | [`POST /accounts/{accountId}/documents`](./api-reference.md#upload-and-create-document) | `IDocumentUploadResponse` |
115
119
  | `list(params?, accountId?)` | [`GET /accounts/{accountId}/documents`](./api-reference.md#list-documents) | `IDocumentListResponse` |
116
120
  | `search(params?, accountId?)` | [`GET /accounts/{accountId}/documents/search`](./api-reference.md#search-documents-lightweight) | `IDocumentListResponse` |
117
- | `details(documentId)` | [`GET /documents/{documentId}`](./api-reference.md#get-document) | `IDocumentDetailsResponse` |
118
- | `get(documentId)` | Same as `details` | `IDocumentDetailsResponse` |
121
+ | `details(documentId, params?)` | [`GET /documents/{documentId}`](./api-reference.md#get-document) | `IDocumentDetailsResponse` |
122
+ | `get(documentId, params?)` | Same as `details` | `IDocumentDetailsResponse` |
123
+ | `getAsSigner(documentId, accessCode)` | `GET /documents/{documentId}`, stripped owner headers | `ISignerDocumentDetailsResponse` |
119
124
  | `rename(documentId, name)` | [`PATCH /documents/{documentId}`](./api-reference.md#rename-document) | `IDocumentDetailsResponse` |
120
125
  | `waitUntilReady(documentId, { maxWaitMs?, pollIntervalMs? }?)` | Polls [Get document](./api-reference.md#get-document) | `IDocumentDetailsResponse`; rejects on terminal failure, permanent 4xx, or timeout |
121
- | `download(documentId, artifactName?)` | [`GET /documents/{documentId}/download/{artifact}`](./api-reference.md#download-document-artifact) | `Buffer` |
122
- | `thumbnail(documentId)` | [`GET /documents/{documentId}/thumbnail`](./api-reference.md#download-document-thumbnail) | JPEG `Buffer` |
123
- | `downloadPage(documentId, pageId)` | [`GET /documents/{documentId}/pages/{pageId}/download`](./api-reference.md#download-document-page) | JPEG `Buffer` |
126
+ | `download(documentId, artifactName?, options?)` | [`GET /documents/{documentId}/download/{artifact}`](./api-reference.md#download-document-artifact) | `Buffer` |
127
+ | `thumbnail(documentId, options?)` | [`GET /documents/{documentId}/thumbnail`](./api-reference.md#download-document-thumbnail) | JPEG `Buffer` |
128
+ | `downloadPage(documentId, pageId, options?)` | [`GET /documents/{documentId}/pages/{pageId}/download`](./api-reference.md#download-document-page) | JPEG `Buffer` |
124
129
  | `activities(documentId, params?)` | [`GET /documents/{documentId}/activities`](./api-reference.md#list-document-activities) | `IDocumentActivity[]` |
125
130
  | `delete(documentId)` | [`DELETE /documents/{documentId}`](./api-reference.md#delete-document) | `IEmptyResult` (`unknown[]`) |
126
131
  | `listTags(documentId, accountId?)` | [`GET /accounts/{accountId}/documents/{documentId}/tags`](./api-reference.md#list-document-tags) | `ITag[]` |
@@ -136,6 +141,8 @@ try {
136
141
  | `isFullySigned(documentId)` | SDK helper over `details` | `boolean` |
137
142
  | `getSigningProgress(documentId)` | SDK helper over `details` | `{ signed; total; pending; percentage }` |
138
143
 
144
+ Watchers require owner credentials; OAuth application tokens cannot manage them. Up to ten workspace contacts with email addresses receive an email when the document is signed by all, declined or expired. The email has no document link or attachment. Setting watchers replaces the whole list, duplicates count once, and `[]` clears it. Changes stop once the document ends. See the complete [staging request and response contracts](./api-reference-staging.md#documents). CLI: `documents watchers` and `documents set-watchers --watcher-ids '["example_signer"]'`.
145
+
139
146
  Upload input and options:
140
147
 
141
148
  ```ts
@@ -152,26 +159,181 @@ interface IDocumentUploadOptions {
152
159
 
153
160
  Uploads must be non-empty PDFs up to 25 MiB. `DocumentArtifactName` is `original | certificated | certificate-page | pades | bundle`; `bundle` is ZIP and the other document artifacts are PDF. `sendToken(documentId, 'signer@example.com')` emails a one-time access token to a signer who has not signed a pending document yet and sends `{ "channel": "email", "recipient": "signer@example.com" }`. Only the `email` channel is accepted; any other channel is rejected locally. The `{ email }` overload sends the same body.
154
161
 
155
- Template document creation sends `{ signers, name?, message?, expires_at?, editor_fields?, tags? }`. Each signer is `{ role_id, id?, email?, name?, whatsapp_phone_number?, verification_method?, notification_methods?, step? }`; supply an existing ID or an email for creation/reuse (an ID takes precedence); each editor field is `{ field_id, value: string }`. Template cost estimation publishes `{ signers: Array<{ role_id, verification_method?, notification_methods? }> }`. The optional cost-signer `id` and `step` properties remain compatibility extensions for existing integrations. A template with placed signer fields creates a `collect` assignment, so it cannot use a `DigitalCertificate` signer. For certificate-bearing template create and estimate calls, the SDK reads the template details first and rejects placed Signer-role fields with `ValidationError.errors.code` set to `digital_certificate_requires_virtual`.
162
+ Template document creation sends `{ signers, name?, message?, expires_at?, editor_fields?, tags?, max_total_credits? }`. Options also accept `idempotencyKey`, sent only in the `Idempotency-Key` header. Each signer is `{ role_id, id?, email?, name?, whatsapp_phone_number?, verification_method?, notification_methods?, step?, embedded? }`; supply an existing ID or an email for creation/reuse (an ID takes precedence); each editor field is `{ field_id, value: string }`. Template cost estimation publishes `{ signers: Array<{ role_id, verification_method?, notification_methods? }> }`. The optional cost-signer `id` and `step` properties remain compatibility extensions for existing integrations. A template with placed signer fields creates a `collect` assignment, so it cannot use a `DigitalCertificate` signer. For certificate-bearing template create and estimate calls, the SDK reads the template details first and rejects placed Signer-role fields with `ValidationError.errors.code` set to `digital_certificate_requires_virtual`.
156
163
 
157
- Document list params are `{ page?, per_page?, status?, method?, tags?, search?, sort? }`; search params omit `method`/`tags`. Supported sort values are `name`, `-name`, `updated_at`, and `-updated_at`.
164
+ Document list params are `{ page?, per_page?, status?, method?, tags?, search?, sort?, envelope_id? }`; search params omit `method`/`tags`. Supported sort values are `name`, `-name`, `updated_at`, and `-updated_at`.
158
165
 
159
166
  In production, `replaceTags` and `addTags` accept tag names, reuse matching tags, and create missing names. Use `replaceTags(documentId, ['Contracts'])` or `addTags(documentId, ['Contracts'])`; an empty replacement removes all associations. Values are sent unchanged. Pass the tag ID from `listTags` to `detachTag`. Document-list tag filters also use IDs.
160
167
 
161
168
  Activity queries use `IDocumentActivityListParams`: `{ page?, per_page?, 'per-page'?, sort?: 'id' | '-id' }`; the default is 20 records per page, newest first. Page until an empty array to read the complete history. Expirations accept `YYYY-MM-DD` (23:59 UTC), an offsetless datetime (UTC), or an RFC 3339 timestamp; values are forwarded unchanged. Template signing steps apply to Signer roles; CopyReceiver steps are ignored. Editor fields do not force a certificate template into collect signing. Template creation/estimation forwards role-specific verification, notification and step settings to the API, which ignores them for CopyReceiver roles. The SDK validates descriptor identity locally without fetching roles solely for validation.
162
169
 
170
+ Owner `get`/`details` params accept `{ expand: "envelope" | "envelope_id" | "envelope,envelope_id" }`; the expanded relation is null for a standalone document. `getAsSigner` returns only the signer-visible assignment fields. Download options accept `{ signerAccessCode? }`; thumbnail/page options also accept `{ artifact: "certificated" }` to render the signed PDF. Omit the code to use owner authentication; a supplied code strips owner credentials, and a blank code is rejected. CLI `documents get|download|thumbnail|download-page --access-code` selects the same behavior.
171
+
163
172
  Document responses expose typed `IDocumentArtifacts`, `IDocumentPage`, inline tags, assignment/signing state, decline state, and creation/update timestamps. `IPublicDocumentInfo` models the complete published public-document payload while retaining the older optional `page_count` and `created_by` fields.
164
173
 
174
+ ## Envelopes (`client.envelopes`)
175
+
176
+ An envelope groups up to 20 processed documents and 20 existing workspace signers. Each document keeps its own assignment, status, certificate, artifacts and webhooks. Creation consumes one document allowance; notifications and biometric verification are charged once per signer for the envelope, while certificate signatures are charged per document. The Envelopes feature is required for creation, adding documents and estimates. OAuth uses `documents:read`/`documents:write`.
177
+
178
+ | SDK method | HTTP operation | SDK result |
179
+ | --- | --- | --- |
180
+ | `list(params?, accountId?)` | `GET /accounts/{accountId}/envelopes`; `{ page?, per_page?, search?, status?: "open" | "closed" }` | `PaginatedResult<IDocumentEnvelope>` |
181
+ | `create(payload, options?)` | `POST /accounts/{accountId}/envelopes`; `ICreateEnvelopePayload` | `IDocumentEnvelope` |
182
+ | `schedule(payload, accountId?)` | `POST /accounts/{accountId}/scheduled-sends` (staging); creation body plus `send_at` | `IScheduledSend` |
183
+ | `estimateResendCost(envelopeId, signerId, accountId?)` | `POST …/{envelopeId}/signers/{signerId}/estimate-resend-cost` (staging); no body | `IResendCostEstimate` |
184
+ | `estimateCost(payload, accountId?)` | `POST /accounts/{accountId}/envelopes/estimate-cost`; same creation body, no changes or charges | `IEstimateCostResponse` |
185
+ | `get(envelopeId, accountId?)` | `GET /accounts/{accountId}/envelopes/{envelopeId}` | `IDocumentEnvelope` |
186
+ | `update(envelopeId, payload, accountId?)` | `PATCH /accounts/{accountId}/envelopes/{envelopeId}`; `{ name?, message?: string | null, document_ids?: string[] }` | `IDocumentEnvelope` |
187
+ | `delete(envelopeId, accountId?)` | `DELETE /accounts/{accountId}/envelopes/{envelopeId}`; no body, requires all documents closed | `[]`; documents remain |
188
+ | `activities(envelopeId, params?, accountId?)` | `GET …/{envelopeId}/activities`; pagination and `sort: "id" | "-id"` | `PaginatedResult<IEnvelopeActivity>` |
189
+ | `download(envelopeId, artifactName?, accountId?)` | `GET …/{envelopeId}/download/{artifactName}`; defaults to certificated | ZIP `Buffer` |
190
+ | `cancel(envelopeId, accountId?)` | `PUT …/{envelopeId}/cancel`, no body | `Array<{ id, status, cancelled: boolean }>` |
191
+ | `resendNotification(envelopeId, signerId, accountId?)` | `PUT …/{envelopeId}/signers/{signerId}/resend`, no body | `{ is_sent: boolean, envelope_id: string, signer_id: string }` |
192
+ | `addDocument(envelopeId, payload, accountId?)` | `POST …/{envelopeId}/documents`; `IEnvelopeDocumentPayload & { max_total_credits?: number }` | `IDocumentEnvelope` |
193
+ | `removeDocument(envelopeId, documentId, accountId?)` | `DELETE …/{envelopeId}/documents/{documentId}`, no body | `IDocumentEnvelope` |
194
+
195
+ Complete creation body (optional controls shown):
196
+
197
+ ```ts
198
+ interface ICreateEnvelopePayload {
199
+ name: string; // 1–255 characters, no <
200
+ message?: string | null;
201
+ max_total_credits?: number;
202
+ signers: Array<{
203
+ id: string;
204
+ verification_method?: 'Email' | 'Whatsapp' | 'DigitalCertificate' | 'IdDocumentFaceMatchBasic';
205
+ notification_methods?: Array<'Email' | 'Whatsapp'>;
206
+ embedded?: boolean;
207
+ }>;
208
+ documents: Array<{
209
+ id: string;
210
+ signer_ids: string[];
211
+ method?: 'virtual' | 'collect';
212
+ entries?: ICollectAssignmentEntry[];
213
+ expires_at?: string | number | null;
214
+ copy_receiver_ids?: string[];
215
+ }>;
216
+ }
217
+ ```
218
+
219
+ Signers act in parallel; `step` is not accepted. Every signer must appear on at least one document, and every document signer must be in the envelope's signer list. A certificate signer must be alone on each virtual document they sign. Collect entries use the assignment field format and exactly that document's signers. The server enforces workspace ownership, document readiness, at most 2,000 fields and 100 copy receivers across the envelope. Expiration accepts ISO dates/timestamps or Unix seconds; null, zero or empty text means no expiration. Reorder updates must name every current document exactly once; null clears only the message.
220
+
221
+ A complete SDK flow:
222
+
223
+ ```ts
224
+ import { randomUUID } from 'node:crypto';
225
+ import { AssinafyClient } from '@assinafy/cli/api';
226
+
227
+ const client = new AssinafyClient({
228
+ apiKey: process.env.ASSINAFY_API_KEY!,
229
+ accountId: process.env.ASSINAFY_ACCOUNT_ID!,
230
+ });
231
+ const signer = await client.signers.create({ full_name: 'Example Signer', email: 'signer@example.com' });
232
+ const documents = [];
233
+ for (const filePath of ['./contract.pdf', './annex.pdf']) {
234
+ const uploaded = await client.documents.upload({ filePath });
235
+ // Persist uploaded.id before waiting so a failure can be resumed.
236
+ await client.documents.waitUntilReady(uploaded.id);
237
+ documents.push({ id: uploaded.id, signer_ids: [signer.id] });
238
+ }
239
+ const payload = {
240
+ name: 'Service agreement',
241
+ message: 'Please review both documents.',
242
+ signers: [{ id: signer.id }],
243
+ documents,
244
+ max_total_credits: 0,
245
+ };
246
+ const estimate = await client.envelopes.estimateCost(payload);
247
+ if (!estimate.has_sufficient_resources) throw new Error('Insufficient resources');
248
+ const idempotencyKey = randomUUID(); // Persist with this business operation before sending.
249
+ const envelope = await client.envelopes.create(payload, { idempotencyKey });
250
+ // Persist envelope.id, then inspect document status and notification history.
251
+ const current = await client.envelopes.get(envelope.id);
252
+ ```
253
+
254
+ The SDK result has this complete shape (the wire body wraps it in `{ status, message, data }`):
255
+
256
+ ```ts
257
+ interface IDocumentEnvelope {
258
+ resource?: string;
259
+ id: string;
260
+ name: string;
261
+ message: string | null;
262
+ documents: Array<{
263
+ id: string;
264
+ position: number;
265
+ name: string;
266
+ status: string;
267
+ artifacts: Record<string, string>;
268
+ signers: Array<{
269
+ id: string;
270
+ full_name: string;
271
+ email: string | null;
272
+ whatsapp_phone_number: string | null;
273
+ completed: boolean;
274
+ signed_at: string | null;
275
+ }>;
276
+ }>;
277
+ counts: Record<string, number> | null;
278
+ signing_urls: Array<{ signer_id: string; url: string | null; embedded?: boolean }>;
279
+ created_at: string;
280
+ }
281
+ ```
282
+
283
+ A successful creation means the envelope exists, not that every invitation arrived. Inspect assignment `notification_history` and WhatsApp delivery history. One invitation covers a signer's documents; the email/WhatsApp code carries across the envelope. `getAssignment(code, undefined, { document_id })` selects a document, and `sign`/`decline` perform that selection automatically. Biometric verification and review are shared across the signer's envelope documents; certificate signing remains one operation per document. Pass `documentId` to `startCertificate(code, documentId)` and `completeCertificate(code, token, documentId)` to select each one.
284
+
285
+ Creation options are `{ accountId?, idempotencyKey? }`. The case-sensitive key belongs to the workspace and does not expire; reusing it returns the original envelope regardless of the replacement body. Persist and deliberately reuse it after an ambiguous failure; never generate a new key for the same intended operation. `IdempotencyKeyInUse` is 409 while the first request runs. A credit ceiling refusal creates and charges nothing. There are no SDK write retries. Deleting an envelope also removes its idempotency replay result.
286
+
287
+ Adding a document uses existing envelope signers, sends updated invitations, and can charge certificate credits. Removing an open document cancels it and notifies recipients; links from it continue to open the rest. Cancel affects only cancellable documents; completed certificates stay valid. Deleting requires every document closed and leaves the documents intact. Document deletion is refused while its envelope remains open, including documents removed from it. CLI cancel/delete/remove-document confirm unless `--yes`.
288
+
289
+ Envelope reminder estimates send and charge nothing. They price one reminder for the whole envelope, independent of document count, and do not check current reminder eligibility. Scheduled envelopes accept the same creation payload plus `send_at`, but do not accept an idempotency key. See [scheduled sends](#scheduled-sends-clientscheduledsends).
290
+
291
+ ## Embedded signing (`client.embed`)
292
+
293
+ The Embed feature and an owner API key or first-party user token are required to mint sessions; OAuth application tokens cannot mint them. Keep that credential on your backend. The Node SDK is not shipped in the browser or a native mobile app; the frontend displays the hosted iframe. See the [official Embedded Signing Guide](https://api.assinafy.com.br/v1/docs) for the frontend message protocol and event payloads.
294
+
295
+ | SDK method | HTTP operation and request | SDK result |
296
+ | --- | --- | --- |
297
+ | `listOrigins(accountId?)` | `GET /accounts/{accountId}/embed-origins`, no body | `IEmbedOrigin[]` |
298
+ | `createOrigin(origin, accountId?)` | `POST /accounts/{accountId}/embed-origins`; `{ origin }` | `IEmbedOrigin` |
299
+ | `updateOrigin(originId, origin, accountId?)` | `PUT …/embed-origins/{originId}`; `{ origin }` | `IEmbedOrigin` |
300
+ | `deleteOrigin(originId, accountId?)` | `DELETE …/embed-origins/{originId}`, no body | `[]` |
301
+ | `createSession(documentId, assignmentId, signerId)` | `POST /documents/{documentId}/assignments/{assignmentId}/signers/{signerId}/embed-sessions`, no body | `IEmbedSession` |
302
+ | `exchangeSession(token, parentOrigin?)` | `POST /embed/sessions/{token}/exchange`; no body or `{ parent_origin }`, no owner headers | `IEmbedSessionExchange` |
303
+
304
+ Complete SDK response types:
305
+
306
+ ```ts
307
+ interface IEmbedOrigin { id: string; origin: string; created_at: string }
308
+ interface IEmbedSession { url: string; expires_at: string }
309
+ interface IEmbedSessionExchange {
310
+ signer_access_code: string;
311
+ signer_id: string;
312
+ document_id: string;
313
+ verification_method: string;
314
+ embed_origins: string[];
315
+ }
316
+ ```
317
+
318
+ 1. Register an exact HTTPS origin with `createOrigin('https://app.example.com')`. HTTP is allowed only on localhost or 127.0.0.1. Paths, credentials, wildcards, query strings and fragments are rejected; at most 10 origins are allowed. No origins means embedding is disabled.
319
+ 2. Create the assignment/template/envelope signer with `embedded: true`, Email or Whatsapp verification, and the matching notification method. Invitations still deliver the OTP; `signing_urls` contains `{ signer_id, url: null, embedded: true }`.
320
+ 3. Your authenticated backend verifies that the logged-in application user may act for that signer, then calls `createSession(documentId, assignmentId, signerId)`. Pass only its URL to that user's frontend. Sessions expire after five minutes and are single-use; mint a new one each time the frame is opened. Limit: 30 per signer per hour.
321
+ 4. Load the URL in the iframe. On load, send `{ v: 1, type: 'assinafy:hello' }` every 500 ms for at most 10 seconds, targeting the exact Assinafy origin, until `ready` or `error`. Repeat the handshake on frame reload. Accept messages only when both `event.origin` and `event.source === iframe.contentWindow` match. Production iframe origin: `https://app.assinafy.com.br`; sandbox: `https://app-sandbox.assinafy.com.br`.
322
+ 5. The hosted page exchanges the token and handles verification, terms and signing. Integrations must not call `exchangeSession` before loading the frame: it consumes the token, including on a 409. That method/CLI operation is exposed for implementing the hosted-page protocol. Unknown, expired or consumed tokens return 410/`embed_session_invalid`.
323
+ 6. Treat frame events as UI hints. Confirm completion using verified webhooks or document reads before releasing goods or changing permissions. An external invitation can also complete signing; the frame reports that with `via: 'external'`.
324
+
325
+ A 409/`document_not_ready` from session creation permits a later deliberate mint after processing. Other refusal codes distinguish `already_signed`, `document_unavailable`, and `embed_origins_missing`; inspect `ApiError.responseData`. Editing the signer's contact before verification rotates the access code and expires open frames. Re-send an invitation only as an intentional notification operation. Never store/log embed URLs or exchange results in browser storage.
326
+
165
327
  ## Contracts (`client.contracts`)
166
328
 
167
- Contract tracking (CLM / Gestão de Contratos) records terms on an existing document. It does not upload a document or request signatures. Writes require a plan with contract tracking; reads remain available when the plan lapses. OAuth uses `documents:read` for reads and `documents:write` for writes.
329
+ Contract tracking (CLM / Gestão de Contratos) records terms on an existing document. It does not upload a document or request signatures. Contract tracking is included in all standard plans, including Free; writes require the feature to be active; reads remain available when the plan lapses. OAuth uses `documents:read` for reads and `documents:write` for writes.
168
330
 
169
331
  | SDK method | HTTP operation | Resolves to |
170
332
  | --- | --- | --- |
171
333
  | `list(params?, accountId?)` | [`GET /accounts/{accountId}/contracts`](./api-reference.md#list-contracts) | `PaginatedResult<IContract>` |
172
334
  | `get(documentId, accountId?)` | [`GET /accounts/{accountId}/documents/{documentId}/contract`](./api-reference.md#get-a-documents-contract-terms) | `IContract \| IContractAmendment` |
173
335
  | `set(documentId, payload, accountId?)` | [`PUT /accounts/{accountId}/documents/{documentId}/contract`](./api-reference.md#set-a-documents-contract-terms) | `IContract \| IContractAmendment` |
174
- | `related(documentId, accountId?)` | [`GET …/contract/related`](./api-reference.md#list-the-contracts-related-to-a-document) | `IContract`, including `amendments` |
336
+ | `related(documentId, accountId?, params?)` | [`GET …/contract/related`](./api-reference.md#list-the-contracts-related-to-a-document) | `IContract`, including `amendments` |
175
337
  | `renew(documentId, payload, accountId?)` | [`POST …/contract/renew`](./api-reference.md#renew-a-contract) | `IContract` |
176
338
  | `terminate(documentId, payload?, accountId?)` | [`POST …/contract/terminate`](./api-reference.md#terminate-a-contract) | `IContract` |
177
339
 
@@ -297,11 +459,16 @@ Termination input (`ITerminateContractPayload`) is `{ reason?: string | null; up
297
459
 
298
460
  The hourly lifecycle uses Brasília calendar days: notice-period alerts, warnings 45/30 days before expiry, then renewal or expiry the day after the end date. Owner notification preferences include `ContractRenewalNotice`, `ContractExpiring`, `ContractExpired` and `ContractRenewed`. Contract activities include `document_contract_updated`, `document_contract_amendment_updated`, `document_contract_amended`, `document_contract_renewal_notice`, `document_contract_expiring`, `document_contract_expired`, `document_contract_renewed` and `document_contract_terminated`. Subscribe explicitly to the event types needed; webhook defaults do not add these events. Reconcile missed events by paging `list({ sort: '-updated_at' })` until older than the last sync, and page `documents.activities(documentId, { page, sort: 'id' })` for history. A lapsed plan pauses lifecycle changes and pending amendments; restoration catches up without sending alerts whose windows have passed.
299
461
 
462
+ `related` accepts `{ expand: "document" }` to include document details, also available as `contracts related --expand document`.
463
+
300
464
  ## Assignments (`client.assignments`)
301
465
 
302
466
  | SDK method | HTTP operation | Resolves to |
303
467
  | --- | --- | --- |
304
468
  | `list(params?, accountId?)` | [`GET /assignments?accountId=…`](./api-reference.md#list-assignments) | `PaginatedResult<IAssignment>` |
469
+ | `schedule(documentId, payload)` | `POST /documents/{documentId}/scheduled-sends` (staging); assignment body plus `send_at` | `IScheduledSend` |
470
+ | `signerCapacities(documentId)` | `GET /documents/{documentId}/signer-capacities` (staging) | `ISignerCapacity[]` (`{ signer_id, sign_as }`) |
471
+ | `notificationHistory(documentId)` | `GET /documents/{documentId}/notification-history` (staging) | `ISignerNotificationHistory[]` |
305
472
  | `create(documentId, payload)` | [`POST /documents/{documentId}/assignments`](./api-reference.md#create-assignment-request-signatures) | `IAssignment` |
306
473
  | `estimateCost(documentId, payload)` | [`POST /documents/{documentId}/assignments/estimate-cost`](./api-reference.md#estimate-assignment-cost) | `IEstimateCostResponse` |
307
474
  | `resetExpiration(documentId, assignmentId, expiresAt)` | [`PUT …/reset-expiration`](./api-reference.md#reset-assignment-expiration) | `IAssignment`; accepts a date, datetime or `null` to clear the deadline |
@@ -320,19 +487,24 @@ Assignment payload:
320
487
  signers?: Array<string | {
321
488
  id?: string;
322
489
  signer_id?: string;
490
+ sign_as?: SignerCapacity | null; // staging
323
491
  verification_method?: 'Email' | 'Whatsapp' | 'DigitalCertificate' | 'IdDocumentFaceMatchBasic';
324
492
  notification_methods?: Array<'Email' | 'Whatsapp'>;
325
493
  step?: number;
494
+ embedded?: boolean;
326
495
  }>;
327
496
  signer_ids?: string[]; // compatibility alias
328
497
  signerIds?: string[]; // compatibility alias
329
498
  message?: string;
330
- expires_at?: string;
499
+ expires_at?: string | number | null;
331
500
  copy_receivers?: string[];
501
+ max_total_credits?: number;
332
502
  entries?: ICollectAssignmentEntry[];
333
503
  }
334
504
  ```
335
505
 
506
+ `max_total_credits` is a finite non-negative ceiling; `0` allows only a free request. A higher live price returns `409`/`CreditCeilingExceeded` before creation or charging. The high-level helper calls this option `maxTotalCredits`; CLI `send`, `assignments create`, and `documents create-from-template` expose `--max-total-credits`. A null balance means unlimited, not zero. `embedded: true` requires Email or Whatsapp verification and the workspace Embed feature; signing links return `url: null`.
507
+
336
508
  Production defaults `notification_methods: []` to `['Email']` and sends an invitation. An empty array is not a way to disable delivery. Choose the intended supported channel explicitly before creating an assignment.
337
509
 
338
510
  `buildAssignmentPayload(payload, options?)` is exported for callers that need the same normalization. It resolves synchronously to the JSON assignment body above; no HTTP call occurs. Options are `{ allowSignersWithoutId?: boolean; skipDigitalCertificateStepValidation?: boolean }`, both false by default. Both support cost estimation: the first accepts signer descriptors without an `id`, and the second bypasses signing-order and certificate-step checks for estimates. An empty signer list always throws `ValidationError('At least one signer is required')`, in `virtual` and `collect` modes and in cost estimates alike. `DigitalCertificate` signers require `method: 'virtual'`: `create` and `estimateCost` reject `collect` before sending a request with `ValidationError.errors.code` set to `digital_certificate_requires_virtual`. `create` also enforces complete contiguous signing steps from 1 when supplied and requires each digital-certificate signer to be alone in its step. The estimate schema has no `step`, so `estimateCost` passes `skipDigitalCertificateStepValidation` to skip that create-only rule. Assignment list params are pagination plus the compatible `sort?: 'created_at' | '-created_at'`; the runtime endpoint requires the SDK's `accountId` query even though the published parameter table omits it. Assignment `search` is unsupported and rejected locally.
@@ -350,6 +522,56 @@ Production defaults `notification_methods: []` to `['Email']` and sends an invit
350
522
 
351
523
  `credit_balance` can be null for unlimited plans. `IResendCostEstimate` also accepts the published `IEstimateCostResponse` shape. Check `'total' in estimate` to select the production shape; use its `has_sufficient_credits` before resending. The published shape uses `total_credits` and `has_sufficient_resources`.
352
524
 
525
+ On staging, `sign_as` records the capacity the sender assigns, printed on the certificate page. Omission or null means `Sign`. Values are exported as `SIGNER_CAPACITIES` and `SignerCapacity`: `Sign`, `Approve`, `Acknowledge`, `Party`, `Witness`, `Intervening`, `Receipt`, `IssuerEndorserGuarantor`, `IssuerEndorserGuarantorSurety`, `Surety`, `PartySurety`, `JointDebtor`, `PartyJointDebtor`, `ContractingParty`, `ContractedParty`, `Landlord`, `Tenant`, `Buyer`, `Seller`, `AttorneyInFact`, `LegalRepresentative`, `Employer`, `Employee`. The SDK preserves it through creation, estimates, scheduling and `uploadAndRequestSignatures`; CLI `assignments create --signers` and `send --signers` accept it in signer JSON. It is fixed on creation and read through `signerCapacities`; invitations, the signing page and webhooks do not carry it. An unsent document returns `[]`.
526
+
527
+ `notificationHistory(documentId)` returns an array of `{ signer_id, notification_history }`, in assignment signer order. Each history entry extends `IAssignmentSignerNotification` with required nullable `delivered_at` and `opened_at`. It retains `event` and `status`, plus optional `error_code`, `error_message`, `sent_at` and `failed_at`. Status is `sent | delivered | opened | failed`; timestamps and error fields are nullable. `error_code` is `MailboxFull | AddressNotFound | AddressSuppressed | ContentRejected | MarkedAsSpam | NotOnWhatsapp | RecipientRestricted | NotSent | Unknown | null`. Delivery and open times are hints: scanners may open email, and blocked images or disabled read receipts may hide opens. An unsent document returns `[]`. Both history and capacities accept OAuth `documents:read`. CLI: `assignments signer-capacities` and `assignments notification-history`.
528
+
529
+ ## Scheduled sends (`client.scheduledSends`)
530
+
531
+ These routes are published on [staging](https://api.angry-pisco.stage.assinafy.com.br/v1/docs). Configure that deployment explicitly; production may return 404 until rollout. Full HTTP parameters, payloads, responses and errors are in [the staging API reference](./api-reference-staging.md).
532
+
533
+ | SDK method | HTTP operation | Resolves to |
534
+ | --- | --- | --- |
535
+ | `list(params?, accountId?)` | `GET /accounts/{accountId}/scheduled-sends`; `{ page?, per_page?, document_id? }` | `PaginatedResult<IScheduledSend>` |
536
+ | `cancel(scheduledSendId, accountId?)` | `PUT /accounts/{accountId}/scheduled-sends/{scheduledSendId}/cancel`; no body | `IScheduledSend` |
537
+ | `send(scheduledSendId, accountId?)` | `PUT /accounts/{accountId}/scheduled-sends/{scheduledSendId}/send`; no body | `IScheduledSend` |
538
+
539
+ Create with `assignments.schedule(documentId, { ...assignment, send_at })` or `envelopes.schedule({ ...envelope, send_at }, accountId?)`. `send_at` accepts an ISO 8601 timestamp (offsetless means UTC) or integer Unix seconds, from one hour to 90 days ahead according to the server clock. Each non-null expiration must be at least two hours after `send_at`. Scheduling validates methods, plan features and workspace signer membership, but charges and sends nothing. A document can have one pending/processing scheduled send. Sending it separately causes the queued request to fail later.
540
+
541
+ ```ts
542
+ const pending = await client.assignments.schedule('example_document', {
543
+ method: 'virtual',
544
+ signers: [{ id: 'example_signer', sign_as: 'Witness' }],
545
+ send_at: new Date(Date.now() + 3 * 60 * 60 * 1000).toISOString(),
546
+ expires_at: null,
547
+ max_total_credits: 0,
548
+ });
549
+ await client.scheduledSends.list({ document_id: 'example_document' });
550
+ await client.scheduledSends.cancel(pending.id);
551
+ ```
552
+
553
+ Every mutation returns this unwrapped shape (IDs and timestamps shown are synthetic):
554
+
555
+ ```json
556
+ {
557
+ "resource": "scheduled_send",
558
+ "id": "example_schedule",
559
+ "type": "assignment",
560
+ "document_ids": ["example_document"],
561
+ "status": "pending",
562
+ "send_at": "2027-01-01T12:00:00Z",
563
+ "assignment_id": null,
564
+ "envelope_id": null,
565
+ "failure_reason": null,
566
+ "created_at": "2027-01-01T09:00:00Z",
567
+ "processed_at": null
568
+ }
569
+ ```
570
+
571
+ `type` is `assignment | envelope`; `status` is `pending | processing | sent | cancelled | failed`. `assignment_id`/`envelope_id` identify the successful result. Deleted documents leave `document_ids`; deleting an envelope clears `envelope_id`. `failure_reason` contains the Portuguese refusal when failed; `processed_at` marks sending, failure or cancellation. The worker checks due sends every five minutes, using the original member's permissions and current balance; failures notify that member, or active owners if the member left. No retry is performed by the SDK.
572
+
573
+ `cancel` and `send` require pending status, otherwise 409. Sending now rechecks the create operation's rules and credit ceiling, sends invitations and can charge credits. A refusal leaves the request pending without a failure email; inspect it before retrying. OAuth requires `documents:write` even to list, because failure details can reveal billing or membership state. CLI: `assignments schedule <documentId> --data <json>`, `envelopes schedule --data <json>`, and `scheduled-sends list|cancel|send`; cancel/send confirm unless `--yes`.
574
+
353
575
  ## Signers (`client.signers`)
354
576
 
355
577
  | SDK method | HTTP operation | Resolves to |
@@ -361,20 +583,20 @@ Production defaults `notification_methods: []` to `['Email']` and sends an invit
361
583
  | `delete(signerId, accountId?)` | [`DELETE /accounts/{accountId}/signers/{signerId}`](./api-reference.md#delete-signer) | `IEmptyResult` (`unknown[]`) |
362
584
  | `findByEmail(email, accountId?)` | SDK helper over `list({ search: email })` | `ISigner | null` |
363
585
 
364
- Create payload: `{ full_name: string; email?; whatsapp_phone_number?; government_id?; phone?; cpf?; metadata? }`. Update payload: `{ full_name?; email?; whatsapp_phone_number?; phone?; government_id?; cpf? }`. `government_id` accepts CPF or numeric/alphanumeric CNPJ and is forwarded unchanged for server normalization. `phone`, create-time `cpf`/`metadata`, and update-time `cpf` are compatibility extensions; the `cpf` alias retains its digit-only normalization. New integrations should use the published fields. Creation is idempotent by exact case-insensitive email when email is supplied; full-name-only signers are valid. Existing email matches are reused without updating their government ID; call `update` explicitly when needed. List params support published `search` and compatible `sort?: 'full_name' | '-full_name'`; ignored sort fields are rejected locally.
586
+ Create payload: `{ full_name: string; email?; whatsapp_phone_number?; government_id?; phone?; cpf?; metadata? }`. Update payload: `{ full_name?; email?; whatsapp_phone_number?; phone?; government_id?; cpf? }`. `government_id` accepts CPF or numeric/alphanumeric CNPJ and is forwarded unchanged for server normalization. `phone`, create-time `cpf`/`metadata`, and update-time `cpf` are compatibility extensions; the `cpf` alias retains its digit-only normalization. New integrations should use the published fields. Creation is idempotent by exact case-insensitive email when email is supplied; full-name-only signers are valid. Existing email matches are reused without updating their government ID; call `update` explicitly when needed. Update `email`, `whatsapp_phone_number` and `government_id` with `null` or `""` to clear them; omitted values stay unchanged. `findByEmail` requests the server maximum of 50 records per page so a capped page cannot end its search early. List params support published `search` and compatible `sort?: 'full_name' | '-full_name'`; ignored sort fields are rejected locally.
365
587
 
366
588
  ## Signer-side flows (`client.signerDocuments`)
367
589
 
368
- These methods use the private `signer-access-code`, not the workspace API key, except for the artifact download that the API publishes as a public route. `listAsOwner` and `searchAsOwner` call the same routes with the client's API key or bearer token instead; the signer must belong to that workspace. For email or WhatsApp verification, obtain the access code from the verification link and the OTP from the same message. An invitation containing only a document ID and recipient is not an access code. Call `self` and `getAssignment` to confirm the signer and document before submitting a decision; keep each document's verification credentials together.
590
+ These methods use the private `signer-access-code` and strip the workspace API key or bearer header. Token-based certified-copy downloads use the private download token instead. `listAsOwner` and `searchAsOwner` call the same routes with the client's API key or bearer token instead; the signer must belong to that workspace. For email or WhatsApp verification, obtain the access code from the verification link and the OTP from the same message. An invitation containing only a document ID and recipient is not an access code. Call `self` and `getAssignment` to confirm the signer and document before submitting a decision; keep each document's verification credentials together.
369
591
 
370
592
  | SDK method | HTTP operation | Resolves to |
371
593
  | --- | --- | --- |
372
- | `getCurrent(signerId, accessCode)` | [`GET /signers/{signerId}/document`](./api-reference.md#get-signers-document) | `IDocumentDetailsResponse` |
594
+ | `getCurrent(signerId, accessCode, params?)` | [`GET /signers/{signerId}/document`](./api-reference.md#get-signers-document) | `ISigningDocument` |
373
595
  | `list(signerId, accessCode, params?)` | [`GET /signers/{signerId}/documents`](./api-reference.md#list-signers-documents) | `IDocumentListResponse` |
374
596
  | `listAsOwner(signerId, params?)` | [`GET /signers/{signerId}/documents`](./api-reference.md#list-signers-documents) with owner credentials | `IDocumentListResponse` |
375
- | `search(signerId, search, accessCode)` | [`GET /signers/{signerId}/documents/search`](./api-reference.md#search-signers-documents) | `IDocumentListResponse` |
376
- | `searchAsOwner(signerId, search)` | [`GET /signers/{signerId}/documents/search`](./api-reference.md#search-signers-documents) with owner credentials | `IDocumentListResponse` |
377
- | `download(signerId, documentId, artifact, accessCode?)` | [`GET /signers/{signerId}/documents/{documentId}/download/{artifact}`](./api-reference.md#download-signers-document-artifact) | `Buffer` |
597
+ | `search(signerId, search, accessCode, params?)` | [`GET /signers/{signerId}/documents/search`](./api-reference.md#search-signers-documents) | `IDocumentListResponse` |
598
+ | `searchAsOwner(signerId, search, params?)` | [`GET /signers/{signerId}/documents/search`](./api-reference.md#search-signers-documents) with owner credentials | `IDocumentListResponse` |
599
+ | `download(signerId, documentId, artifact, accessCode?)` | [`GET /signers/{signerId}/documents/{documentId}/download/{artifact}`](./api-reference.md#download-the-document-to-sign) | `Buffer` |
378
600
  | `signMultiple(documentIds, accessCode)` | [`PUT /signers/documents/sign-multiple`](./api-reference.md#sign-multiple-documents) | `unknown[]` |
379
601
  | `declineMultiple(documentIds, reason, accessCode)` | [`PUT /signers/documents/decline-multiple`](./api-reference.md#decline-multiple-documents) | `unknown[]` |
380
602
  | `self(accessCode)` | [`GET /signers/self`](./api-reference.md#get-current-signer) | `ISignerSelf` |
@@ -383,18 +605,18 @@ These methods use the private `signer-access-code`, not the workspace API key, e
383
605
  | `verifyEmail(payload: IVerifySignerCodePayload)` | Compatibility alias for `verifyCode` | `IEmptyResult \| IStatusResponse` |
384
606
  | `getIdentityVerification(accessCode)` | [`GET /signers/identity-verification`](./api-reference.md#identity-document-verification-status) | `IIdentityVerificationState` |
385
607
  | `startIdentityVerification(accessCode, payload)` | [`POST /signers/identity-verification`](./api-reference.md#start-identity-document-verification) | `IIdentityVerificationSession`; payload is `{ consent: true }` |
386
- | `startCertificate(accessCode)` | [`POST /signers/certificate/start`](#icp-brasil-a1a3-certificates) | `ICertificateStartResponse` (`{ token: string }`) |
387
- | `completeCertificate(accessCode, token)` | [`POST /signers/certificate/complete`](#icp-brasil-a1a3-certificates) | `ICertificateCompleteResponse` (`{ signerName: string }`) |
608
+ | `startCertificate(accessCode, documentId?)` | [`POST /signers/certificate/start`](#icp-brasil-a1a3-certificates) | `ICertificateStartResponse` (`{ token: string }`) |
609
+ | `completeCertificate(accessCode, token, documentId?)` | [`POST /signers/certificate/complete`](#icp-brasil-a1a3-certificates) | `ICertificateCompleteResponse` (`{ signerName: string }`) |
388
610
  | `confirmData(documentId, accessCode, payload)` | [`PUT /documents/{documentId}/signers/confirm-data`](./api-reference.md#confirm-signer-data) | `ISigner \| IEmptyResult` |
389
611
  | `uploadSignature(accessCode, image, options?)` | [`POST /signature`](./api-reference.md#upload-signature-image) | `IEmptyResult \| IStatusResponse` |
390
612
  | `downloadSignature(accessCode, imageType?)` | [`GET /signature/{type}`](./api-reference.md#download-signature-image) | `Buffer` |
391
- | `getAssignment(accessCode, hasAcceptedTerms?)` | [`GET /sign`](./api-reference.md#view-document-to-sign) | `IDocumentDetailsResponse` |
613
+ | `getAssignment(accessCode, hasAcceptedTerms?, params?)` | [`GET /sign`](./api-reference.md#view-document-to-sign) | `ISigningDocument` |
392
614
  | `sign(documentId, assignmentId, accessCode, entries)` | [`POST /documents/{documentId}/assignments/{assignmentId}`](./api-reference.md#sign-assignment-items) | `Record<string, unknown>` |
393
615
  | `decline(documentId, assignmentId, accessCode, reason)` | [`PUT …/reject`](./api-reference.md#reject-decline-assignment) | `unknown[]` |
394
616
 
395
617
  `confirmData` accepts `{ full_name?, email?, government_id?, whatsapp_phone_number?, has_accepted_terms? }`. `uploadSignature` accepts a non-empty image `Buffer` plus `{ imageType?: 'signature' | 'initial'; contentType?: string; reuse?: boolean }`. Each signing entry is `{ itemId, fieldId, pageId, value }`.
396
618
 
397
- `confirmData`, `sign`, and `decline` first load `getAssignment(accessCode)` and reject a mismatched document or assignment before writing. These methods make one additional GET request. For virtual assignments, confirm the signer's data and then call `sign(documentId, assignmentId, accessCode, [])`. Collect assignments require a non-empty array with the actual assignment item, field, and page IDs. Signing resolves to the server's assignment result; poll document details until `certificated` before downloading final artifacts.
619
+ `confirmData` preflights `GET /documents/{documentId}` with the signer code: `/sign` is blocked until certificate data and terms are confirmed. `sign` and `decline` preflight `getAssignment(accessCode, undefined, { document_id: documentId })`, enabling selection of another document of the same envelope and checking the returned document/assignment IDs before writing. These methods make one additional GET request. For virtual assignments, confirm the signer's data and then call `sign(documentId, assignmentId, accessCode, [])`. Collect assignments require a non-empty array with the actual assignment item, field, and page IDs. Signing resolves to the server's assignment result; poll document details until `certificated` before downloading final artifacts.
398
620
 
399
621
  Each request below includes `?signer-access-code=<private-access-code>`. These are complete example bodies and SDK results for production:
400
622
 
@@ -407,7 +629,19 @@ Each request below includes `?signer-access-code=<private-access-code>`. These a
407
629
 
408
630
  An empty result is successful acknowledgement, not a signer profile. Use `self(accessCode)` afterward when you need the updated profile, terms acceptance, or signature flags. The response types retain the published status/profile alternatives without converting or fabricating response fields.
409
631
 
410
- The artifact `download` route is public in the published API. If `accessCode` is supplied, the SDK first verifies it through `/signers/self` and confirms that it belongs to the requested signer before downloading.
632
+ `getCurrent` accepts `{ expand: "envelope" }`; `getAssignment` additionally accepts `document_id` for another document of the same envelope. List/search params accept `envelope_id` and pagination. The API carries email/WhatsApp verification across documents of that envelope. `ISigningDocument` exposes `current_signer`, `is_signer_access_closed`, and `certified_copy`; closed links return only identity and copy state, and other signer operations return 410. Code closure occurs 30 minutes after this signer's work is done across the envelope. Assignment details contain only this signer's items, without other signers or their private links.
633
+
634
+ The legacy `download` signature is retained, but the current API permits only `original` with an access code; without one it redirects to an expired-link page, which the SDK rejects rather than following. Supplied codes get a `/signers/self` identity preflight. Use `downloadCertifiedCopy` for completed PDFs.
635
+
636
+ | SDK method | HTTP operation and request | SDK response |
637
+ | --- | --- | --- |
638
+ | `getTheme(accessCode)` | `GET /sign/theme`, no body | `IAccountTheme` |
639
+ | `downloadLogo(accessCode)` | `GET /sign/logo`, no body | Image `Buffer`; 404 if absent |
640
+ | `resendCertifiedCopy(accessCode, documentId?)` | `POST /sign/certified-copy`; no body or `{ document_id }` for an envelope document | `ICertifiedCopyResponse` |
641
+ | `downloadCertifiedCopy(token, artifact?)` | `GET /signers/downloads/{token}`; `artifact: "pades"` selects `/pades`; default `"certificated"` | PDF `Buffer` |
642
+ | `resendDownloadLink(token)` | `POST /signers/downloads/{token}/resend`, no body | `ICertifiedCopyResponse` |
643
+
644
+ Certified-copy requests deliver to the original signing contact, never an arbitrary recipient. The result is `{ available: boolean, notification_method: "Email" | "Whatsapp", sent_to: string, resends_left: number | null }`. Links last 30 minutes. Email allows one resend every two minutes and ten per 24 hours; WhatsApp allows one resend per signature request. `sent_to` is masked. See the [HTTP reference](./api-reference.md) for refusal payloads. Expired download URLs return 302, surfaced as `ApiError`; the SDK never follows the redirect. CLI `signer certified-copy`, `download-copy`, and `resend-download-link` use `ASSINAFY_SIGNER_ACCESS_CODE` or `ASSINAFY_DOWNLOAD_TOKEN`. Theme and logo need no owner credential. Protect download URLs and the resulting files as private documents.
411
645
 
412
646
  ### Email and WhatsApp verification
413
647
 
@@ -506,9 +740,9 @@ Both A1 and A3 use `verification_method: "DigitalCertificate"`; they are not sep
506
740
 
507
741
  1. Create or select the signer and set their CPF/CNPJ with `signers.update(signerId, { government_id })`. An existing signer returned by `create` is reused without updating their data. Configure an eligible workspace, estimate cost, then create a `virtual` assignment with `DigitalCertificate` and one delivery channel. Use contiguous steps beginning at `1`, with each certificate signer alone in their step. The same descriptor works for template roles only when the template has no placed signer fields.
508
742
  2. Obtain the private signer access code through the delivered link. Load `self` and `getAssignment` to confirm the identity and document. Present the document and terms; call `acceptTerms` only after the signer agrees.
509
- 3. Call `startCertificate(accessCode)` and retain its operation token with that signer session.
743
+ 3. Call `startCertificate(accessCode, documentId?)` and retain its operation token with that signer session.
510
744
  4. On the signer's device, use an initialized Web PKI browser client to select their A1 certificate or A3 device and execute `pki.signWithRestPki({ thumbprint, token })`. Wait for its success callback. The private key, PFX password, and device PIN stay with the local certificate provider.
511
- 5. Call `completeCertificate(accessCode, token)` with the **same operation token**, only after Web PKI succeeds. This returns the certificate signer's name. The API validates the certificate against the required CPF/CNPJ; normal `sign` and `signMultiple` do not perform certificate signing.
745
+ 5. Call `completeCertificate(accessCode, token, documentId?)` with the **same operation token**, only after Web PKI succeeds. This returns the certificate signer's name. The API validates the certificate against the required CPF/CNPJ; normal `sign` and `signMultiple` do not perform certificate signing.
512
746
  6. Track document status until `certificated`, then download `pades` or `bundle`. The PAdES artifact exists only for documents with certificate signatures.
513
747
 
514
748
  The SDK exposes the server handshake. Browser certificate selection, the Web PKI extension/native component, and signer approval belong to the signing application. For the hosted experience, use the Assinafy signing page reached through the invitation; no separate CLI certificate driver is required.
@@ -562,7 +796,10 @@ assinafy documents download example_document --artifact pades -o signed-pades.pd
562
796
  | --- | --- | --- |
563
797
  | `create(payload)` | [`POST /accounts`](./api-reference.md#create-account) | `IWorkspaceResponse` |
564
798
  | `list()` | [`GET /accounts`](./api-reference.md#list-my-accounts) | `IWorkspaceListResponse` |
565
- | `get(accountId)` | [`GET /accounts/{accountId}`](./api-reference.md#get-account) | `IWorkspaceResponse` |
799
+ | `get(accountId, params?)` | [`GET /accounts/{accountId}`](./api-reference.md#get-account) | `IWorkspaceResponse` |
800
+ | `usage(accountId)` | `GET /accounts/{accountId}/usage`, no body | `IAccountUsage` |
801
+ | `getNotificationPolicy(accountId)` | `GET /accounts/{accountId}/notification-policy`, no body | `INotificationPolicy` |
802
+ | `updateNotificationPolicy(accountId, payload)` | `PUT /accounts/{accountId}/notification-policy` | `INotificationPolicy` |
566
803
  | `getTheme(accountId)` | [`GET /accounts/{accountId}/theme`](./api-reference.md#get-account-theme) | `IAccountTheme` |
567
804
  | `downloadLogo(accountId)` | [`GET /accounts/{accountId}/logo`](./api-reference.md#download-account-logo) | image `Buffer` |
568
805
  | `uploadLogo(accountId, logo, options?)` | [`POST /accounts/{accountId}/logo`](./api-reference.md#upload-account-logo) | `IStatusResponse` |
@@ -573,6 +810,10 @@ assinafy documents download example_document --artifact pades -o signed-pades.pd
573
810
 
574
811
  Create/update payloads use `name` and `notification_sender_type?: 'User' | 'Account'`; legacy color fields remain accepted for compatibility. List/detail responses include `resource`, `id`, `name`, nullable colors, `notification_sender_type`, roles, delete permission, and `created_at`. `IAccountTheme` is `{ account_name; primary_color; secondary_color: string | null; logo: string | null }`. Logo options are `{ fileName?, contentType? }`. Statistics params are `{ granularity?: 'monthly' | 'daily'; month?: 'YYYY-MM' }`; `month` is required for daily data.
575
812
 
813
+ `get(accountId, { expand: "signing_features" })` adds the available verification, notification and Embed features. `usage` returns `{ plan: string | null, documents_renewal_date: string | null, balances: { documents: { balance: number | null, limit: number | null, spent: number }, credits: { balance: number | null, limit: number | null, spent: number } } }`. Treat null balances as unlimited. These reads are also CLI `workspaces get <id> --expand signing_features` and `workspaces usage <id>`. Usage is unavailable to third-party OAuth application tokens.
814
+
815
+ Notification policy GET returns `{ editable: boolean, owners_receive_all: boolean, events: INotificationPolicyEvents }`. PUT accepts a non-empty partial `{ owners_receive_all?: boolean, events?: Partial<INotificationPolicyEvents> }`; omitted settings stay unchanged and explicit false disables that setting. The 16 event keys are the union of the email and push preference keys below. Only owners may edit. Workspace false overrides a user's preference, while `owners_receive_all` still respects each owner's preferences. Identity review email is always sent; the corresponding policy key affects only push. CLI `workspaces notification-policy update example_account --data '{"owners_receive_all":false,"events":{"SignerViewed":false}}'` sends that exact body.
816
+
576
817
  OAuth `account:read` permits workspace statistics; user statistics still require an endpoint-supported owner or first-party credential.
577
818
 
578
819
  Both account and user statistics resolve to the complete published row:
@@ -604,11 +845,17 @@ Notification counters can overlap when a request uses multiple delivery channels
604
845
  | --- | --- | --- |
605
846
  | `self()` | [`GET /users/self`](./api-reference.md#get-the-authenticated-user) | `IUserSelfResponse` |
606
847
  | `stats(params?)` | [`GET /users/self/stats`](./api-reference.md#my-cross-account-document-kpis) | `IDocumentStatsRow[]` |
848
+ | `getPushPreferences()` | `GET /users/self/push-preferences`, no body | `IPushPreferences` |
849
+ | `updatePushPreferences(payload)` | `PUT /users/self/push-preferences` | `IPushPreferences` |
607
850
  | `getNotificationPreferences()` | [`GET /users/self/notification-preferences`](./api-reference.md#get-my-notification-preferences) | `INotificationPreferences` |
608
851
  | `updateNotificationPreferences(payload)` | [`PUT /users/self/notification-preferences`](./api-reference.md#update-my-notification-preferences) | `INotificationPreferences` |
609
852
 
610
853
  `IUserSelfResponse` accepts the published user object and the compatible `{ user, accounts }` envelope. Preference payloads are a non-empty partial mapping of the exported `NOTIFICATION_PREFERENCE_CODES` to booleans. The production OpenAPI publishes these routes; a lagging sandbox deployment may return route-level 404s for statistics/preferences.
611
854
 
855
+ Email keys: `DocumentCompleted`, `SignerDeclined`, `DocumentCancelled`, `DocumentAboutToExpire`, `DocumentExpired`, `DocumentExpirationReset`, `DocumentProcessingFailed`, `TemplateProcessingFailed`, `SignerWhatsappFailed`, `ContractRenewalNotice`, `ContractExpiring`, `ContractExpired`, `ContractRenewed`. Push keys (`PUSH_PREFERENCE_CODES`): `SignerViewed`, `SignerSigned`, `DocumentCompleted`, `SignerDeclined`, `DocumentAboutToExpire`, `DocumentExpired`, `SignerIdentityReviewRequired`, `SignerWhatsappFailed`.
856
+
857
+ Push reads/writes return all eight booleans. Update accepts a non-empty partial map, for example `{ "SignerViewed": false }`; CLI `users push-preferences update --set '{"SignerViewed":false}'` sends that body. These are user phone preferences, separate from email. Delivery also requires the mobile app's device registration; this Node SDK does not manage devices or implement a mobile client. OAuth application tokens cannot access user preferences; use endpoint-supported owner/first-party authentication.
858
+
612
859
  ## Authentication (`client.auth`)
613
860
 
614
861
  | SDK method | HTTP operation | Request / result |
@@ -744,15 +991,16 @@ An account can register 1 webhook endpoint, or up to 3 on paid plans. Each endpo
744
991
  | `deleteEndpoint(endpointId, accountId?)` | [`DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}`](./api-reference.md#delete-webhook-endpoint) | `IEmptyResult` (`[]`) |
745
992
  | `deleteEndpointByUrl(url, accountId?)` | [`DELETE /accounts/{accountId}/webhooks/endpoints?url=…`](./api-reference.md#delete-webhook-endpoint-by-url) | `IEmptyResult` (`[]`); exact registered URL required |
746
993
  | `getEndpointSecret(endpointId, accountId?)` | [`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret`](./api-reference.md#get-webhook-endpoint-signing-secret) | `IWebhookEndpointSecret` (`{ secret }`) |
747
- | `rotateEndpointSecret(endpointId, accountId?)` | [`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`](./api-reference.md#rotate-webhook-endpoint-signing-secret) | `IWebhookEndpointSecret` |
994
+ | `rotateEndpointSecret(endpointId, accountId?, options?)` | [`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`](./api-reference.md#rotate-webhook-endpoint-signing-secret) | `IWebhookEndpointSecret` |
748
995
  | `register(payload, accountId?)` | [`PUT /accounts/{accountId}/webhooks/subscriptions`](./api-reference.md#update-webhook-subscription) | `IWebhookSubscription` (oldest endpoint) |
749
996
  | `get(accountId?)` | [`GET /accounts/{accountId}/webhooks/subscriptions`](./api-reference.md#get-webhook-subscription) | `IWebhookSubscription | null` |
750
997
  | `inactivate(accountId?)` | [`PUT /accounts/{accountId}/webhooks/inactivate`](./api-reference.md#inactivate-webhook-subscription) | `IWebhookSubscription` |
751
998
  | `listEventTypes()` | [`GET /webhooks/event-types`](./api-reference.md#list-webhook-event-types) | `IWebhookEventTypeInfo[]` |
752
999
  | `listDispatches(params?, accountId?)` | [`GET /accounts/{accountId}/webhooks`](./api-reference.md#list-webhook-deliveries) | `PaginatedResult<IWebhookDispatch>` |
1000
+ | `testEndpoint(endpointId, accountId?)` | `POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/test`, no body | `IWebhookDispatch` |
753
1001
  | `retryDispatch(dispatchId, accountId?)` | [`POST /accounts/{accountId}/webhooks/{dispatchId}/retry`](./api-reference.md#retry-webhook-delivery) | `IWebhookDispatch` |
754
1002
 
755
- Endpoint payload: `{ url: string; email: string; events?: string[]; name?: string; is_active?: boolean; signing_enabled?: boolean }`. Update sends only the given fields and requires at least one. New or changed URLs must be HTTPS and unique within the workspace (`400`); legacy HTTP URLs remain usable for exact lookup/deletion; creating past the plan limit returns `403`. Enabling signing creates a `whsec_` secret if none exists; disabling it discards the secret. Secret read and rotation return `400` when signing is disabled. OAuth applications cannot read an existing secret, but `webhooks:write` permits rotation; rotation invalidates the previous secret immediately.
1003
+ Endpoint payload: `{ url: string; email: string; events?: string[]; name?: string; is_active?: boolean; signing_enabled?: boolean }`. Update sends only the given fields and requires at least one. New or changed URLs must be HTTPS and unique within the workspace (`400`); legacy HTTP URLs remain usable for exact lookup/deletion; creating past the plan limit returns `403`. Enabling signing creates a `whsec_` secret if none exists; disabling it discards the secret. Secret read and rotation return `400` when signing is disabled. OAuth applications cannot read an existing secret, but `webhooks:write` permits rotation; rotation invalidates the previous secret immediately unless `{ keep_previous: true }` is passed. That option signs deliveries with both secrets for 24 hours and returns `previous_secret_expires_at`; another rotation replaces the one retained secret. CLI `rotate-secret --keep-previous` exposes the overlap. `testEndpoint` sends a synthetic event to the registered receiver and records its delivery; it is a write, not a connectivity read. CLI: `webhooks endpoints test <endpointId>`. Dispatches include `duration_ms` when measured.
756
1004
 
757
1005
  ```ts
758
1006
  const endpoint = await client.webhooks.createEndpoint({
@@ -827,7 +1075,7 @@ Verify the raw bytes before parsing; re-serialized JSON does not match. The enve
827
1075
 
828
1076
  ## Contract boundaries
829
1077
 
830
- - Production OpenAPI currently publishes 118 operations. Some sandbox deployments lag it; account/user statistics and user notification-preference routes may return route-level 404s even though production documentation includes them.
831
- - Certificate start/complete are deployed production extensions, exposed by `startCertificate` and `completeCertificate` with the signing application's payloads. They supplement the 118 OpenAPI operations; the API manifest contains only published paths.
1078
+ - Production OpenAPI publishes 147 operations; staging publishes 157, all exposed by the SDK. Watchers, scheduled sends, signer capacities, notification delivery times and envelope reminder estimates require staging until their production rollout. Some sandbox deployments lag it; account/user statistics and user notification-preference routes may return route-level 404s even though production documentation includes them.
1079
+ - Certificate start/complete are deployed production extensions, exposed by `startCertificate` and `completeCertificate` with the signing application's payloads. They supplement the 147 OpenAPI operations; the API manifest contains only published paths.
832
1080
  - The SDK retains the two template compatibility routes above. Both `sendToken` call forms send the email-only production body.
833
- - Signer artifact downloads are public in the published contract. Supplying a signer access code opts into an SDK identity preflight; it does not change the server route into a private endpoint.
1081
+ - Original signer artifacts require a signer code. Completed copies use private expiring download tokens. Older download call forms remain callable for compatibility; server authorization and lifecycle rules apply.