@assinafy/sdk 2.5.1 → 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,58 @@ 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
+
45
+ ## [2.5.2] - 2026-10-05
46
+
47
+ ### Fixed
48
+
49
+ - OAuth callbacks reject repeated protocol parameters before exchanging a code.
50
+ - API errors preserve authentication challenges and decoded binary error bodies
51
+ when a custom transport resolves a non-success response. OAuth errors retain
52
+ the authentication challenge when converted to `OAuthError`.
53
+ - Sandbox OAuth setup uses discovery and keeps client registration, issuer and
54
+ API requests in the same environment.
55
+ - Resource reference documentation includes JSON request payloads alongside
56
+ response examples; upload examples describe filename handling accurately.
57
+
58
+ ### Security
59
+
60
+ - Update the development dependency override for `brace-expansion` to 5.0.12.
61
+
10
62
  ## [2.5.1] - 2026-09-28
11
63
 
12
64
  ### Fixed
@@ -166,10 +218,6 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
166
218
  **A3** are recorded explicitly as certificate media — a file in software or a
167
219
  token/smartcard, chosen by the signer in the browser — both modelled by the
168
220
  single `DigitalCertificate` value, with no separate field to send.
169
- - `bun run audit:api` additionally fetches the two OAuth discovery documents
170
- and checks the issuer, the authorization and token endpoints, PKCE `S256` and
171
- the RFC 9207 `iss` parameter against the published contract. They are the
172
- only part of the OAuth surface that does not live in the OpenAPI document.
173
221
  - `docs/API_COVERAGE.md` maps the four new OAuth operations, bringing the
174
222
  ledger to 93 of 93.
175
223
  - The Portuguese README is now the complete reference rather than a summary
@@ -295,7 +343,7 @@ type, or API surface changed.
295
343
  operations across 68 paths**, including account theme/logo/statistics, OAuth
296
344
  URL helpers/linking, authenticated-user profile/statistics, and all signer
297
345
  response/acknowledgement shapes.
298
- - An exhaustive machine-auditable endpoint ledger (`docs/API_COVERAGE.md`),
346
+ - A complete endpoint ledger (`docs/API_COVERAGE.md`),
299
347
  compatibility record, and a scheduled OpenAPI operation-drift gate.
300
348
  - Strict test-source typechecking and enforced Bun coverage floors. The suite
301
349
  now executes every public HTTP wrapper and covers the production source at
@@ -343,12 +391,6 @@ type, or API surface changed.
343
391
 
344
392
  ### Additional fixes (completed 2026-07-19)
345
393
 
346
- Validated against the live sandbox API (`https://sandbox.assinafy.com.br/v1`)
347
- and the OpenAPI reference: every safely runnable operation was exercised live,
348
- operations that depend on fixtures or legal consent were recorded as explicit
349
- skips, and the SDK was brought in line with the observed request/response
350
- shapes.
351
-
352
394
  #### Fixed
353
395
 
354
396
  - **`signerDocuments.acceptTerms()` and `signerDocuments.verifyEmail()` were
@@ -364,7 +406,7 @@ shapes.
364
406
  `pages`, and the embedded `assignment` are current.
365
407
  - **README workspace example used an invalid colour.** `primary_color:
366
408
  '#ff0066'` is rejected by the account endpoints, which require exactly 6 hex
367
- characters with **no** leading `#` (verified live). Fixed the example and
409
+ characters with **no** leading `#`. Fixed the example and
368
410
  documented the format on the payload types.
369
411
 
370
412
  #### Added
@@ -419,7 +461,7 @@ shapes.
419
461
 
420
462
  - **`per_page` was silently ignored on every list call.** The API reads only
421
463
  `per-page`; `per_page` is accepted and discarded, so the response fell back to
422
- 20 items (verified: `?per-page=2` → 2 items, `?per_page=2` → 20). Every list
464
+ 20 items. Every list
423
465
  method's documentation advertised `per_page`, so paging appeared to work while
424
466
  quietly returning the wrong page size. Both spellings are now honoured —
425
467
  `per_page` is normalised to `per-page`, and an explicit `per-page` wins.
@@ -522,23 +564,19 @@ shapes.
522
564
  not return either field, so the old type promised a required `pages` array
523
565
  that was `undefined` at runtime.
524
566
  - **`ICreateAssignmentPayload.copy_receivers` is documented as unreliable.** On
