@assinafy/sdk 2.5.2 → 2.6.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 CHANGED
@@ -7,6 +7,41 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.6.0] - 2026-10-07
11
+
12
+ ### Added
13
+
14
+ - Multiple webhook endpoints: `webhooks.listEndpoints()`, `createEndpoint()`,
15
+ `getEndpoint()`, `updateEndpoint()` and `deleteEndpoint()`. Accounts have one
16
+ endpoint, or up to three on paid plans.
17
+ - Webhook signatures: `webhooks.getEndpointSecret()` and
18
+ `rotateEndpointSecret()`, and `webhookVerifier.verifySignature()`, which
19
+ verifies the Standard Webhooks `webhook-signature` header with a
20
+ `webhook-timestamp` replay window. Accepts Node/Express header objects and
21
+ Fetch `Headers`.
22
+ - `webhooks.listDispatches()` accepts an `endpoint_id` filter; dispatch records
23
+ carry `endpoint_id`.
24
+ - Two-factor authentication: `auth.verifyMfa()` completes a login that returned
25
+ an `mfa_token`, and `users.getMfa()`, `startTotpEnrollment()`,
26
+ `confirmTotpEnrollment()`, `regenerateRecoveryCodes()` and
27
+ `deleteMfaMethod()` manage authenticator apps and recovery codes.
28
+ - `signers.create()` accepts `government_id`, and signer responses type the
29
+ returned `government_id`.
30
+
31
+ ### Changed
32
+
33
+ - The subscription methods (`webhooks.register()`, `get()`, `inactivate()`)
34
+ are documented as acting on the account's oldest endpoint.
35
+
36
+ ### Deprecated
37
+
38
+ - `webhookVerifier.verify()`; use `verifySignature()`.
39
+
40
+ ### Fixed
41
+
42
+ - Signer `government_id` is sent as given instead of being reduced to digits,
43
+ so alphanumeric CNPJs keep their letters. The API normalizes the formatting.
44
+
10
45
  ## [2.5.2] - 2026-10-05
11
46
 
12
47
  ### Fixed
@@ -705,7 +740,8 @@ signer fields with `cpf` and `whatsapp_phone_number`.
705
740
  - High-level `uploadAndRequestSignatures` helper on `AssinafyClient`.
706
741
  - `PaginatedResult<T>` with parsed `X-Pagination-*` header meta.
707
742
 
708
- [Unreleased]: https://github.com/assinafy/typescript-sdk/compare/v2.5.2...HEAD
743
+ [Unreleased]: https://github.com/assinafy/typescript-sdk/compare/v2.6.0...HEAD
744
+ [2.6.0]: https://github.com/assinafy/typescript-sdk/compare/v2.5.2...v2.6.0
709
745
  [2.5.2]: https://github.com/assinafy/typescript-sdk/compare/v2.5.1...v2.5.2
710
746
  [2.5.1]: https://github.com/assinafy/typescript-sdk/compare/v2.5.0...v2.5.1
711
747
  [2.5.0]: https://github.com/assinafy/typescript-sdk/compare/v2.4.2...v2.5.0
