@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.
- package/CHANGELOG.md +126 -1
- package/README.en.md +89 -1649
- package/README.md +87 -1607
- package/dist/index.d.mts +1646 -340
- package/dist/index.d.ts +1646 -340
- package/dist/index.js +1740 -311
- package/dist/index.mjs +1738 -311
- package/docs/API_COVERAGE.md +67 -20
- package/docs/COMPATIBILITY.md +127 -64
- package/docs/README.en.md +1863 -0
- package/docs/README.md +1818 -0
- package/docs/RELEASING.md +1 -1
- package/package.json +3 -2
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)
|
|
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
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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+
|
|
57
|
-
|
|
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,1644 +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
|
-
{
|
|
94
|
-
|
|
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(
|
|
100
|
-
console.log('Assignment ID:', result.assignment.id);
|
|
47
|
+
console.log(result.document.id, result.assignment.id);
|
|
101
48
|
```
|
|
102
49
|
|
|
103
|
-
|
|
104
|
-
|
|
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
|
-
|
|
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
|
-
| `
|
|
234
|
-
| `
|
|
235
|
-
|
|
|
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
|
|
327
|
-
|
|
328
|
-
```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
|
-
await client.assignments.resetExpiration(documentId, assignmentId, null);
|
|
994
|
-
|
|
995
|
-
await client.assignments.resendNotification(documentId, assignmentId, signerId);
|
|
996
|
-
// → { is_sent: true, document_id: '…', signer_id: '…' }
|
|
997
|
-
|
|
998
|
-
const resendCost = await client.assignments.estimateResendCost(documentId, assignmentId, signerId);
|
|
999
|
-
// Official response: ICostEstimate. Older deployments can return the compact
|
|
1000
|
-
// IResendCostEstimate branch with `total` and `has_sufficient_credits`; narrow
|
|
1001
|
-
// with `'total_credits' in resendCost` before reading branch-specific fields.
|
|
1002
|
-
```
|
|
1003
|
-
|
|
1004
|
-
The `create` response is an `IAssignment`: `{ id, method, signers: [...],
|
|
1005
|
-
items: [{ display_settings, ... }], signing_urls: [{ signer_id, url }], … }`.
|
|
1006
|
-
|
|
1007
|
-
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.
|
|
1008
|
-
|
|
1009
|
-
**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:
|
|
1010
|
-
|
|
1011
|
-
```ts
|
|
1012
|
-
await client.documents.delete(documentId); // workspace-side
|
|
1013
|
-
await client.signerDocuments.decline(documentId, assignmentId, accessCode, 'No longer needed'); // signer-side
|
|
1014
|
-
```
|
|
1015
|
-
|
|
1016
|
-
### Paid signing branches
|
|
1017
|
-
|
|
1018
|
-
Keep the email flow as the default. Enable either branch below only after the
|
|
1019
|
-
workspace has the required plan or feature and the returned cost estimate is
|
|
1020
|
-
acceptable.
|
|
1021
|
-
|
|
1022
|
-
The verification method and the notification method are **coupled**: send one,
|
|
1023
|
-
both, or neither — the missing side is inferred. With neither, both default
|
|
1024
|
-
to `Email`.
|
|
1025
|
-
|
|
1026
|
-
| Verification | How the signer proves who they are | Allowed notification | Cost per signer |
|
|
1027
|
-
| --- | --- | --- | --- |
|
|
1028
|
-
| `Email` *(default)* | One-time code (OTP) by email | `Email` | Free |
|
|
1029
|
-
| `Whatsapp` | One-time code (OTP) by WhatsApp | `Whatsapp` | 0.45 credit (the notification), paid plans only |
|
|
1030
|
-
| `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 |
|
|
1031
|
-
| `IdDocumentFaceMatchBasic` | Hosted identity-document, face and liveness verification | `Email` **or** `Whatsapp` | Use `estimateCost()` |
|
|
1032
|
-
|
|
1033
|
-
Exactly one notification method per signer. The SDK rejects an invalid
|
|
1034
|
-
combination before the request; the API would answer `400`.
|
|
1035
|
-
|
|
1036
|
-
#### WhatsApp verification and notification
|
|
1037
|
-
|
|
1038
|
-
WhatsApp is available only on paid subscriptions and costs 0.45 credit per
|
|
1039
|
-
notification. Create a phone-only signer or add a phone to an existing signer,
|
|
1040
|
-
then request the `Whatsapp` channel explicitly:
|
|
1041
|
-
|
|
1042
|
-
```ts
|
|
1043
|
-
const phoneSigner = await client.signers.create({
|
|
1044
|
-
full_name: 'Mobile Signer',
|
|
1045
|
-
whatsapp_phone_number: '+5511999990000',
|
|
1046
|
-
});
|
|
1047
|
-
|
|
1048
|
-
const whatsappCost = await client.assignments.estimateCost(documentId, {
|
|
1049
|
-
method: 'virtual',
|
|
1050
|
-
signers: [{ verification_method: 'Whatsapp', notification_methods: ['Whatsapp'] }],
|
|
1051
|
-
});
|
|
1052
|
-
|
|
1053
|
-
const whatsappAssignment = await client.assignments.create(documentId, {
|
|
1054
|
-
method: 'virtual',
|
|
1055
|
-
signers: [{
|
|
1056
|
-
id: phoneSigner.id,
|
|
1057
|
-
verification_method: 'Whatsapp',
|
|
1058
|
-
notification_methods: ['Whatsapp'],
|
|
1059
|
-
}],
|
|
1060
|
-
});
|
|
1061
|
-
|
|
1062
|
-
const notices = await client.assignments.listWhatsAppNotifications(
|
|
1063
|
-
documentId,
|
|
1064
|
-
whatsappAssignment.id,
|
|
1065
|
-
);
|
|
1066
|
-
// IWhatsAppNotification[]:
|
|
1067
|
-
// [{ sent_at, header, body, buttons: [{ text, url? }], phone_number, signer_id }]
|
|
1068
|
-
```
|
|
1069
|
-
|
|
1070
|
-
The high-level helper selects this paid branch for a signer that has a phone
|
|
1071
|
-
number but no email. Button URLs can contain signer credentials; do not log or
|
|
1072
|
-
forward them outside the signing flow.
|
|
1073
|
-
|
|
1074
|
-
#### ICP-Brasil digital certificate
|
|
1075
|
-
|
|
1076
|
-
`DigitalCertificate` requires `method: 'virtual'`, the account feature, a CPF
|
|
1077
|
-
or CNPJ in the signer's `government_id`, and exactly one certificate signer in
|
|
1078
|
-
that signing step. It costs 0.5 credits per certificate signer in addition to
|
|
1079
|
-
the selected notification cost. A certificate flow completes the signer's
|
|
1080
|
-
virtual item; it cannot submit placed fields through the ordinary `collect`
|
|
1081
|
-
signing endpoint.
|
|
1082
|
-
|
|
1083
|
-
The SDK rejects certificate signers on a `collect` assignment in both
|
|
1084
|
-
`create()` and `estimateCost()` before any request. Branch on
|
|
1085
|
-
`ValidationError.errors.code ===
|
|
1086
|
-
'digital_certificate_requires_virtual_method'`, or compare it with the
|
|
1087
|
-
exported `DIGITAL_CERTIFICATE_REQUIRES_VIRTUAL_METHOD` constant; do not match
|
|
1088
|
-
the human-readable message.
|
|
1089
|
-
|
|
1090
|
-
**A1 and A3 are certificate media**, chosen by the signer in their browser at
|
|
1091
|
-
signing time: A1 lives in software (a file on the machine) and A3 in hardware
|
|
1092
|
-
(a token or smartcard). The API models both with the single
|
|
1093
|
-
`DigitalCertificate` value — there is no `A1`/`A3` field to send, and the
|
|
1094
|
-
resulting PAdES signature is qualified in either case. Certificate signers
|
|
1095
|
-
complete a Web PKI handshake on two production-only routes that are not part
|
|
1096
|
-
of this SDK.
|
|
1097
|
-
|
|
1098
|
-
```ts
|
|
1099
|
-
const certificateSigner = await client.signers.update(signerId, {
|
|
1100
|
-
government_id: '390.533.447-05',
|
|
1101
|
-
});
|
|
1102
|
-
|
|
1103
|
-
const certificateCost = await client.assignments.estimateCost(documentId, {
|
|
1104
|
-
method: 'virtual',
|
|
1105
|
-
signers: [{ verification_method: 'DigitalCertificate', notification_methods: ['Email'] }],
|
|
1106
|
-
});
|
|
1107
|
-
|
|
1108
|
-
await client.assignments.create(documentId, {
|
|
1109
|
-
method: 'virtual',
|
|
1110
|
-
signers: [{
|
|
1111
|
-
id: certificateSigner.id,
|
|
1112
|
-
step: 1,
|
|
1113
|
-
verification_method: 'DigitalCertificate',
|
|
1114
|
-
notification_methods: ['Email'],
|
|
1115
|
-
}],
|
|
1116
|
-
});
|
|
1117
|
-
```
|
|
1118
|
-
|
|
1119
|
-
Before opening the assignment, the signer must confirm identity data and accept
|
|
1120
|
-
terms with `confirmData(..., { has_accepted_terms: true })` or `acceptTerms()`.
|
|
1121
|
-
The regular `sign()` endpoint rejects certificate signers; they complete the
|
|
1122
|
-
ICP-Brasil flow through Assinafy's browser integration. After completion,
|
|
1123
|
-
`documents.download(documentId, 'pades')` returns the qualified PAdES artifact.
|
|
1124
|
-
|
|
1125
|
-
### Templates
|
|
1126
|
-
|
|
1127
|
-
`templates.list()` is part of the current OpenAPI document. Existing
|
|
1128
|
-
integrations can also use five template-management routes—`create`, `get`,
|
|
1129
|
-
`update`, `delete`, and `downloadPage`—that are absent from that document. See
|
|
1130
|
-
[compatibility notes](docs/COMPATIBILITY.md#template-management-extensions).
|
|
1131
|
-
Template status casing can vary by deployment; normalize with
|
|
1132
|
-
`template.status.toLowerCase()` when branching on it.
|
|
1133
|
-
|
|
1134
|
-
```ts
|
|
1135
|
-
// Create a template by uploading a PDF (multipart). The template starts in
|
|
1136
|
-
// an uploaded state and becomes ready once its pages are processed.
|
|
1137
|
-
const created = await client.templates.create(
|
|
1138
|
-
{ filePath: './nda.pdf' }, // or { buffer, fileName: 'nda.pdf' }
|
|
1139
|
-
{ name: 'NDA template' },
|
|
1140
|
-
);
|
|
1141
|
-
// →
|
|
1142
|
-
// {
|
|
1143
|
-
// resource: 'template', id: '1032...', name: 'nda.pdf',
|
|
1144
|
-
// document_name: 'nda.pdf', message: null, status: 'Uploaded',
|
|
1145
|
-
// roles: [{ id: '1032...', name: 'TemplateEditor', assignment_type: 'Editor' }],
|
|
1146
|
-
// pages: [], tags: [], created_at: '2026-…', updated_at: '2026-…'
|
|
1147
|
-
// }
|
|
1148
|
-
|
|
1149
|
-
const { data, meta } = await client.templates.list({ search: 'NDA', 'per-page': 20 });
|
|
1150
|
-
const template = await client.templates.get(created.id); // includes pages[] + default_document_tags
|
|
1151
|
-
await client.templates.update(created.id, { name: 'NDA v2', message: 'Please sign' });
|
|
1152
|
-
const firstPage = template.pages?.[0];
|
|
1153
|
-
if (firstPage) await client.templates.downloadPage(created.id, firstPage.id); // → Buffer (JPEG)
|
|
1154
|
-
await client.templates.delete(created.id);
|
|
1155
|
-
|
|
1156
|
-
// Create a document from an existing, configured template. Fresh uploads have
|
|
1157
|
-
// only an Editor role; add signer roles in Assinafy's editor first.
|
|
1158
|
-
const configured = await client.templates.get(templateId);
|
|
1159
|
-
const signerRole = configured.roles?.find(
|
|
1160
|
-
(role) => typeof role.assignment_type === 'string'
|
|
1161
|
-
&& role.assignment_type.toLowerCase() !== 'editor',
|
|
1162
|
-
);
|
|
1163
|
-
if (!signerRole) throw new Error('Template has no signer role');
|
|
1164
|
-
await client.documents.createFromTemplate(
|
|
1165
|
-
templateId,
|
|
1166
|
-
[{ role_id: signerRole.id, id: signerId, verification_method: 'Email', notification_methods: ['Email'] }],
|
|
1167
|
-
{ name: 'NDA - John Doe', message: 'Please sign at your earliest convenience.' },
|
|
1168
|
-
);
|
|
1169
|
-
|
|
1170
|
-
// Estimate the cost before creating → ICostEstimate
|
|
1171
|
-
await client.documents.estimateCostFromTemplate(templateId, [
|
|
1172
|
-
{ role_id: 'role_id', verification_method: 'Email', notification_methods: ['Email'] },
|
|
1173
|
-
]);
|
|
1174
|
-
// → { documents: 1, total_credits: 0, document_balance: 67, credit_balance: 0,
|
|
1175
|
-
// has_sufficient_resources: true, blocking_reason: null, breakdown: [], … }
|
|
1176
|
-
```
|
|
1177
|
-
|
|
1178
|
-
The server derives a template assignment's method from its placed fields, and
|
|
1179
|
-
currently accepts certificate signers even when that produces an unusable
|
|
1180
|
-
`collect` assignment. Until the API enforces the virtual-only rule atomically,
|
|
1181
|
-
the SDK rejects `DigitalCertificate` in both `createFromTemplate()` and
|
|
1182
|
-
`estimateCostFromTemplate()` with the same stable validation code. Create a
|
|
1183
|
-
direct `virtual` assignment for certificate signers instead.
|
|
1184
|
-
|
|
1185
|
-
Template creation only uploads the PDF and provisions the default editor role —
|
|
1186
|
-
configure roles/fields in the Assinafy editor (or the web UI) afterwards.
|
|
1187
|
-
The `download_url` values in template page objects are protected URLs; prefer
|
|
1188
|
-
`templates.downloadPage()` so the API credential is attached.
|
|
1189
|
-
|
|
1190
|
-
### Tags
|
|
1191
|
-
|
|
1192
|
-
Workspace-scoped labels that can be attached to documents and templates. Tag names are unique per workspace (case-insensitive).
|
|
1193
|
-
|
|
1194
|
-
```ts
|
|
1195
|
-
await client.tags.list({ search: 'contract' }); // ITag[]
|
|
1196
|
-
const tag = await client.tags.create({ name: 'Contracts', color: 'ff8800' });
|
|
1197
|
-
await client.tags.update(tag.id, { name: 'Sales Contracts' });
|
|
1198
|
-
await client.tags.update(tag.id, { color: null }); // clear the color
|
|
1199
|
-
await client.tags.delete(tag.id); // 409 if still attached
|
|
1200
|
-
await client.tags.delete(tag.id, { force: true }); // detach everywhere, then delete
|
|
1201
|
-
```
|
|
1202
|
-
|
|
1203
|
-
Attach/detach tags on a specific document via `client.documents.listTags / replaceTags / addTags / detachTag` (see [Documents](#documents)).
|
|
1204
|
-
|
|
1205
|
-
The published attachment contract takes tag IDs. Older sandbox deployments
|
|
1206
|
-
instead interpret strings as names and create ID-named tags for ID inputs;
|
|
1207
|
-
pass existing names intentionally there. See [document tag compatibility](docs/COMPATIBILITY.md#document-tags).
|
|
1208
|
-
|
|
1209
|
-
### Workspaces
|
|
1210
|
-
|
|
1211
|
-
The official create/update request schemas define `name` and
|
|
1212
|
-
`notification_sender_type`. The sandbox also accepts the color fields shown
|
|
1213
|
-
below; they are retained as a documented compatibility extension.
|
|
1214
|
-
|
|
1215
|
-
```ts
|
|
1216
|
-
// Colours are 6-char hex WITHOUT a leading '#' (unlike tags, which strip it).
|
|
1217
|
-
// '#ff0066' is rejected — the account endpoints want exactly 6 characters.
|
|
1218
|
-
await client.workspaces.create({
|
|
1219
|
-
name: 'My Workspace',
|
|
1220
|
-
notification_sender_type: 'Account',
|
|
1221
|
-
primary_color: 'ff0066',
|
|
1222
|
-
secondary_color: '0066ff',
|
|
1223
|
-
});
|
|
1224
|
-
// → { id, name, primary_color: 'ff0066', secondary_color: '0066ff', created_at }
|
|
1225
|
-
await client.workspaces.list();
|
|
1226
|
-
await client.workspaces.get(accountId);
|
|
1227
|
-
await client.workspaces.update(accountId, {
|
|
1228
|
-
name: 'Renamed',
|
|
1229
|
-
notification_sender_type: 'User',
|
|
1230
|
-
primary_color: '112233',
|
|
1231
|
-
});
|
|
1232
|
-
|
|
1233
|
-
// Branding
|
|
1234
|
-
const theme = await client.workspaces.getTheme(accountId);
|
|
1235
|
-
const logo = await client.workspaces.downloadLogo(accountId); // Buffer
|
|
1236
|
-
await client.workspaces.uploadLogo(accountId, { filePath: './logo.png' });
|
|
1237
|
-
await client.workspaces.uploadLogo(accountId, {
|
|
1238
|
-
buffer: logoBuffer,
|
|
1239
|
-
fileName: 'logo.png',
|
|
1240
|
-
contentType: 'image/png',
|
|
1241
|
-
});
|
|
1242
|
-
await client.workspaces.deleteLogo(accountId);
|
|
1243
|
-
|
|
1244
|
-
// Latest 12 months by default; daily statistics require a YYYY-MM month.
|
|
1245
|
-
await client.workspaces.getStats(accountId);
|
|
1246
|
-
await client.workspaces.getStats(accountId, {
|
|
1247
|
-
granularity: 'daily',
|
|
1248
|
-
month: '2026-06',
|
|
1249
|
-
});
|
|
1250
|
-
|
|
1251
|
-
await client.workspaces.delete(accountId);
|
|
1252
|
-
// `force` cancels an active paid subscription as part of account deletion. It
|
|
1253
|
-
// is not a general bypass for unrelated deletion restrictions.
|
|
1254
|
-
await client.workspaces.delete(restrictedAccountId, { force: true });
|
|
1255
|
-
```
|
|
1256
|
-
|
|
1257
|
-
### Field definitions
|
|
1258
|
-
|
|
1259
|
-
Custom field types used by `collect`-method assignments.
|
|
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 |
|
|
1260
60
|
|
|
1261
61
|
```ts
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
await client.fields.update(fieldId, { name: 'Updated Name' });
|
|
1266
|
-
await client.fields.delete(fieldId);
|
|
1267
|
-
|
|
1268
|
-
// Workspace credentials apply; signerAccessCode is an optional legacy query.
|
|
1269
|
-
await client.fields.validate(fieldId, '400.676.228-36', { signerAccessCode });
|
|
1270
|
-
|
|
1271
|
-
// Validate multiple values at once
|
|
1272
|
-
await client.fields.validateMultiple(
|
|
1273
|
-
[
|
|
1274
|
-
{ field_id: 'f1', value: '1111111111111' },
|
|
1275
|
-
{ field_id: 'f2', value: 'value@example.com' },
|
|
1276
|
-
],
|
|
1277
|
-
{ signerAccessCode },
|
|
1278
|
-
);
|
|
1279
|
-
|
|
1280
|
-
// Catalog of every field type the platform recognises
|
|
1281
|
-
await client.fields.listTypes();
|
|
1282
|
-
```
|
|
1283
|
-
|
|
1284
|
-
### Authentication / API key management
|
|
1285
|
-
|
|
1286
|
-
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.
|
|
1287
|
-
|
|
1288
|
-
```ts
|
|
1289
|
-
// Browser OAuth: redirect the user to this URL. The callback helper returns the
|
|
1290
|
-
// Assinafy callback URL for provider configuration; neither follows a redirect.
|
|
1291
|
-
const oauthStart = client.auth.getSocialLoginUrl('google');
|
|
1292
|
-
const oauthCallback = client.auth.getSocialLoginCallbackUrl();
|
|
1293
|
-
|
|
1294
|
-
let session = await client.auth.login('me@example.com', 'pw');
|
|
1295
|
-
// With two-factor authentication on, login returns `mfa_token`; exchange it
|
|
1296
|
-
// within 5 minutes for an authenticator code or a recovery code.
|
|
1297
|
-
if (session.mfa_token) {
|
|
1298
|
-
session = await client.auth.verifyMfa(session.mfa_token, '123456');
|
|
1299
|
-
}
|
|
1300
|
-
const { access_token, user, accounts } = session;
|
|
1301
|
-
await client.auth.socialLogin({ provider: 'google', token: 'google-id-token', has_accepted_terms: true });
|
|
1302
|
-
await client.auth.linkSocialLogin({ provider: 'google', token: 'google-id-token' });
|
|
1303
|
-
|
|
1304
|
-
// Personal API key
|
|
1305
|
-
await client.auth.createApiKey('current-password');
|
|
1306
|
-
await client.auth.getApiKey(); // → { api_key: '****...nBNr' } or null
|
|
1307
|
-
await client.auth.deleteApiKey();
|
|
1308
|
-
|
|
1309
|
-
// Password lifecycle
|
|
1310
|
-
await client.auth.changePassword({ email, password: 'current', new_password: 'next' });
|
|
1311
|
-
await client.auth.requestPasswordReset('me@example.com');
|
|
1312
|
-
await client.auth.resetPassword({ email, token: 'tk', new_password: 'next' });
|
|
1313
|
-
```
|
|
1314
|
-
|
|
1315
|
-
### Authenticated user
|
|
1316
|
-
|
|
1317
|
-
```ts
|
|
1318
|
-
const user = await client.users.getCurrent();
|
|
1319
|
-
// → { id, name, email, telephone, government_id, is_email_verified,
|
|
1320
|
-
// has_accepted_terms, created_at, to_be_deleted_at }
|
|
1321
|
-
|
|
1322
|
-
// Cross-account document funnel, latest 12 monthly periods by default.
|
|
1323
|
-
const monthly = await client.users.getStats();
|
|
1324
|
-
const daily = await client.users.getStats({
|
|
1325
|
-
granularity: 'daily',
|
|
1326
|
-
month: '2026-06',
|
|
1327
|
-
});
|
|
1328
|
-
// Each row includes period, upload/send/certification totals, notification
|
|
1329
|
-
// counts for email/WhatsApp/bypass, verification counts for
|
|
1330
|
-
// email/WhatsApp/bypass/digital-certificate, viewed, and completed counts.
|
|
1331
|
-
|
|
1332
|
-
const preferences = await client.users.getNotificationPreferences();
|
|
1333
|
-
await client.users.updateNotificationPreferences({
|
|
1334
|
-
SignerDeclined: false,
|
|
1335
|
-
DocumentExpired: false,
|
|
1336
|
-
ContractExpiring: true,
|
|
1337
|
-
});
|
|
1338
|
-
// Updates merge: omitted keys keep their current value. Both methods return
|
|
1339
|
-
// the complete thirteen-key notification preference map.
|
|
1340
|
-
```
|
|
1341
|
-
|
|
1342
|
-
#### Two-factor authentication
|
|
1343
|
-
|
|
1344
|
-
Available in production. The TOTP secret and the recovery codes are shown once.
|
|
1345
|
-
|
|
1346
|
-
```ts
|
|
1347
|
-
const enrollment = await client.users.startTotpEnrollment('My phone');
|
|
1348
|
-
// → { id, secret, provisioning_uri } — render provisioning_uri as a QR code
|
|
1349
|
-
const { recovery_codes } = await client.users.confirmTotpEnrollment({
|
|
1350
|
-
id: enrollment.id,
|
|
1351
|
-
code: '123456', // current code from the new device
|
|
1352
|
-
});
|
|
1353
|
-
// From now on every login needs the second factor.
|
|
1354
|
-
|
|
1355
|
-
const { methods, recovery_codes_remaining } = await client.users.getMfa();
|
|
1356
|
-
await client.users.regenerateRecoveryCodes({ password: 'current-password' }); // or { code }
|
|
1357
|
-
await client.users.deleteMfaMethod(methods[0]!.id, { code: '123456' }); // → { is_mfa_enabled }
|
|
1358
|
-
```
|
|
1359
|
-
|
|
1360
|
-
Replacing an already confirmed authenticator also needs `password` or
|
|
1361
|
-
`reauth_code` in `confirmTotpEnrollment()`; first-time enrollment does not.
|
|
1362
|
-
|
|
1363
|
-
### Webhooks
|
|
1364
|
-
|
|
1365
|
-
An account has 1 webhook endpoint, or up to 3 on paid plans. Every active
|
|
1366
|
-
endpoint subscribed to an event receives it independently. OAuth tokens need
|
|
1367
|
-
`account:read` to read endpoints and `webhooks:write` to change them; the
|
|
1368
|
-
creation response includes `secret` when signing is enabled. Store it then,
|
|
1369
|
-
including for OAuth integrations; reading or rotating it later requires an API key.
|
|
1370
|
-
|
|
1371
|
-
```ts
|
|
1372
|
-
const endpoint = await client.webhooks.createEndpoint({
|
|
1373
|
-
name: 'ERP',
|
|
1374
|
-
url: 'https://example.com/webhooks/assinafy',
|
|
1375
|
-
email: 'ops@example.com',
|
|
1376
|
-
events: ['document_ready', 'signer_signed_document', 'signer_rejected_document'],
|
|
1377
|
-
signing_enabled: true, // sign deliveries with Standard Webhooks
|
|
1378
|
-
});
|
|
1379
|
-
// → { id, name, url, email, events, is_active, signing_enabled, created_at, updated_at }
|
|
1380
|
-
|
|
1381
|
-
const secret = endpoint.secret; // 'whsec_…'; store securely at creation
|
|
1382
|
-
await client.webhooks.listEndpoints(); // IWebhookEndpoint[]
|
|
1383
|
-
await client.webhooks.listEndpoints(undefined, { url: endpoint.url }); // exact URL filter
|
|
1384
|
-
await client.webhooks.getEndpoint(endpoint.id);
|
|
1385
|
-
await client.webhooks.updateEndpoint(endpoint.id, { is_active: false }); // only the fields sent
|
|
1386
|
-
await client.webhooks.rotateEndpointSecret(endpoint.id); // the old secret stops at once
|
|
1387
|
-
await client.webhooks.deleteEndpoint(endpoint.id); // frees the plan slot
|
|
1388
|
-
// Alternative when the integration kept only the registered URL:
|
|
1389
|
-
// await client.webhooks.deleteEndpointByUrl(endpoint.url);
|
|
1390
|
-
|
|
1391
|
-
await client.webhooks.listEventTypes();
|
|
1392
|
-
const history = await client.webhooks.listDispatches({
|
|
1393
|
-
endpoint_id: endpoint.id,
|
|
1394
|
-
delivered: false,
|
|
1395
|
-
page: 1,
|
|
1396
|
-
'per-page': 20,
|
|
1397
|
-
}); // { data: IWebhookDispatch[], meta?: PaginationMeta }
|
|
1398
|
-
const retried = await client.webhooks.retryDispatch(dispatchId); // IWebhookDispatch
|
|
1399
|
-
```
|
|
1400
|
-
|
|
1401
|
-
`createEndpoint()` returns `403` once the plan's limit is reached and `400`
|
|
1402
|
-
when another endpoint of the workspace already uses the same `url`. When
|
|
1403
|
-
`events` is omitted or empty, the SDK sends the exported
|
|
1404
|
-
`DEFAULT_WEBHOOK_EVENTS`: `document_ready`, `document_prepared`,
|
|
1405
|
-
`signer_signed_document`, `signer_rejected_document`, and
|
|
1406
|
-
`document_processing_failed`. In
|
|
1407
|
-
`updateEndpoint()`, `signing_enabled: true` generates a secret if there is none
|
|
1408
|
-
and `false` discards it.
|
|
1409
|
-
|
|
1410
|
-
The earlier routes remain and act on the account's oldest endpoint:
|
|
1411
|
-
`register()` (create or update), `get()` (`IWebhookSubscription | null`) and
|
|
1412
|
-
`inactivate()`.
|
|
1413
|
-
|
|
1414
|
-
Assinafy delivers each event as an HTTP `POST` with
|
|
1415
|
-
`Content-Type: application/json`, `Connection: close` and the headers
|
|
1416
|
-
`webhook-id` (identical on every attempt of the same event to the same
|
|
1417
|
-
endpoint — deduplicate on it), `webhook-timestamp` and, with signing on,
|
|
1418
|
-
`webhook-signature`. Any `2xx` is success. There are at most two attempts,
|
|
1419
|
-
three seconds apart. After ten consecutive failed events, ordinary delivery
|
|
1420
|
-
pauses and about 5% of later events are attempted until one succeeds; use
|
|
1421
|
-
`retryDispatch()` for an immediate redelivery. The dispatch history retains only
|
|
1422
|
-
the first 2,000 characters of the receiver's response body.
|
|
1423
|
-
|
|
1424
|
-
Each history or retry result is an `IWebhookDispatch`:
|
|
1425
|
-
|
|
1426
|
-
```ts
|
|
1427
|
-
type WebhookDispatchShape = {
|
|
1428
|
-
resource?: string;
|
|
1429
|
-
id: string;
|
|
1430
|
-
event: string;
|
|
1431
|
-
activity_id: number;
|
|
1432
|
-
endpoint_id?: string | null; // null once the endpoint is deleted
|
|
1433
|
-
endpoint: string | null;
|
|
1434
|
-
payload: IWebhookPayload | Record<string, unknown> | null;
|
|
1435
|
-
delivered: boolean;
|
|
1436
|
-
http_status: number | null;
|
|
1437
|
-
response_body: string | null;
|
|
1438
|
-
error: string | null;
|
|
1439
|
-
created_at: string;
|
|
1440
|
-
updated_at?: string;
|
|
1441
|
-
};
|
|
1442
|
-
```
|
|
1443
|
-
|
|
1444
|
-
Every delivery body uses this envelope:
|
|
1445
|
-
|
|
1446
|
-
```ts
|
|
1447
|
-
type WebhookPayloadShape = {
|
|
1448
|
-
id: number; // use for idempotent processing
|
|
1449
|
-
event: string;
|
|
1450
|
-
message: string | null;
|
|
1451
|
-
payload: Record<string, unknown> | null;
|
|
1452
|
-
origin: { ip?: string; 'user-agent'?: string } | null;
|
|
1453
|
-
created_at: number; // Unix seconds
|
|
1454
|
-
subject: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
|
|
1455
|
-
object: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
|
|
1456
|
-
account_id: string;
|
|
1457
|
-
};
|
|
1458
|
-
```
|
|
1459
|
-
|
|
1460
|
-
Event-specific values are:
|
|
1461
|
-
|
|
1462
|
-
| `event` | `subject.type` | `object.type` | `payload` keys |
|
|
1463
|
-
| --- | --- | --- | --- |
|
|
1464
|
-
| `document_uploaded` | `User` | `Document` | — |
|
|
1465
|
-
| `document_metadata_ready` | `User` | `Document` | — |
|
|
1466
|
-
| `document_prepared` | `User` | `Document` | — |
|
|
1467
|
-
| `assignment_created` | `User` | `Document` | `user_name`, `user_email`, `user_telephone` |
|
|
1468
|
-
| `document_ready` | `Account` | `Document` | — |
|
|
1469
|
-
| `document_processing_failed` | `Account` | `Document` | `error_message` |
|
|
1470
|
-
| `signature_requested` | `User` | `Document` | `signer_email`, `signer_full_name`, or `signer_whatsapp_phone_number`, according to channel |
|
|
1471
|
-
| `signer_created` | `User` | `Signer` | `signer_full_name` |
|
|
1472
|
-
| `signer_email_verified` | `Signer` | `Document` | `signer_email` |
|
|
1473
|
-
| `signer_whatsapp_verified` | `Signer` | `Document` | `signer_whatsapp_phone_number` |
|
|
1474
|
-
| `signer_data_confirmed` | `Signer` | `Document` | `signer_email` |
|
|
1475
|
-
| `signer_viewed_document` | `Signer` | `Document` | `signer_full_name` |
|
|
1476
|
-
| `signer_identity_verified` | `Signer` | `Document` | `signer_full_name`, `evidence` when available |
|
|
1477
|
-
| `signer_identity_verification_failed` | `Signer` | `Document` | `signer_full_name`, `reason` |
|
|
1478
|
-
| `signer_identity_review_required` | `Signer` | `Document` | `signer_full_name`, `reason_codes` |
|
|
1479
|
-
| `signer_identity_review_approved` | `Signer` | `Document` | `signer_full_name`, `reviewer_id`, `reviewer_name`, `reason_codes` |
|
|
1480
|
-
| `signer_identity_review_rejected` | `Signer` | `Document` | `signer_full_name`, `reviewer_id`, `reviewer_name`, `note` |
|
|
1481
|
-
| `signer_signed_document` | `Signer` | `Document` | `signer_full_name` |
|
|
1482
|
-
| `signer_rejected_document` | `Signer` | `Document` | `signer_full_name` |
|
|
1483
|
-
| `user_rejected_document` | `User` | `Document` | `user_name` |
|
|
1484
|
-
| `template_created` | `User` | `Template` | — |
|
|
1485
|
-
| `template_processed` | `User` | `Template` | — |
|
|
1486
|
-
| `template_processing_failed` | `Account` | `Template` | `error_message` |
|
|
1487
|
-
|
|
1488
|
-
`payload`, `subject`, and `object` are event-dependent. Accept unknown fields
|
|
1489
|
-
for forward compatibility and acknowledge only after durable, idempotent
|
|
1490
|
-
processing. Non-`2xx` responses, timeouts, and connection failures all count as
|
|
1491
|
-
failed deliveries. `assignment_created` and `document_metadata_ready` have no
|
|
1492
|
-
guaranteed ordering. For account entities, Assinafy removes the `integration`
|
|
1493
|
-
property before delivery.
|
|
1494
|
-
|
|
1495
|
-
### Webhook verification
|
|
1496
|
-
|
|
1497
|
-
With `signing_enabled: true`, every delivery is signed following
|
|
1498
|
-
[Standard Webhooks](https://www.standardwebhooks.com): HMAC-SHA256 over
|
|
1499
|
-
`{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64 value after
|
|
1500
|
-
the `whsec_` prefix. `verifySignature()` compares in constant time and rejects a
|
|
1501
|
-
`webhook-timestamp` more than 5 minutes from the local clock. Pass the **raw**
|
|
1502
|
-
body, never re-serialized JSON.
|
|
1503
|
-
|
|
1504
|
-
```ts
|
|
1505
|
-
import express from 'express';
|
|
1506
|
-
|
|
1507
|
-
const webhookClient = new AssinafyClient({
|
|
1508
|
-
webhookSecret: process.env.ASSINAFY_WEBHOOK_SECRET, // 'whsec_…' from getEndpointSecret()
|
|
1509
|
-
});
|
|
1510
|
-
|
|
1511
|
-
app.post('/webhooks/assinafy', express.raw({ type: 'application/json' }), (req, res) => {
|
|
1512
|
-
const rawBody = req.body as Buffer;
|
|
1513
|
-
if (!webhookClient.webhookVerifier.verifySignature(rawBody, req.headers)) {
|
|
1514
|
-
return res.status(401).send('Invalid signature');
|
|
1515
|
-
}
|
|
1516
|
-
|
|
1517
|
-
const event = webhookClient.webhookVerifier.extractEvent(rawBody);
|
|
1518
|
-
const type = webhookClient.webhookVerifier.getEventType(event);
|
|
1519
|
-
const data = webhookClient.webhookVerifier.getEventData(event);
|
|
1520
|
-
// Deduplicate on req.headers['webhook-id'] before processing.
|
|
1521
|
-
|
|
1522
|
-
switch (type) {
|
|
1523
|
-
case 'document_ready': break;
|
|
1524
|
-
case 'signer_signed_document': break;
|
|
1525
|
-
case 'signer_rejected_document': break;
|
|
1526
|
-
case 'document_processing_failed': break;
|
|
1527
|
-
}
|
|
1528
|
-
res.sendStatus(200);
|
|
1529
|
-
});
|
|
1530
|
-
```
|
|
1531
|
-
|
|
1532
|
-
On Fetch runtimes (`Request`), pass `await request.text()` and
|
|
1533
|
-
`request.headers`. The clock tolerance is the optional third argument, in
|
|
1534
|
-
seconds. After `rotateEndpointSecret()`, update the receiver's secret at once.
|
|
1535
|
-
|
|
1536
|
-
### Signer-side endpoints
|
|
1537
|
-
|
|
1538
|
-
For building custom signer portals. Most calls require the `signer-access-code`
|
|
1539
|
-
URL parameter that Assinafy emails/whatsapps to the signer. Artifact download is
|
|
1540
|
-
the documented public exception; its optional fourth access-code argument exists
|
|
1541
|
-
only for compatibility with deployments that still expect the legacy query.
|
|
1542
|
-
|
|
1543
|
-
```ts
|
|
1544
|
-
await client.signerDocuments.self(accessCode);
|
|
1545
|
-
await client.signerDocuments.verifyEmail({ signerAccessCode: accessCode, verificationCode: '123456' });
|
|
1546
|
-
|
|
1547
|
-
await client.signerDocuments.getCurrent(signerId, accessCode);
|
|
1548
|
-
const { data } = await client.signerDocuments.list(signerId, accessCode, { 'per-page': 20 });
|
|
1549
|
-
// Signer-side counterpart of documents.search(), authorised by the access code.
|
|
1550
|
-
const found = await client.signerDocuments.search(signerId, accessCode, 'invoice');
|
|
1551
|
-
await client.signerDocuments.download(signerId, documentId, 'original');
|
|
1552
|
-
// Available only after an ICP-Brasil certificate signer completes signing.
|
|
1553
|
-
await client.signerDocuments.download(signerId, documentId, 'pades');
|
|
1554
|
-
|
|
1555
|
-
await client.signerDocuments.confirmData(documentId, accessCode, {
|
|
1556
|
-
email: 'me@example.com',
|
|
1557
|
-
full_name: 'Example Signer',
|
|
1558
|
-
government_id: '123.456.789-00',
|
|
1559
|
-
has_accepted_terms: true,
|
|
62
|
+
const withApiKey = new AssinafyClient({
|
|
63
|
+
apiKey: process.env.ASSINAFY_API_KEY!,
|
|
64
|
+
accountId: process.env.ASSINAFY_ACCOUNT_ID!,
|
|
1560
65
|
});
|
|
1561
|
-
// Alternatively, accept terms separately before getAssignment():
|
|
1562
|
-
// await client.signerDocuments.acceptTerms(accessCode);
|
|
1563
|
-
|
|
1564
|
-
// Signature image management ({ reuse: true } persists it for future documents)
|
|
1565
|
-
await client.signerDocuments.uploadSignature(accessCode, pngBuffer, { imageType: 'signature', reuse: true });
|
|
1566
|
-
await client.signerDocuments.downloadSignature(accessCode, 'signature');
|
|
1567
|
-
|
|
1568
|
-
// Sign / decline
|
|
1569
|
-
const signable = await client.signerDocuments.getAssignment(accessCode);
|
|
1570
|
-
// `sign()` is for collect assignments and requires every placed field value.
|
|
1571
|
-
await client.signerDocuments.sign(documentId, assignmentId, accessCode, [
|
|
1572
|
-
{ itemId, fieldId, pageId, value: 'Signed by John' },
|
|
1573
|
-
]);
|
|
1574
|
-
await client.signerDocuments.decline(documentId, assignmentId, accessCode, 'Not authorized');
|
|
1575
|
-
|
|
1576
|
-
// `signMultiple()` is for virtual assignments only.
|
|
1577
|
-
await client.signerDocuments.signMultiple(['doc-1', 'doc-2'], accessCode);
|
|
1578
|
-
await client.signerDocuments.declineMultiple(['doc-1'], 'Unfavorable terms', accessCode);
|
|
1579
|
-
```
|
|
1580
|
-
|
|
1581
|
-
`sign()` also requires virtual signers to have confirmed their data first, but
|
|
1582
|
-
virtual assignments should normally use `signMultiple()`. Certificate signers
|
|
1583
|
-
cannot use `sign()`; see [Paid signing branches](#paid-signing-branches).
|
|
1584
|
-
|
|
1585
|
-
## High-level helper
|
|
1586
66
|
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
```ts
|
|
1591
|
-
const result = await client.uploadAndRequestSignatures({
|
|
1592
|
-
source: { filePath: './contract.pdf' },
|
|
1593
|
-
signers: [
|
|
1594
|
-
{ name: 'John', email: 'john@example.com' },
|
|
1595
|
-
{ name: 'Jane', email: 'jane@example.com' },
|
|
1596
|
-
],
|
|
1597
|
-
message: 'Please sign',
|
|
1598
|
-
metadata: { year: 2026 }, // compatibility upload part; omit for file-only wire format
|
|
1599
|
-
waitForReady: true,
|
|
1600
|
-
waitOptions: { maxWaitMs: 30_000, pollIntervalMs: 1_000 },
|
|
1601
|
-
expiresAt: '2027-12-31T00:00:00Z',
|
|
1602
|
-
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!,
|
|
1603
70
|
});
|
|
1604
|
-
|
|
1605
|
-
result.document; // fully-processed IDocumentDetailsResponse (waitForReady: true, the default);
|
|
1606
|
-
// the raw IDocumentUploadResponse when waitForReady: false
|
|
1607
|
-
result.assignment; // IAssignment
|
|
1608
|
-
result.signer_ids; // string[]
|
|
1609
71
|
```
|
|
1610
72
|
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
virtual assignments in `uploaded` and `metadata_processing` and promote them
|
|
1615
|
-
automatically; only `collect` assignments require rendered pages.
|
|
1616
|
-
Every signer above uses the default email channel. A phone-only signer selects
|
|
1617
|
-
the paid WhatsApp branch described earlier. `copyReceivers` accepts existing
|
|
1618
|
-
signer IDs, not email addresses; check the returned assignment before treating
|
|
1619
|
-
a copy receiver as registered.
|
|
1620
|
-
|
|
1621
|
-
The helper is not transactional. A post-assignment polling error includes the
|
|
1622
|
-
created `documentId`, `assignmentId`, and `signerIds` in its `context` (and in
|
|
1623
|
-
`ValidationError.errors` for timeouts); inspect those IDs before deciding
|
|
1624
|
-
whether to retry the workflow.
|
|
1625
|
-
|
|
1626
|
-
## Errors
|
|
1627
|
-
|
|
1628
|
-
HTTP methods reject with an `AssinafyError` subclass. Synchronous helpers such
|
|
1629
|
-
as `getSocialLoginUrl()` and `readAuthorizationCallback()` can throw
|
|
1630
|
-
`ValidationError` before any request.
|
|
1631
|
-
|
|
1632
|
-
```ts
|
|
1633
|
-
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.
|
|
1634
76
|
|
|
1635
|
-
|
|
1636
|
-
await client.documents.upload({ filePath: './x.pdf' });
|
|
1637
|
-
} catch (err) {
|
|
1638
|
-
if (err instanceof ValidationError) {
|
|
1639
|
-
console.error('Validation failed:', err.errors);
|
|
1640
|
-
} else if (err instanceof OAuthError) {
|
|
1641
|
-
// OAuthError extends ApiError; branch on the RFC 6749 code, not the message.
|
|
1642
|
-
console.error('OAuth error:', err.error, err.errorDescription);
|
|
1643
|
-
} else if (err instanceof ApiError) {
|
|
1644
|
-
console.error(`API error ${err.statusCode}:`, err.responseData);
|
|
1645
|
-
// `err.challenge` carries the parsed WWW-Authenticate header when the API
|
|
1646
|
-
// sent one — on a 403 it names the OAuth scope that is missing.
|
|
1647
|
-
} else if (err instanceof NetworkError) {
|
|
1648
|
-
console.error('Network error:', err.message);
|
|
1649
|
-
} else if (err instanceof AssinafyError) {
|
|
1650
|
-
console.error('SDK error:', err.message, err.context);
|
|
1651
|
-
}
|
|
1652
|
-
}
|
|
1653
|
-
```
|
|
1654
|
-
|
|
1655
|
-
`err.challenge` is an already-parsed `IAuthenticateChallenge`. The parser used
|
|
1656
|
-
internally is exported as `parseWwwAuthenticate()`, for reading the
|
|
1657
|
-
`WWW-Authenticate` header of responses received outside the SDK.
|
|
1658
|
-
|
|
1659
|
-
## Environments
|
|
77
|
+
## Configuration
|
|
1660
78
|
|
|
1661
|
-
| | |
|
|
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 |
|
|
1662
112
|
| --- | --- |
|
|
1663
|
-
|
|
|
1664
|
-
|
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
`
|
|
1668
|
-
|
|
1669
|
-
|
|
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.
|
|
1670
128
|
|
|
1671
|
-
|
|
1672
|
-
const client = new AssinafyClient({ baseUrl: 'https://sandbox.assinafy.com.br/v1' });
|
|
1673
|
-
const metadata = await client.oauth.getAuthorizationServerMetadata();
|
|
1674
|
-
const request = await client.oauth.createAuthorizationUrl({
|
|
1675
|
-
clientId: process.env.ASSINAFY_CLIENT_ID!,
|
|
1676
|
-
redirectUri: 'https://myapp.example.com/oauth/callback',
|
|
1677
|
-
scopes: ['documents:read', 'account:read', 'offline_access'],
|
|
1678
|
-
});
|
|
1679
|
-
```
|
|
129
|
+
## Documentation
|
|
1680
130
|
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
|
|
1685
|
-
|
|
1686
|
-
|
|
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)
|
|
1687
137
|
|
|
1688
138
|
## Development
|
|
1689
139
|
|
|
1690
140
|
```bash
|
|
1691
141
|
bun install --frozen-lockfile
|
|
1692
|
-
bun run
|
|
1693
|
-
bun run
|
|
1694
|
-
bun
|
|
1695
|
-
bun run test:coverage
|
|
1696
|
-
bun run build # tsup → dist/ (CJS + ESM + .d.ts)
|
|
1697
|
-
bun run lint:pkg # publint + arethetypeswrong
|
|
1698
|
-
bun run verify # complete local release gate
|
|
142
|
+
bun run verify
|
|
143
|
+
bun run audit
|
|
144
|
+
bun run audit:api
|
|
1699
145
|
```
|
|
1700
146
|
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
- **[README.md](README.md)** — a mesma referência completa, em português
|
|
1704
|
-
- [docs/API_COVERAGE.md](docs/API_COVERAGE.md) — operation map
|
|
1705
|
-
- [docs/COMPATIBILITY.md](docs/COMPATIBILITY.md) — per-deployment request and response variants
|
|
1706
|
-
- [docs/RELEASING.md](docs/RELEASING.md) — publishing process
|
|
1707
|
-
- [API documentation](https://api.assinafy.com.br/v1/docs)
|
|
147
|
+
`bun run verify` runs type checks, lint, tests, coverage, build, and package validation.
|
|
1708
148
|
|
|
1709
149
|
## License
|
|
1710
150
|
|
|
1711
|
-
MIT
|
|
151
|
+
Distributed under the [MIT License](LICENSE).
|