@assinafy/sdk 2.6.0 → 2.7.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,37 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [2.7.0] - 2026-10-10
11
+
12
+ ### Changed
13
+
14
+ - The `documents.sendToken()` reference documents the published
15
+ `{ recipient, channel }` body and its `email` channel. The two-argument form
16
+ keeps sending `{ email }` and retries the documented shape when a deployment
17
+ requires `recipient`/`channel`.
18
+ - `assignments.resetExpiration()` documents that the `expires_at` key is always
19
+ sent and that `null` removes the expiration.
20
+ - `AssinafyClient.fromConfig()` resolves `max_retries` before `maxRetries`,
21
+ like every other snake_case/camelCase option pair.
22
+ - The document lifecycle walkthrough in both READMEs starts at workspace
23
+ selection and verifies the webhook signature before processing completion
24
+ events and downloading artifacts.
25
+ - The READMEs document `MAX_UPLOAD_BYTES`, `buildAssignmentPayload()`,
26
+ `DEFAULT_WEBHOOK_EVENTS`, `parseWwwAuthenticate()` and `ClientConfigInput`.
27
+
28
+ ### Fixed
29
+
30
+ - `ApiError.fromResponse()` falls back to a non-empty message when the error
31
+ body carries empty `message` and `error` strings.
32
+ - `serializeJsonRecord()` keeps its specific "must serialize to a JSON object"
33
+ message instead of the generic serialization failure.
34
+ - JSDoc corrections: a `buildAssignmentPayload()` example that mixed stepped
35
+ and unstepped signers, a duplicated request-body block in
36
+ `auth.linkSocialLogin()`, the `mfa_token` note placement in `auth.login()`,
37
+ the request-body placement in `oauth.revokeToken()`, `fs.promises.writeFile`
38
+ in the binary-download examples, and the parameter list of the two-argument
39
+ `documents.sendToken()` overload.
40
+
10
41
  ## [2.6.0] - 2026-10-07
11
42
 
12
43
  ### Added