package/README.en.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  TypeScript SDK for the [Assinafy API](https://api.assinafy.com.br/v1/docs) — a Brazilian digital signature platform.
6
6
 
7
- Covers all 93 operations in the current official OpenAPI document: accounts,
7
+ Covers all 106 operations in the current official OpenAPI document: accounts,
8
8
  authentication, OAuth 2.1 applications, users, documents, assignments, signers,
9
9
  signer-side flows, templates, tags, fields, webhooks, branding, statistics, and
10
10
  the high-level `uploadAndRequestSignatures` workflow. Five additional
@@ -232,7 +232,7 @@ await client.oauth.getUserInfo(tokens.access_token); // OIDC claims; needs `open
232
232
  | `templates:read` | Read templates |
233
233
  | `templates:write` | Create and change templates |
234
234
  | `account:read` | Read the workspace's profile, theme and logo |
235
- | `webhooks:write` | Update or inactivate the workspace's webhook subscription |
235
+ | `webhooks:write` | Create, change, deactivate and delete the workspace's webhook endpoints |
236
236
  | `openid` | Receive an `id_token` identifying the user |
237
237
  | `profile` | Read the user's name |
238
238
  | `email` | Read the user's email and whether it is verified |
@@ -300,7 +300,7 @@ anything for them.
300
300
  | `token` | string | — | Access token (sent as `Authorization: Bearer`). |
301
301
  | `accountId` | string | — | Default workspace/account ID. |
302
302
  | `baseUrl` | string | `https://api.assinafy.com.br/v1` | Absolute API base without credentials, query, or fragment. Must be `https` unless the host is loopback. |
303
- | `webhookSecret` | string | — | Opt-in HMAC secret used by `WebhookVerifier`; see its [contract caveat](docs/COMPATIBILITY.md#webhook-signature-verification-is-not-in-the-openapi-contract). |
303
+ | `webhookSecret` | string | — | Webhook endpoint `whsec_…` secret; enables `webhookVerifier.verifySignature()`. |
304
304
  | `timeout` | number | `30000` | Request timeout in milliseconds. |
305
305
  | `maxRetries` | number | `2` | Auto-retries eligible HTTP 429 responses, honoring `Retry-After`. `0` disables. |
306
306
  | `logger` | `Logger` | no-op | Optional `{debug,info,warn,error}` logger. |
@@ -331,7 +331,7 @@ const client = AssinafyClient.fromConfig({
331
331
 
332
332
  ## Endpoint coverage
333
333
 
334
- All 93 operations documented at https://api.assinafy.com.br/v1/docs are
334
+ All 106 operations documented at https://api.assinafy.com.br/v1/docs are
335
335
  covered. The table below is the resource-level summary; the detailed operation
336
336
  ledger is in [docs/API_COVERAGE.md](docs/API_COVERAGE.md).
337
337
 
@@ -343,13 +343,13 @@ ledger is in [docs/API_COVERAGE.md](docs/API_COVERAGE.md).
343
343
  | `client.templates` | **create**, list, get, **update**, **delete**, downloadPage |
344
344
  | `client.tags` | list, create, update, delete |
345
345
  | `client.workspaces` | create, list, get, update, delete, getTheme, downloadLogo, uploadLogo, deleteLogo, getStats |
346
- | `client.webhooks` | register, get, inactivate, listEventTypes, listDispatches, retryDispatch |
346
+ | `client.webhooks` | listEndpoints, createEndpoint, getEndpoint, updateEndpoint, deleteEndpoint, getEndpointSecret, rotateEndpointSecret, register, get, inactivate, listEventTypes, listDispatches, retryDispatch |
347
347
  | `client.fields` | create, list, get, update, delete, validate, validateMultiple, listTypes |
348
348
  | `client.oauth` | **getProtectedResourceMetadata**, **getAuthorizationServerMetadata**, **createAuthorizationUrl**, **readAuthorizationCallback**, **exchangeCode**, **refreshToken**, **revokeToken**, **getUserInfo** |
349
- | `client.auth` | getSocialLoginUrl, getSocialLoginCallbackUrl, login, socialLogin, linkSocialLogin, createApiKey, getApiKey, deleteApiKey, changePassword, requestPasswordReset, resetPassword |
350
- | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences |
349
+ | `client.auth` | getSocialLoginUrl, getSocialLoginCallbackUrl, login, verifyMfa, socialLogin, linkSocialLogin, createApiKey, getApiKey, deleteApiKey, changePassword, requestPasswordReset, resetPassword |
350
+ | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences, getMfa, startTotpEnrollment, confirmTotpEnrollment, regenerateRecoveryCodes, deleteMfaMethod |
351
351
  | `client.signerDocuments` | getCurrent, list, **search**, download, signMultiple, declineMultiple, self, acceptTerms, verifyEmail, confirmData, uploadSignature, downloadSignature, getAssignment, sign, decline |
352
- | `client.webhookVerifier` | verify, extractEvent, getEventType, getEventData |
352
+ | `client.webhookVerifier` | verifySignature, extractEvent, getEventType, getEventData |
353
353
 
354
354
  Every HTTP wrapper has TypeScript-checked request/response shapes and
355
355
  method-level JSDoc covering the wire payload, return shape, validation,
@@ -1082,7 +1082,13 @@ Most server-side integrations should just use `X-Api-Key` directly. Use these en
1082
1082
  const oauthStart = client.auth.getSocialLoginUrl('google');
1083
1083
  const oauthCallback = client.auth.getSocialLoginCallbackUrl();
1084
1084
 
1085
- const { access_token, user, accounts } = await client.auth.login('me@example.com', 'pw');
1085
+ let session = await client.auth.login('me@example.com', 'pw');
1086
+ // With two-factor authentication on, login returns `mfa_token`; exchange it
1087
+ // within 5 minutes for an authenticator code or a recovery code.
1088
+ if (session.mfa_token) {
1089
+ session = await client.auth.verifyMfa(session.mfa_token, '123456');
1090
+ }
1091
+ const { access_token, user, accounts } = session;
1086
1092
  await client.auth.socialLogin({ provider: 'google', token: 'google-id-token', has_accepted_terms: true });
1087
1093
  await client.auth.linkSocialLogin({ provider: 'google', token: 'google-id-token' });
1088
1094
 
@@ -1123,29 +1129,54 @@ await client.users.updateNotificationPreferences({
1123
1129
  // the complete nine-key notification preference map.
1124
1130
  ```
1125
1131
 
1132
+ #### Two-factor authentication
1133
+
1134
+ Available in production. The TOTP secret and the recovery codes are shown once.
1135
+
1136
+ ```ts
1137
+ const enrollment = await client.users.startTotpEnrollment('My phone');
1138
+ // → { id, secret, provisioning_uri } — render provisioning_uri as a QR code
1139
+ const { recovery_codes } = await client.users.confirmTotpEnrollment({
1140
+ id: enrollment.id,
1141
+ code: '123456', // current code from the new device
1142
+ });
1143
+ // From now on every login needs the second factor.
1144
+
1145
+ const { methods, recovery_codes_remaining } = await client.users.getMfa();
1146
+ await client.users.regenerateRecoveryCodes({ password: 'current-password' }); // or { code }
1147
+ await client.users.deleteMfaMethod(methods[0]!.id, { code: '123456' }); // → { is_mfa_enabled }
1148
+ ```
1149
+
1150
+ Replacing an already confirmed authenticator also needs `password` or
1151
+ `reauth_code` in `confirmTotpEnrollment()`; first-time enrollment does not.
1152
+
1126
1153
  ### Webhooks
1127
1154
 
1128
- OAuth tokens need `webhooks:write` for `register()` and `inactivate()`.
1155
+ An account has 1 webhook endpoint, or up to 3 on paid plans. Every active
1156
+ endpoint subscribed to an event receives it independently. OAuth tokens need
1157
+ `account:read` to read endpoints and `webhooks:write` to change them; the
1158
+ signing secret is available only with an API key.
1129
1159
 
1130
1160
  ```ts
1131
- await client.webhooks.register({
1161
+ const endpoint = await client.webhooks.createEndpoint({
1162
+ name: 'ERP',
1132
1163
  url: 'https://example.com/webhooks/assinafy',
1133
- email: 'admin@example.com',
1134
- is_active: true,
1135
- // events defaults to the current SDK default set below
1136
- events: [
1137
- 'document_ready',
1138
- 'document_prepared',
1139
- 'signer_signed_document',
1140
- 'signer_rejected_document',
1141
- 'document_processing_failed',
1142
- ],
1164
+ email: 'ops@example.com',
1165
+ events: ['document_ready', 'signer_signed_document', 'signer_rejected_document'],
1166
+ signing_enabled: true, // sign deliveries with Standard Webhooks
1143
1167
  });
1168
+ // → { id, name, url, email, events, is_active, signing_enabled, created_at, updated_at }
1169
+
1170
+ const { secret } = await client.webhooks.getEndpointSecret(endpoint.id); // 'whsec_…'
1171
+ await client.webhooks.listEndpoints(); // IWebhookEndpoint[]
1172
+ await client.webhooks.getEndpoint(endpoint.id);
1173
+ await client.webhooks.updateEndpoint(endpoint.id, { is_active: false }); // only the fields sent
1174
+ await client.webhooks.rotateEndpointSecret(endpoint.id); // the old secret stops at once
1175
+ await client.webhooks.deleteEndpoint(endpoint.id); // frees the plan slot
1144
1176
 
1145
- await client.webhooks.get(); // IWebhookSubscription | null
1146
- await client.webhooks.inactivate(); // stop deliveries (no delete route exists)
1147
1177
  await client.webhooks.listEventTypes();
1148
1178
  const history = await client.webhooks.listDispatches({
1179
+ endpoint_id: endpoint.id,
1149
1180
  delivered: false,
1150
1181
  page: 1,
1151
1182
  'per-page': 20,
@@ -1153,14 +1184,24 @@ const history = await client.webhooks.listDispatches({
1153
1184
  const retried = await client.webhooks.retryDispatch(dispatchId); // IWebhookDispatch
1154
1185
  ```
1155
1186
 
1156
- `register` sends `{ events, is_active, url, email }` and returns
1157
- `{ events, is_active, url, email, updated_at? }`. Assinafy delivers each event
1158
- as an HTTP `POST` with `Content-Type: application/json` and `Connection: close`.
1159
- Any `2xx` is success. There are at most two automatic attempts, separated by
1160
- three seconds. After ten consecutive failed events, ordinary delivery pauses
1161
- and about 5% of later events are attempted until one succeeds; use
1162
- `retryDispatch()` for an immediate manual redelivery. The dispatch history
1163
- retains only the first 2,000 characters of the receiver's response body.
1187
+ `createEndpoint()` returns `403` once the plan's limit is reached and `400`
1188
+ when another endpoint of the workspace already uses the same `url`. In
1189
+ `updateEndpoint()`, `signing_enabled: true` generates a secret if there is none
1190
+ and `false` discards it.
1191
+
1192
+ The earlier routes remain and act on the account's oldest endpoint:
1193
+ `register()` (create or update), `get()` (`IWebhookSubscription | null`) and
1194
+ `inactivate()`.
1195
+
1196
+ Assinafy delivers each event as an HTTP `POST` with
1197
+ `Content-Type: application/json`, `Connection: close` and the headers
1198
+ `webhook-id` (identical on every attempt of the same event to the same
1199
+ endpoint — deduplicate on it), `webhook-timestamp` and, with signing on,
1200
+ `webhook-signature`. Any `2xx` is success. There are at most two attempts,
1201
+ three seconds apart. After ten consecutive failed events, ordinary delivery
1202
+ pauses and about 5% of later events are attempted until one succeeds; use
1203
+ `retryDispatch()` for an immediate redelivery. The dispatch history retains only
1204
+ the first 2,000 characters of the receiver's response body.
1164
1205
 
1165
1206
  Each history or retry result is an `IWebhookDispatch`:
1166
1207
 
@@ -1170,6 +1211,7 @@ type WebhookDispatchShape = {
1170
1211
  id: string;
1171
1212
  event: string;
1172
1213
  activity_id: number;
1214
+ endpoint_id?: string | null; // null once the endpoint is deleted
1173
1215
  endpoint: string | null;
1174
1216
  payload: IWebhookPayload | Record<string, unknown> | null;
1175
1217
  delivered: boolean;
@@ -1229,46 +1271,45 @@ property before delivery.
1229
1271
 
1230
1272
  ### Webhook verification
1231
1273
 
1232
- `WebhookVerifier` is an opt-in HMAC-SHA256 utility for integrations whose
1233
- Assinafy environment provides a shared secret and signature header. The
1234
- current official OpenAPI document does **not** define a webhook signature
1235
- scheme or header name. Confirm the delivery contract for your environment
1236
- before enabling this check; do not reject production callbacks based on an
1237
- assumed header. The example below uses an application-configured header name.
1274
+ With `signing_enabled: true`, every delivery is signed following
1275
+ [Standard Webhooks](https://www.standardwebhooks.com): HMAC-SHA256 over
1276
+ `{webhook-id}.{webhook-timestamp}.{raw body}`, keyed with the base64 value after
1277
+ the `whsec_` prefix. `verifySignature()` compares in constant time and rejects a
1278
+ `webhook-timestamp` more than 5 minutes from the local clock. Pass the **raw**
1279
+ body, never re-serialized JSON.
1238
1280
 
1239
1281
  ```ts
1240
1282
  import express from 'express';
1241
1283
 
1242
- const webhookSecret = process.env.ASSINAFY_WEBHOOK_SECRET;
1243
- const signatureHeader = process.env.ASSINAFY_SIGNATURE_HEADER;
1244
- if (!webhookSecret || !signatureHeader) {
1245
- throw new Error('This deployment has no confirmed webhook-signature contract');
1246
- }
1247
-
1248
- const webhookClient = new AssinafyClient({ webhookSecret });
1284
+ const webhookClient = new AssinafyClient({
1285
+ webhookSecret: process.env.ASSINAFY_WEBHOOK_SECRET, // 'whsec_…' from getEndpointSecret()
1286
+ });
1249
1287
 
1250
1288
  app.post('/webhooks/assinafy', express.raw({ type: 'application/json' }), (req, res) => {
1251
- const signature = req.header(signatureHeader) ?? '';
1252
1289
  const rawBody = req.body as Buffer;
1253
-
1254
- if (!webhookClient.webhookVerifier.verify(rawBody, signature)) {
1290
+ if (!webhookClient.webhookVerifier.verifySignature(rawBody, req.headers)) {
1255
1291
  return res.status(401).send('Invalid signature');
1256
1292
  }
1257
1293
 
1258
1294
  const event = webhookClient.webhookVerifier.extractEvent(rawBody);
1259
1295
  const type = webhookClient.webhookVerifier.getEventType(event);
1260
1296
  const data = webhookClient.webhookVerifier.getEventData(event);
1297
+ // Deduplicate on req.headers['webhook-id'] before processing.
1261
1298
 
1262
1299
  switch (type) {
1263
- case 'document_ready': break;
1264
- case 'signer_signed_document': break;
1265
- case 'signer_rejected_document': break;
1266
- case 'document_processing_failed':break;
1300
+ case 'document_ready': break;
1301
+ case 'signer_signed_document': break;
1302
+ case 'signer_rejected_document': break;
1303
+ case 'document_processing_failed': break;
1267
1304
  }
1268
1305
  res.sendStatus(200);
1269
1306
  });
1270
1307
  ```
1271
1308
 
1309
+ On Fetch runtimes (`Request`), pass `await request.text()` and
1310
+ `request.headers`. The clock tolerance is the optional third argument, in
1311
+ seconds. After `rotateEndpointSecret()`, update the receiver's secret at once.
1312
+
1272
1313
  ### Signer-side endpoints
1273
1314
 
1274
1315
  For building custom signer portals. Most calls require the `signer-access-code`
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  SDK oficial em TypeScript para a [API Assinafy](https://api.assinafy.com.br/v1/docs) — plataforma
6
6
  brasileira de assinatura eletrônica de documentos.
7
7
 
8
- Cobre as 93 operações do documento OpenAPI oficial: contas, autenticação, aplicações OAuth 2.1,
8
+ Cobre as 106 operações do documento OpenAPI oficial: contas, autenticação, aplicações OAuth 2.1,
9
9
  usuários, documentos, assignments, signatários, fluxos do lado do signatário, templates, tags,
10
10
  campos, webhooks, identidade visual, estatísticas e o fluxo de alto nível
11
11
  `uploadAndRequestSignatures`. Cinco rotas adicionais de gestão de templates usadas por integrações
@@ -224,7 +224,7 @@ await client.oauth.getUserInfo(tokens.access_token); // claims OIDC; exige `ope
224
224
  | `templates:read` | Ler templates |
225
225
  | `templates:write` | Criar e alterar templates |
226
226
  | `account:read` | Ler perfil, tema e logotipo do workspace |
227
- | `webhooks:write` | Atualizar ou inativar a assinatura de webhooks do workspace |
227
+ | `webhooks:write` | Criar, alterar, inativar e excluir endpoints de webhook do workspace |
228
228
  | `openid` | Receber um `id_token` identificando o usuário |
229
229
  | `profile` | Ler o nome do usuário |
230
230
  | `email` | Ler o e-mail do usuário e se está verificado |
@@ -288,7 +288,7 @@ configurações de conector; seus usuários não precisam que você registre nad
288
288
  | `token` | string | — | Token de acesso (enviado como `Authorization: Bearer`). Serve também para tokens OAuth. |
289
289
  | `accountId` | string | — | ID padrão da conta / workspace. |
290
290
  | `baseUrl` | string | `https://api.assinafy.com.br/v1` | Base absoluta da API, sem credenciais, query ou fragmento. Precisa ser `https`, salvo em loopback. |
291
- | `webhookSecret` | string | — | Segredo HMAC opcional usado pelo `WebhookVerifier`; veja a [ressalva de contrato](docs/COMPATIBILITY.md#webhook-signature-verification-is-not-in-the-openapi-contract). |
291
+ | `webhookSecret` | string | — | Segredo `whsec_…` do endpoint de webhook; habilita `webhookVerifier.verifySignature()`. |
292
292
  | `timeout` | number | `30000` | Timeout da requisição, em milissegundos. |
293
293
  | `maxRetries` | number | `2` | Retenta automaticamente respostas `429` elegíveis, respeitando `Retry-After`. `0` desativa. |
294
294
  | `logger` | `Logger` | no-op | Logger opcional `{debug,info,warn,error}`. |
@@ -318,7 +318,7 @@ const client = AssinafyClient.fromConfig({
318
318
 
319
319
  ## Cobertura de endpoints
320
320
 
321
- As 93 operações documentadas em https://api.assinafy.com.br/v1/docs estão cobertas. A tabela abaixo
321
+ As 106 operações documentadas em https://api.assinafy.com.br/v1/docs estão cobertas. A tabela abaixo
322
322
  é o resumo por recurso; o mapa detalhado por operação está em
323
323
  [docs/API_COVERAGE.md](docs/API_COVERAGE.md).
324
324
 
@@ -330,13 +330,13 @@ As 93 operações documentadas em https://api.assinafy.com.br/v1/docs estão cob
330
330
  | `client.templates` | create, list, get, update, delete, downloadPage |
331
331
  | `client.tags` | list, create, update, delete |
332
332
  | `client.workspaces` | create, list, get, update, delete, getTheme, downloadLogo, uploadLogo, deleteLogo, getStats |
333
- | `client.webhooks` | register, get, inactivate, listEventTypes, listDispatches, retryDispatch |
333
+ | `client.webhooks` | listEndpoints, createEndpoint, getEndpoint, updateEndpoint, deleteEndpoint, getEndpointSecret, rotateEndpointSecret, register, get, inactivate, listEventTypes, listDispatches, retryDispatch |
334
334
  | `client.fields` | create, list, get, update, delete, validate, validateMultiple, listTypes |
335
335
  | `client.oauth` | **getProtectedResourceMetadata**, **getAuthorizationServerMetadata**, **createAuthorizationUrl**, **readAuthorizationCallback**, **exchangeCode**, **refreshToken**, **revokeToken**, **getUserInfo** |
336
- | `client.auth` | getSocialLoginUrl, getSocialLoginCallbackUrl, login, socialLogin, linkSocialLogin, createApiKey, getApiKey, deleteApiKey, changePassword, requestPasswordReset, resetPassword |
337
- | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences |
336
+ | `client.auth` | getSocialLoginUrl, getSocialLoginCallbackUrl, login, verifyMfa, socialLogin, linkSocialLogin, createApiKey, getApiKey, deleteApiKey, changePassword, requestPasswordReset, resetPassword |
337
+ | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences, getMfa, startTotpEnrollment, confirmTotpEnrollment, regenerateRecoveryCodes, deleteMfaMethod |
338
338
  | `client.signerDocuments` | getCurrent, list, search, download, signMultiple, declineMultiple, self, acceptTerms, verifyEmail, confirmData, uploadSignature, downloadSignature, getAssignment, sign, decline |
339
- | `client.webhookVerifier` | verify, extractEvent, getEventType, getEventData |
339
+ | `client.webhookVerifier` | verifySignature, extractEvent, getEventType, getEventData |
340
340
 
341
341
  Todo wrapper HTTP tem tipos de requisição e resposta verificados pelo TypeScript e JSDoc por método,
342
342
  cobrindo o payload de rede, o formato de retorno, validação, erros relevantes da API e um exemplo
@@ -1056,7 +1056,13 @@ precisar abrir uma sessão para uma pessoa. Para apps conectados por terceiros,
1056
1056
  const inicioOauth = client.auth.getSocialLoginUrl('google');
1057
1057
  const callbackOauth = client.auth.getSocialLoginCallbackUrl();
1058
1058
 
1059
- const { access_token, user, accounts } = await client.auth.login('eu@exemplo.com.br', 'senha');
1059
+ let sessao = await client.auth.login('eu@exemplo.com.br', 'senha');
1060
+ // Com autenticação em dois fatores ativa, o login devolve `mfa_token`; troque-o
1061
+ // em até 5 minutos pelo código do app autenticador ou por um código de recuperação.
1062
+ if (sessao.mfa_token) {
1063
+ sessao = await client.auth.verifyMfa(sessao.mfa_token, '123456');
1064
+ }
1065
+ const { access_token, user, accounts } = sessao;
1060
1066
  await client.auth.socialLogin({ provider: 'google', token: 'google-id-token', has_accepted_terms: true });
1061
1067
  await client.auth.linkSocialLogin({ provider: 'google', token: 'google-id-token' });
1062
1068
 
@@ -1097,29 +1103,53 @@ await client.users.updateNotificationPreferences({
1097
1103
  // métodos devolvem o mapa completo de nove preferências.
1098
1104
  ```
1099
1105
 
1106
+ #### Autenticação em dois fatores
1107
+
1108
+ Disponível em produção. O segredo TOTP e os códigos de recuperação aparecem uma única vez.
1109
+
1110
+ ```ts
1111
+ const inscricao = await client.users.startTotpEnrollment('Meu celular');
1112
+ // → { id, secret, provisioning_uri } — mostre provisioning_uri como QR code
1113
+ const { recovery_codes } = await client.users.confirmTotpEnrollment({
1114
+ id: inscricao.id,
1115
+ code: '123456', // código atual do novo dispositivo
1116
+ });
1117
+ // A partir daqui todo login exige o segundo fator.
1118
+
1119
+ const { methods, recovery_codes_remaining } = await client.users.getMfa();
1120
+ await client.users.regenerateRecoveryCodes({ password: 'senha-atual' }); // ou { code }
1121
+ await client.users.deleteMfaMethod(methods[0]!.id, { code: '123456' }); // → { is_mfa_enabled }
1122
+ ```
1123
+
1124
+ Trocar um autenticador já confirmado exige também `password` ou `reauth_code` em
1125
+ `confirmTotpEnrollment()`; a primeira inscrição não exige.
1126
+
1100
1127
  ### Webhooks
1101
1128
 
1102
- Tokens OAuth exigem `webhooks:write` para `register()` e `inactivate()`.
1129
+ Uma conta tem 1 endpoint de webhook, ou até 3 nos planos pagos. Cada endpoint ativo inscrito em um
1130
+ evento o recebe, de forma independente. Tokens OAuth exigem `account:read` para ler endpoints e
1131
+ `webhooks:write` para alterá-los; o segredo de assinatura só é acessível com chave de API.
1103
1132
 
1104
1133
  ```ts
1105
- await client.webhooks.register({
1134
+ const endpoint = await client.webhooks.createEndpoint({
1135
+ name: 'ERP',
1106
1136
  url: 'https://exemplo.com.br/webhooks/assinafy',
1107
- email: 'admin@exemplo.com.br',
1108
- is_active: true,
1109
- // `events` assume o conjunto padrão do SDK, abaixo
1110
- events: [
1111
- 'document_ready',
1112
- 'document_prepared',
1113
- 'signer_signed_document',
1114
- 'signer_rejected_document',
1115
- 'document_processing_failed',
1116
- ],
1137
+ email: 'operacoes@exemplo.com.br',
1138
+ events: ['document_ready', 'signer_signed_document', 'signer_rejected_document'],
1139
+ signing_enabled: true, // assina as entregas no padrão Standard Webhooks
1117
1140
  });
1141
+ // → { id, name, url, email, events, is_active, signing_enabled, created_at, updated_at }
1142
+
1143
+ const { secret } = await client.webhooks.getEndpointSecret(endpoint.id); // 'whsec_…'
1144
+ await client.webhooks.listEndpoints(); // IWebhookEndpoint[]
1145
+ await client.webhooks.getEndpoint(endpoint.id);
1146
+ await client.webhooks.updateEndpoint(endpoint.id, { is_active: false }); // só os campos enviados
1147
+ await client.webhooks.rotateEndpointSecret(endpoint.id); // o segredo antigo para na hora
1148
+ await client.webhooks.deleteEndpoint(endpoint.id); // libera a vaga do plano
1118
1149
 
1119
- await client.webhooks.get(); // IWebhookSubscription | null
1120
- await client.webhooks.inactivate(); // interrompe entregas (não existe rota de exclusão)
1121
1150
  await client.webhooks.listEventTypes();
1122
1151
  const historico = await client.webhooks.listDispatches({
1152
+ endpoint_id: endpoint.id,
1123
1153
  delivered: false,
1124
1154
  page: 1,
1125
1155
  'per-page': 20,
@@ -1127,13 +1157,20 @@ const historico = await client.webhooks.listDispatches({
1127
1157
  const reenviado = await client.webhooks.retryDispatch(dispatchId); // IWebhookDispatch
1128
1158
  ```
1129
1159
 
1130
- `register` envia `{ events, is_active, url, email }` e devolve
1131
- `{ events, is_active, url, email, updated_at? }`. A Assinafy entrega cada evento como um `POST` HTTP
1132
- com `Content-Type: application/json` e `Connection: close`. Qualquer `2xx` é sucesso. São no máximo
1133
- duas tentativas automáticas, com três segundos de intervalo. Depois de dez eventos falhos
1134
- consecutivos, a entrega comum é pausada e cerca de 5% dos eventos seguintes são tentados até um dar
1135
- certo; use `retryDispatch()` para reenviar manualmente na hora. O histórico guarda apenas os
1136
- primeiros 2.000 caracteres do corpo de resposta do receptor.
1160
+ `createEndpoint()` devolve `403` quando o limite do plano foi atingido e `400` quando outro endpoint
1161
+ do workspace já usa a mesma `url`. Em `updateEndpoint()`, `signing_enabled: true` gera um segredo se
1162
+ ainda não houver e `false` o descarta.
1163
+
1164
+ As rotas anteriores continuam disponíveis e operam sobre o endpoint mais antigo da conta:
1165
+ `register()` (cria ou atualiza), `get()` (`IWebhookSubscription | null`) e `inactivate()`.
1166
+
1167
+ A Assinafy entrega cada evento como um `POST` HTTP com `Content-Type: application/json`,
1168
+ `Connection: close` e os headers `webhook-id` (igual em todas as tentativas do mesmo evento para o
1169
+ mesmo endpoint — use-o para deduplicar), `webhook-timestamp` e, com assinatura ativa,
1170
+ `webhook-signature`. Qualquer `2xx` é sucesso. São no máximo duas tentativas, com três segundos de
1171
+ intervalo. Depois de dez eventos falhos consecutivos, a entrega comum é pausada e cerca de 5% dos
1172
+ eventos seguintes são tentados até um dar certo; use `retryDispatch()` para reenviar na hora. O
1173
+ histórico guarda apenas os primeiros 2.000 caracteres do corpo de resposta do receptor.
1137
1174
 
1138
1175
  Cada item do histórico (ou resultado de reenvio) é um `IWebhookDispatch`:
1139
1176
 
@@ -1143,6 +1180,7 @@ type WebhookDispatchShape = {
1143
1180
  id: string;
1144
1181
  event: string;
1145
1182
  activity_id: number;
1183
+ endpoint_id?: string | null; // null depois que o endpoint é excluído
1146
1184
  endpoint: string | null;
1147
1185
  payload: IWebhookPayload | Record<string, unknown> | null;
1148
1186
  delivered: boolean;
@@ -1201,34 +1239,29 @@ propriedade `integration` antes de entregar.
1201
1239
 
1202
1240
  ### Verificação de webhooks
1203
1241
 
1204
- `WebhookVerifier` é um utilitário HMAC-SHA256 opcional, para integrações cujo ambiente Assinafy
1205
- forneça um segredo compartilhado e um header de assinatura. O documento OpenAPI oficial atual
1206
- **não** define esquema nem nome de header de assinatura de webhook. Confirme o contrato de entrega
1207
- do seu ambiente antes de habilitar essa checagem; não rejeite callbacks de produção com base em um
1208
- header presumido. O exemplo abaixo usa um nome de header configurado pela aplicação.
1242
+ Com `signing_enabled: true`, cada entrega é assinada no padrão
1243
+ [Standard Webhooks](https://www.standardwebhooks.com): HMAC-SHA256 sobre
1244
+ `{webhook-id}.{webhook-timestamp}.{corpo bruto}`, com a chave em base64 após o prefixo `whsec_`.
1245
+ `verifySignature()` confere a assinatura em tempo constante e rejeita `webhook-timestamp` a mais de
1246
+ 5 minutos do relógio local. Passe o corpo **bruto**, nunca o JSON re-serializado.
1209
1247
 
1210
1248
  ```ts
1211
1249
  import express from 'express';
1212
1250
 
1213
- const webhookSecret = process.env.ASSINAFY_WEBHOOK_SECRET;
1214
- const signatureHeader = process.env.ASSINAFY_SIGNATURE_HEADER;
1215
- if (!webhookSecret || !signatureHeader) {
1216
- throw new Error('Este ambiente não tem contrato confirmado de assinatura de webhook');
1217
- }
1218
-
1219
- const webhookClient = new AssinafyClient({ webhookSecret });
1251
+ const webhookClient = new AssinafyClient({
1252
+ webhookSecret: process.env.ASSINAFY_WEBHOOK_SECRET, // 'whsec_…' de getEndpointSecret()
1253
+ });
1220
1254
 
1221
1255
  app.post('/webhooks/assinafy', express.raw({ type: 'application/json' }), (req, res) => {
1222
- const assinatura = req.header(signatureHeader) ?? '';
1223
1256
  const corpoBruto = req.body as Buffer;
1224
-
1225
- if (!webhookClient.webhookVerifier.verify(corpoBruto, assinatura)) {
1257
+ if (!webhookClient.webhookVerifier.verifySignature(corpoBruto, req.headers)) {
1226
1258
  return res.status(401).send('Assinatura inválida');
1227
1259
  }
1228
1260
 
1229
1261
  const evento = webhookClient.webhookVerifier.extractEvent(corpoBruto);
1230
1262
  const tipo = webhookClient.webhookVerifier.getEventType(evento);
1231
1263
  const dados = webhookClient.webhookVerifier.getEventData(evento);
1264
+ // Deduplique por req.headers['webhook-id'] antes de processar.
1232
1265
 
1233
1266
  switch (tipo) {
1234
1267
  case 'document_ready': break;
@@ -1240,6 +1273,10 @@ app.post('/webhooks/assinafy', express.raw({ type: 'application/json' }), (req,
1240
1273
  });
1241
1274
  ```
1242
1275
 
1276
+ Em runtimes com Fetch (`Request`), passe `await request.text()` e `request.headers`. A tolerância
1277
+ de horário pode ser ajustada no terceiro argumento, em segundos. Depois de `rotateEndpointSecret()`,
1278
+ atualize o segredo do receptor imediatamente.
1279
+
1243
1280
  ### Endpoints do signatário
1244
1281
 
1245
1282
  Para construir portais de assinatura próprios. Quase todas as chamadas exigem o parâmetro de URL