525
- the sandbox plan the API accepts it and persists nothing — verified `[]` from
567
+ the sandbox plan the API accepts it and persists nothing — `[]` from
526
568
  `create`, `list` and `details().assignment`, for both emails and signer IDs.
527
569
  Kept (it may be plan-gated) but do not assume a CC was delivered.
528
570
 
529
571
  ## [1.5.0] - 2026-06-05
530
572
 
531
- Full coverage of [the live API docs](https://api.assinafy.com.br/v1/docs),
532
- re-validated end-to-end against the live **sandbox**
533
- (`https://sandbox.assinafy.com.br/v1`). Closes the last coverage gap (Template
534
- create/update/delete), removes a dead endpoint, tightens types to the real
535
- wire shapes, and modernises the toolchain.
573
+ Adds template management, aligns types with response payloads, and updates the toolchain.
536
574
 
537
575
  ### Removed
538
576
 
539
577
  - **`assignments.cancel`** — it called
540
578
  `POST /accounts/{id}/signature-requests/{id}/cancel`, which is undocumented and
541
- returns `404` on the live API (verified). There is no workspace-side cancel
579
+ returns `404` on the live API. There is no workspace-side cancel
542
580
  endpoint — cancel by deleting the document (`documents.delete`, when its status
543
581
  is deletable) or via the signer-side decline
544
582
  (`signerDocuments.decline(documentId, assignmentId, accessCode, reason)`).
@@ -597,19 +635,10 @@ wire shapes, and modernises the toolchain.
597
635
  for publishing, and npm provenance (`--provenance` + `id-token: write`).
598
636
  - esbuild pinned via `overrides` to keep the bun + npm lockfiles reproducible.
599
637
 
600
- ### Tests
601
-
602
- 113 unit tests pass (`bun test`). New suites cover `TemplateResource` (incl. the
603
- new CRUD), the `BaseResource` helpers (`callOptional` 404→null, `callVoid`,
604
- `callBinary`, `callList`), the rate-limit retry helpers, and assignment/document
605
- response shapes. All read and write paths re-verified against the live sandbox,
606
- including template create/get/update/downloadPage/delete.
607
638
 
608
639
  ## [1.4.0] - 2026-05-27
609
640
 
610
- Full coverage of [the live API docs](https://api.assinafy.com.br/v1/docs),
611
- re-validated end-to-end against the live API. Closes the last coverage gap
612
- (Tags) and fixes signer-creation and type accuracy.
641
+ Adds tags and fixes signer creation and response types.
613
642
 
614
643
  ### Added
615
644
 
@@ -642,18 +671,9 @@ re-validated end-to-end against the live API. Closes the last coverage gap
642
671
  is typed as the `{ ip, user-agent }` object the API actually returns, with the
643
672
  event `payload` snapshot added.
644
673
 
645
- ### Tests
646
-
647
- 86 unit tests pass (`bun test`). New `tags` and `documents` suites cover Tag CRUD
648
- and document-tag attach/detach; new signer tests cover WhatsApp-only creation and
649
- CPF normalisation. All read and write paths re-verified against the live API
650
- (`scripts/live-smoke.ts --write`).
651
674
 
652
675
  ## [1.3.0] - 2026-05-12
653
676
 
654
- 100% endpoint coverage of [the live API docs](https://api.assinafy.com.br/v1/docs),
655
- validated end-to-end against the live API.
656
-
657
677
  ### Added
658
678
 
659
679
  - **`AuthenticationResource`** (new — `client.auth`): `login`, `socialLogin`,
@@ -684,11 +704,6 @@ validated end-to-end against the live API.
684
704
  - Live smoke-test script (`scripts/live-smoke.ts`) covering every read-only
685
705
  endpoint plus optional `--write` and `--upload` modes.
686
706
 
687
- ### Tests
688
-
689
- 70 unit tests pass (`bun test`). New suites cover the authentication, fields,
690
- and signer-documents resources. Build + ESM/CJS bundles validated against the
691
- live API.
692
707
 
693
708
  ## [1.2.0] - 2026-05-06
694
709
 
@@ -725,7 +740,9 @@ signer fields with `cpf` and `whatsapp_phone_number`.
725
740
  - High-level `uploadAndRequestSignatures` helper on `AssinafyClient`.
726
741
  - `PaginatedResult<T>` with parsed `X-Pagination-*` header meta.
727
742
 
728
- [Unreleased]: https://github.com/assinafy/typescript-sdk/compare/v2.5.1...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
745
+ [2.5.2]: https://github.com/assinafy/typescript-sdk/compare/v2.5.1...v2.5.2
729
746
  [2.5.1]: https://github.com/assinafy/typescript-sdk/compare/v2.5.0...v2.5.1
730
747
  [2.5.0]: https://github.com/assinafy/typescript-sdk/compare/v2.4.2...v2.5.0
731
748
  [2.4.2]: https://github.com/assinafy/typescript-sdk/compare/v2.4.1...v2.4.2
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
@@ -186,7 +186,7 @@ const tokens = await client.oauth.exchangeCode({
186
186
  codeVerifier: session.oauth.codeVerifier,
187
187
  redirectUri: 'https://myapp.example.com/oauth/callback',
188
188
  clientId: process.env.ASSINAFY_CLIENT_ID!,
189
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET, // confidential apps only
189
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!, // confidential apps only
190
190
  });
191
191
  // → { access_token, token_type: 'Bearer', expires_in: 3600,
192
192
  // scope: 'documents:read documents:write',
@@ -201,7 +201,7 @@ const accountId = data[0]?.id; // store it with the tokens
201
201
  const renewed = await client.oauth.refreshToken({
202
202
  refreshToken: connection.refreshToken,
203
203
  clientId: process.env.ASSINAFY_CLIENT_ID!,
204
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
204
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
205
205
  });
206
206
  await connection.save({ refreshToken: renewed.refresh_token }); // BEFORE using it
207
207
 
@@ -211,7 +211,7 @@ await client.oauth.revokeToken({
211
211
  token: current.refreshToken,
212
212
  tokenTypeHint: 'refresh_token',
213
213
  clientId: process.env.ASSINAFY_CLIENT_ID!,
214
- clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
214
+ clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
215
215
  });
216
216
  ```
217
217
 
@@ -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,
@@ -378,7 +378,7 @@ display-name override (used as that file part's filename) and an optional JSON
378
378
  `IDocumentUploadResponse`:
379
379
 
380
380
  ```ts
381
- {
381
+ type DocumentUploadShape = {
382
382
  resource?: string;
383
383
  id: string;
384
384
  account_id: string;
@@ -402,7 +402,7 @@ display-name override (used as that file part's filename) and an optional JSON
402
402
  is_closed: boolean;
403
403
  decline_reason: string | null;
404
404
  declined_by: ISigner | null;
405
- }
405
+ };
406
406
  ```
407
407
 
408
408
  `DocumentStatus` covers `uploading`, `uploaded`, `metadata_processing`,
@@ -438,7 +438,7 @@ const signerB = await client.signers.create({
438
438
  The wire body is `{ full_name, email }`. Each response is an `ISigner`:
439
439
 
440
440
  ```ts
441
- {
441
+ type SignerShape = {
442
442
  resource?: string;
443
443
  id: string;
444
444
  full_name: string;
@@ -450,7 +450,7 @@ The wire body is `{ full_name, email }`. Each response is an `ISigner`:
450
450
  has_initial?: boolean; // signer-self response only
451
451
  is_signature_reusable?: boolean; // signer-self response only
452
452
  metadata?: Record<string, unknown>;
453
- }
453
+ };
454
454
  ```
455
455
 
456
456
  When an email is present, `signers.create()` first looks up that email in the
@@ -507,7 +507,7 @@ const assignment = await client.assignments.create(uploaded.id, {
507
507
  The request returns an `IAssignment`:
508
508
 
509
509
  ```ts
510
- {
510
+ type AssignmentShape = {
511
511
  resource?: string;
512
512
  id: string;
513
513
  sender_email?: string;
@@ -524,7 +524,7 @@ The request returns an `IAssignment`:
524
524
  signers: Array<ISigner & { completed?: boolean }>;
525
525
  };
526
526
  signing_urls?: Array<{ signer_id: string; url: string }>;
527
- }
527
+ };
528
528
  ```
529
529
 
530
530
  The URLs and delivered messages contain signer credentials; treat them as
@@ -556,7 +556,7 @@ await signerClient.signerDocuments.verifyEmail({
556
556
  const confirmed = await signerClient.signerDocuments.confirmData(
557
557
  uploaded.id,
558
558
  accessCode,
559
- { full_name: self.full_name, email: self.email ?? undefined },
559
+ { full_name: self.full_name, ...(self.email === null ? {} : { email: self.email }) },
560
560
  ); // ISigner
561
561
 
562
562
  const signable = await signerClient.signerDocuments.getAssignment(accessCode, true);
@@ -617,10 +617,10 @@ const doc = await client.documents.upload(
617
617
  { filePath: './contract.pdf' },
618
618
  { name: 'Service agreement', metadata: { type: 'service' } },
619
619
  );
620
- // `name` and `metadata` are compatibility multipart parts outside the published
621
- // file-only request schema.
622
- // `name` is optional and defaults to the file's own name. The API derives the
623
- // display name from the uploaded filename and appends `.pdf` when absent, so
620
+ // `metadata` is a compatibility multipart part outside the published schema.
621
+ // `name` sets the filename of the file part; it is not sent as a separate field.
622
+ // When omitted, it defaults to the original filename. The API appends `.pdf`
623
+ // when absent, so
624
624
  // the document above is stored as 'Service agreement.pdf'. Accents are
625
625
  // transliterated by the API ('Contrato de Serviço' → 'Contrato de Servico.pdf').
626
626
  // → {
@@ -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,23 +1184,34 @@ 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
 
1167
1208
  ```ts
1168
- {
1209
+ type WebhookDispatchShape = {
1169
1210
  resource?: string;
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;
@@ -1178,13 +1220,13 @@ Each history or retry result is an `IWebhookDispatch`:
1178
1220
  error: string | null;
1179
1221
  created_at: string;
1180
1222
  updated_at?: string;
1181
- }
1223
+ };
1182
1224
  ```
1183
1225
 
1184
1226
  Every delivery body uses this envelope:
1185
1227
 
1186
1228
  ```ts
1187
- {
1229
+ type WebhookPayloadShape = {
1188
1230
  id: number; // use for idempotent processing
1189
1231
  event: string;
1190
1232
  message: string | null;
@@ -1194,7 +1236,7 @@ Every delivery body uses this envelope:
1194
1236
  subject: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
1195
1237
  object: { type: 'User' | 'Signer' | 'Account' | 'Document' | 'Template'; [key: string]: unknown };
1196
1238
  account_id: string;
1197
- }
1239
+ };
1198
1240
  ```
1199
1241
 
1200
1242
  Event-specific values are:
@@ -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`
@@ -1397,24 +1438,25 @@ try {
1397
1438
 
1398
1439
  The sandbox runs its own authorization server at
1399
1440
  `https://auth-sandbox.assinafy.com.br`, with the consent screen at
1400
- `/oauth/authorize`. Its discovery documents are unreachable: nginx refuses
1401
- paths that start with a dot, so pass the endpoints explicitly:
1441
+ `/oauth/authorize`. Discovery is available and selects that server from the
1442
+ configured `baseUrl`:
1402
1443
 
1403
1444
  ```ts
1404
1445
  const client = new AssinafyClient({ baseUrl: 'https://sandbox.assinafy.com.br/v1' });
1405
-
1446
+ const metadata = await client.oauth.getAuthorizationServerMetadata();
1406
1447
  const request = await client.oauth.createAuthorizationUrl({
1407
1448
  clientId: process.env.ASSINAFY_CLIENT_ID!,
1408
1449
  redirectUri: 'https://myapp.example.com/oauth/callback',
1409
- scopes: ['documents:read'],
1410
- issuer: 'https://auth-sandbox.assinafy.com.br',
1411
- authorizationEndpoint: 'https://auth-sandbox.assinafy.com.br/oauth/authorize',
1450
+ scopes: ['documents:read', 'account:read', 'offline_access'],
1412
1451
  });
1413
1452
  ```
1414
1453
 
1415
- The token, revocation and userinfo endpoints follow the configured `baseUrl`.
1416
- Confirm that the sandbox exposes them before running the exchange step
1417
- there — see [docs/COMPATIBILITY.md](docs/COMPATIBILITY.md).
1454
+ Register the application in the matching environment. Production and sandbox
1455
+ have separate issuers, client IDs, credentials and workspaces; keep each
1456
+ connection entirely in one environment. Token, revocation and userinfo requests
1457
+ use the configured `baseUrl`. For local testing, expose only the callback
1458
+ through an HTTPS tunnel, register its exact URL and revoke tokens afterward.
1459
+ See [docs/COMPATIBILITY.md](docs/COMPATIBILITY.md).
1418
1460
 
1419
1461
  ## Development
1420
1462