@assinafy/sdk 2.11.0 → 3.0.1

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