@assinafy/sdk 2.10.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1863 @@
1
+ # @assinafy/sdk — Complete manual
2
+
3
+ *[Leia em português](README.md) · English · [Package overview](../README.en.md)*
4
+
5
+ TypeScript SDK for the [Assinafy API](https://api.assinafy.com.br/v1/docs) — a Brazilian digital signature platform.
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,
10
+ envelopes, embedded signing, signers, signer-side flows, contract lifecycle
11
+ management (CLM), templates, tags, fields, webhooks, branding, plan usage,
12
+ notification policy, statistics, and
13
+ the high-level `uploadAndRequestSignatures` workflow. Five additional
14
+ template-management routes used by existing integrations and two legacy browser
15
+ URL helpers are retained for compatibility.
16
+
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.
20
+
21
+ ## Contents
22
+
23
+ This document runs from setup to a complete signature workflow, then to
24
+ per-resource detail. Read it in order the first time; use it as a reference
25
+ afterwards.
26
+
27
+ **Getting set up** — [Requirements](#requirements) ·
28
+ [Installation](#installation) · [Quick start](#quick-start) ·
29
+ [Authentication](#authentication) ·
30
+ [OAuth applications](#oauth-applications) · [Configuration](#configuration)
31
+ ([rate limiting](#rate-limiting), [factories](#factories)) ·
32
+ [Endpoint coverage](#endpoint-coverage)
33
+
34
+ **The end-to-end flow** — [Document lifecycle](#document-lifecycle):
35
+ [workspace selection](#1-select-the-workspace) → [upload](#2-upload-the-pdf) →
36
+ [signers](#3-create-or-reuse-the-email-signers) →
37
+ [price and request signatures](#4-price-then-request-signatures) →
38
+ [the signer's side](#5-complete-the-email-signer-flow) →
39
+ [completion and artifacts](#6-observe-completion-and-download-artifacts)
40
+
41
+ **Per-resource detail** — [Resource reference](#resource-reference):
42
+ [documents](#documents) · [signers](#signers) · [assignments](#assignments) ·
43
+ [contract lifecycle management](#contract-lifecycle-management-clm) ·
44
+ [paid signing branches](#paid-signing-branches) · [envelopes](#envelopes) ·
45
+ [embedded signing](#embedded-signing) · [templates](#templates) ·
46
+ [tags](#tags) · [workspaces](#workspaces) ·
47
+ [field definitions](#field-definitions) ·
48
+ [auth and API keys](#authentication--api-key-management) ·
49
+ [the current user](#authenticated-user) · [webhooks](#webhooks)
50
+ ([verification](#webhook-verification)) ·
51
+ [signer-side endpoints](#signer-side-endpoints)
52
+
53
+ **Everything else** — [High-level helper](#high-level-helper) ·
54
+ [Errors](#errors) · [Environments](#environments) ·
55
+ [Development](#development) · [License](#license)
56
+
57
+ ## Requirements
58
+
59
+ - Node.js 22+ for the built-in `FormData` / `Blob` APIs used by uploads. Packed
60
+ CJS and ESM imports are tested on 22 and 24 (maintenance LTS) and 26 (active
61
+ LTS); Node 20 reached end-of-life in April 2026 and is unsupported.
62
+ - or Bun 1.4.4 (the version pinned for development and CI)
63
+ - HTTPS with TLS 1.2 or higher, which the API requires; Node.js 22+ and Bun
64
+ negotiate it by default
65
+
66
+ ## Installation
67
+
68
+ ```bash
69
+ npm install @assinafy/sdk
70
+ # or
71
+ bun add @assinafy/sdk
72
+ ```
73
+
74
+ The package is published to both [npmjs.com](https://www.npmjs.com/package/@assinafy/sdk) and [GitHub Packages](https://github.com/assinafy/typescript-sdk/packages). To install from GitHub Packages, add to your `.npmrc`:
75
+
76
+ ```
77
+ @assinafy:registry=https://npm.pkg.github.com
78
+ //npm.pkg.github.com/:_authToken=${GITHUB_TOKEN}
79
+ ```
80
+
81
+ ## Quick start
82
+
83
+ ```ts
84
+ import { AssinafyClient } from '@assinafy/sdk';
85
+
86
+ const baseUrl = process.env.ASSINAFY_BASE_URL ?? 'https://api.assinafy.com.br/v1';
87
+ const client = new AssinafyClient({
88
+ apiKey: process.env.ASSINAFY_API_KEY!,
89
+ accountId: process.env.ASSINAFY_ACCOUNT_ID!,
90
+ baseUrl,
91
+ });
92
+
93
+ const result = await client.uploadAndRequestSignatures({
94
+ source: { filePath: './contract.pdf' },
95
+ signers: [
96
+ { name: 'Example Signer A', email: 'signer-a@example.com' },
97
+ { name: 'Example Signer B', email: 'signer-b@example.com' },
98
+ ],
99
+ message: 'Please sign this contract',
100
+ });
101
+
102
+ console.log('Document ID:', result.document.id);
103
+ console.log('Assignment ID:', result.assignment.id);
104
+ ```
105
+
106
+ This path uses email verification and notification for every signer. WhatsApp
107
+ and ICP-Brasil certificate signing have separate prerequisites and costs; see
108
+ [Paid signing branches](#paid-signing-branches) before enabling either one.
109
+
110
+ ## Authentication
111
+
112
+ The API supports three credentials. Which one you need depends on *whose*
113
+ workspace you are acting in.
114
+
115
+ | Credential | Acts on | Choose it when |
116
+ | --- | --- | --- |
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). |
120
+
121
+ Prefer `apiKey` for a server-to-server integration — it maps to the `X-Api-Key`
122
+ header recommended by Assinafy for backend services.
123
+
124
+ ```ts
125
+ // Preferred: X-Api-Key header
126
+ new AssinafyClient({ apiKey: 'k_xxx', accountId: 'acc_xxx' });
127
+
128
+ // Access token: Authorization: Bearer <token>
129
+ new AssinafyClient({ token: 'jwt_xxx', accountId: 'acc_xxx' });
130
+ ```
131
+
132
+ Credentials are optional at construction time. A credentialless client uses a
133
+ separate, auth-free transport for public authentication and signer-access-code
134
+ operations, so an API key or Bearer token is never attached accidentally:
135
+
136
+ ```ts
137
+ const publicClient = new AssinafyClient({
138
+ baseUrl: 'https://api.assinafy.com.br/v1',
139
+ });
140
+
141
+ await publicClient.auth.login('me@example.com', 'password');
142
+ await publicClient.documents.getPublic(documentId);
143
+ await publicClient.signerDocuments.self(signerAccessCode);
144
+ ```
145
+
146
+ Protected methods still require `apiKey` or `token`; the API returns its normal
147
+ `401` response if one is called without credentials.
148
+
149
+ Every SDK transport, including public and signer-access-code requests, sends
150
+ `User-Agent: Assinafy-Typescript-SDK/v<VERSION>`, where `<VERSION>` is the
151
+ installed package version. The exact value is also exported as
152
+ `SDK_USER_AGENT` for custom transport checks and observability rules.
153
+
154
+ ## OAuth applications
155
+
156
+ Use OAuth when your product is connected by *its users* to *their* Assinafy
157
+ workspaces, so you never hold their password or API key. Automating your own
158
+ workspace needs none of this — keep using an API key.
159
+
160
+ Register the application in the Assinafy app under **Settings → OAuth
161
+ applications → New application**. You choose its redirect URIs (exact-match
162
+ `https://`, no fragment), the maximum permissions it may ever request, and
163
+ whether it is **confidential** (runs on your server, gets a `client_secret`) or
164
+ **public** (runs on the user's device, PKCE only). Applications cannot be
165
+ created through the API.
166
+
167
+ The flow spans two hosts on purpose: the consent page lives on the
168
+ authorization server (`https://auth.assinafy.com.br`) while the token,
169
+ revocation and userinfo endpoints live on this API. Read both from discovery
170
+ rather than hardcoding them.
171
+
172
+ ```ts
173
+ import { AssinafyClient, ApiError, OAuthError } from '@assinafy/sdk';
174
+
175
+ const client = new AssinafyClient(); // no credentials needed
176
+
177
+ // 1 — before redirecting the user. Store the whole request in their session:
178
+ // `state` and `issuer` prove the callback is yours, `codeVerifier`
179
+ // completes PKCE, `nonce` validates the id_token.
180
+ const request = await client.oauth.createAuthorizationUrl({
181
+ clientId: process.env.ASSINAFY_CLIENT_ID!,
182
+ redirectUri: 'https://myapp.example.com/oauth/callback',
183
+ scopes: ['documents:read', 'documents:write', 'offline_access'],
184
+ });
185
+ session.oauth = request;
186
+ response.redirect(request.url); // full page navigation
187
+
188
+ // 2 — on https://myapp.example.com/oauth/callback
189
+ const { code } = client.oauth.readAuthorizationCallback(query, session.oauth);
190
+ const tokens = await client.oauth.exchangeCode({
191
+ code,
192
+ codeVerifier: session.oauth.codeVerifier,
193
+ redirectUri: 'https://myapp.example.com/oauth/callback',
194
+ clientId: process.env.ASSINAFY_CLIENT_ID!,
195
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!, // confidential apps only
196
+ });
197
+ // → { access_token, token_type: 'Bearer', expires_in: 3600,
198
+ // scope: 'documents:read documents:write',
199
+ // refresh_token?, id_token? }
200
+
201
+ // 3 — a token covers exactly ONE workspace: the one the user picked.
202
+ const connected = new AssinafyClient({ token: tokens.access_token });
203
+ const { data } = await connected.workspaces.list();
204
+ const accountId = data[0]?.id; // store it with the tokens
205
+
206
+ // 4 — renew before the hour is up (needs `offline_access`)
207
+ const renewed = await client.oauth.refreshToken({
208
+ refreshToken: connection.refreshToken,
209
+ clientId: process.env.ASSINAFY_CLIENT_ID!,
210
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
211
+ });
212
+ await connection.save({ refreshToken: renewed.refresh_token }); // BEFORE using it
213
+
214
+ // 5 — when the user disconnects: revoke the token you saved most recently
215
+ const current = await connection.load(); // never a retired copy
216
+ await client.oauth.revokeToken({
217
+ token: current.refreshToken,
218
+ tokenTypeHint: 'refresh_token',
219
+ clientId: process.env.ASSINAFY_CLIENT_ID!,
220
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
221
+ });
222
+ ```
223
+
224
+ Discovery and identity, when you need them:
225
+
226
+ ```ts
227
+ await client.oauth.getProtectedResourceMetadata(); // RFC 9728, at the host root
228
+ await client.oauth.getAuthorizationServerMetadata(); // RFC 8414, on auth.assinafy.com.br
229
+ await client.oauth.getUserInfo(tokens.access_token); // OIDC claims; needs `openid`
230
+ ```
231
+
232
+ ### Scopes
233
+
234
+ | Scope | Lets your app |
235
+ | --- | --- |
236
+ | `documents:read` | Read documents, their signers, assignments and activity |
237
+ | `documents:write` | Create documents and send them for signature |
238
+ | `templates:read` | Read templates |
239
+ | `templates:write` | Create and change templates |
240
+ | `account:read` | Read the workspace's profile, theme, logo, document KPIs, webhook subscription and endpoints, and which signing features it can use |
241
+ | `webhooks:write` | Change the webhook subscription, manage endpoints, re-send and test deliveries, and obtain a new signing secret |
242
+ | `openid` | Receive an `id_token` identifying the user |
243
+ | `profile` | Read the user's name |
244
+ | `email` | Read the user's email and whether it is verified |
245
+ | `offline_access` | Receive a refresh token |
246
+
247
+ Request the minimum: the user approves all of them or none. Read the `scope`
248
+ returned by the token endpoint instead of assuming the request was honoured in
249
+ full — `offline_access` never appears there, because it is a request-time
250
+ signal rather than a permission. Billing, workspace membership, credentials and
251
+ administration are never reachable with an OAuth token, whatever its scopes.
252
+
253
+ ### What the SDK enforces for you
254
+
255
+ - A fresh RFC 7636 verifier (S256) and `state` per attempt.
256
+ - `state` compared in constant time, and `iss` checked (RFC 9207), before the
257
+ response is trusted at all.
258
+ - The RFC 8414 document's own `issuer` matched against the URL it came from.
259
+ - `redirect_uri` required to be absolute `https://` with no fragment.
260
+ - The RFC 8707 `resource` indicator defaulted to the configured API origin, and
261
+ kept identical between the authorize and token legs.
262
+
263
+ ### Handling failure
264
+
265
+ ```ts
266
+ try {
267
+ await connected.documents.upload({ filePath: './contract.pdf' });
268
+ } catch (error) {
269
+ if (error instanceof ApiError && error.challenge?.error === 'insufficient_scope') {
270
+ // Reconnect asking for error.challenge.scope, e.g. 'documents:write'.
271
+ }
272
+ }
273
+ ```
274
+
275
+ | Situation | What you see | What to do |
276
+ | --- | --- | --- |
277
+ | The user declined | `OAuthError` with `error: 'access_denied'` from `readAuthorizationCallback` | Nothing; tell the user |
278
+ | Code spent, expired (60 s) or mismatched | `OAuthError` `invalid_grant` | Restart the authorization flow |
279
+ | Refresh token replayed or expired | `OAuthError` `invalid_grant` | The whole connection ended; ask the user to reconnect |
280
+ | Wrong `client_id` / secret, app disabled | `OAuthError` `invalid_client` | Fix configuration; retrying will not help |
281
+ | Token expired or revoked | `ApiError` `401` | Refresh; if that fails, reconnect |
282
+ | Missing permission | `ApiError` `403` with `challenge.error === 'insufficient_scope'` | Reconnect requesting `challenge.scope` |
283
+ | `403` without a challenge | `ApiError` `403` | Another workspace, or a surface OAuth cannot reach |
284
+
285
+ Refresh tokens **rotate**: every refresh returns a new one and retires the old
286
+ one, and replaying a retired token ends the entire connection. Persist the new
287
+ value before using the response, and never refresh one connection twice
288
+ concurrently. Treat a timeout as "it may have worked": re-read your stored
289
+ token, and if it is still the one you sent, never send it again — ask the user
290
+ to reconnect. Only a failure that provably happened before sending (DNS,
291
+ refused connection, TLS handshake) is safe to retry. A refresh token is valid for 30 days, and every
292
+ refresh returns a new one with a fresh 30 days: a connection only expires if
293
+ your app goes 30 days without refreshing it, after which the user has to
294
+ connect again. The authorize/token endpoints accept 50 requests per minute per
295
+ IP.
296
+
297
+ AI assistants such as Claude, Claude Code and ChatGPT connect to Assinafy
298
+ through their own connector settings; your users do not need you to register
299
+ anything for them.
300
+
301
+ ## Configuration
302
+
303
+ | Option | Type | Default | Description |
304
+ | --------------- | -------- | --------------------------------------- | --------------------------------------------- |
305
+ | `apiKey` | string | — | Preferred credential (sent as `X-Api-Key`). |
306
+ | `token` | string | — | Access token (sent as `Authorization: Bearer`). |
307
+ | `accountId` | string | — | Default workspace/account ID. |
308
+ | `baseUrl` | string | `https://api.assinafy.com.br/v1` | Absolute API base without credentials, query, or fragment. Must be `https` unless the host is loopback. |
309
+ | `webhookSecret` | string | — | Webhook endpoint `whsec_…` secret; enables `webhookVerifier.verifySignature()`. |
310
+ | `timeout` | number | `30000` | Request timeout in milliseconds. |
311
+ | `maxRetries` | number | `2` | Auto-retries eligible HTTP 429 responses, honoring `Retry-After`. `0` disables. |
312
+ | `logger` | `Logger` | no-op | Optional `{debug,info,warn,error}` logger. |
313
+
314
+ ### Rate limiting
315
+
316
+ Once retries are spent, the `ApiError` carries `err.rateLimit` with `limit`,
317
+ `remaining`, `reset` (from `X-Rate-Limit-*`) and `retryAfter` (`Retry-After`,
318
+ in seconds).
319
+
320
+ On an HTTP `429`, the client automatically retries up to `maxRetries` times,
321
+ waiting for the server-provided `Retry-After` (or `X-Rate-Limit-Reset`) delay
322
+ before each attempt. Automatic replay is limited to read-safe `GET`, `HEAD`,
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
326
+ and template document creation deduplicate it server-side, so
327
+ `envelopes.create(…, { idempotencyKey })` and `documents.createFromTemplate(…,
328
+ { idempotencyKey })` are safe to retry; other routes ignore the header. No
329
+ other HTTP status is retried.
330
+
331
+ ### Factories
332
+
333
+ ```ts
334
+ // Positional factory
335
+ const client = AssinafyClient.create('api-key', 'account-id');
336
+
337
+ // From a plain object (accepts snake_case or camelCase keys)
338
+ const client = AssinafyClient.fromConfig({
339
+ api_key: process.env.ASSINAFY_API_KEY!,
340
+ account_id: process.env.ASSINAFY_ACCOUNT_ID!,
341
+ });
342
+ ```
343
+
344
+ The configuration object accepted by `fromConfig` has the exported type
345
+ `ClientConfigInput`.
346
+
347
+ ## Endpoint coverage
348
+
349
+ All 147 operations documented at https://api.assinafy.com.br/v1/docs are
350
+ mapped: 146 have SDK methods, and the embed session exchange is reserved for
351
+ Assinafy's embed page. The table below is the resource-level summary; the detailed operation
352
+ ledger is in [API_COVERAGE.md](API_COVERAGE.md).
353
+
354
+ | Resource | Endpoints |
355
+ | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
356
+ | `client.documents` | list, **search**, upload, details, get, **rename**, activities, listActivities, waitUntilReady, download, thumbnail, downloadPage, statuses, delete, verify, createFromTemplate, estimateCostFromTemplate, getPublic, sendToken, listTags, replaceTags, addTags, detachTag, isFullySigned, getSigningProgress |
357
+ | `client.signers` | create, get, list, update, delete, findByEmail |
358
+ | `client.assignments` | list, create, estimateCost, resetExpiration, resendNotification, estimateResendCost, listWhatsAppNotifications, getIdentityVerification, downloadIdentityVerificationImage, reviewIdentityVerification |
359
+ | `client.contracts` | list, get, set, listRelated, renew, terminate |
360
+ | `client.envelopes` | list, get, create, estimateCost, update, delete, cancel, listActivities, download, addDocument, removeDocument, resendNotification |
361
+ | `client.embed` | listOrigins, addOrigin, updateOrigin, deleteOrigin, createSession |
362
+ | `client.templates` | create, list, get, update, delete, downloadPage |
363
+ | `client.tags` | list, create, update, delete |
364
+ | `client.workspaces` | create, list, get, update, delete, getTheme, downloadLogo, uploadLogo, deleteLogo, getStats, getUsage, getNotificationPolicy, updateNotificationPolicy |
365
+ | `client.webhooks` | listEndpoints, createEndpoint, getEndpoint, updateEndpoint, deleteEndpoint, deleteEndpointByUrl, getEndpointSecret, rotateEndpointSecret, testEndpoint, register, get, inactivate, listEventTypes, listDispatches, retryDispatch |
366
+ | `client.fields` | create, list, get, update, delete, validate, validateMultiple, listTypes |
367
+ | `client.oauth` | **getProtectedResourceMetadata**, **getAuthorizationServerMetadata**, **createAuthorizationUrl**, **readAuthorizationCallback**, **exchangeCode**, **refreshToken**, **revokeToken**, **getUserInfo** |
368
+ | `client.auth` | getSocialLoginUrl, getSocialLoginCallbackUrl, login, verifyMfa, socialLogin, linkSocialLogin, createApiKey, getApiKey, deleteApiKey, changePassword, requestPasswordReset, resetPassword |
369
+ | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences, getPushPreferences, updatePushPreferences, getMfa, startTotpEnrollment, confirmTotpEnrollment, regenerateRecoveryCodes, deleteMfaMethod |
370
+ | `client.signerDocuments` | getCurrent, list, search, listAsWorkspace, searchAsWorkspace, download, signMultiple, declineMultiple, self, getIdentityVerification, startIdentityVerification, acceptTerms, verifyEmail, confirmData, uploadSignature, downloadSignature, getAssignment, getTheme, downloadLogo, resendCertifiedCopy, downloadCertifiedCopy, resendCertifiedCopyFromLink, sign, decline |
371
+ | `client.webhookVerifier` | verifySignature, extractEvent, getEventType, getEventData |
372
+
373
+ Every HTTP wrapper has TypeScript-checked request/response shapes and
374
+ method-level JSDoc covering the wire payload, return shape, validation,
375
+ relevant API errors, and a copyable example. Reusable and OpenAPI schema-level
376
+ payloads are exported as named types; small method-local option bags remain
377
+ inline in the generated declarations. Editors expose the reference on hover,
378
+ and declaration files ship with the package. The coverage ledger links those
379
+ typed methods back to each upstream operation without duplicating the schema.
380
+
381
+ ## Document lifecycle
382
+
383
+ The normal integration has an account-owner phase, a signer phase, and a final
384
+ artifact phase. The example below keeps every signer on email and uses a
385
+ `virtual` assignment, so no page coordinates or paid notification channel are
386
+ required.
387
+
388
+ ### 1. Select the workspace
389
+
390
+ Every account-scoped operation happens inside a workspace. With an API key,
391
+ pass the `accountId` when building the client (or as the last argument of any
392
+ account-scoped method). With OAuth, list the user's workspaces and keep the
393
+ chosen `id` with the tokens — a token is bound to exactly one workspace (see
394
+ [OAuth applications](#oauth-applications)):
395
+
396
+ ```ts
397
+ const { data: workspaces } = await client.workspaces.list();
398
+ const accountId = workspaces[0]?.id; // e.g. new AssinafyClient({ apiKey, accountId })
399
+ ```
400
+
401
+ The examples below assume a `client` already pointing at the chosen workspace.
402
+
403
+ ### 2. Upload the PDF
404
+
405
+ ```ts
406
+ const uploaded = await client.documents.upload({ filePath: './contract.pdf' });
407
+ ```
408
+
409
+ The official multipart body contains the `file` part. The SDK also supports a
410
+ display-name override (used as that file part's filename) and an optional JSON
411
+ `metadata` part for deployments that accept it. A successful response is
412
+ `IDocumentUploadResponse`:
413
+
414
+ ```ts
415
+ type DocumentUploadShape = {
416
+ resource?: string;
417
+ id: string;
418
+ account_id: string;
419
+ template_id: string | null;
420
+ name: string;
421
+ status: DocumentStatus;
422
+ assignment?: IAssignment | null;
423
+ artifacts: {
424
+ original: string;
425
+ certificated?: string;
426
+ 'certificate-page'?: string;
427
+ pades?: string;
428
+ bundle?: string;
429
+ thumbnail?: string;
430
+ };
431
+ signing_url?: string;
432
+ pages: Array<{ id: string; number: number; height: number; width: number; download_url: string }>;
433
+ tags?: Array<{ id: string; name: string; color?: string | null }>;
434
+ created_at: string;
435
+ updated_at: string;
436
+ is_closed: boolean;
437
+ decline_reason: string | null;
438
+ declined_by: ISigner | null;
439
+ };
440
+ ```
441
+
442
+ `DocumentStatus` covers `uploading`, `uploaded`, `metadata_processing`,
443
+ `metadata_ready`, `pending_signature`, `pending_identity_review`, `expired`, `certificating`,
444
+ `certificated`, `rejected_by_signer`, `rejected_by_user`, and `failed`.
445
+
446
+ Uploads must be PDFs, at most 25 MB and at most 2,000 pages (the byte limit is
447
+ exported as `MAX_UPLOAD_BYTES`). The SDK checks the
448
+ extension, size, and `%PDF-` header before sending. A new upload can have an
449
+ empty `pages` array until metadata processing finishes. Wait before creating a
450
+ `collect` assignment because its fields refer to rendered page IDs; a
451
+ `virtual` assignment may be created immediately.
452
+
453
+ ```ts
454
+ const prepared = await client.documents.waitUntilReady(uploaded.id, {
455
+ maxWaitMs: 30_000,
456
+ pollIntervalMs: 2_000,
457
+ });
458
+ ```
459
+
460
+ ### 3. Create or reuse the email signers
461
+
462
+ ```ts
463
+ const signerA = await client.signers.create({
464
+ full_name: 'Example Signer A',
465
+ email: 'signer-a@example.com',
466
+ });
467
+ const signerB = await client.signers.create({
468
+ full_name: 'Example Signer B',
469
+ email: 'signer-b@example.com',
470
+ });
471
+ ```
472
+
473
+ The wire body is `{ full_name, email }`. Each response is an `ISigner`:
474
+
475
+ ```ts
476
+ type SignerShape = {
477
+ resource?: string;
478
+ id: string;
479
+ full_name: string;
480
+ email: string | null;
481
+ whatsapp_phone_number?: string | null;
482
+ cpf?: string | null; // compatibility type; not echoed by the API
483
+ has_accepted_terms?: boolean;
484
+ has_signature?: boolean; // signer-self response only
485
+ has_initial?: boolean; // signer-self response only
486
+ is_signature_reusable?: boolean; // signer-self response only
487
+ metadata?: Record<string, unknown>;
488
+ };
489
+ ```
490
+
491
+ When an email is present, `signers.create()` first looks up that email in the
492
+ workspace and reuses the matching signer; a name-only or phone-only request
493
+ always creates a new signer.
494
+
495
+ ### 4. Price, then request signatures
496
+
497
+ Cost estimation takes channel descriptors, not signer IDs:
498
+
499
+ ```ts
500
+ const estimate = await client.assignments.estimateCost(uploaded.id, {
501
+ method: 'virtual',
502
+ signers: [{}, {}], // `{}` selects Email for each signer
503
+ });
504
+
505
+ if (!estimate.has_sufficient_resources) {
506
+ throw new Error(estimate.blocking_reason ?? estimate.message ?? 'Insufficient resources');
507
+ }
508
+ ```
509
+
510
+ The response is `ICostEstimate`:
511
+
512
+ ```ts
513
+ {
514
+ documents: number;
515
+ credits: number;
516
+ needs_extra_document: boolean;
517
+ extra_document_cost: number;
518
+ total_credits: number;
519
+ breakdown: Array<{ code: string; name: string; cost: number; quantity?: number; unit_cost?: number }>;
520
+ document_balance: number | null; // null when documents are not limited
521
+ credit_balance: number | null; // null when credits are not limited
522
+ has_sufficient_resources: boolean;
523
+ blocking_reason: 'PendingPayment' | 'InsufficientDocuments' | 'InsufficientCredits' | null;
524
+ message: string | null;
525
+ }
526
+ ```
527
+
528
+ Create the email assignment only after accepting that estimate:
529
+
530
+ ```ts
531
+ const assignment = await client.assignments.create(uploaded.id, {
532
+ method: 'virtual',
533
+ signers: [
534
+ { id: signerA.id, verification_method: 'Email', notification_methods: ['Email'] },
535
+ { id: signerB.id, verification_method: 'Email', notification_methods: ['Email'] },
536
+ ],
537
+ message: 'Please review and sign',
538
+ expires_at: '2027-12-31T23:59:00Z',
539
+ });
540
+ ```
541
+
542
+ The request returns an `IAssignment`:
543
+
544
+ ```ts
545
+ type AssignmentShape = {
546
+ resource?: string;
547
+ id: string;
548
+ sender_email?: string;
549
+ method: 'virtual' | 'collect';
550
+ expires_at?: string | null;
551
+ expiration?: string;
552
+ message?: string | null;
553
+ signers: IAssignmentSigner[];
554
+ copy_receivers?: Array<Record<string, unknown>>;
555
+ items?: IAssignmentItem[];
556
+ summary?: {
557
+ signer_count: number;
558
+ completed_count: number;
559
+ signers: Array<ISigner & { completed?: boolean }>;
560
+ };
561
+ // url is null for an embedded signer (mint embed.createSession) and a WhatsApp-only signer.
562
+ signing_urls?: Array<{ signer_id: string; url: string | null; embedded?: boolean }>;
563
+ };
564
+ ```
565
+
566
+ The URLs and delivered messages contain signer credentials; treat them as
567
+ secrets.
568
+
569
+ ### 5. Complete the email signer flow
570
+
571
+ Assinafy sends each signer a link containing their access code and sends the
572
+ one-time verification code through the selected channel. Neither value is
573
+ returned as a standalone owner-side API field. A custom signer portal must
574
+ obtain both values from the signer-delivery flow; do not manufacture them or
575
+ log them.
576
+
577
+ ```ts
578
+ // Signer-side client: no account API credential is needed or sent.
579
+ const signerClient = new AssinafyClient({
580
+ baseUrl,
581
+ });
582
+
583
+ const self = await signerClient.signerDocuments.self(accessCode); // ISignerSelf
584
+
585
+ // Query: signer-access-code=<accessCode>
586
+ // Body: { 'verification-code': '<six-digit code>' }
587
+ await signerClient.signerDocuments.verifyEmail({
588
+ signerAccessCode: accessCode,
589
+ verificationCode,
590
+ }); // Promise<void>
591
+
592
+ // Send the contact the signer's channel needs; it must be the signer's own.
593
+ await signerClient.signerDocuments.confirmData(
594
+ uploaded.id,
595
+ accessCode,
596
+ { ...(self.email === null ? {} : { email: self.email }), has_accepted_terms: true },
597
+ ); // null on production (data: [])
598
+
599
+ const signable = await signerClient.signerDocuments.getAssignment(accessCode, {
600
+ hasAcceptedTerms: true,
601
+ expand: ['envelope'],
602
+ });
603
+ // `getAssignment` returns ISigningDocument and records that the signer viewed
604
+ // the assignment. Do not issue it merely as a health check. Once the code is
605
+ // closed it returns only id, name, status, current_signer, certified_copy and
606
+ // envelope, with is_signer_access_closed: true.
607
+
608
+ await signerClient.signerDocuments.signMultiple([signable.id], accessCode);
609
+ // Wire body: { document_ids: [signable.id] }; acknowledgement has no data.
610
+ ```
611
+
612
+ Repeat this phase separately for each signer with that signer's own access code
613
+ and one-time code. The two signers in this example share the default step and
614
+ can sign in parallel.
615
+
616
+ `signMultiple` is only for `virtual` assignments. For `collect`, read
617
+ `signable.assignment.items`, then call `sign(documentId, assignmentId,
618
+ accessCode, entries)` with a non-empty array of
619
+ `{ itemId, fieldId, pageId, value }`. A virtual signer must confirm their data
620
+ before signing. A `DigitalCertificate` signer cannot call `sign`; that branch
621
+ uses Assinafy's certificate flow, described in
622
+ [ICP-Brasil digital certificate](#icp-brasil-digital-certificate).
623
+
624
+ #### Identity-document verification branch
625
+
626
+ For a separate assignment configured with `verification_method:
627
+ 'IdDocumentFaceMatchBasic'`, enable the **ID Document + Face Match** feature
628
+ and register a valid CPF in the signer's `government_id`. Either notification
629
+ channel is supported; estimate the fee before creating the assignment.
630
+ `self.verification_method` tells a custom signing portal to use this branch
631
+ instead of the email/WhatsApp OTP step.
632
+
633
+ ```ts
634
+ const state = await signerClient.signerDocuments.getIdentityVerification(accessCode);
635
+ // Only after the signer's explicit biometric-processing consent:
636
+ if (state.can_start && signerConsented) {
637
+ const capture = await signerClient.signerDocuments.startIdentityVerification(
638
+ accessCode, { consent: true },
639
+ );
640
+ response.redirect(capture.url); // preserve the fragment; never log or store this bearer URL
641
+ }
642
+ ```
643
+
644
+ An existing `Pending` session exposes its capture link in `state.url`.
645
+ Only no session or `Expired` allows a new start; `Declined` and `Abandoned`
646
+ require a new document/assignment. An elapsed `expires_at` alone does not
647
+ authorize a restart. Once `Approved` or `InReview`, continue with data/terms
648
+ confirmation and signing. `InReview` holds certification; after everyone
649
+ signs the document becomes `pending_identity_review`.
650
+
651
+ ```ts
652
+ // Account-side review, using workspace credentials:
653
+ const review = await client.assignments.getIdentityVerification(documentId, assignmentId, signerId);
654
+ const image = review.images[0];
655
+ if (image) {
656
+ const bytes = await client.assignments.downloadIdentityVerificationImage(documentId, assignmentId, signerId, image);
657
+ // Show to the authorized reviewer without caching or logging the evidence.
658
+ }
659
+ // Send only the account reviewer's explicit decision:
660
+ await client.assignments.reviewIdentityVerification(documentId, assignmentId, signerId, {
661
+ decision: 'Approved', note: 'Verified independently.',
662
+ });
663
+ ```
664
+
665
+ Approval permits certification after all signatures and reviews are complete.
666
+ `Rejected` cancels the document and notifies signers and copy receivers; the
667
+ optional note (up to 2000 characters, or null) stays hidden from them.
668
+ Images are available only while `InReview`.
669
+
670
+ ### 6. Observe completion and download artifacts
671
+
672
+ Subscribe to `document_ready` for event-driven completion — on an endpoint with
673
+ `signing_enabled`, [verify the signature](#webhook-verification) of every
674
+ delivery before processing it — or fetch `documents.details(documentId)` until
675
+ `status === 'certificated'`. Webhook
676
+ deliveries can repeat, so use the `webhook-id` header as an
677
+ idempotency key. Once complete:
678
+
679
+ ```ts
680
+ const finalDocument = await client.documents.details(uploaded.id);
681
+ const signedPdf = await client.documents.download(uploaded.id, 'certificated');
682
+ const certificatePage = await client.documents.download(uploaded.id, 'certificate-page');
683
+ const bundleZip = await client.documents.download(uploaded.id, 'bundle');
684
+
685
+ // Validate an Assinafy signature hash when your workflow has extracted it.
686
+ const validation = await client.documents.verify(documentSignatureHash);
687
+ ```
688
+
689
+ `original`, `certificated`, and `certificate-page` are PDFs. `bundle` is a ZIP
690
+ containing those three artifacts and also `pades` when the document had an
691
+ ICP-Brasil certificate signer. The `pades` PDF exists only for documents that
692
+ had certificate signers. An artifact can return `404` before generation has
693
+ finished. `decline_reason` is included in document details only when the access
694
+ token belongs to the document creator.
695
+
696
+ ## Resource reference
697
+
698
+ Most account-scoped methods accept an optional `accountId` that overrides the
699
+ client default. Workspace `get`, `update`, `delete`, branding, and statistics
700
+ methods always require an explicit account ID.
701
+
702
+ ### Documents
703
+
704
+ ```ts
705
+ // Upload from a file path (recommended)
706
+ const doc = await client.documents.upload(
707
+ { filePath: './contract.pdf' },
708
+ { name: 'Service agreement', metadata: { type: 'service' } },
709
+ );
710
+ // `metadata` is a compatibility multipart part outside the published schema.
711
+ // `name` sets the filename of the file part; it is not sent as a separate field.
712
+ // When omitted, it defaults to the original filename. The API appends `.pdf`
713
+ // when absent, so
714
+ // the document above is stored as 'Service agreement.pdf'. Accents are
715
+ // transliterated by the API ('Contrato de Serviço' → 'Contrato de Servico.pdf').
716
+ // → {
717
+ // resource: 'document', id: '1031…', account_id: '102d…', template_id: null,
718
+ // name: 'Service agreement.pdf', status: 'uploaded',
719
+ // artifacts: { original: 'https://…/download/original' },
720
+ // signing_url: 'https://app…/sign/1031…',
721
+ // pages: [], // populated once status reaches `metadata_ready`
722
+ // tags: [], is_closed: false, created_at: '2026-…', updated_at: '2026-…'
723
+ // }
724
+
725
+ // …or from a Buffer already in memory
726
+ await client.documents.upload({ buffer, fileName: 'contract.pdf' });
727
+
728
+ // List → { data: IDocumentListItem[], meta?: { current_page, per_page, total, last_page } }
729
+ const { data, meta } = await client.documents.list({ page: 1, 'per-page': 20, sort: 'updated_at' });
730
+
731
+ // Search is the lightweight alternative to list: same item shape, but the API
732
+ // skips the expanded `assignment`/`pages`. Prefer it for name lookups.
733
+ const hits = await client.documents.search({ search: 'agreement', status: 'pending_signature', 'per-page': 20 });
734
+
735
+ await client.documents.details(doc.id);
736
+ // Production: page 2 of activities, oldest first; returns an array.
737
+ await client.documents.activities(doc.id, { page: 2, 'per-page': 100, sort: 'id' });
738
+ // Use listActivities for { data, meta }, including total and last_page.
739
+ await client.documents.listActivities(doc.id, { page: 2, 'per-page': 100, sort: 'id' });
740
+ await client.documents.waitUntilReady(doc.id, { maxWaitMs: 30_000 });
741
+
742
+ // Rename. The API rejects this with 400 while the document is still in
743
+ // `metadata_processing`, so await waitUntilReady() first on a fresh upload.
744
+ // (Passing `name` to upload() avoids both the round-trip and the race.)
745
+ await client.documents.rename(doc.id, 'Signed service agreement.pdf');
746
+
747
+ await client.documents.download(doc.id, 'certificated'); // signed PDF
748
+ await client.documents.download(doc.id, 'certificate-page');
749
+ await client.documents.download(doc.id, 'bundle'); // ZIP
750
+ // `pades` exists only when at least one signer used DigitalCertificate.
751
+ await client.documents.download(doc.id, 'pades');
752
+ await client.documents.thumbnail(doc.id);
753
+ await client.documents.downloadPage(doc.id, pageId);
754
+
755
+ await client.documents.statuses(); // list every status code + deletable flag
756
+ await client.documents.isFullySigned(doc.id);
757
+ await client.documents.getSigningProgress(doc.id);
758
+ await client.documents.delete(doc.id);
759
+
760
+ // Verify a signed document by its Assinafy signature hash
761
+ await client.documents.verify('FE32EDDADE7CBDDCBB934E7402047450B0E59C02');
762
+
763
+ // Public endpoints (no auth)
764
+ await client.documents.getPublic(doc.id);
765
+ // Body: { channel: 'email', recipient: 'signer@example.com' } (email only)
766
+ await client.documents.sendToken(doc.id, 'signer@example.com');
767
+
768
+ // The current OpenAPI contract requires existing tag IDs.
769
+ const contractsTag = await client.tags.create({ name: 'Contracts' });
770
+ const quarterTag = await client.tags.create({ name: '2026-Q1' });
771
+ const urgentTag = await client.tags.create({ name: 'Urgent' });
772
+ await client.documents.listTags(doc.id);
773
+ await client.documents.replaceTags(doc.id, [contractsTag.id, quarterTag.id]); // [] detaches all
774
+ await client.documents.addTags(doc.id, [urgentTag.id]); // append
775
+ await client.documents.detachTag(doc.id, urgentTag.id); // → { detached: true }
776
+ ```
777
+
778
+ Uploads are validated locally: only `.pdf` files up to 25 MB whose bytes begin
779
+ with the PDF magic header (`%PDF-`) are accepted. The API also limits documents
780
+ to 2,000 pages.
781
+
782
+ Page and artifact URLs embedded in JSON responses still require the same
783
+ account authentication as their download operations. Prefer
784
+ `documents.downloadPage()` and `documents.download()` so the SDK applies the
785
+ credential and returns a `Buffer`. `bundle` contains `original`, `certificated`,
786
+ and `certificate-page`, plus `pades` when available.
787
+
788
+ List endpoints return `{ data, meta }`, where `meta` is populated from the
789
+ `X-Pagination-*` response headers. Two API behaviours are worth knowing because
790
+ both are silent rather than errors:
791
+
792
+ - Only the hyphenated `per-page` is read. `per_page` is accepted and ignored,
793
+ falling back to 20 rows — so the SDK rewrites `per_page` to `per-page` on
794
+ every list method, and an explicit `per-page` wins when both are given.
795
+ - Document and signer lists have been observed to clamp `per-page` to **50**.
796
+ Asking for 100 returns 50 rows with a `200` on those deployments.
797
+ The exported `MAX_LIST_PAGE_SIZE` constant is that observed ceiling; page through with
798
+ `page` rather than requesting a larger page, and trust `meta.per_page` over
799
+ the value you asked for.
800
+
801
+ `documents.activities(documentId, params?)` keeps its array return type and does
802
+ not expose pagination metadata; use `documents.listActivities()` for `{ data, meta }`.
803
+ In production, these methods return **20 entries per page**
804
+ by default and documents a maximum `per-page` of **100**. Use `page` to fetch later
805
+ entries; an empty array marks the end. `sort: 'id'` returns oldest first, and
806
+ `sort: '-id'` (the default) returns newest first. Sandbox still returns the full,
807
+ unpaged log and may ignore these parameters, so do not loop through pages there.
808
+ Existing integrations that read the entire history in one request must now
809
+ request subsequent pages. See the [migration example](COMPATIBILITY.md#document-activities).
810
+
811
+ ### Contract lifecycle management (CLM)
812
+
813
+ Contract lifecycle management tracks the business terms attached to an existing
814
+ document without changing how that document is uploaded, sent, or signed. The
815
+ production API supports the complete flow below; a sandbox can lag a newly
816
+ released CLM route or plan entitlement (see
817
+ [compatibility notes](COMPATIBILITY.md#contract-lifecycle-management-clm)).
818
+
819
+ ```ts
820
+ // 1. Upload or select the contract document, then attach its terms.
821
+ const document = await client.documents.upload({ filePath: './agreement.pdf' });
822
+ const contract = await client.contracts.set(document.id, {
823
+ status: 'active',
824
+ counterparty_name: 'Example Ltda',
825
+ counterparty_taxpayer_id: '11.222.333/0001-81',
826
+ value: 120000.50,
827
+ currency: 'BRL',
828
+ start_date: '2026-11-01',
829
+ end_date: '2027-10-31',
830
+ auto_renew: true,
831
+ renewal_term_months: 12,
832
+ notice_period_days: 30,
833
+ metadata: { crm_stage: 'won' },
834
+ external_references: [{ system: 'crm', id: '98765' }],
835
+ });
836
+
837
+ // 2. Read or synchronize the portfolio. `updated_at` moves after every change.
838
+ const current = await client.contracts.get(document.id);
839
+ const endingSoon = await client.contracts.list({
840
+ status: ['active'],
841
+ ending_within_days: 30,
842
+ sort: 'end_date',
843
+ expand: 'document',
844
+ });
845
+
846
+ // 3. Use the value you read to reject a concurrent edit with HTTP 409.
847
+ if (current.resource === 'document_contract') {
848
+ await client.contracts.set(document.id, {
849
+ notice_period_days: 60,
850
+ updated_at: current.updated_at,
851
+ });
852
+ }
853
+
854
+ // 4. A signed amendment is another document linked to the root contract.
855
+ const amendment = await client.documents.upload({ filePath: './amendment.pdf' });
856
+ await client.contracts.set(amendment.id, {
857
+ parent_document_id: document.id,
858
+ relation_type: 'amendment',
859
+ value: 130000,
860
+ end_date: '2028-06-30',
861
+ });
862
+ // Send and sign `amendment` through the ordinary assignment flow. Its delta is
863
+ // applied to the root after certification; inspect the complete family here:
864
+ const family = await client.contracts.listRelated(amendment.id);
865
+
866
+ // 5. Start a new term directly, or close the lifecycle.
867
+ const renewed = await client.contracts.renew(document.id, {
868
+ term: family.term,
869
+ value: 135000,
870
+ updated_at: family.updated_at,
871
+ });
872
+ await client.contracts.terminate(document.id, {
873
+ reason: 'Replaced by a new agreement',
874
+ updated_at: renewed.updated_at,
875
+ });
876
+ ```
877
+
878
+ Writes need `documents:write` for OAuth and a workspace plan with contract
879
+ tracking. Reads need `documents:read` and continue working after the plan lapses.
880
+ The hourly lifecycle emits renewal-notice, expiring, expired, and renewed
881
+ notifications; configure the owner preferences and subscribe to the matching
882
+ webhook events when your integration must react:
883
+
884
+ ```ts
885
+ await client.users.updateNotificationPreferences({
886
+ ContractRenewalNotice: true,
887
+ ContractExpiring: true,
888
+ ContractExpired: true,
889
+ ContractRenewed: true,
890
+ });
891
+
892
+ await client.webhooks.createEndpoint({
893
+ url: 'https://example.com/webhooks/assinafy',
894
+ email: 'operations@example.com',
895
+ events: [
896
+ 'document_contract_updated',
897
+ 'document_contract_renewal_notice',
898
+ 'document_contract_expiring',
899
+ 'document_contract_expired',
900
+ 'document_contract_renewed',
901
+ 'document_contract_terminated',
902
+ 'document_contract_amended',
903
+ 'document_contract_amendment_updated',
904
+ ],
905
+ });
906
+ ```
907
+
908
+ `set()`, `renew()`, and `terminate()` are not automatically retried. A lost
909
+ response is safe to resolve by reading the contract again: `updated_at`, the
910
+ current `term`, and the explicit renewal date provide the concurrency and
911
+ repeat protections documented by the API.
912
+
913
+ ### Signers
914
+
915
+ ```ts
916
+ await client.signers.create({
917
+ full_name: 'Example Signer',
918
+ email: 'signer@example.com',
919
+ cpf: '123.456.789-00', // legacy compatibility input; non-digits are stripped
920
+ });
921
+ // → { id: '19e6…', full_name: 'Example Signer', email: 'signer@example.com',
922
+ // whatsapp_phone_number: null, has_accepted_terms: false }
923
+ // (note: `cpf` is accepted on input but never echoed back by the API)
924
+
925
+ // Both contacts are optional. A name-only signer cannot be notified until a
926
+ // contact is added.
927
+ await client.signers.create({ full_name: 'Contact Pending' });
928
+
929
+ await client.signers.create({
930
+ full_name: 'Example Signer',
931
+ email: 'signer@example.com',
932
+ });
933
+
934
+ await client.signers.get(signerId);
935
+ await client.signers.list({ page: 1, 'per-page': 50, search: 'signer' });
936
+ await client.signers.update(signerId, {
937
+ full_name: 'Updated Signer',
938
+ government_id: '390.533.447-05', // official update field; sent as digits
939
+ });
940
+ await client.signers.delete(signerId);
941
+
942
+ const existing = await client.signers.findByEmail('signer@example.com');
943
+ ```
944
+
945
+ When an `email` is supplied, `signers.create()` is idempotent by email: it
946
+ reuses an existing signer when the same email is already present in the
947
+ workspace. Signers without email are always created fresh. See
948
+ [Paid signing branches](#paid-signing-branches) for phone-only signers.
949
+
950
+ ### Assignments
951
+
952
+ ```ts
953
+ // List every assignment in the workspace.
954
+ // → { data: IAssignment[], meta?: { current_page, per_page, total, last_page } }
955
+ const { data, meta } = await client.assignments.list({ page: 1, 'per-page': 20 });
956
+
957
+ // Signers may be ids or objects — the SDK normalises to the API shape.
958
+ await client.assignments.create(documentId, {
959
+ method: 'virtual',
960
+ signers: ['signer-1', 'signer-2'],
961
+ message: 'Please review and sign',
962
+ expires_at: '2027-12-31T23:59:00Z',
963
+ copy_receivers: ['copy-recipient-signer-id'],
964
+ });
965
+
966
+ // Sequential signing: `step` controls signing order (parallel within a step).
967
+ await client.assignments.create(documentId, {
968
+ method: 'virtual',
969
+ signers: [
970
+ { id: 'signer-1', step: 1 },
971
+ { id: 'signer-2', step: 2 }, // notified only after step 1 finishes
972
+ ],
973
+ });
974
+
975
+ // Collect fields use 150-DPI page-image pixels measured from the upper-left.
976
+ await client.assignments.create(documentId, {
977
+ method: 'collect',
978
+ signers: [{ id: signerId }],
979
+ entries: [{
980
+ page_id: pageId,
981
+ fields: [{
982
+ signer_id: signerId,
983
+ field_id: fieldId,
984
+ display_settings: {
985
+ left: 69, top: 282, width: 421, height: 45.86, fontSize: 22,
986
+ fontFamily: 'Arial', backgroundColor: '#D5EBFF',
987
+ },
988
+ }],
989
+ }],
990
+ });
991
+ ```
992
+
993
+ To assemble an assignment body outside the client — for example, to inspect it
994
+ before sending — use the exported `buildAssignmentPayload()` helper, which
995
+ applies the same validation and normalization as `create()`.
996
+
997
+ ```ts
998
+ // Estimate cost (the endpoint prices channel descriptors, not signer IDs) → ICostEstimate
999
+ await client.assignments.estimateCost(documentId, { signers: [{}] }); // default Email
1000
+ // → {
1001
+ // documents: 1, credits: 0, needs_extra_document: false, extra_document_cost: 0,
1002
+ // total_credits: 0, breakdown: [], document_balance: 67, credit_balance: 0,
1003
+ // has_sufficient_resources: true, blocking_reason: null, message: null
1004
+ // }
1005
+
1006
+ await client.assignments.resetExpiration(documentId, assignmentId, '2027-06-30T00:00:00Z');
1007
+ // The `expires_at` key is required by the contract; send `null` to remove the expiration.
1008
+ // Date-only values end at 23:59 UTC; date-times without an offset are UTC.
1009
+ await client.assignments.resetExpiration(documentId, assignmentId, null);
1010
+
1011
+ await client.assignments.resendNotification(documentId, assignmentId, signerId);
1012
+ // → { is_sent: true, document_id: '…', signer_id: '…' }
1013
+
1014
+ const resendCost = await client.assignments.estimateResendCost(documentId, assignmentId, signerId);
1015
+ // Production: { total, breakdown, credit_balance, has_sufficient_credits }. Older
1016
+ // deployments return a full ICostEstimate; narrow with `'total_credits' in resendCost`.
1017
+ ```
1018
+
1019
+ The `create` response is an `IAssignment`: `{ id, method, signers: [...],
1020
+ items: [{ display_settings, ... }], signing_urls: [{ signer_id, url, embedded }], … }`.
1021
+
1022
+ For backwards compatibility, the SDK also accepts legacy `signer_ids` and `signerIds` payloads and rewrites them to the current `signers: [{ id }]` format expected by the API.
1023
+
1024
+ **Cancelling a signature request.** Assinafy has no workspace-side "cancel" endpoint. To stop a pending request either delete the document (when its status is deletable) or have the signer decline:
1025
+
1026
+ ```ts
1027
+ await client.documents.delete(documentId); // workspace-side (an envelope: envelopes.cancel)
1028
+ await client.signerDocuments.decline(documentId, assignmentId, accessCode, 'No longer needed'); // signer-side
1029
+ ```
1030
+
1031
+ ### Paid signing branches
1032
+
1033
+ Keep the email flow as the default. Enable either branch below only after the
1034
+ workspace has the required plan or feature and the returned cost estimate is
1035
+ acceptable.
1036
+
1037
+ The verification method and the notification method are **coupled**: send one,
1038
+ both, or neither — the missing side is inferred. With neither, both default
1039
+ to `Email`.
1040
+
1041
+ | Verification | How the signer proves who they are | Allowed notification | Cost per signer |
1042
+ | --- | --- | --- | --- |
1043
+ | `Email` *(default)* | One-time code (OTP) by email | `Email` | Free |
1044
+ | `Whatsapp` | One-time code (OTP) by WhatsApp | `Whatsapp` | 0.45 credit (the notification), paid plans only |
1045
+ | `DigitalCertificate` | The signer signs with their **own ICP-Brasil certificate — A1 or A3 —** through the Web PKI extension, producing a **qualified PAdES signature**; requires `method: 'virtual'` | `Email` **or** `Whatsapp` | 0.5 credits + the notification |
1046
+ | `IdDocumentFaceMatchBasic` | Hosted identity-document, face and liveness verification | `Email` **or** `Whatsapp` | Use `estimateCost()` |
1047
+ | `Bypass` | No code: your app has already authenticated the signer. Enabled per account by Assinafy | `Email`, `Whatsapp` **or** `Bypass` (sends no invitation) | The notification |
1048
+
1049
+ Check what the plan allows before offering a method:
1050
+ `(await client.workspaces.get(accountId, { expand: 'signing_features' })).signing_features`
1051
+ holds `DigitalCertificate`, `VerificationIdDocumentFaceMatchBasic`,
1052
+ `WhatsappNotification`, `VerificationBypass` and `Embed`; a `false` feature
1053
+ answers `403` with `ApiError.code === 'PlanRestricted'`.
1054
+
1055
+ Exactly one notification method per signer. The SDK rejects an invalid
1056
+ combination before the request; the API would answer `400`.
1057
+
1058
+ #### WhatsApp verification and notification
1059
+
1060
+ WhatsApp is available only on paid subscriptions and costs 0.45 credit per
1061
+ notification. Create a phone-only signer or add a phone to an existing signer,
1062
+ then request the `Whatsapp` channel explicitly:
1063
+
1064
+ ```ts
1065
+ const phoneSigner = await client.signers.create({
1066
+ full_name: 'Mobile Signer',
1067
+ whatsapp_phone_number: '+5511999990000',
1068
+ });
1069
+
1070
+ const whatsappCost = await client.assignments.estimateCost(documentId, {
1071
+ method: 'virtual',
1072
+ signers: [{ verification_method: 'Whatsapp', notification_methods: ['Whatsapp'] }],
1073
+ });
1074
+
1075
+ const whatsappAssignment = await client.assignments.create(documentId, {
1076
+ method: 'virtual',
1077
+ signers: [{
1078
+ id: phoneSigner.id,
1079
+ verification_method: 'Whatsapp',
1080
+ notification_methods: ['Whatsapp'],
1081
+ }],
1082
+ });
1083
+
1084
+ const notices = await client.assignments.listWhatsAppNotifications(
1085
+ documentId,
1086
+ whatsappAssignment.id,
1087
+ );
1088
+ // IWhatsAppNotification[]:
1089
+ // [{ sent_at, header, body, buttons: [{ text, url? }], phone_number, signer_id }]
1090
+ ```
1091
+
1092
+ The high-level helper selects this paid branch for a signer that has a phone
1093
+ number but no email. Button URLs can contain signer credentials; do not log or
1094
+ forward them outside the signing flow.
1095
+
1096
+ #### ICP-Brasil digital certificate
1097
+
1098
+ `DigitalCertificate` requires `method: 'virtual'`, the account feature, a CPF
1099
+ or CNPJ in the signer's `government_id`, and exactly one certificate signer in
1100
+ that signing step. It costs 0.5 credits per certificate signer in addition to
1101
+ the selected notification cost. A certificate flow completes the signer's
1102
+ virtual item; it cannot submit placed fields through the ordinary `collect`
1103
+ signing endpoint.
1104
+
1105
+ The SDK rejects certificate signers on a `collect` assignment in both
1106
+ `create()` and `estimateCost()` before any request. Branch on
1107
+ `ValidationError.errors.code ===
1108
+ 'digital_certificate_requires_virtual_method'`, or compare it with the
1109
+ exported `DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD` constant; do not match
1110
+ the human-readable message.
1111
+
1112
+ **A1 and A3 are certificate media**, chosen by the signer in their browser at
1113
+ signing time: A1 lives in software (a file on the machine) and A3 in hardware
1114
+ (a token or smartcard). The API models both with the single
1115
+ `DigitalCertificate` value — there is no `A1`/`A3` field to send, and the
1116
+ resulting PAdES signature is qualified in either case. Certificate signers
1117
+ complete a Web PKI handshake on two production-only routes that are not part
1118
+ of this SDK.
1119
+
1120
+ ```ts
1121
+ const certificateSigner = await client.signers.update(signerId, {
1122
+ government_id: '390.533.447-05',
1123
+ });
1124
+
1125
+ const certificateCost = await client.assignments.estimateCost(documentId, {
1126
+ method: 'virtual',
1127
+ signers: [{ verification_method: 'DigitalCertificate', notification_methods: ['Email'] }],
1128
+ });
1129
+
1130
+ await client.assignments.create(documentId, {
1131
+ method: 'virtual',
1132
+ signers: [{
1133
+ id: certificateSigner.id,
1134
+ step: 1,
1135
+ verification_method: 'DigitalCertificate',
1136
+ notification_methods: ['Email'],
1137
+ }],
1138
+ });
1139
+ ```
1140
+
1141
+ Before opening the assignment, the signer must confirm identity data and accept
1142
+ terms with `confirmData(..., { has_accepted_terms: true })` or `acceptTerms()`.
1143
+ The regular `sign()` endpoint rejects certificate signers; they complete the
1144
+ ICP-Brasil flow through Assinafy's browser integration. After completion,
1145
+ `documents.download(documentId, 'pades')` returns the qualified PAdES artifact.
1146
+
1147
+ ### Envelopes
1148
+
1149
+ An envelope sends up to 20 documents to the same signers (up to 20) at once:
1150
+ one invitation per signer, one signing link for all of their documents, and one
1151
+ document charge for the whole envelope. Each document keeps its own assignment,
1152
+ status, certificate, downloads and webhooks. Upload the documents and wait for
1153
+ `metadata_ready` first; do not create assignments on them.
1154
+
1155
+ ```ts
1156
+ const body = {
1157
+ name: 'Admission kit',
1158
+ message: 'Please sign the documents below.',
1159
+ signers: [{ id: anaId }, { id: bobId, verification_method: 'Whatsapp' as const }],
1160
+ documents: [
1161
+ { id: contractId, signer_ids: [anaId, bobId], expires_at: '2026-12-31' },
1162
+ { id: policyId, signer_ids: [anaId] },
1163
+ ],
1164
+ };
1165
+
1166
+ const estimate = await client.envelopes.estimateCost(body); // ICostEstimate, documents: 1
1167
+ const envelope = await client.envelopes.create(
1168
+ { ...body, max_total_credits: estimate.total_credits },
1169
+ { idempotencyKey: crypto.randomUUID() }, // safe to retry after a lost response
1170
+ );
1171
+ // IEnvelope: { id, name, message, documents: [{ id, position, name, status, artifacts,
1172
+ // signers: [{ id, full_name, email, whatsapp_phone_number, completed, signed_at }] }],
1173
+ // counts: { pending_signature: 2 }, signing_urls: [{ signer_id, url, embedded }], created_at }
1174
+
1175
+ await client.envelopes.resendNotification(envelope.id, anaId); // one reminder for every document
1176
+ const trail = await client.envelopes.listActivities(envelope.id, { sort: 'id' }); // each names document_id
1177
+ const zip = await client.envelopes.download(envelope.id, 'certificated'); // 1 - contract.pdf, …
1178
+ ```
1179
+
1180
+ - Envelope signers sign at once (no `step`). A `DigitalCertificate` signer
1181
+ signs only `virtual` documents, alone on each; `collect` documents need
1182
+ `entries` whose signers are exactly their `signer_ids`.
1183
+ - `update()` renames, changes the message or reorders (`document_ids`) without
1184
+ sending anything. `addDocument()` adds an unassigned document for existing
1185
+ signers; `removeDocument()` cancels one and the others carry on.
1186
+ - `cancel()` cancels every open document and is safe to repeat. `delete()` works
1187
+ only once every document is closed (`409 EnvelopeOpen` before); the documents
1188
+ remain. A document of an open envelope cannot be deleted on its own.
1189
+ - `documents.list({ envelope_id })` and `documents.details(id, { expand:
1190
+ ['envelope'] })` find an envelope's documents and a document's envelope.
1191
+ - Creating, adding and estimating need the Envelopes plan feature (`403
1192
+ PlanRestricted`).
1193
+
1194
+ ### Embedded signing
1195
+
1196
+ Embedded signing shows Assinafy's signing screen in an iframe inside your app.
1197
+ This SDK covers the backend half; the browser half (iframe and `postMessage`
1198
+ handshake) follows the API's Embedded Signing Guide. It needs the Embed plan
1199
+ feature and an API key or user token — OAuth application tokens cannot mint
1200
+ sessions.
1201
+
1202
+ ```ts
1203
+ // Once per origin: exact https://host[:port], at most 10; http only for localhost.
1204
+ await client.embed.addOrigin('https://app.example.com');
1205
+
1206
+ const assignment = await client.assignments.create(documentId, {
1207
+ method: 'virtual',
1208
+ signers: [{ id: signerId, verification_method: 'Email', embedded: true }],
1209
+ });
1210
+ // The embedded signer's signing_urls entry is { signer_id, url: null, embedded: true }.
1211
+
1212
+ // Every time the frame is shown (including reloads), on your backend:
1213
+ const { url, expires_at } = await client.embed.createSession(documentId, assignment.id, signerId);
1214
+ // Hand `url` to that signer's page only; it works once, within 5 minutes. Never log or store it.
1215
+ ```
1216
+
1217
+ - The signer still receives the normal invitation with the 6-digit code they
1218
+ type in the frame. With `Bypass` verification and the `Bypass` notification
1219
+ (enabled per account) nothing is sent and no code is asked.
1220
+ - `createSession()` answers `409` with `ApiError.code` `document_not_ready`
1221
+ (retry shortly), `already_signed`, `document_unavailable` or
1222
+ `embed_origins_missing`, and `429` after 30 sessions per signer per hour.
1223
+ - Frame events are UI hints. Confirm the outcome from webhooks or by reading the
1224
+ document before unlocking anything.
1225
+
1226
+ ### Templates
1227
+
1228
+ `templates.list()` is part of the current OpenAPI document. Existing
1229
+ integrations can also use five template-management routes—`create`, `get`,
1230
+ `update`, `delete`, and `downloadPage`—that are absent from that document. See
1231
+ [compatibility notes](COMPATIBILITY.md#template-management-extensions).
1232
+ Template status casing can vary by deployment; normalize with
1233
+ `template.status.toLowerCase()` when branching on it.
1234
+
1235
+ ```ts
1236
+ // Create a template by uploading a PDF (multipart). The template starts in
1237
+ // an uploaded state and becomes ready once its pages are processed.
1238
+ const created = await client.templates.create(
1239
+ { filePath: './nda.pdf' }, // or { buffer, fileName: 'nda.pdf' }
1240
+ { name: 'NDA template' },
1241
+ );
1242
+ // →
1243
+ // {
1244
+ // resource: 'template', id: '1032...', name: 'nda.pdf',
1245
+ // document_name: 'nda.pdf', message: null, status: 'Uploaded',
1246
+ // roles: [{ id: '1032...', name: 'TemplateEditor', assignment_type: 'Editor' }],
1247
+ // pages: [], tags: [], created_at: '2026-…', updated_at: '2026-…'
1248
+ // }
1249
+
1250
+ const { data, meta } = await client.templates.list({ search: 'NDA', 'per-page': 20 });
1251
+ const template = await client.templates.get(created.id); // includes pages[] + default_document_tags
1252
+ await client.templates.update(created.id, { name: 'NDA v2', message: 'Please sign' });
1253
+ const firstPage = template.pages?.[0];
1254
+ if (firstPage) await client.templates.downloadPage(created.id, firstPage.id); // → Buffer (JPEG)
1255
+ await client.templates.delete(created.id);
1256
+
1257
+ // Create a document from an existing, configured template. Fresh uploads have
1258
+ // only an Editor role; add signer roles in Assinafy's editor first.
1259
+ const configured = await client.templates.get(templateId);
1260
+ const signerRole = configured.roles?.find(
1261
+ (role) => typeof role.assignment_type === 'string'
1262
+ && role.assignment_type.toLowerCase() !== 'editor',
1263
+ );
1264
+ if (!signerRole) throw new Error('Template has no signer role');
1265
+ const generated = await client.documents.createFromTemplate(
1266
+ templateId,
1267
+ [{
1268
+ role_id: signerRole.id,
1269
+ email: 'signer@example.com',
1270
+ name: 'Example Signer',
1271
+ verification_method: 'Email',
1272
+ notification_methods: ['Email'],
1273
+ }],
1274
+ { name: 'NDA - Example', message: 'Please sign at your earliest convenience.' },
1275
+ );
1276
+ // The response starts at status: 'uploaded' with assignment: null. Follow
1277
+ // documents.get(generated.id) or webhooks for pending_signature / failed.
1278
+
1279
+ // Estimate the cost before creating → ICostEstimate
1280
+ await client.documents.estimateCostFromTemplate(templateId, [
1281
+ { role_id: 'role_id', verification_method: 'Email', notification_methods: ['Email'] },
1282
+ ]);
1283
+ // → { documents: 1, total_credits: 0, document_balance: 67, credit_balance: 0,
1284
+ // has_sufficient_resources: true, blocking_reason: null, breakdown: [], … }
1285
+ ```
1286
+
1287
+ Each template signer uses an existing `id` or an `email`; `id` wins when both
1288
+ are sent. An email reuses the matching account signer or creates one with the
1289
+ supplied `name` and optional E.164 `whatsapp_phone_number`.
1290
+
1291
+ The server derives the assignment method from the template. A template without
1292
+ placed signer fields supports `DigitalCertificate`; a template with placed
1293
+ fields returns `400` because it produces a `collect` assignment. The same rule
1294
+ is applied by `estimateCostFromTemplate()`.
1295
+
1296
+ Template creation only uploads the PDF and provisions the default editor role —
1297
+ configure roles/fields in the Assinafy editor (or the web UI) afterwards.
1298
+ The `download_url` values in template page objects are protected URLs; prefer
1299
+ `templates.downloadPage()` so the API credential is attached.
1300
+
1301
+ ### Tags
1302
+
1303
+ Workspace-scoped labels that can be attached to documents and templates. Tag names are unique per workspace (case-insensitive).
1304
+
1305
+ ```ts
1306
+ await client.tags.list({ search: 'contract' }); // ITag[]
1307
+ const tag = await client.tags.create({ name: 'Contracts', color: 'ff8800' });
1308
+ await client.tags.update(tag.id, { name: 'Sales Contracts' });
1309
+ await client.tags.update(tag.id, { color: null }); // clear the color
1310
+ await client.tags.delete(tag.id); // 409 if still attached
1311
+ await client.tags.delete(tag.id, { force: true }); // detach everywhere, then delete
1312
+ ```
1313
+
1314
+ Attach/detach tags on a specific document via `client.documents.listTags / replaceTags / addTags / detachTag` (see [Documents](#documents)).
1315
+
1316
+ The published attachment contract takes tag IDs. Older sandbox deployments
1317
+ instead interpret strings as names and create ID-named tags for ID inputs;
1318
+ pass existing names intentionally there. See [document tag compatibility](COMPATIBILITY.md#document-tags).
1319
+
1320
+ ### Workspaces
1321
+
1322
+ The official create/update request schemas define `name` and
1323
+ `notification_sender_type`. The sandbox also accepts the color fields shown
1324
+ below; they are retained as a documented compatibility extension.
1325
+
1326
+ ```ts
1327
+ // Colours are 6-char hex WITHOUT a leading '#' (unlike tags, which strip it).
1328
+ // '#ff0066' is rejected — the account endpoints want exactly 6 characters.
1329
+ await client.workspaces.create({
1330
+ name: 'My Workspace',
1331
+ notification_sender_type: 'Account',
1332
+ primary_color: 'ff0066',
1333
+ secondary_color: '0066ff',
1334
+ });
1335
+ // → { id, name, primary_color: 'ff0066', secondary_color: '0066ff', created_at }
1336
+ await client.workspaces.list();
1337
+ await client.workspaces.get(accountId);
1338
+ // → also { limits: { webhook_endpoints: 3 } }; with the expansion, signing_features.
1339
+ const { signing_features } = await client.workspaces.get(accountId, { expand: 'signing_features' });
1340
+ await client.workspaces.update(accountId, {
1341
+ name: 'Renamed',
1342
+ notification_sender_type: 'User',
1343
+ primary_color: '112233',
1344
+ });
1345
+
1346
+ // Branding
1347
+ const theme = await client.workspaces.getTheme(accountId);
1348
+ const logo = await client.workspaces.downloadLogo(accountId); // Buffer
1349
+ await client.workspaces.uploadLogo(accountId, { filePath: './logo.png' });
1350
+ await client.workspaces.uploadLogo(accountId, {
1351
+ buffer: logoBuffer,
1352
+ fileName: 'logo.png',
1353
+ contentType: 'image/png',
1354
+ });
1355
+ await client.workspaces.deleteLogo(accountId);
1356
+
1357
+ // Latest 12 months by default; daily statistics require a YYYY-MM month.
1358
+ await client.workspaces.getStats(accountId);
1359
+ await client.workspaces.getStats(accountId, {
1360
+ granularity: 'daily',
1361
+ month: '2026-06',
1362
+ });
1363
+
1364
+ // Plan meter (not for OAuth applications): balances null = unlimited.
1365
+ const usage = await client.workspaces.getUsage(accountId);
1366
+ // → { plan: 'Pro', documents_renewal_date: '2026-12-11',
1367
+ // balances: { documents: { balance, limit, spent }, credits: { balance, limit, spent } } }
1368
+
1369
+ // Workspace-wide alerts, set by owners; false silences an alert for everyone.
1370
+ const policy = await client.workspaces.getNotificationPolicy(accountId); // { editable, owners_receive_all, events }
1371
+ await client.workspaces.updateNotificationPolicy(accountId, { events: { SignerViewed: false } });
1372
+
1373
+ await client.workspaces.delete(accountId);
1374
+ // `force` cancels an active paid subscription as part of account deletion. It
1375
+ // is not a general bypass for unrelated deletion restrictions.
1376
+ await client.workspaces.delete(restrictedAccountId, { force: true });
1377
+ ```
1378
+
1379
+ ### Field definitions
1380
+
1381
+ Custom field types used by `collect`-method assignments.
1382
+
1383
+ ```ts
1384
+ await client.fields.create({ type: 'text', name: 'Contract Number' });
1385
+ await client.fields.list({ include_inactive: true, include_standard: true });
1386
+ await client.fields.get(fieldId);
1387
+ await client.fields.update(fieldId, { name: 'Updated Name' });
1388
+ await client.fields.delete(fieldId);
1389
+
1390
+ // Workspace credentials apply; signerAccessCode is an optional legacy query.
1391
+ await client.fields.validate(fieldId, '400.676.228-36', { signerAccessCode });
1392
+
1393
+ // Validate multiple values at once
1394
+ await client.fields.validateMultiple(
1395
+ [
1396
+ { field_id: 'f1', value: '1111111111111' },
1397
+ { field_id: 'f2', value: 'value@example.com' },
1398
+ ],
1399
+ { signerAccessCode },
1400
+ );
1401
+
1402
+ // Catalog of every field type the platform recognises
1403
+ await client.fields.listTypes();
1404
+ ```
1405
+
1406
+ ### Authentication / API key management
1407
+
1408
+ 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.
1409
+
1410
+ ```ts
1411
+ // Browser OAuth: redirect the user to this URL. The callback helper returns the
1412
+ // Assinafy callback URL for provider configuration; neither follows a redirect.
1413
+ const oauthStart = client.auth.getSocialLoginUrl('google');
1414
+ const oauthCallback = client.auth.getSocialLoginCallbackUrl();
1415
+
1416
+ let session = await client.auth.login('me@example.com', 'pw');
1417
+ // With two-factor authentication on, login returns `mfa_token`; exchange it
1418
+ // within 5 minutes for an authenticator code or a recovery code.
1419
+ if (session.mfa_token) {
1420
+ session = await client.auth.verifyMfa(session.mfa_token, '123456');
1421
+ }
1422
+ const { access_token, user, accounts } = session;
1423
+ await client.auth.socialLogin({ provider: 'google', token: 'google-id-token', has_accepted_terms: true });
1424
+ await client.auth.linkSocialLogin({ provider: 'google', token: 'google-id-token' });
1425
+
1426
+ // Personal API key
1427
+ await client.auth.createApiKey('current-password');
1428
+ await client.auth.getApiKey(); // → { api_key: '****...nBNr' } or null
1429
+ await client.auth.deleteApiKey();
1430
+
1431
+ // Password lifecycle
1432
+ await client.auth.changePassword({ email, password: 'current', new_password: 'next' });
1433
+ await client.auth.requestPasswordReset('me@example.com');
1434
+ await client.auth.resetPassword({ email, token: 'tk', new_password: 'next' });
1435
+ ```
1436
+
1437
+ ### Authenticated user
1438
+
1439
+ ```ts
1440
+ const user = await client.users.getCurrent();
1441
+ // → { id, name, email, telephone, government_id, is_email_verified,
1442
+ // has_accepted_terms, created_at, to_be_deleted_at }
1443
+
1444
+ // Cross-account document funnel, latest 12 monthly periods by default.
1445
+ const monthly = await client.users.getStats();
1446
+ const daily = await client.users.getStats({
1447
+ granularity: 'daily',
1448
+ month: '2026-06',
1449
+ });
1450
+ // Each row includes period, upload/send/certification totals, notification
1451
+ // counts for email/WhatsApp/bypass, verification counts for
1452
+ // email/WhatsApp/bypass/digital-certificate, viewed, and completed counts.
1453
+
1454
+ const preferences = await client.users.getNotificationPreferences();
1455
+ await client.users.updateNotificationPreferences({
1456
+ SignerDeclined: false,
1457
+ DocumentExpired: false,
1458
+ ContractExpiring: true,
1459
+ });
1460
+ // Updates merge: omitted keys keep their current value. Both methods return
1461
+ // the complete thirteen-key notification preference map.
1462
+
1463
+ // Push notifications on the user's phones, separate from e-mail (not for OAuth apps).
1464
+ const push = await client.users.getPushPreferences(); // every key, default true
1465
+ await client.users.updatePushPreferences({ SignerViewed: false });
1466
+ ```
1467
+
1468
+ #### Two-factor authentication
1469
+
1470
+ Available in production. The TOTP secret and the recovery codes are shown once.
1471
+
1472
+ ```ts
1473
+ const enrollment = await client.users.startTotpEnrollment('My phone');
1474
+ // → { id, secret, provisioning_uri } — render provisioning_uri as a QR code
1475
+ const { recovery_codes } = await client.users.confirmTotpEnrollment({
1476
+ id: enrollment.id,
1477
+ code: '123456', // current code from the new device
1478
+ });
1479
+ // From now on every login needs the second factor.
1480
+
1481
+ const { methods, recovery_codes_remaining } = await client.users.getMfa();
1482
+ await client.users.regenerateRecoveryCodes({ password: 'current-password' }); // or { code }
1483
+ await client.users.deleteMfaMethod(methods[0]!.id, { code: '123456' }); // → { is_mfa_enabled }
1484
+ ```
1485
+
1486
+ Replacing an already confirmed authenticator also needs `password` or
1487
+ `reauth_code` in `confirmTotpEnrollment()`; first-time enrollment does not.
1488
+
1489
+ ### Webhooks
1490
+
1491
+ An account has 1 webhook endpoint, or up to 3 on paid plans. Every active
1492
+ endpoint subscribed to an event receives it independently. OAuth tokens need
1493
+ `account:read` to read endpoints and `webhooks:write` to change them; the
1494
+ creation response includes `secret` when signing is enabled. Store it then,
1495
+ including for OAuth integrations. Reading it later requires an API key; OAuth
1496
+ apps with `webhooks:write` can rotate a lost secret.
1497
+
1498
+ ```ts
1499
+ const endpoint = await client.webhooks.createEndpoint({
1500
+ name: 'ERP',
1501
+ url: 'https://example.com/webhooks/assinafy',
1502
+ email: 'ops@example.com',
1503
+ events: ['document_ready', 'signer_signed_document', 'signer_rejected_document'],
1504
+ signing_enabled: true, // sign deliveries with Standard Webhooks
1505
+ });
1506
+ // → { id, name, url, email, events, is_active, is_held, held_since,
1507
+ // signing_enabled, secret, created_at, updated_at }
1508
+
1509
+ const secret = endpoint.secret; // 'whsec_…'; store securely at creation
1510
+ await client.webhooks.listEndpoints(); // IWebhookEndpoint[]
1511
+ await client.webhooks.listEndpoints(undefined, { url: endpoint.url }); // exact URL filter
1512
+ await client.webhooks.getEndpoint(endpoint.id);
1513
+ await client.webhooks.updateEndpoint(endpoint.id, { is_active: false }); // only the fields sent
1514
+ await client.webhooks.rotateEndpointSecret(endpoint.id); // the old secret stops at once
1515
+ // Or keep the old secret signing beside the new one for 24 hours while the receiver switches:
1516
+ // → { secret: 'whsec_…', previous_secret_expires_at: '2026-11-12T14:00:00Z' }
1517
+ await client.webhooks.rotateEndpointSecret(endpoint.id, undefined, { keep_previous: true });
1518
+ // One signed `webhook_test` delivery now (also to a held endpoint); 10 per 10 minutes.
1519
+ const attempt = await client.webhooks.testEndpoint(endpoint.id); // IWebhookDispatch, kind: 'manual'
1520
+ await client.webhooks.deleteEndpoint(endpoint.id); // frees the plan slot
1521
+ // Alternative when the integration kept only the registered URL:
1522
+ // await client.webhooks.deleteEndpointByUrl(endpoint.url);
1523
+
1524
+ await client.webhooks.listEventTypes();
1525
+ const history = await client.webhooks.listDispatches({
1526
+ endpoint_id: endpoint.id,
1527
+ delivered: false,
1528
+ page: 1,
1529
+ 'per-page': 20,
1530
+ }); // { data: IWebhookDispatch[], meta?: PaginationMeta }
1531
+ const retried = await client.webhooks.retryDispatch(dispatchId); // IWebhookDispatch
1532
+ ```
1533
+
1534
+ New or changed webhook URLs must use HTTPS. `createEndpoint()` returns `403`
1535
+ once the plan's limit is reached and `400`
1536
+ when another endpoint of the workspace already uses the same `url`. When
1537
+ `events` is omitted or empty, the SDK sends the exported
1538
+ `DEFAULT_WEBHOOK_EVENTS`: `document_ready`, `document_prepared`,
1539
+ `signer_signed_document`, `signer_rejected_document`, and
1540
+ `document_processing_failed`. In
1541
+ `updateEndpoint()`, `signing_enabled: true` generates a secret if there is none
1542
+ and returns that new secret once; `false` discards it.
1543
+
1544
+ The earlier routes remain and act on the account's oldest endpoint:
1545
+ `register()` (create or update), `get()` (`IWebhookSubscription | null`) and
1546
+ `inactivate()`.
1547
+
1548
+ Assinafy delivers each event as an HTTP `POST` with
1549
+ `Content-Type: application/json`, `Connection: close` and the headers
1550
+ `webhook-id` (identical on every attempt of the same event to the same
1551
+ endpoint — deduplicate on it), `webhook-timestamp` and, with signing on,
1552
+ `webhook-signature`. Any `2xx` is success. Connection errors, timeouts, `408`,
1553
+ `429`, and `5xx` responses receive up to six attempts about ten minutes apart;
1554
+ other statuses are final. After ten failed deliveries in a row, `is_held`
1555
+ becomes true and the oldest missed event is probed after 3, 15, and 60 minutes,
1556
+ then every six hours. Success resumes delivery and replays missed events oldest
1557
+ first. `retryDispatch()` sends once immediately, even while held. Dispatch
1558
+ history keeps the first 2,000 response characters for seven days.
1559
+
1560
+ Each history or retry result is an `IWebhookDispatch`:
1561
+
1562
+ ```ts
1563
+ type WebhookDispatchShape = {
1564
+ resource?: string;
1565
+ id: string;
1566
+ event: string;
1567
+ activity_id: number;
1568
+ endpoint_id?: string | null; // null once the endpoint is deleted
1569
+ endpoint: string | null;
1570
+ payload: IWebhookPayload | Record<string, unknown> | null;
1571
+ delivered: boolean;
1572
+ webhook_id?: string | null;
1573
+ attempt?: number | null;
1574
+ kind?: 'scheduled' | 'probe' | 'manual' | string;
1575
+ will_retry?: boolean;
1576
+ http_status: number | null;
1577
+ response_body: string | null;
1578
+ error: string | null;
1579
+ created_at: string;
1580
+ updated_at?: string;
1581
+ };
1582
+ ```
1583
+
1584
+ Every delivery body uses this envelope:
1585
+
1586
+ ```ts
1587
+ type WebhookPayloadShape = {
1588
+ id: number; // internal activity ID; deduplicate on webhook-id
1589
+ event: string;
1590
+ message: string | null;
1591
+ payload: Record<string, unknown> | null;
1592
+ origin: { ip?: string; 'user-agent'?: string } | null;
1593
+ created_at: number; // Unix seconds
1594
+ subject: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
1595
+ object: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
1596
+ account_id: string;
1597
+ };
1598
+ ```
1599
+
1600
+ Event-specific values are:
1601
+
1602
+ | `event` | `subject.type` | `object.type` | `payload` keys |
1603
+ | --- | --- | --- | --- |
1604
+ | `document_uploaded` | `User` | `Document` | — |
1605
+ | `document_metadata_ready` | `User` | `Document` | — |
1606
+ | `document_prepared` | `User` | `Document` | — |
1607
+ | `assignment_created` | `User` | `Document` | `user_name`, `user_email`, `user_telephone` |
1608
+ | `document_ready` | `Account` | `Document` | — |
1609
+ | `document_processing_failed` | `Account` | `Document` | `error_message` |
1610
+ | `signature_requested` | `User` | `Document` | `signer_email`, `signer_full_name`, or `signer_whatsapp_phone_number`, according to channel |
1611
+ | `signer_created` | `User` | `Signer` | `signer_full_name` |
1612
+ | `signer_email_verified` | `Signer` | `Document` | `signer_email` |
1613
+ | `signer_whatsapp_verified` | `Signer` | `Document` | `signer_whatsapp_phone_number` |
1614
+ | `signer_data_confirmed` | `Signer` | `Document` | `signer_email` |
1615
+ | `signer_viewed_document` | `Signer` | `Document` | `signer_full_name` |
1616
+ | `signer_identity_verified` | `Signer` | `Document` | `signer_full_name`, `evidence` when available |
1617
+ | `signer_identity_verification_failed` | `Signer` | `Document` | `signer_full_name`, `reason` |
1618
+ | `signer_identity_review_required` | `Signer` | `Document` | `signer_full_name`, `reason_codes` |
1619
+ | `signer_identity_review_approved` | `Signer` | `Document` | `signer_full_name`, `reviewer_id`, `reviewer_name`, `reason_codes` |
1620
+ | `signer_identity_review_rejected` | `Signer` | `Document` | `signer_full_name`, `reviewer_id`, `reviewer_name`, `note` |
1621
+ | `signer_signed_document` | `Signer` | `Document` | `signer_full_name` |
1622
+ | `signer_rejected_document` | `Signer` | `Document` | `signer_full_name` |
1623
+ | `user_rejected_document` | `User` | `Document` | `user_name` |
1624
+ | `template_created` | `User` | `Template` | — |
1625
+ | `template_processed` | `User` | `Template` | — |
1626
+ | `template_processing_failed` | `Account` | `Template` | `error_message` |
1627
+
1628
+ `payload`, `subject`, and `object` are event-dependent. Accept unknown fields
1629
+ for forward compatibility and acknowledge only after durable, idempotent
1630
+ processing. Non-`2xx` responses, timeouts, and connection failures all count as
1631
+ failed deliveries. `assignment_created` and `document_metadata_ready` have no
1632
+ guaranteed ordering. For account entities, Assinafy removes the `integration`
1633
+ property before delivery.
1634
+
1635
+ ### Webhook verification
1636
+
1637
+ With `signing_enabled: true`, every delivery is signed following
1638
+ [Standard Webhooks](https://www.standardwebhooks.com): HMAC-SHA256 over
1639
+ `{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64 value after
1640
+ the `whsec_` prefix. `verifySignature()` compares in constant time and rejects a
1641
+ `webhook-timestamp` more than 5 minutes from the local clock. Pass the **raw**
1642
+ body, never re-serialized JSON.
1643
+
1644
+ ```ts
1645
+ import express from 'express';
1646
+
1647
+ const webhookClient = new AssinafyClient({
1648
+ webhookSecret: process.env.ASSINAFY_WEBHOOK_SECRET, // 'whsec_…' from getEndpointSecret()
1649
+ });
1650
+
1651
+ app.post('/webhooks/assinafy', express.raw({ type: 'application/json' }), (req, res) => {
1652
+ const rawBody = req.body as Buffer;
1653
+ if (!webhookClient.webhookVerifier.verifySignature(rawBody, req.headers)) {
1654
+ return res.status(401).send('Invalid signature');
1655
+ }
1656
+
1657
+ const event = webhookClient.webhookVerifier.extractEvent(rawBody);
1658
+ const type = webhookClient.webhookVerifier.getEventType(event);
1659
+ const data = webhookClient.webhookVerifier.getEventData(event);
1660
+ // Deduplicate on req.headers['webhook-id'] before processing.
1661
+
1662
+ switch (type) {
1663
+ case 'document_ready': break;
1664
+ case 'signer_signed_document': break;
1665
+ case 'signer_rejected_document': break;
1666
+ case 'document_processing_failed': break;
1667
+ }
1668
+ res.sendStatus(200);
1669
+ });
1670
+ ```
1671
+
1672
+ On Fetch runtimes (`Request`), pass `await request.text()` and
1673
+ `request.headers`. The clock tolerance is the optional third argument, in
1674
+ seconds. After `rotateEndpointSecret()`, update the receiver's secret at once.
1675
+
1676
+ ### Signer-side endpoints
1677
+
1678
+ For building custom signer portals. Every call takes the `signer-access-code`
1679
+ that Assinafy emails/whatsapps to the signer, on a transport that never carries
1680
+ the workspace credentials. A code closes 30 minutes after its signer is done;
1681
+ reads then return only the signer's status and every other route answers `410`.
1682
+ An envelope code opens each of the envelope's documents.
1683
+
1684
+ ```ts
1685
+ await client.signerDocuments.self(accessCode);
1686
+ await client.signerDocuments.verifyEmail({ signerAccessCode: accessCode, verificationCode: '123456' });
1687
+
1688
+ await client.signerDocuments.getCurrent(signerId, accessCode, { expand: ['envelope'] });
1689
+ const { data } = await client.signerDocuments.list(signerId, accessCode, { envelope_id, 'per-page': 20 });
1690
+ // Signer-side counterpart of documents.search(), authorised by the access code.
1691
+ const found = await client.signerDocuments.search(signerId, accessCode, 'invoice');
1692
+ // Only the original; an unusable code redirects, which the SDK reports as ApiError 302.
1693
+ await client.signerDocuments.download(signerId, documentId, 'original', accessCode);
1694
+
1695
+ // The contact the signer's channel needs (it must be theirs) and the terms:
1696
+ await client.signerDocuments.confirmData(documentId, accessCode, {
1697
+ email: 'me@example.com',
1698
+ has_accepted_terms: true,
1699
+ }); // null on production
1700
+ // Alternatively, accept terms separately before getAssignment():
1701
+ // await client.signerDocuments.acceptTerms(accessCode); // { full_name, email, has_accepted_terms }
1702
+
1703
+ // Branding for every screen, also before verification and after deletion
1704
+ const theme = await client.signerDocuments.getTheme(accessCode); // { account_name, primary_color, secondary_color, logo }
1705
+ const logo = await client.signerDocuments.downloadLogo(accessCode); // Buffer; 404 without a logo
1706
+
1707
+ // The certified copy is never downloaded with the code; it is sent to the signer.
1708
+ // signable.certified_copy → { available, notification_method, resends_left }
1709
+ await client.signerDocuments.resendCertifiedCopy(accessCode); // { available, notification_method, resends_left, sent_to }
1710
+ // From the link in that message (token = its last path segment):
1711
+ const certified = await client.signerDocuments.downloadCertifiedCopy(token); // 302 → ApiError when expired
1712
+ await client.signerDocuments.resendCertifiedCopyFromLink(token);
1713
+
1714
+ // Signature image management ({ reuse: true } persists it for future documents)
1715
+ await client.signerDocuments.uploadSignature(accessCode, pngBuffer, { imageType: 'signature', reuse: true });
1716
+ await client.signerDocuments.downloadSignature(accessCode, 'signature');
1717
+
1718
+ // Sign / decline (records a view; an envelope code may name another of its documents)
1719
+ const signable = await client.signerDocuments.getAssignment(accessCode, { documentId });
1720
+ // `sign()` is for collect assignments and requires every placed field value.
1721
+ await client.signerDocuments.sign(documentId, assignmentId, accessCode, [
1722
+ { itemId, fieldId, pageId, value: 'Signed by the signer' },
1723
+ ]);
1724
+ await client.signerDocuments.decline(documentId, assignmentId, accessCode, 'Not authorized');
1725
+
1726
+ // `signMultiple()` is for virtual assignments only.
1727
+ await client.signerDocuments.signMultiple(['doc-1', 'doc-2'], accessCode);
1728
+ await client.signerDocuments.declineMultiple(['doc-1'], 'Unfavorable terms', accessCode);
1729
+ ```
1730
+
1731
+ `sign()` also requires virtual signers to have confirmed their data first, but
1732
+ virtual assignments should normally use `signMultiple()`. Certificate signers
1733
+ cannot use `sign()`; see [Paid signing branches](#paid-signing-branches).
1734
+
1735
+ ## High-level helper
1736
+
1737
+ Uploads a PDF, reuses or creates signers by email, creates a virtual assignment
1738
+ immediately, and optionally waits for processing before returning.
1739
+
1740
+ ```ts
1741
+ const result = await client.uploadAndRequestSignatures({
1742
+ source: { filePath: './contract.pdf' },
1743
+ signers: [
1744
+ { name: 'Example Signer A', email: 'signer-a@example.com' },
1745
+ { name: 'Example Signer B', email: 'signer-b@example.com' },
1746
+ ],
1747
+ message: 'Please sign',
1748
+ metadata: { year: 2026 }, // compatibility upload part; omit for file-only wire format
1749
+ waitForReady: true,
1750
+ waitOptions: { maxWaitMs: 30_000, pollIntervalMs: 1_000 },
1751
+ expiresAt: '2027-12-31T00:00:00Z',
1752
+ copyReceivers: ['existing-copy-recipient-signer-id'],
1753
+ });
1754
+
1755
+ result.document; // fully-processed IDocumentDetailsResponse (waitForReady: true, the default);
1756
+ // the raw IDocumentUploadResponse when waitForReady: false
1757
+ result.assignment; // IAssignment
1758
+ result.signer_ids; // string[]
1759
+ ```
1760
+
1761
+ `waitForReady: false` skips post-assignment polling and returns the initial
1762
+ upload response. With the default `true`, the helper creates the assignment first and
1763
+ then waits for the current document details. Both production and sandbox allow
1764
+ virtual assignments in `uploaded` and `metadata_processing` and promote them
1765
+ automatically; only `collect` assignments require rendered pages.
1766
+ Every signer above uses the default email channel. A phone-only signer selects
1767
+ the paid WhatsApp branch described earlier. `copyReceivers` accepts existing
1768
+ signer IDs, not email addresses; check the returned assignment before treating
1769
+ a copy receiver as registered.
1770
+
1771
+ The helper is not transactional. A post-assignment polling error includes the
1772
+ created `documentId`, `assignmentId`, and `signerIds` in its `context` (and in
1773
+ `ValidationError.errors` for timeouts); inspect those IDs before deciding
1774
+ whether to retry the workflow.
1775
+
1776
+ ## Errors
1777
+
1778
+ HTTP methods reject with an `AssinafyError` subclass. Synchronous helpers such
1779
+ as `getSocialLoginUrl()` and `readAuthorizationCallback()` can throw
1780
+ `ValidationError` before any request.
1781
+
1782
+ ```ts
1783
+ import { ApiError, OAuthError, ValidationError, NetworkError, AssinafyError } from '@assinafy/sdk';
1784
+
1785
+ try {
1786
+ await client.documents.upload({ filePath: './x.pdf' });
1787
+ } catch (err) {
1788
+ if (err instanceof ValidationError) {
1789
+ console.error('Validation failed:', err.errors);
1790
+ } else if (err instanceof OAuthError) {
1791
+ // OAuthError extends ApiError; branch on the RFC 6749 code, not the message.
1792
+ console.error('OAuth error:', err.error, err.errorDescription);
1793
+ } else if (err instanceof ApiError) {
1794
+ console.error(`API error ${err.statusCode}:`, err.code, err.fieldErrors);
1795
+ // `err.code` names refusals you can act on ('PlanRestricted', 'CreditCeilingExceeded',
1796
+ // 'IdempotencyKeyInUse', 'EnvelopeOpen', …); `err.fieldErrors` lists each refused
1797
+ // field of a 400 as { field, code, message }. `err.challenge` carries the parsed
1798
+ // WWW-Authenticate header — on a 403 it names the OAuth scope that is missing.
1799
+ } else if (err instanceof NetworkError) {
1800
+ console.error('Network error:', err.message);
1801
+ } else if (err instanceof AssinafyError) {
1802
+ console.error('SDK error:', err.message, err.context);
1803
+ }
1804
+ }
1805
+ ```
1806
+
1807
+ `err.challenge` is an already-parsed `IAuthenticateChallenge`. The parser used
1808
+ internally is exported as `parseWwwAuthenticate()`, for reading the
1809
+ `WWW-Authenticate` header of responses received outside the SDK.
1810
+
1811
+ ## Environments
1812
+
1813
+ | | |
1814
+ | --- | --- |
1815
+ | Production | `https://api.assinafy.com.br/v1` |
1816
+ | Sandbox | `https://sandbox.assinafy.com.br/v1` |
1817
+
1818
+ The sandbox runs its own authorization server at
1819
+ `https://auth-sandbox.assinafy.com.br`, with the consent screen at
1820
+ `/oauth/authorize`. Discovery is available and selects that server from the
1821
+ configured `baseUrl`:
1822
+
1823
+ ```ts
1824
+ const client = new AssinafyClient({ baseUrl: 'https://sandbox.assinafy.com.br/v1' });
1825
+ const metadata = await client.oauth.getAuthorizationServerMetadata();
1826
+ const request = await client.oauth.createAuthorizationUrl({
1827
+ clientId: process.env.ASSINAFY_CLIENT_ID!,
1828
+ redirectUri: 'https://myapp.example.com/oauth/callback',
1829
+ scopes: ['documents:read', 'account:read', 'offline_access'],
1830
+ });
1831
+ ```
1832
+
1833
+ Register the application in the matching environment. Production and sandbox
1834
+ have separate issuers, client IDs, credentials and workspaces; keep each
1835
+ connection entirely in one environment. Token, revocation and userinfo requests
1836
+ use the configured `baseUrl`. For local testing, expose only the callback
1837
+ through an HTTPS tunnel, register its exact URL and revoke tokens afterward.
1838
+ See [COMPATIBILITY.md](COMPATIBILITY.md).
1839
+
1840
+ ## Development
1841
+
1842
+ ```bash
1843
+ bun install --frozen-lockfile
1844
+ bun run typecheck # source, script, and test type checks
1845
+ bun run lint
1846
+ bun test # bun:test suites
1847
+ bun run test:coverage
1848
+ bun run build # tsup → dist/ (CJS + ESM + .d.ts)
1849
+ bun run lint:pkg # publint + arethetypeswrong
1850
+ bun run verify # complete local release gate
1851
+ ```
1852
+
1853
+ ## Documentation
1854
+
1855
+ - **[README.md](README.md)** — the same complete reference in Portuguese
1856
+ - [API_COVERAGE.md](API_COVERAGE.md) — operation map
1857
+ - [COMPATIBILITY.md](COMPATIBILITY.md) — per-deployment request and response variants
1858
+ - [RELEASING.md](RELEASING.md) — publishing process
1859
+ - [API documentation](https://api.assinafy.com.br/v1/docs)
1860
+
1861
+ ## License
1862
+
1863
+ MIT