package/README.en.md CHANGED
@@ -29,10 +29,11 @@ afterwards.
29
29
  [Endpoint coverage](#endpoint-coverage)
30
30
 
31
31
  **The end-to-end flow** — [Document lifecycle](#document-lifecycle):
32
- [upload](#1-upload-the-pdf) → [signers](#2-create-or-reuse-the-email-signers) →
33
- [price and request signatures](#3-price-then-request-signatures) →
34
- [the signer's side](#4-complete-the-email-signer-flow) →
35
- [completion and artifacts](#5-observe-completion-and-download-artifacts)
32
+ [workspace selection](#1-select-the-workspace) → [upload](#2-upload-the-pdf) →
33
+ [signers](#3-create-or-reuse-the-email-signers) →
34
+ [price and request signatures](#4-price-then-request-signatures) →
35
+ [the signer's side](#5-complete-the-email-signer-flow) →
36
+ [completion and artifacts](#6-observe-completion-and-download-artifacts)
36
37
 
37
38
  **Per-resource detail** — [Resource reference](#resource-reference):
38
39
  [documents](#documents) · [signers](#signers) · [assignments](#assignments) ·
@@ -164,7 +165,7 @@ revocation and userinfo endpoints live on this API. Read both from discovery
164
165
  rather than hardcoding them.
165
166
 
166
167
  ```ts
167
- import { AssinafyClient, OAuthError } from '@assinafy/sdk';
168
+ import { AssinafyClient, ApiError, OAuthError } from '@assinafy/sdk';
168
169
 
169
170
  const client = new AssinafyClient(); // no credentials needed
170
171
 
@@ -329,6 +330,9 @@ const client = AssinafyClient.fromConfig({
329
330
  });
330
331
  ```
331
332
 
333
+ The configuration object accepted by `fromConfig` has the exported type
334
+ `ClientConfigInput`.
335
+
332
336
  ## Endpoint coverage
333
337
 
334
338
  All 106 operations documented at https://api.assinafy.com.br/v1/docs are
@@ -339,8 +343,8 @@ ledger is in [docs/API_COVERAGE.md](docs/API_COVERAGE.md).
339
343
  | --------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
340
344
  | `client.documents` | list, **search**, upload, details, get, **rename**, activities, waitUntilReady, download, thumbnail, downloadPage, statuses, delete, verify, createFromTemplate, estimateCostFromTemplate, getPublic, sendToken, listTags, replaceTags, addTags, detachTag, isFullySigned, getSigningProgress |
341
345
  | `client.signers` | create, get, list, update, delete, findByEmail |
342
- | `client.assignments` | **list**, create, estimateCost, resetExpiration, resendNotification, estimateResendCost, listWhatsAppNotifications |
343
- | `client.templates` | **create**, list, get, **update**, **delete**, downloadPage |
346
+ | `client.assignments` | list, create, estimateCost, resetExpiration, resendNotification, estimateResendCost, listWhatsAppNotifications |
347
+ | `client.templates` | create, list, get, update, delete, downloadPage |
344
348
  | `client.tags` | list, create, update, delete |
345
349
  | `client.workspaces` | create, list, get, update, delete, getTheme, downloadLogo, uploadLogo, deleteLogo, getStats |
346
350
  | `client.webhooks` | listEndpoints, createEndpoint, getEndpoint, updateEndpoint, deleteEndpoint, getEndpointSecret, rotateEndpointSecret, register, get, inactivate, listEventTypes, listDispatches, retryDispatch |
@@ -348,7 +352,7 @@ ledger is in [docs/API_COVERAGE.md](docs/API_COVERAGE.md).
348
352
  | `client.oauth` | **getProtectedResourceMetadata**, **getAuthorizationServerMetadata**, **createAuthorizationUrl**, **readAuthorizationCallback**, **exchangeCode**, **refreshToken**, **revokeToken**, **getUserInfo** |
349
353
  | `client.auth` | getSocialLoginUrl, getSocialLoginCallbackUrl, login, verifyMfa, socialLogin, linkSocialLogin, createApiKey, getApiKey, deleteApiKey, changePassword, requestPasswordReset, resetPassword |
350
354
  | `client.users` | getCurrent, getStats, getNotificationPreferences, updateNotificationPreferences, getMfa, startTotpEnrollment, confirmTotpEnrollment, regenerateRecoveryCodes, deleteMfaMethod |
351
- | `client.signerDocuments` | getCurrent, list, **search**, download, signMultiple, declineMultiple, self, acceptTerms, verifyEmail, confirmData, uploadSignature, downloadSignature, getAssignment, sign, decline |
355
+ | `client.signerDocuments` | getCurrent, list, search, download, signMultiple, declineMultiple, self, acceptTerms, verifyEmail, confirmData, uploadSignature, downloadSignature, getAssignment, sign, decline |
352
356
  | `client.webhookVerifier` | verifySignature, extractEvent, getEventType, getEventData |
353
357
 
354
358
  Every HTTP wrapper has TypeScript-checked request/response shapes and
@@ -366,7 +370,22 @@ artifact phase. The example below keeps every signer on email and uses a
366
370
  `virtual` assignment, so no page coordinates or paid notification channel are
367
371
  required.
368
372
 
369
- ### 1. Upload the PDF
373
+ ### 1. Select the workspace
374
+
375
+ Every account-scoped operation happens inside a workspace. With an API key,
376
+ pass the `accountId` when building the client (or as the last argument of any
377
+ account-scoped method). With OAuth, list the user's workspaces and keep the
378
+ chosen `id` with the tokens — a token is bound to exactly one workspace (see
379
+ [OAuth applications](#oauth-applications)):
380
+
381
+ ```ts
382
+ const { data: workspaces } = await client.workspaces.list();
383
+ const accountId = workspaces[0]?.id; // e.g. new AssinafyClient({ apiKey, accountId })
384
+ ```
385
+
386
+ The examples below assume a `client` already pointing at the chosen workspace.
387
+
388
+ ### 2. Upload the PDF
370
389
 
371
390
  ```ts
372
391
  const uploaded = await client.documents.upload({ filePath: './contract.pdf' });
@@ -409,7 +428,8 @@ type DocumentUploadShape = {
409
428
  `metadata_ready`, `pending_signature`, `expired`, `certificating`,
410
429
  `certificated`, `rejected_by_signer`, `rejected_by_user`, and `failed`.
411
430
 
412
- Uploads must be PDFs, at most 25 MB and at most 2,000 pages. The SDK checks the
431
+ Uploads must be PDFs, at most 25 MB and at most 2,000 pages (the byte limit is
432
+ exported as `MAX_UPLOAD_BYTES`). The SDK checks the
413
433
  extension, size, and `%PDF-` header before sending. A new upload can have an
414
434
  empty `pages` array until metadata processing finishes. Wait before creating a
415
435
  `collect` assignment because its fields refer to rendered page IDs; a
@@ -422,7 +442,7 @@ const prepared = await client.documents.waitUntilReady(uploaded.id, {
422
442
  });
423
443
  ```
424
444
 
425
- ### 2. Create or reuse the email signers
445
+ ### 3. Create or reuse the email signers
426
446
 
427
447
  ```ts
428
448
  const signerA = await client.signers.create({
@@ -457,7 +477,7 @@ When an email is present, `signers.create()` first looks up that email in the
457
477
  workspace and reuses the matching signer; a name-only or phone-only request
458
478
  always creates a new signer.
459
479
 
460
- ### 3. Price, then request signatures
480
+ ### 4. Price, then request signatures
461
481
 
462
482
  Cost estimation takes channel descriptors, not signer IDs:
463
483
 
@@ -530,7 +550,7 @@ type AssignmentShape = {
530
550
  The URLs and delivered messages contain signer credentials; treat them as
531
551
  secrets.
532
552
 
533
- ### 4. Complete the email signer flow
553
+ ### 5. Complete the email signer flow
534
554
 
535
555
  Assinafy sends each signer a link containing their access code and sends the
536
556
  one-time verification code through the selected channel. Neither value is
@@ -579,11 +599,13 @@ before signing. A `DigitalCertificate` signer cannot call `sign`; that branch
579
599
  uses Assinafy's certificate flow, described in
580
600
  [ICP-Brasil digital certificate](#icp-brasil-digital-certificate).
581
601
 
582
- ### 5. Observe completion and download artifacts
602
+ ### 6. Observe completion and download artifacts
583
603
 
584
- Subscribe to `document_ready` for event-driven completion, or fetch
585
- `documents.details(documentId)` until `status === 'certificated'`. Webhook
586
- deliveries can repeat, so use their numeric `id` as an
604
+ Subscribe to `document_ready` for event-driven completion — on an endpoint with
605
+ `signing_enabled`, [verify the signature](#webhook-verification) of every
606
+ delivery before processing it — or fetch `documents.details(documentId)` until
607
+ `status === 'certificated'`. Webhook
608
+ deliveries can repeat, so use the `webhook-id` header as an
587
609
  idempotency key. Once complete:
588
610
 
589
611
  ```ts
@@ -786,7 +808,13 @@ await client.assignments.create(documentId, {
786
808
  }],
787
809
  }],
788
810
  });
811
+ ```
812
+
813
+ To assemble an assignment body outside the client — for example, to inspect it
814
+ before sending — use the exported `buildAssignmentPayload()` helper, which
815
+ applies the same validation and normalization as `create()`.
789
816
 
817
+ ```ts
790
818
  // Estimate cost (the endpoint prices channel descriptors, not signer IDs) → ICostEstimate
791
819
  await client.assignments.estimateCost(documentId, { signers: [{}] }); // default Email
792
820
  // → {
@@ -796,8 +824,7 @@ await client.assignments.estimateCost(documentId, { signers: [{}] }); // default
796
824
  // }
797
825
 
798
826
  await client.assignments.resetExpiration(documentId, assignmentId, '2027-06-30T00:00:00Z');
799
- // Compatibility only: the published request requires a date-time string.
800
- // Confirm target support before using `null` to clear an expiration.
827
+ // The `expires_at` key is required by the contract; send `null` to remove the expiration.
801
828
  await client.assignments.resetExpiration(documentId, assignmentId, null);
802
829
 
803
830
  await client.assignments.resendNotification(documentId, assignmentId, signerId);
@@ -1185,7 +1212,11 @@ const retried = await client.webhooks.retryDispatch(dispatchId); // IWebhookDisp
1185
1212
  ```
1186
1213
 
1187
1214
  `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
1215
+ when another endpoint of the workspace already uses the same `url`. When
1216
+ `events` is omitted or empty, the SDK sends the exported
1217
+ `DEFAULT_WEBHOOK_EVENTS`: `document_ready`, `document_prepared`,
1218
+ `signer_signed_document`, `signer_rejected_document`, and
1219
+ `document_processing_failed`. In
1189
1220
  `updateEndpoint()`, `signing_enabled: true` generates a secret if there is none
1190
1221
  and `false` discards it.
1191
1222
 
@@ -1429,6 +1460,10 @@ try {
1429
1460
  }
1430
1461
  ```
1431
1462
 
1463
+ `err.challenge` is an already-parsed `IAuthenticateChallenge`. The parser used
1464
+ internally is exported as `parseWwwAuthenticate()`, for reading the
1465
+ `WWW-Authenticate` header of responses received outside the SDK.
1466
+
1432
1467
  ## Environments
1433
1468
 
1434
1469
  | | |
@@ -1471,6 +1506,14 @@ bun run lint:pkg # publint + arethetypeswrong
1471
1506
  bun run verify # complete local release gate
1472
1507
  ```
1473
1508
 
1509
+ ## Documentation
1510
+
1511
+ - **[README.md](README.md)** — a mesma referência completa, em português
1512
+ - [docs/API_COVERAGE.md](docs/API_COVERAGE.md) — operation map
1513
+ - [docs/COMPATIBILITY.md](docs/COMPATIBILITY.md) — per-deployment request and response variants
1514
+ - [docs/RELEASING.md](docs/RELEASING.md) — publishing process
1515
+ - [API documentation](https://api.assinafy.com.br/v1/docs)
1516
+
1474
1517
  ## License
1475
1518
 
1476
1519
  MIT
package/README.md CHANGED
@@ -26,10 +26,11 @@ recurso. Leia na ordem na primeira vez; use como referência depois.
26
26
  [Cobertura de endpoints](#cobertura-de-endpoints)
27
27
 
28
28
  **O fluxo ponta a ponta** — [Ciclo de vida do documento](#ciclo-de-vida-do-documento):
29
- [envio do PDF](#1-envie-o-pdf) → [signatários](#2-crie-ou-reaproveite-os-signatários-por-e-mail) →
30
- [orçamento e pedido de assinatura](#3-orce-depois-peça-as-assinaturas) →
31
- [o lado do signatário](#4-conclua-o-fluxo-do-signatário-por-e-mail) →
32
- [conclusão e artefatos](#5-acompanhe-a-conclusão-e-baixe-os-artefatos)
29
+ [seleção do workspace](#1-selecione-o-workspace) → [envio do PDF](#2-envie-o-pdf) →
30
+ [signatários](#3-crie-ou-reaproveite-os-signatários-por-e-mail) →
31
+ [orçamento e pedido de assinatura](#4-orce-depois-peça-as-assinaturas) →
32
+ [o lado do signatário](#5-conclua-o-fluxo-do-signatário-por-e-mail) →
33
+ [conclusão e artefatos](#6-acompanhe-a-conclusão-e-baixe-os-artefatos)
33
34
 
34
35
  **Detalhe por recurso** — [Referência de recursos](#referência-de-recursos):
35
36
  [documentos](#documentos) · [signatários](#signatários) · [assignments](#assignments) ·
@@ -156,7 +157,7 @@ O fluxo passa por dois hosts de propósito: a tela de consentimento fica no serv
156
157
  API. Leia os dois da descoberta em vez de fixá-los no código.
157
158
 
158
159
  ```ts
159
- import { AssinafyClient, OAuthError } from '@assinafy/sdk';
160
+ import { AssinafyClient, ApiError, OAuthError } from '@assinafy/sdk';
160
161
 
161
162
  const client = new AssinafyClient(); // nenhuma credencial necessária
162
163
 
@@ -316,6 +317,8 @@ const client = AssinafyClient.fromConfig({
316
317
  });
317
318
  ```
318
319
 
320
+ O objeto aceito por `fromConfig` tem o tipo exportado `ClientConfigInput`.
321
+
319
322
  ## Cobertura de endpoints
320
323
 
321
324
  As 106 operações documentadas em https://api.assinafy.com.br/v1/docs estão cobertas. A tabela abaixo
@@ -348,7 +351,21 @@ A integração normal tem uma fase do dono da conta, uma fase do signatário e u
348
351
  artefatos. O exemplo abaixo mantém todos os signatários no e-mail e usa um assignment `virtual`,
349
352
  então não exige coordenadas de página nem canal pago de notificação.
350
353
 
351
- ### 1. Envie o PDF
354
+ ### 1. Selecione o workspace
355
+
356
+ Toda operação com escopo de conta acontece dentro de um workspace. Com chave de API, informe o
357
+ `accountId` ao construir o cliente (ou como último argumento de cada método com escopo de conta).
358
+ Com OAuth, liste os workspaces do usuário e guarde o `id` do escolhido junto com os tokens — um
359
+ token vale para exatamente um workspace (veja [Aplicações OAuth](#aplicações-oauth)):
360
+
361
+ ```ts
362
+ const { data: workspaces } = await client.workspaces.list();
363
+ const accountId = workspaces[0]?.id; // ex.: new AssinafyClient({ apiKey, accountId })
364
+ ```
365
+
366
+ Os exemplos abaixo assumem um `client` já apontando para o workspace escolhido.
367
+
368
+ ### 2. Envie o PDF
352
369
 
353
370
  ```ts
354
371
  const enviado = await client.documents.upload({ filePath: './contrato.pdf' });
@@ -390,7 +407,8 @@ type DocumentUploadShape = {
390
407
  `pending_signature`, `expired`, `certificating`, `certificated`, `rejected_by_signer`,
391
408
  `rejected_by_user` e `failed`.
392
409
 
393
- O envio precisa ser um PDF de no máximo 25 MB e 2.000 páginas. O SDK confere extensão, tamanho e o
410
+ O envio precisa ser um PDF de no máximo 25 MB e 2.000 páginas (o limite em bytes está exportado
411
+ como `MAX_UPLOAD_BYTES`). O SDK confere extensão, tamanho e o
394
412
  cabeçalho `%PDF-` antes de enviar. Um upload novo pode ter `pages` vazio até o processamento de
395
413
  metadados terminar. Espere antes de criar um assignment `collect`, porque seus campos referenciam
396
414
  IDs de páginas renderizadas; um assignment `virtual` pode ser criado imediatamente.
@@ -402,7 +420,7 @@ const preparado = await client.documents.waitUntilReady(enviado.id, {
402
420
  });
403
421
  ```
404
422
 
405
- ### 2. Crie ou reaproveite os signatários por e-mail
423
+ ### 3. Crie ou reaproveite os signatários por e-mail
406
424
 
407
425
  ```ts
408
426
  const signatarioA = await client.signers.create({
@@ -436,7 +454,7 @@ type SignerShape = {
436
454
  Quando há e-mail, `signers.create()` primeiro procura esse endereço no workspace e reaproveita o
437
455
  signatário correspondente; uma requisição só com nome ou só com telefone sempre cria um novo.
438
456
 
439
- ### 3. Orce, depois peça as assinaturas
457
+ ### 4. Orce, depois peça as assinaturas
440
458
 
441
459
  A estimativa de custo recebe descritores de canal, não IDs de signatário:
442
460
 
@@ -508,7 +526,7 @@ type AssignmentShape = {
508
526
 
509
527
  As URLs e as mensagens entregues contêm credenciais do signatário; trate-as como segredo.
510
528
 
511
- ### 4. Conclua o fluxo do signatário por e-mail
529
+ ### 5. Conclua o fluxo do signatário por e-mail
512
530
 
513
531
  A Assinafy envia a cada signatário um link com o código de acesso dele e manda o código de
514
532
  verificação de uso único pelo canal escolhido. Nenhum dos dois valores é devolvido como campo
@@ -552,11 +570,13 @@ assinar. Um signatário `DigitalCertificate` não pode usar `sign`; esse ramo pa
552
570
  certificado da Assinafy, descrito em
553
571
  [Certificado digital ICP-Brasil](#certificado-digital-icp-brasil).
554
572
 
555
- ### 5. Acompanhe a conclusão e baixe os artefatos
573
+ ### 6. Acompanhe a conclusão e baixe os artefatos
556
574
 
557
- Assine o evento `document_ready` para saber da conclusão por evento, ou consulte
558
- `documents.details(documentId)` até `status === 'certificated'`. As entregas de webhook podem se
559
- repetir — use o `id` numérico como chave de idempotência. Concluído:
575
+ Assine o evento `document_ready` para saber da conclusão por evento — em um endpoint com
576
+ `signing_enabled`, [verifique a assinatura](#verificação-de-webhooks) de cada entrega antes de
577
+ processá-la — ou consulte `documents.details(documentId)` até `status === 'certificated'`. As
578
+ entregas de webhook podem se repetir — use o cabeçalho `webhook-id` como chave de idempotência.
579
+ Concluído:
560
580
 
561
581
  ```ts
562
582
  const documentoFinal = await client.documents.details(enviado.id);
@@ -747,7 +767,13 @@ await client.assignments.create(documentId, {
747
767
  }],
748
768
  }],
749
769
  });
770
+ ```
771
+
772
+ Para montar o corpo de um assignment fora do cliente — por exemplo, para inspecioná-lo antes do
773
+ envio — use o helper exportado `buildAssignmentPayload()`, que aplica as mesmas validações e
774
+ normalizações de `create()`.
750
775
 
776
+ ```ts
751
777
  // Estimativa de custo (o endpoint orça descritores de canal, não IDs) → ICostEstimate
752
778
  await client.assignments.estimateCost(documentId, { signers: [{}] }); // Email padrão
753
779
  // → {
@@ -757,8 +783,7 @@ await client.assignments.estimateCost(documentId, { signers: [{}] }); // Email p
757
783
  // }
758
784
 
759
785
  await client.assignments.resetExpiration(documentId, assignmentId, '2027-06-30T00:00:00Z');
760
- // Só compatibilidade: a requisição publicada exige uma data-hora.
761
- // Confirme o suporte do destino antes de usar `null` para limpar a expiração.
786
+ // A chave `expires_at` é exigida pelo contrato; envie `null` para remover a expiração.
762
787
  await client.assignments.resetExpiration(documentId, assignmentId, null);
763
788
 
764
789
  await client.assignments.resendNotification(documentId, assignmentId, signerId);
@@ -1158,7 +1183,9 @@ const reenviado = await client.webhooks.retryDispatch(dispatchId); // IWebhookDi
1158
1183
  ```
1159
1184
 
1160
1185
  `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
1186
+ do workspace já usa a mesma `url`. Quando `events` é omitido ou vazio, o SDK envia
1187
+ `DEFAULT_WEBHOOK_EVENTS` (exportado): `document_ready`, `document_prepared`,
1188
+ `signer_signed_document`, `signer_rejected_document` e `document_processing_failed`. Em `updateEndpoint()`, `signing_enabled: true` gera um segredo se
1162
1189
  ainda não houver e `false` o descarta.
1163
1190
 
1164
1191
  As rotas anteriores continuam disponíveis e operam sobre o endpoint mais antigo da conta:
@@ -1400,6 +1427,10 @@ try {
1400
1427
  }
1401
1428
  ```
1402
1429
 
1430
+ `err.challenge` é um `IAuthenticateChallenge` já interpretado. O parser usado internamente está
1431
+ exportado como `parseWwwAuthenticate()`, para quem precisa ler o cabeçalho `WWW-Authenticate` de
1432
+ respostas recebidas fora do SDK.
1433
+
1403
1434
  ## Ambientes
1404
1435
 
1405
1436
  | | |
package/SECURITY.md CHANGED
@@ -62,10 +62,15 @@ opportunity to upgrade.
62
62
  compared in constant time and `iss` must match the expected issuer. Do not
63
63
  bypass `readAuthorizationCallback()` and exchange a code straight from the
64
64
  query string.
65
- - The webhook HMAC helper is an opt-in utility, not proof of an official
66
- Assinafy signing contract. Confirm the header, algorithm, encoding, and secret
67
- delivery mechanism with Assinafy before enforcing it. See
68
- `docs/COMPATIBILITY.md`.
65
+ - Signed webhook endpoints are verified before any event is processed. The API
66
+ generates the `whsec_…` secret (`webhooks.getEndpointSecret()`), and
67
+ `webhookVerifier.verifySignature()` checks the Standard Webhooks
68
+ `webhook-signature` header against the raw, unparsed request body — parse the
69
+ JSON only after verification. The default five-minute timestamp tolerance
70
+ blocks replayed deliveries; keep the receiver clock synchronized. Rotate the
71
+ secret with `webhooks.rotateEndpointSecret()` when it may have leaked —
72
+ rotation is immediate and the secret/rotate routes accept an API key only,
73
+ not OAuth tokens. See `docs/COMPATIBILITY.md`.
69
74
  - Dependency changes must keep `bun.lock` synchronized and pass `bun run audit`.
70
75
  GitHub Actions are pinned to immutable commit SHAs and updated through
71
76
  Dependabot review.
package/dist/index.d.mts CHANGED
@@ -2274,40 +2274,36 @@ declare class DocumentResource extends BaseResource {
2274
2274
  */
2275
2275
  getPublic(documentId: string): Promise<IPublicDocumentInfo>;
2276
2276
  /**
2277
- * Send the signer's access token to their email / WhatsApp
2277
+ * Send the signer's access token to their email
2278
2278
  * (`PUT /public/documents/{documentId}/send-token`).
2279
2279
  *
2280
2280
  * Part of the public signing flow: dispatches the 6-digit verification
2281
2281
  * token the signer enters to view the document. The documented request body
2282
- * is `{ email }`. For compatibility with Assinafy environments that still
2283
- * require the older contract, passing an explicit `channel` sends
2284
- * `{ recipient, channel }`; the two-argument documented call also retries
2285
- * that legacy shape only when the server explicitly reports that
2286
- * `channel`/`recipient` is required.
2282
+ * is `{ recipient, channel }` with `channel` set to `email`. This
2283
+ * two-argument form sends the legacy `{ email }` shape, which current
2284
+ * deployments still accept, and retries the documented shape only when the
2285
+ * server explicitly reports that `channel`/`recipient` is required. Use the
2286
+ * three-argument overload to send the documented shape directly.
2287
2287
  *
2288
2288
  * Request body (`application/json`):
2289
2289
  * ```jsonc
2290
2290
  * { "email": "signer@example.com" }
2291
2291
  * ```
2292
- * Compatibility fallback or explicit-channel body:
2292
+ * Documented body, sent on the explicit-channel overload or on retry:
2293
2293
  * ```jsonc
2294
2294
  * { "recipient": "signer@example.com", "channel": "email" }
2295
2295
  * ```
2296
2296
  *
2297
2297
  * @param documentId - The document to send the token for.
2298
- * @param recipient - The signer's email address (or WhatsApp number when an
2299
- * explicit channel is supplied).
2300
- * @param channel - Optional legacy delivery channel.
2298
+ * @param email - The signer's email address.
2301
2299
  * @returns Nothing after the API's empty acknowledgement.
2302
- * @throws {ValidationError} If `documentId` or `recipient` is missing, the
2303
- * official two-argument form does not receive a valid email address, or a
2304
- * supplied `channel` is not a non-empty string.
2300
+ * @throws {ValidationError} If `documentId` is missing or `email` is not a
2301
+ * valid email address.
2305
2302
  * @throws {ApiError} If the API rejects the request.
2306
2303
  *
2307
2304
  * @example
2308
2305
  * ```ts
2309
2306
  * await client.documents.sendToken('doc-1', 'signer@example.com');
2310
- * await client.documents.sendToken('doc-1', '+5511999998888', 'whatsapp');
2311
2307
  * ```
2312
2308
  */
2313
2309
  sendToken(documentId: string, email: string): Promise<void>;
@@ -2957,10 +2953,10 @@ declare class WorkspaceResource extends BaseResource {
2957
2953
  * ```ts
2958
2954
  * const body = buildAssignmentPayload({
2959
2955
  * method: 'virtual',
2960
- * signers: ['signer-1', { signer_id: 'signer-2', step: 2 }],
2956
+ * signers: [{ signer_id: 'signer-1', step: 1 }, { signer_id: 'signer-2', step: 2 }],
2961
2957
  * message: 'Please sign',
2962
2958
  * });
2963
- * // body.signers → [{ id: 'signer-1' }, { id: 'signer-2', step: 2 }]
2959
+ * // body.signers → [{ id: 'signer-1', step: 1 }, { id: 'signer-2', step: 2 }]
2964
2960
  * ```
2965
2961
  */
2966
2962
  declare function buildAssignmentPayload(payload: ICreateAssignmentPayload): Record<string, unknown>;
@@ -3250,9 +3246,10 @@ declare class AssignmentResource extends BaseResource {
3250
3246
  * Update the expiration date of an existing assignment
3251
3247
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
3252
3248
  *
3253
- * Sends `{ expires_at }` verbatim. Use an ISO-8601 date/time string; `null`
3254
- * is retained as a compatibility value and, unlike ordinary nullable
3255
- * inputs, is intentionally not stripped from the body.
3249
+ * Sends `{ expires_at }` verbatim; the key itself is required by the
3250
+ * contract. Use an ISO-8601 date/time string, or `null` to remove the
3251
+ * expiration — `null` is the documented clear mechanism and, unlike
3252
+ * ordinary nullable inputs, is intentionally not stripped from the body.
3256
3253
  *
3257
3254
  * Request body (`application/json`):
3258
3255
  * ```jsonc
@@ -3263,8 +3260,8 @@ declare class AssignmentResource extends BaseResource {
3263
3260
  *
3264
3261
  * @param documentId - The document the assignment belongs to.
3265
3262
  * @param assignmentId - The assignment to update.
3266
- * @param expiresAt - New expiry as an ISO-8601 date/time string. `null` is
3267
- * a compatibility value intended to clear it.
3263
+ * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
3264
+ * to remove the expiration.
3268
3265
  * @returns The updated {@link IAssignment} — the same full shape
3269
3266
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
3270
3267
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -4197,7 +4194,7 @@ declare class TemplateResource extends BaseResource {
4197
4194
  * ```ts
4198
4195
  * const tmpl = await client.templates.get('103ad2171db7979468c3e97eb067');
4199
4196
  * const jpeg = await client.templates.downloadPage(tmpl.id, tmpl.pages[0].id);
4200
- * await fs.writeFile('page-1.jpg', jpeg);
4197
+ * await fs.promises.writeFile('page-1.jpg', jpeg);
4201
4198
  * ```
4202
4199
  */
4203
4200
  downloadPage(templateId: string, pageId: string, accountId?: string): Promise<Buffer>;
@@ -4472,10 +4469,10 @@ declare class AuthenticationResource extends BaseResource {
4472
4469
  * ]
4473
4470
  * }
4474
4471
  * ```
4475
- * @throws {ValidationError} If `email` or `password` is missing.
4476
4472
  * When the user has two-factor authentication enabled the response carries
4477
4473
  * an `mfa_token` instead of a usable session; finish with
4478
4474
  * {@link AuthenticationResource.verifyMfa}.
4475
+ * @throws {ValidationError} If `email` or `password` is missing.
4479
4476
  * @throws {ApiError} `400` if the credentials are rejected.
4480
4477
  *
4481
4478
  * @example
@@ -4597,13 +4594,6 @@ declare class AuthenticationResource extends BaseResource {
4597
4594
  * Link a Google identity to the authenticated user
4598
4595
  * (`POST /auth/link-social-login`).
4599
4596
  *
4600
- * Request body:
4601
- * ```jsonc
4602
- * { "provider": "google", "token": "provider-issued-token" }
4603
- * ```
4604
- * The response is the standard status/message acknowledgement with no data,
4605
- * so this method resolves to `void`.
4606
- *
4607
4597
  * Request body (`application/json`):
4608
4598
  * ```jsonc
4609
4599
  * {
@@ -4611,6 +4601,8 @@ declare class AuthenticationResource extends BaseResource {
4611
4601
  * "token": "provider_token_example"
4612
4602
  * }
4613
4603
  * ```
4604
+ * The response is the standard status/message acknowledgement with no data,
4605
+ * so this method resolves to `void`.
4614
4606
  *
4615
4607
  * @param payload - Social provider and provider-issued access/ID token.
4616
4608
  * @returns Resolves when the API acknowledges that the identity was linked.
@@ -5269,6 +5261,11 @@ declare class OAuthResource extends BaseResource {
5269
5261
  * already-revoked included — so the endpoint cannot be used to probe
5270
5262
  * whether a token exists. Only failed client authentication returns `401`.
5271
5263
  *
5264
+ * Request body (`application/x-www-form-urlencoded`):
5265
+ * ```text
5266
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
5267
+ * ```
5268
+ *
5272
5269
  * @param options - Revocation options.
5273
5270
  * @param options.token - The access or refresh token to revoke.
5274
5271
  * @param options.clientId - The application's `client_id`.
@@ -5277,10 +5274,6 @@ declare class OAuthResource extends BaseResource {
5277
5274
  * @param options.tokenTypeHint - Optional `access_token` or
5278
5275
  * `refresh_token` hint that lets the server skip a lookup.
5279
5276
  * @returns Nothing; resolves once the API acknowledges the request.
5280
- * Request body (`application/x-www-form-urlencoded`):
5281
- * ```text
5282
- * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
5283
- * ```
5284
5277
  * @throws {ValidationError} If `token` or `clientId` is missing, or
5285
5278
  * `tokenTypeHint` is not one of the two documented values.
5286
5279
  * @throws {OAuthError} `invalid_client` when client authentication fails.
@@ -5856,7 +5849,7 @@ declare class SignerDocumentsResource extends BaseResource {
5856
5849
  * documentId,
5857
5850
  * 'original',
5858
5851
  * );
5859
- * await fs.writeFile('to-sign.pdf', pdf);
5852
+ * await fs.promises.writeFile('to-sign.pdf', pdf);
5860
5853
  * ```
5861
5854
  */
5862
5855
  download(signerId: string, documentId: string, artifactName: DocumentArtifactName, signerAccessCode?: string): Promise<Buffer>;
@@ -6179,7 +6172,7 @@ declare class SignerDocumentsResource extends BaseResource {
6179
6172
  * @example
6180
6173
  * ```ts
6181
6174
  * const png = await client.signerDocuments.downloadSignature(accessCode, 'signature');
6182
- * await fs.writeFile('signature.png', png);
6175
+ * await fs.promises.writeFile('signature.png', png);
6183
6176
  * ```
6184
6177
  */
6185
6178
  downloadSignature(signerAccessCode: string, imageType?: SignatureImageType): Promise<Buffer>;
package/dist/index.d.ts CHANGED
@@ -2274,40 +2274,36 @@ declare class DocumentResource extends BaseResource {
2274
2274
  */
2275
2275
  getPublic(documentId: string): Promise<IPublicDocumentInfo>;
2276
2276
  /**
2277
- * Send the signer's access token to their email / WhatsApp
2277
+ * Send the signer's access token to their email
2278
2278
  * (`PUT /public/documents/{documentId}/send-token`).
2279
2279
  *
2280
2280
  * Part of the public signing flow: dispatches the 6-digit verification
2281
2281
  * token the signer enters to view the document. The documented request body
2282
- * is `{ email }`. For compatibility with Assinafy environments that still
2283
- * require the older contract, passing an explicit `channel` sends
2284
- * `{ recipient, channel }`; the two-argument documented call also retries
2285
- * that legacy shape only when the server explicitly reports that
2286
- * `channel`/`recipient` is required.
2282
+ * is `{ recipient, channel }` with `channel` set to `email`. This
2283
+ * two-argument form sends the legacy `{ email }` shape, which current
2284
+ * deployments still accept, and retries the documented shape only when the
2285
+ * server explicitly reports that `channel`/`recipient` is required. Use the
2286
+ * three-argument overload to send the documented shape directly.
2287
2287
  *
2288
2288
  * Request body (`application/json`):
2289
2289
  * ```jsonc
2290
2290
  * { "email": "signer@example.com" }
2291
2291
  * ```
2292
- * Compatibility fallback or explicit-channel body:
2292
+ * Documented body, sent on the explicit-channel overload or on retry:
2293
2293
  * ```jsonc
2294
2294
  * { "recipient": "signer@example.com", "channel": "email" }
2295
2295
  * ```
2296
2296
  *
2297
2297
  * @param documentId - The document to send the token for.
2298
- * @param recipient - The signer's email address (or WhatsApp number when an
2299
- * explicit channel is supplied).
2300
- * @param channel - Optional legacy delivery channel.
2298
+ * @param email - The signer's email address.
2301
2299
  * @returns Nothing after the API's empty acknowledgement.
2302
- * @throws {ValidationError} If `documentId` or `recipient` is missing, the
2303
- * official two-argument form does not receive a valid email address, or a
2304
- * supplied `channel` is not a non-empty string.
2300
+ * @throws {ValidationError} If `documentId` is missing or `email` is not a
2301
+ * valid email address.
2305
2302
  * @throws {ApiError} If the API rejects the request.
2306
2303
  *
2307
2304
  * @example
2308
2305
  * ```ts
2309
2306
  * await client.documents.sendToken('doc-1', 'signer@example.com');
2310
- * await client.documents.sendToken('doc-1', '+5511999998888', 'whatsapp');
2311
2307
  * ```
2312
2308
  */
2313
2309
  sendToken(documentId: string, email: string): Promise<void>;
@@ -2957,10 +2953,10 @@ declare class WorkspaceResource extends BaseResource {
2957
2953
  * ```ts
2958
2954
  * const body = buildAssignmentPayload({
2959
2955
  * method: 'virtual',
2960
- * signers: ['signer-1', { signer_id: 'signer-2', step: 2 }],
2956
+ * signers: [{ signer_id: 'signer-1', step: 1 }, { signer_id: 'signer-2', step: 2 }],
2961
2957
  * message: 'Please sign',
2962
2958
  * });
2963
- * // body.signers → [{ id: 'signer-1' }, { id: 'signer-2', step: 2 }]
2959
+ * // body.signers → [{ id: 'signer-1', step: 1 }, { id: 'signer-2', step: 2 }]
2964
2960
  * ```
2965
2961
  */
2966
2962
  declare function buildAssignmentPayload(payload: ICreateAssignmentPayload): Record<string, unknown>;
@@ -3250,9 +3246,10 @@ declare class AssignmentResource extends BaseResource {
3250
3246
  * Update the expiration date of an existing assignment
3251
3247
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
3252
3248
  *
3253
- * Sends `{ expires_at }` verbatim. Use an ISO-8601 date/time string; `null`
3254
- * is retained as a compatibility value and, unlike ordinary nullable
3255
- * inputs, is intentionally not stripped from the body.
3249
+ * Sends `{ expires_at }` verbatim; the key itself is required by the
3250
+ * contract. Use an ISO-8601 date/time string, or `null` to remove the
3251
+ * expiration — `null` is the documented clear mechanism and, unlike
3252
+ * ordinary nullable inputs, is intentionally not stripped from the body.
3256
3253
  *
3257
3254
  * Request body (`application/json`):
3258
3255
  * ```jsonc
@@ -3263,8 +3260,8 @@ declare class AssignmentResource extends BaseResource {
3263
3260
  *
3264
3261
  * @param documentId - The document the assignment belongs to.
3265
3262
  * @param assignmentId - The assignment to update.
3266
- * @param expiresAt - New expiry as an ISO-8601 date/time string. `null` is
3267
- * a compatibility value intended to clear it.
3263
+ * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
3264
+ * to remove the expiration.
3268
3265
  * @returns The updated {@link IAssignment} — the same full shape
3269
3266
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
3270
3267
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -4197,7 +4194,7 @@ declare class TemplateResource extends BaseResource {
4197
4194
  * ```ts
4198
4195
  * const tmpl = await client.templates.get('103ad2171db7979468c3e97eb067');
4199
4196
  * const jpeg = await client.templates.downloadPage(tmpl.id, tmpl.pages[0].id);
4200
- * await fs.writeFile('page-1.jpg', jpeg);
4197
+ * await fs.promises.writeFile('page-1.jpg', jpeg);
4201
4198
  * ```
4202
4199
  */
4203
4200
  downloadPage(templateId: string, pageId: string, accountId?: string): Promise<Buffer>;
@@ -4472,10 +4469,10 @@ declare class AuthenticationResource extends BaseResource {
4472
4469
  * ]
4473
4470
  * }
4474
4471
  * ```
4475
- * @throws {ValidationError} If `email` or `password` is missing.
4476
4472
  * When the user has two-factor authentication enabled the response carries
4477
4473
  * an `mfa_token` instead of a usable session; finish with
4478
4474
  * {@link AuthenticationResource.verifyMfa}.
4475
+ * @throws {ValidationError} If `email` or `password` is missing.
4479
4476
  * @throws {ApiError} `400` if the credentials are rejected.
4480
4477
  *
4481
4478
  * @example
@@ -4597,13 +4594,6 @@ declare class AuthenticationResource extends BaseResource {
4597
4594
  * Link a Google identity to the authenticated user
4598
4595
  * (`POST /auth/link-social-login`).
4599
4596
  *
4600
- * Request body:
4601
- * ```jsonc
4602
- * { "provider": "google", "token": "provider-issued-token" }
4603
- * ```
4604
- * The response is the standard status/message acknowledgement with no data,
4605
- * so this method resolves to `void`.
4606
- *
4607
4597
  * Request body (`application/json`):
4608
4598
  * ```jsonc
4609
4599
  * {
@@ -4611,6 +4601,8 @@ declare class AuthenticationResource extends BaseResource {
4611
4601
  * "token": "provider_token_example"
4612
4602
  * }
4613
4603
  * ```
4604
+ * The response is the standard status/message acknowledgement with no data,
4605
+ * so this method resolves to `void`.
4614
4606
  *
4615
4607
  * @param payload - Social provider and provider-issued access/ID token.
4616
4608
  * @returns Resolves when the API acknowledges that the identity was linked.
@@ -5269,6 +5261,11 @@ declare class OAuthResource extends BaseResource {
5269
5261
  * already-revoked included — so the endpoint cannot be used to probe
5270
5262
  * whether a token exists. Only failed client authentication returns `401`.
5271
5263
  *
5264
+ * Request body (`application/x-www-form-urlencoded`):
5265
+ * ```text
5266
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
5267
+ * ```
5268
+ *
5272
5269
  * @param options - Revocation options.
5273
5270
  * @param options.token - The access or refresh token to revoke.
5274
5271
  * @param options.clientId - The application's `client_id`.
@@ -5277,10 +5274,6 @@ declare class OAuthResource extends BaseResource {
5277
5274
  * @param options.tokenTypeHint - Optional `access_token` or
5278
5275
  * `refresh_token` hint that lets the server skip a lookup.
5279
5276
  * @returns Nothing; resolves once the API acknowledges the request.
5280
- * Request body (`application/x-www-form-urlencoded`):
5281
- * ```text
5282
- * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
5283
- * ```
5284
5277
  * @throws {ValidationError} If `token` or `clientId` is missing, or
5285
5278
  * `tokenTypeHint` is not one of the two documented values.
5286
5279
  * @throws {OAuthError} `invalid_client` when client authentication fails.
@@ -5856,7 +5849,7 @@ declare class SignerDocumentsResource extends BaseResource {
5856
5849
  * documentId,
5857
5850
  * 'original',
5858
5851
  * );
5859
- * await fs.writeFile('to-sign.pdf', pdf);
5852
+ * await fs.promises.writeFile('to-sign.pdf', pdf);
5860
5853
  * ```
5861
5854
  */
5862
5855
  download(signerId: string, documentId: string, artifactName: DocumentArtifactName, signerAccessCode?: string): Promise<Buffer>;
@@ -6179,7 +6172,7 @@ declare class SignerDocumentsResource extends BaseResource {
6179
6172
  * @example
6180
6173
  * ```ts
6181
6174
  * const png = await client.signerDocuments.downloadSignature(accessCode, 'signature');
6182
- * await fs.writeFile('signature.png', png);
6175
+ * await fs.promises.writeFile('signature.png', png);
6183
6176
  * ```
6184
6177
  */
6185
6178
  downloadSignature(signerAccessCode: string, imageType?: SignatureImageType): Promise<Buffer>;
package/dist/index.js CHANGED
@@ -158,7 +158,7 @@ var ApiError = class _ApiError extends AssinafyError {
158
158
  const data = responseData ?? {};
159
159
  const rawMessage = data["message"];
160
160
  const rawError = data["error"];
161
- const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : FALLBACK_MESSAGE;
161
+ const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" && rawError.length > 0 ? rawError : FALLBACK_MESSAGE;
162
162
  return new _ApiError(message, statusCode, responseData);
163
163
  }
164
164
  };
@@ -455,15 +455,16 @@ function assertDocumentArtifactName(value) {
455
455
  }
456
456
  function serializeJsonRecord(value, label) {
457
457
  assertRecord(value, label);
458
+ let serialized;
458
459
  try {
459
- const serialized = JSON.stringify(value);
460
- if (typeof serialized !== "string" || !serialized.startsWith("{")) {
461
- throw new ValidationError(`${label} must serialize to a JSON object`);
462
- }
463
- return serialized;
460
+ serialized = JSON.stringify(value);
464
461
  } catch {
465
462
  throw new ValidationError(`${label} must be JSON-serializable`);
466
463
  }
464
+ if (typeof serialized !== "string" || !serialized.startsWith("{")) {
465
+ throw new ValidationError(`${label} must serialize to a JSON object`);
466
+ }
467
+ return serialized;
467
468
  }
468
469
  function assertDateTime(value, label) {
469
470
  if (typeof value !== "string") throw new ValidationError(`${label} must be an ISO-8601 date-time`);
@@ -651,7 +652,7 @@ var import_axios2 = __toESM(require("axios"));
651
652
  // package.json
652
653
  var package_default = {
653
654
  name: "@assinafy/sdk",
654
- version: "2.6.0",
655
+ version: "2.7.0",
655
656
  packageManager: "bun@1.4.0",
656
657
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
657
658
  type: "commonjs",
@@ -1545,9 +1546,10 @@ var AssignmentResource = class extends BaseResource {
1545
1546
  * Update the expiration date of an existing assignment
1546
1547
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
1547
1548
  *
1548
- * Sends `{ expires_at }` verbatim. Use an ISO-8601 date/time string; `null`
1549
- * is retained as a compatibility value and, unlike ordinary nullable
1550
- * inputs, is intentionally not stripped from the body.
1549
+ * Sends `{ expires_at }` verbatim; the key itself is required by the
1550
+ * contract. Use an ISO-8601 date/time string, or `null` to remove the
1551
+ * expiration — `null` is the documented clear mechanism and, unlike
1552
+ * ordinary nullable inputs, is intentionally not stripped from the body.
1551
1553
  *
1552
1554
  * Request body (`application/json`):
1553
1555
  * ```jsonc
@@ -1558,8 +1560,8 @@ var AssignmentResource = class extends BaseResource {
1558
1560
  *
1559
1561
  * @param documentId - The document the assignment belongs to.
1560
1562
  * @param assignmentId - The assignment to update.
1561
- * @param expiresAt - New expiry as an ISO-8601 date/time string. `null` is
1562
- * a compatibility value intended to clear it.
1563
+ * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
1564
+ * to remove the expiration.
1563
1565
  * @returns The updated {@link IAssignment} — the same full shape
1564
1566
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
1565
1567
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -4808,7 +4810,7 @@ var TemplateResource = class extends BaseResource {
4808
4810
  * ```ts
4809
4811
  * const tmpl = await client.templates.get('103ad2171db7979468c3e97eb067');
4810
4812
  * const jpeg = await client.templates.downloadPage(tmpl.id, tmpl.pages[0].id);
4811
- * await fs.writeFile('page-1.jpg', jpeg);
4813
+ * await fs.promises.writeFile('page-1.jpg', jpeg);
4812
4814
  * ```
4813
4815
  */
4814
4816
  async downloadPage(templateId, pageId, accountId) {
@@ -5145,10 +5147,10 @@ var AuthenticationResource = class extends BaseResource {
5145
5147
  * ]
5146
5148
  * }
5147
5149
  * ```
5148
- * @throws {ValidationError} If `email` or `password` is missing.
5149
5150
  * When the user has two-factor authentication enabled the response carries
5150
5151
  * an `mfa_token` instead of a usable session; finish with
5151
5152
  * {@link AuthenticationResource.verifyMfa}.
5153
+ * @throws {ValidationError} If `email` or `password` is missing.
5152
5154
  * @throws {ApiError} `400` if the credentials are rejected.
5153
5155
  *
5154
5156
  * @example
@@ -5296,13 +5298,6 @@ var AuthenticationResource = class extends BaseResource {
5296
5298
  * Link a Google identity to the authenticated user
5297
5299
  * (`POST /auth/link-social-login`).
5298
5300
  *
5299
- * Request body:
5300
- * ```jsonc
5301
- * { "provider": "google", "token": "provider-issued-token" }
5302
- * ```
5303
- * The response is the standard status/message acknowledgement with no data,
5304
- * so this method resolves to `void`.
5305
- *
5306
5301
  * Request body (`application/json`):
5307
5302
  * ```jsonc
5308
5303
  * {
@@ -5310,6 +5305,8 @@ var AuthenticationResource = class extends BaseResource {
5310
5305
  * "token": "provider_token_example"
5311
5306
  * }
5312
5307
  * ```
5308
+ * The response is the standard status/message acknowledgement with no data,
5309
+ * so this method resolves to `void`.
5313
5310
  *
5314
5311
  * @param payload - Social provider and provider-issued access/ID token.
5315
5312
  * @returns Resolves when the API acknowledges that the identity was linked.
@@ -6066,6 +6063,11 @@ var OAuthResource = class extends BaseResource {
6066
6063
  * already-revoked included — so the endpoint cannot be used to probe
6067
6064
  * whether a token exists. Only failed client authentication returns `401`.
6068
6065
  *
6066
+ * Request body (`application/x-www-form-urlencoded`):
6067
+ * ```text
6068
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
6069
+ * ```
6070
+ *
6069
6071
  * @param options - Revocation options.
6070
6072
  * @param options.token - The access or refresh token to revoke.
6071
6073
  * @param options.clientId - The application's `client_id`.
@@ -6074,10 +6076,6 @@ var OAuthResource = class extends BaseResource {
6074
6076
  * @param options.tokenTypeHint - Optional `access_token` or
6075
6077
  * `refresh_token` hint that lets the server skip a lookup.
6076
6078
  * @returns Nothing; resolves once the API acknowledges the request.
6077
- * Request body (`application/x-www-form-urlencoded`):
6078
- * ```text
6079
- * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
6080
- * ```
6081
6079
  * @throws {ValidationError} If `token` or `clientId` is missing, or
6082
6080
  * `tokenTypeHint` is not one of the two documented values.
6083
6081
  * @throws {OAuthError} `invalid_client` when client authentication fails.
@@ -6932,7 +6930,7 @@ var SignerDocumentsResource = class extends BaseResource {
6932
6930
  * documentId,
6933
6931
  * 'original',
6934
6932
  * );
6935
- * await fs.writeFile('to-sign.pdf', pdf);
6933
+ * await fs.promises.writeFile('to-sign.pdf', pdf);
6936
6934
  * ```
6937
6935
  */
6938
6936
  async download(signerId, documentId, artifactName, signerAccessCode) {
@@ -7239,7 +7237,7 @@ var SignerDocumentsResource = class extends BaseResource {
7239
7237
  * @example
7240
7238
  * ```ts
7241
7239
  * const png = await client.signerDocuments.downloadSignature(accessCode, 'signature');
7242
- * await fs.writeFile('signature.png', png);
7240
+ * await fs.promises.writeFile('signature.png', png);
7243
7241
  * ```
7244
7242
  */
7245
7243
  async downloadSignature(signerAccessCode, imageType = "signature") {
@@ -8255,7 +8253,7 @@ var AssinafyClient = class _AssinafyClient {
8255
8253
  if (baseUrl !== void 0) opts.baseUrl = baseUrl;
8256
8254
  if (webhookSecret !== void 0) opts.webhookSecret = webhookSecret;
8257
8255
  if (config.timeout !== void 0) opts.timeout = config.timeout;
8258
- const maxRetries = config.maxRetries ?? config.max_retries;
8256
+ const maxRetries = config.max_retries ?? config.maxRetries;
8259
8257
  if (maxRetries !== void 0) opts.maxRetries = maxRetries;
8260
8258
  if (config.logger !== void 0) opts.logger = config.logger;
8261
8259
  return new _AssinafyClient(opts);
package/dist/index.mjs CHANGED
@@ -98,7 +98,7 @@ var ApiError = class _ApiError extends AssinafyError {
98
98
  const data = responseData ?? {};
99
99
  const rawMessage = data["message"];
100
100
  const rawError = data["error"];
101
- const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : FALLBACK_MESSAGE;
101
+ const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" && rawError.length > 0 ? rawError : FALLBACK_MESSAGE;
102
102
  return new _ApiError(message, statusCode, responseData);
103
103
  }
104
104
  };
@@ -395,15 +395,16 @@ function assertDocumentArtifactName(value) {
395
395
  }
396
396
  function serializeJsonRecord(value, label) {
397
397
  assertRecord(value, label);
398
+ let serialized;
398
399
  try {
399
- const serialized = JSON.stringify(value);
400
- if (typeof serialized !== "string" || !serialized.startsWith("{")) {
401
- throw new ValidationError(`${label} must serialize to a JSON object`);
402
- }
403
- return serialized;
400
+ serialized = JSON.stringify(value);
404
401
  } catch {
405
402
  throw new ValidationError(`${label} must be JSON-serializable`);
406
403
  }
404
+ if (typeof serialized !== "string" || !serialized.startsWith("{")) {
405
+ throw new ValidationError(`${label} must serialize to a JSON object`);
406
+ }
407
+ return serialized;
407
408
  }
408
409
  function assertDateTime(value, label) {
409
410
  if (typeof value !== "string") throw new ValidationError(`${label} must be an ISO-8601 date-time`);
@@ -591,7 +592,7 @@ import axios2 from "axios";
591
592
  // package.json
592
593
  var package_default = {
593
594
  name: "@assinafy/sdk",
594
- version: "2.6.0",
595
+ version: "2.7.0",
595
596
  packageManager: "bun@1.4.0",
596
597
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
597
598
  type: "commonjs",
@@ -1485,9 +1486,10 @@ var AssignmentResource = class extends BaseResource {
1485
1486
  * Update the expiration date of an existing assignment
1486
1487
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
1487
1488
  *
1488
- * Sends `{ expires_at }` verbatim. Use an ISO-8601 date/time string; `null`
1489
- * is retained as a compatibility value and, unlike ordinary nullable
1490
- * inputs, is intentionally not stripped from the body.
1489
+ * Sends `{ expires_at }` verbatim; the key itself is required by the
1490
+ * contract. Use an ISO-8601 date/time string, or `null` to remove the
1491
+ * expiration — `null` is the documented clear mechanism and, unlike
1492
+ * ordinary nullable inputs, is intentionally not stripped from the body.
1491
1493
  *
1492
1494
  * Request body (`application/json`):
1493
1495
  * ```jsonc
@@ -1498,8 +1500,8 @@ var AssignmentResource = class extends BaseResource {
1498
1500
  *
1499
1501
  * @param documentId - The document the assignment belongs to.
1500
1502
  * @param assignmentId - The assignment to update.
1501
- * @param expiresAt - New expiry as an ISO-8601 date/time string. `null` is
1502
- * a compatibility value intended to clear it.
1503
+ * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
1504
+ * to remove the expiration.
1503
1505
  * @returns The updated {@link IAssignment} — the same full shape
1504
1506
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
1505
1507
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -4748,7 +4750,7 @@ var TemplateResource = class extends BaseResource {
4748
4750
  * ```ts
4749
4751
  * const tmpl = await client.templates.get('103ad2171db7979468c3e97eb067');
4750
4752
  * const jpeg = await client.templates.downloadPage(tmpl.id, tmpl.pages[0].id);
4751
- * await fs.writeFile('page-1.jpg', jpeg);
4753
+ * await fs.promises.writeFile('page-1.jpg', jpeg);
4752
4754
  * ```
4753
4755
  */
4754
4756
  async downloadPage(templateId, pageId, accountId) {
@@ -5085,10 +5087,10 @@ var AuthenticationResource = class extends BaseResource {
5085
5087
  * ]
5086
5088
  * }
5087
5089
  * ```
5088
- * @throws {ValidationError} If `email` or `password` is missing.
5089
5090
  * When the user has two-factor authentication enabled the response carries
5090
5091
  * an `mfa_token` instead of a usable session; finish with
5091
5092
  * {@link AuthenticationResource.verifyMfa}.
5093
+ * @throws {ValidationError} If `email` or `password` is missing.
5092
5094
  * @throws {ApiError} `400` if the credentials are rejected.
5093
5095
  *
5094
5096
  * @example
@@ -5236,13 +5238,6 @@ var AuthenticationResource = class extends BaseResource {
5236
5238
  * Link a Google identity to the authenticated user
5237
5239
  * (`POST /auth/link-social-login`).
5238
5240
  *
5239
- * Request body:
5240
- * ```jsonc
5241
- * { "provider": "google", "token": "provider-issued-token" }
5242
- * ```
5243
- * The response is the standard status/message acknowledgement with no data,
5244
- * so this method resolves to `void`.
5245
- *
5246
5241
  * Request body (`application/json`):
5247
5242
  * ```jsonc
5248
5243
  * {
@@ -5250,6 +5245,8 @@ var AuthenticationResource = class extends BaseResource {
5250
5245
  * "token": "provider_token_example"
5251
5246
  * }
5252
5247
  * ```
5248
+ * The response is the standard status/message acknowledgement with no data,
5249
+ * so this method resolves to `void`.
5253
5250
  *
5254
5251
  * @param payload - Social provider and provider-issued access/ID token.
5255
5252
  * @returns Resolves when the API acknowledges that the identity was linked.
@@ -6006,6 +6003,11 @@ var OAuthResource = class extends BaseResource {
6006
6003
  * already-revoked included — so the endpoint cannot be used to probe
6007
6004
  * whether a token exists. Only failed client authentication returns `401`.
6008
6005
  *
6006
+ * Request body (`application/x-www-form-urlencoded`):
6007
+ * ```text
6008
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
6009
+ * ```
6010
+ *
6009
6011
  * @param options - Revocation options.
6010
6012
  * @param options.token - The access or refresh token to revoke.
6011
6013
  * @param options.clientId - The application's `client_id`.
@@ -6014,10 +6016,6 @@ var OAuthResource = class extends BaseResource {
6014
6016
  * @param options.tokenTypeHint - Optional `access_token` or
6015
6017
  * `refresh_token` hint that lets the server skip a lookup.
6016
6018
  * @returns Nothing; resolves once the API acknowledges the request.
6017
- * Request body (`application/x-www-form-urlencoded`):
6018
- * ```text
6019
- * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
6020
- * ```
6021
6019
  * @throws {ValidationError} If `token` or `clientId` is missing, or
6022
6020
  * `tokenTypeHint` is not one of the two documented values.
6023
6021
  * @throws {OAuthError} `invalid_client` when client authentication fails.
@@ -6872,7 +6870,7 @@ var SignerDocumentsResource = class extends BaseResource {
6872
6870
  * documentId,
6873
6871
  * 'original',
6874
6872
  * );
6875
- * await fs.writeFile('to-sign.pdf', pdf);
6873
+ * await fs.promises.writeFile('to-sign.pdf', pdf);
6876
6874
  * ```
6877
6875
  */
6878
6876
  async download(signerId, documentId, artifactName, signerAccessCode) {
@@ -7179,7 +7177,7 @@ var SignerDocumentsResource = class extends BaseResource {
7179
7177
  * @example
7180
7178
  * ```ts
7181
7179
  * const png = await client.signerDocuments.downloadSignature(accessCode, 'signature');
7182
- * await fs.writeFile('signature.png', png);
7180
+ * await fs.promises.writeFile('signature.png', png);
7183
7181
  * ```
7184
7182
  */
7185
7183
  async downloadSignature(signerAccessCode, imageType = "signature") {
@@ -8195,7 +8193,7 @@ var AssinafyClient = class _AssinafyClient {
8195
8193
  if (baseUrl !== void 0) opts.baseUrl = baseUrl;
8196
8194
  if (webhookSecret !== void 0) opts.webhookSecret = webhookSecret;
8197
8195
  if (config.timeout !== void 0) opts.timeout = config.timeout;
8198
- const maxRetries = config.maxRetries ?? config.max_retries;
8196
+ const maxRetries = config.max_retries ?? config.maxRetries;
8199
8197
  if (maxRetries !== void 0) opts.maxRetries = maxRetries;
8200
8198
  if (config.logger !== void 0) opts.logger = config.logger;
8201
8199
  return new _AssinafyClient(opts);
@@ -179,7 +179,7 @@ Five additional routes are documented separately under
179
179
  | `POST` | `/v1/users/self/mfa/totp` | `client.users.startTotpEnrollment(label?)` | Covered |
180
180
  | `PUT` | `/v1/users/self/mfa/totp/confirm` | `client.users.confirmTotpEnrollment(payload)` | Covered |
181
181
  | `POST` | `/v1/users/self/mfa/recovery-codes` | `client.users.regenerateRecoveryCodes(proof)` | Covered |
182
- | `DELETE` | `/v1/users/self/mfa/{customId}` | `client.users.deleteMfaMethod(customId, proof)` | Covered |
182
+ | `DELETE` | `/v1/users/self/mfa/{customId}` | `client.users.deleteMfaMethod(methodId, proof)` | Covered |
183
183
 
184
184
  ## Webhooks — 13/13
185
185
 
@@ -194,29 +194,30 @@ and returns the JPEG bytes as a `Buffer`.
194
194
 
195
195
  ## Public send-token request
196
196
 
197
- The official operation sends an email body:
197
+ The official operation requires a recipient and a channel (`email` is the only
198
+ documented channel):
198
199
 
199
200
  ```http
200
201
  PUT /v1/public/documents/{documentId}/send-token
201
202
  Content-Type: application/json
202
203
 
203
- { "email": "signer@example.com" }
204
+ { "recipient": "signer@example.com", "channel": "email" }
204
205
  ```
205
206
 
206
207
  ```ts
207
- await client.documents.sendToken(documentId, 'signer@example.com');
208
+ await client.documents.sendToken(documentId, 'signer@example.com', 'email');
208
209
  ```
209
210
 
210
- Older environments can require `{ recipient, channel }`. The explicit
211
- three-argument overload sends that shape:
211
+ The two-argument overload sends the legacy `{ email }` shape, which current
212
+ deployments still accept:
212
213
 
213
214
  ```ts
214
- await client.documents.sendToken(documentId, '+5511999990000', 'whatsapp');
215
+ await client.documents.sendToken(documentId, 'signer@example.com');
215
216
  ```
216
217
 
217
- For a two-argument call, the SDK starts with `{ email }` and retries the older
218
- email shape only when the validation response names `recipient` or `channel` as
219
- required. Other errors are returned unchanged.
218
+ When a deployment rejects `{ email }` with a validation response naming
219
+ `recipient` or `channel` as required, the SDK retries the documented shape
220
+ automatically. Other errors are returned unchanged.
220
221
 
221
222
  ## Document tags
222
223
 
@@ -344,9 +345,9 @@ Document upload accepts a PDF of at most 25 MB and 2,000 pages. The multipart
344
345
  schema documents the file; the SDK's optional `metadata` JSON part is retained
345
346
  for deployments that accept application-owned opaque metadata.
346
347
 
347
- The reset-expiration schema requires an ISO-8601 date-time string. The SDK also
348
- accepts `null` for older integrations that clear an expiration this way. Confirm
349
- support in the target deployment before sending `null`.
348
+ The reset-expiration schema requires the `expires_at` key itself: send an
349
+ ISO-8601 date-time string, or `null` to remove the expiration. The SDK's
350
+ `resetExpiration` always sends the key and accepts `null` for clearing.
350
351
 
351
352
  ## Resend-cost response variants
352
353
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@assinafy/sdk",
3
- "version": "2.6.0",
3
+ "version": "2.7.0",
4
4
  "packageManager": "bun@1.4.0",
5
5
  "description": "TypeScript SDK for Assinafy API - Digital signature platform",
6
6
  "type": "commonjs",