@assinafy/cli 2.4.2 → 2.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.example +4 -2
- package/README.en.md +46 -21
- package/README.md +34 -15
- package/dist/api.cjs +295 -55
- package/dist/api.cjs.map +1 -1
- package/dist/api.js +295 -55
- package/dist/api.js.map +1 -1
- package/dist/cli.cjs +635 -100
- package/dist/types/api/errors.d.ts +9 -0
- package/dist/types/api/errors.d.ts.map +1 -1
- package/dist/types/api/index.d.ts +1 -1
- package/dist/types/api/index.d.ts.map +1 -1
- package/dist/types/api/resources/authentication.d.ts +33 -3
- package/dist/types/api/resources/authentication.d.ts.map +1 -1
- package/dist/types/api/resources/documents.d.ts +4 -3
- package/dist/types/api/resources/documents.d.ts.map +1 -1
- package/dist/types/api/resources/oauth.d.ts +1 -1
- package/dist/types/api/resources/oauth.d.ts.map +1 -1
- package/dist/types/api/resources/signer-documents.d.ts +9 -4
- package/dist/types/api/resources/signer-documents.d.ts.map +1 -1
- package/dist/types/api/resources/webhooks.d.ts +39 -6
- package/dist/types/api/resources/webhooks.d.ts.map +1 -1
- package/dist/types/api/support/webhook-verifier.d.ts +31 -14
- package/dist/types/api/support/webhook-verifier.d.ts.map +1 -1
- package/dist/types/api/types.d.ts +110 -21
- package/dist/types/api/types.d.ts.map +1 -1
- package/dist/types/api/utils.d.ts.map +1 -1
- package/docs/README.md +1 -1
- package/docs/api-operations.json +105 -1
- package/docs/api-reference.md +2380 -2057
- package/docs/auth.md +125 -4
- package/docs/documents.md +5 -6
- package/docs/migration-v2.md +1 -1
- package/docs/sdk-reference.md +84 -23
- package/docs/signer.md +4 -2
- package/docs/webhooks.md +185 -20
- package/package.json +2 -2
package/.env.example
CHANGED
|
@@ -32,9 +32,11 @@ ASSINAFY_RESET_TOKEN=
|
|
|
32
32
|
ASSINAFY_SIGNER_ACCESS_CODE=
|
|
33
33
|
ASSINAFY_VERIFICATION_CODE=
|
|
34
34
|
ASSINAFY_CERTIFICATE_TOKEN=
|
|
35
|
+
ASSINAFY_MFA_CODE=
|
|
36
|
+
ASSINAFY_MFA_TOKEN=
|
|
35
37
|
|
|
36
|
-
#
|
|
37
|
-
#
|
|
38
|
+
# Endpoint signing secret (whsec_...) used by the SDK WebhookVerifier.
|
|
39
|
+
# Read it with `assinafy webhooks endpoints secret <endpointId>`.
|
|
38
40
|
ASSINAFY_WEBHOOK_SECRET=
|
|
39
41
|
|
|
40
42
|
# Named profile to select from the config file (~/.config/assinafy/config.json).
|
package/README.en.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
The official command-line interface and Node.js SDK for the [Assinafy API](https://api.assinafy.com.br/v1/docs), a Brazilian digital-signature platform. Upload PDFs, manage signers, request signatures, track activity history, and download certified documents — from a terminal, a shell script, or an application.
|
|
6
6
|
|
|
7
|
-
The CLI is a single self-contained executable. It prints human-readable tables by default and structured JSON with `--json`, so the same commands serve both interactive use and automation. The same package exposes a fully typed SDK at `@assinafy/cli/api` covering all
|
|
7
|
+
The CLI is a single self-contained executable. It prints human-readable tables by default and structured JSON with `--json`, so the same commands serve both interactive use and automation. The same package exposes a fully typed SDK at `@assinafy/cli/api` covering all 106 published API operations.
|
|
8
8
|
|
|
9
9
|
This document reads top to bottom: install, authenticate, send your first signature request, then understand the model well enough to automate it. The [command reference](#command-reference) and [SDK](#nodejs-sdk) sections near the end are lookup tables you can jump to once the flow makes sense.
|
|
10
10
|
|
|
@@ -92,6 +92,8 @@ assinafy auth login you@example.com # returns a JWT
|
|
|
92
92
|
assinafy auth api-keys create --token <jwt> # generates (and rotates) the key
|
|
93
93
|
```
|
|
94
94
|
|
|
95
|
+
When two-factor authentication is enabled, `auth login` asks for an authenticator or recovery code (or reads `--mfa-code` / `ASSINAFY_MFA_CODE`); the challenge is single-use and expires after 5 minutes. `auth mfa enroll`, `confirm`, `list`, `recovery-codes`, and `remove` manage the authenticator and recovery codes.
|
|
96
|
+
|
|
95
97
|
Store the key once, then confirm it works:
|
|
96
98
|
|
|
97
99
|
```bash
|
|
@@ -242,7 +244,7 @@ assinafy signer sign <documentId> <assignmentId> --entries '[
|
|
|
242
244
|
]'
|
|
243
245
|
```
|
|
244
246
|
|
|
245
|
-
Where email or WhatsApp verification is configured, the signer also confirms a 6-digit code. `documents send-token <documentId> --recipient <email
|
|
247
|
+
Where email or WhatsApp verification is configured, the signer also confirms a 6-digit code. The code arrives in the invitation message itself. To email a fresh access token to a signer who has not signed a pending document yet, run `documents send-token <documentId> --recipient <email>` (email channel only; it sends `{ "channel": "email", "recipient": "signer@example.com" }` and returns `document`, `channel`, and `recipient`; `--email` is an alias). Both channels use `signer verify-code`; `verify-email` remains an alias. Set `ASSINAFY_VERIFICATION_CODE` to keep the OTP out of command arguments and preserve leading zeroes. `signer decline` (or `decline-multiple`) rejects with a reason, and `sign-multiple` completes several documents in one call.
|
|
246
248
|
|
|
247
249
|
For A1/A3 certificates, use Assinafy's hosted signing page or integrate Web PKI with the SDK. After document review and terms acceptance, `signer certificate-start --json` returns `{ "token": "..." }`. Have the browser sign that operation on the signer's device, then set `ASSINAFY_CERTIFICATE_TOKEN` to the same token and run `signer certificate-complete --json`; it returns `{ "signerName": "..." }`. Private keys and passwords/PINs stay on the device. Wait for `certificated` status and download `--artifact pades` or `bundle`. The ordinary `sign` command does not perform this handshake. These two production routes use the signing application's payloads and are not yet OpenAPI paths.
|
|
248
250
|
|
|
@@ -263,24 +265,46 @@ Owner API credentials are stripped from every public and signer-side request, so
|
|
|
263
265
|
|
|
264
266
|
## Webhooks
|
|
265
267
|
|
|
266
|
-
Polling works, but webhooks are the right way to react to signing events
|
|
268
|
+
Polling works, but webhooks are the right way to react to signing events. A workspace can register 1 webhook endpoint, or up to 3 on paid plans. Each endpoint has its own URL, events, active flag, and signing setting, and every active endpoint subscribed to an event receives it independently.
|
|
267
269
|
|
|
268
270
|
```bash
|
|
269
271
|
assinafy webhooks event-types # what the platform can send
|
|
270
|
-
assinafy webhooks
|
|
272
|
+
assinafy webhooks endpoints create \
|
|
271
273
|
--url https://example.com/hooks/assinafy \
|
|
272
274
|
--email ops@example.com \
|
|
273
|
-
--
|
|
274
|
-
|
|
275
|
-
|
|
275
|
+
--name ERP \
|
|
276
|
+
--events document_ready,signer_signed_document,signer_rejected_document \
|
|
277
|
+
--signing # sign deliveries
|
|
278
|
+
assinafy webhooks endpoints list
|
|
279
|
+
assinafy webhooks endpoints secret <endpointId> # whsec_ secret for your receiver
|
|
280
|
+
assinafy webhooks endpoints update <endpointId> --inactive
|
|
281
|
+
assinafy webhooks endpoints rotate-secret <endpointId>
|
|
282
|
+
assinafy webhooks endpoints delete <endpointId>
|
|
283
|
+
|
|
284
|
+
assinafy webhooks dispatches --endpoint <endpointId> --delivered false
|
|
276
285
|
assinafy webhooks retry <dispatchId> # redeliver one event
|
|
277
|
-
|
|
278
|
-
assinafy webhooks
|
|
286
|
+
# check a saved delivery with ASSINAFY_WEBHOOK_SECRET (exit code 1 when invalid)
|
|
287
|
+
assinafy webhooks verify body.json --id <webhook-id> --timestamp <webhook-timestamp> --signature <webhook-signature>
|
|
279
288
|
```
|
|
280
289
|
|
|
281
|
-
|
|
290
|
+
Omitting `--events` subscribes to `document_ready`, `document_prepared`, `signer_signed_document`, `signer_rejected_document`, and `document_processing_failed`. `endpoints update` changes only the flags given (`--active`/`--inactive`, `--signing`/`--no-signing`, `--url`, `--email`, `--name`, `--events`); disabling signing discards the secret. `rotate-secret` invalidates the previous secret immediately. A duplicate URL within the workspace returns `400`; creating past the plan limit returns `403`. Secret read and rotation are not available to OAuth applications. `retry` re-sends only to that delivery's endpoint, and only while it is active.
|
|
291
|
+
|
|
292
|
+
`webhooks register`, `webhooks get`, and `webhooks inactivate` remain and act on the workspace's oldest endpoint.
|
|
293
|
+
|
|
294
|
+
Each delivery is a JSON `POST` with a `webhook-id` header (stable across retries of the same event to the same endpoint; use it to deduplicate) and a `webhook-timestamp`. Signed endpoints add a [Standard Webhooks](https://www.standardwebhooks.com) `webhook-signature`. Verify the raw body before parsing it:
|
|
295
|
+
|
|
296
|
+
```ts
|
|
297
|
+
import { WebhookVerifier } from '@assinafy/cli/api';
|
|
298
|
+
|
|
299
|
+
const verifier = new WebhookVerifier(process.env.ASSINAFY_WEBHOOK_SECRET);
|
|
300
|
+
// rawBody: the Buffer exactly as received; headers: the request headers
|
|
301
|
+
if (!verifier.verifyDelivery(rawBody, headers)) {
|
|
302
|
+
// answer 401 and drop the delivery
|
|
303
|
+
}
|
|
304
|
+
const event = verifier.extractEvent(rawBody);
|
|
305
|
+
```
|
|
282
306
|
|
|
283
|
-
|
|
307
|
+
`verifyDelivery` compares the HMAC-SHA256 of `{webhook-id}.{webhook-timestamp}.{body}` in constant time and rejects timestamps more than 5 minutes from your clock. Answer with a `2xx` quickly: a failure is retried once after 3 seconds, and 10 consecutive failed events pause the endpoint until a delivery succeeds. `document_ready` means the last signer signed, not that upload processing finished. Treat events as signals and confirm state through the API before irreversible actions.
|
|
284
308
|
|
|
285
309
|
## Output and scripting
|
|
286
310
|
|
|
@@ -336,7 +360,7 @@ Empty optional settings are ignored, including `.env.example` defaults. Configur
|
|
|
336
360
|
| API base URL | `--base-url` | `ASSINAFY_BASE_URL` |
|
|
337
361
|
| Config profile | `-p, --profile` | `ASSINAFY_PROFILE` |
|
|
338
362
|
| Config directory | — | `ASSINAFY_CONFIG_DIR` |
|
|
339
|
-
|
|
|
363
|
+
| Webhook endpoint signing secret (`whsec_`) | _(config only)_ | `ASSINAFY_WEBHOOK_SECRET` |
|
|
340
364
|
| Password / new password | `--password` / `--new-password` | `ASSINAFY_PASSWORD` / `ASSINAFY_NEW_PASSWORD` |
|
|
341
365
|
| Social provider / reset token | `--provider-token` / `--reset-token` | `ASSINAFY_PROVIDER_TOKEN` / `ASSINAFY_RESET_TOKEN` |
|
|
342
366
|
| Signer access code / email or WhatsApp OTP | `--access-code` / `--code` | `ASSINAFY_SIGNER_ACCESS_CODE` / `ASSINAFY_VERIFICATION_CODE` |
|
|
@@ -415,7 +439,7 @@ assinafy send contract.pdf \
|
|
|
415
439
|
| `documents verify <hash>` | Verify by signature hash (public) |
|
|
416
440
|
| `documents statuses` | List every document status and whether it is deletable |
|
|
417
441
|
| `documents public <id>` | Public unauthenticated lookup |
|
|
418
|
-
| `documents send-token <id> --recipient <email
|
|
442
|
+
| `documents send-token <id> --recipient <email>` | Email a one-time access token to a pending signer (email channel only) |
|
|
419
443
|
| `documents progress <id>` | Signing progress |
|
|
420
444
|
| `documents wait <id> [--timeout] [--interval]` | Poll until ready, failed, or timed out |
|
|
421
445
|
|
|
@@ -458,7 +482,7 @@ Field definitions are what `--method collect` assignments gather. Run `fields ty
|
|
|
458
482
|
|
|
459
483
|
### `webhooks`
|
|
460
484
|
|
|
461
|
-
`register --url --email [--events] [--inactive]` · `get` · `inactivate` · `event-types` · `dispatches [--event] [--delivered] [--from] [--to] [--page] [--per-page] [--sort]` · `retry <dispatchId>`
|
|
485
|
+
`endpoints list` · `endpoints create --url --email [--name] [--events] [--active|--inactive] [--signing]` · `endpoints get <id>` · `endpoints update <id> [--url] [--email] [--name] [--events] [--active|--inactive] [--signing|--no-signing]` · `endpoints delete <id> [-y]` · `endpoints secret <id>` · `endpoints rotate-secret <id> [-y]` · `register --url --email [--events] [--inactive]` · `get` · `inactivate` · `event-types` · `dispatches [--endpoint] [--event] [--delivered] [--from] [--to] [--page] [--per-page] [--sort]` · `retry <dispatchId>`
|
|
462
486
|
|
|
463
487
|
### `workspaces` (alias `accounts`)
|
|
464
488
|
|
|
@@ -478,9 +502,9 @@ Every signer command except the public artifact `download` requires `--access-co
|
|
|
478
502
|
|
|
479
503
|
### `auth`
|
|
480
504
|
|
|
481
|
-
`login <email
|
|
505
|
+
`login <email> [--mfa-code]` · `social-login` · `link-social-login` · `change-password` · `request-password-reset <email>` · `reset-password --reset-token` · `api-keys create|get|delete` · `mfa verify --mfa-token [--mfa-code]` · `mfa list` · `mfa enroll [--label]` · `mfa confirm <methodId> [--code] [--password|--reauth-code]` · `mfa recovery-codes [--password|--mfa-code]` · `mfa remove <methodId> [--password|--mfa-code] [-y]`
|
|
482
506
|
|
|
483
|
-
For server-to-server use, prefer an API key (`assinafy login` or `--api-key`) and skip this group. `auth login`, `auth social-login`, `auth request-password-reset`, and `auth reset-password` run without stored credentials; the rest accept the API key or JWT documented for their endpoint.
|
|
507
|
+
For server-to-server use, prefer an API key (`assinafy login` or `--api-key`) and skip this group. `auth login`, `auth mfa verify`, `auth social-login`, `auth request-password-reset`, and `auth reset-password` run without stored credentials; the rest accept the API key or JWT documented for their endpoint.
|
|
484
508
|
|
|
485
509
|
### `oauth`
|
|
486
510
|
|
|
@@ -515,7 +539,7 @@ await client.documents.waitUntilReady(document.id);
|
|
|
515
539
|
|
|
516
540
|
CommonJS uses `require('@assinafy/cli/api')`. JSON `data` envelopes are unwrapped, paginated calls resolve to `{ data, meta }` built from the `X-Pagination-*` headers, downloads resolve to a `Buffer`, and status-only responses keep their documented object.
|
|
517
541
|
|
|
518
|
-
Errors are typed: `ValidationError` for local input, `ApiError` (with `statusCode`, `responseData`, `wwwAuthenticate`, and `
|
|
542
|
+
Errors are typed: `ValidationError` for local input, `ApiError` (with `statusCode`, `responseData`, `wwwAuthenticate`, `retryAfter`, and `rateLimit` from the `X-Rate-Limit-*` headers; on `429`, wait `Retry-After` seconds — the SDK never retries automatically) for HTTP failures, `NetworkError` for transport failures, and `PartialWorkflowError` when `uploadAndRequestSignatures` fails after creating resources — it exposes the `documentId` and `signerIds` that already exist so you can inspect and resume. Never automatically delete these signers: they may have been reused from other documents. For example:
|
|
519
543
|
|
|
520
544
|
```ts
|
|
521
545
|
try {
|
|
@@ -572,11 +596,12 @@ The [release runbook](./docs/releasing.md) covers tags, trusted publishing, and
|
|
|
572
596
|
|
|
573
597
|
## Contract boundaries
|
|
574
598
|
|
|
575
|
-
- The production OpenAPI publishes
|
|
599
|
+
- The production OpenAPI publishes 106 operations and the SDK implements all of them. Sandbox deployments can lag individual routes — account/user statistics and user notification preferences may return route-level 404s there despite being documented in production.
|
|
576
600
|
- The SDK keeps two platform-compatible template routes (`GET /accounts/{id}/templates/{id}` and its page download) that are absent from the published OpenAPI paths.
|
|
577
|
-
- Certificate start/complete are deployed production extensions of the public signing frontend, exposed as `signerDocuments.startCertificate(accessCode)` and `signerDocuments.completeCertificate(accessCode, token)`. Start posts `{ "signer-access-code": code }` and returns `{ token }`; complete posts `{ "signer-access-code": code, token }` and returns `{ signerName }`. Both also carry the access code in the query string and strip owner credentials. They supplement, but are not part of, the
|
|
578
|
-
-
|
|
579
|
-
- `
|
|
601
|
+
- Certificate start/complete are deployed production extensions of the public signing frontend, exposed as `signerDocuments.startCertificate(accessCode)` and `signerDocuments.completeCertificate(accessCode, token)`. Start posts `{ "signer-access-code": code }` and returns `{ token }`; complete posts `{ "signer-access-code": code, token }` and returns `{ signerName }`. Both also carry the access code in the query string and strip owner credentials. They supplement, but are not part of, the 106 OpenAPI operations.
|
|
602
|
+
- `send-token` sends the email-only body `{ "channel": "email", "recipient": "..." }`; WhatsApp and the older `{ "email" }` body are rejected by the API with `400`.
|
|
603
|
+
- `signer documents` and `signer search` accept the workspace API key or token when `--access-code` is omitted.
|
|
604
|
+
- Webhook signatures follow Standard Webhooks; `WebhookVerifier.verifyDelivery` implements the published scheme. The older `verify(body, signature)` method is deprecated and does not match Assinafy deliveries.
|
|
580
605
|
|
|
581
606
|
## License
|
|
582
607
|
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
*Português · [Read in English](README.en.md)*
|
|
4
4
|
|
|
5
|
-
A CLI e o SDK Node.js da [API Assinafy](https://api.assinafy.com.br/v1/docs) permitem enviar PDFs, cadastrar signatários, solicitar assinaturas, acompanhar o processamento e baixar documentos certificados. O pacote inclui um executável para terminal e um SDK TypeScript em `@assinafy/cli/api`, com acesso às
|
|
5
|
+
A CLI e o SDK Node.js da [API Assinafy](https://api.assinafy.com.br/v1/docs) permitem enviar PDFs, cadastrar signatários, solicitar assinaturas, acompanhar o processamento e baixar documentos certificados. O pacote inclui um executável para terminal e um SDK TypeScript em `@assinafy/cli/api`, com acesso às 106 operações publicadas.
|
|
6
6
|
|
|
7
7
|
Este guia segue o fluxo de uma integração: instalação, autenticação, envio, assinatura e armazenamento do resultado. A [referência do SDK](docs/sdk-reference.md) documenta cada método; a [referência HTTP](docs/api-reference.md) contém os parâmetros e os payloads completos de requisição e resposta publicados pela Assinafy.
|
|
8
8
|
|
|
@@ -84,7 +84,7 @@ assinafy whoami
|
|
|
84
84
|
|
|
85
85
|
`login` solicita a chave e o ID do workspace. `whoami` lista os workspaces acessíveis e confirma a credencial e a URL base. Verifique se o workspace selecionado aparece nessa lista; `whoami` não valida automaticamente o ID padrão configurado.
|
|
86
86
|
|
|
87
|
-
`auth login user@example.com` inicia uma sessão de usuário. `auth api-keys create` gera e rotaciona a chave dessa conta; use esse comando apenas quando essa rotação fizer parte do seu fluxo. Prefira prompts protegidos e variáveis de ambiente a segredos em argumentos.
|
|
87
|
+
`auth login user@example.com` inicia uma sessão de usuário. Com a verificação em duas etapas ativa, o comando pede o código do aplicativo autenticador ou um código de recuperação (`--mfa-code` ou `ASSINAFY_MFA_CODE`); o desafio expira em 5 minutos e só pode ser usado uma vez. `auth mfa enroll`, `auth mfa confirm`, `auth mfa list`, `auth mfa recovery-codes` e `auth mfa remove` gerenciam o autenticador e os códigos de recuperação. `auth api-keys create` gera e rotaciona a chave dessa conta; use esse comando apenas quando essa rotação fizer parte do seu fluxo. Prefira prompts protegidos e variáveis de ambiente a segredos em argumentos.
|
|
88
88
|
|
|
89
89
|
### Aplicativos OAuth
|
|
90
90
|
|
|
@@ -310,11 +310,11 @@ assinafy signer sign "$DOCUMENT_ID" example_assignment --entries '[
|
|
|
310
310
|
]' --json
|
|
311
311
|
```
|
|
312
312
|
|
|
313
|
-
Os IDs e valores de campos vêm do assignment apresentado ao signatário.
|
|
313
|
+
Os IDs e valores de campos vêm do assignment apresentado ao signatário. Na verificação por e-mail ou WhatsApp, o código chega na própria mensagem do convite. Para enviar um novo token de acesso por e-mail a um signatário que ainda não assinou um documento pendente, use `documents send-token <id> --recipient <email>` (somente o canal `email`; o corpo enviado é `{ "channel": "email", "recipient": "signer@example.com" }` e a resposta traz `document`, `channel` e `recipient`). Os dois métodos usam `signer verify-code`; `verify-email` continua disponível como alias. Configure `ASSINAFY_VERIFICATION_CODE` para manter o OTP fora dos argumentos e preservar zeros iniciais. `decline` e `decline-multiple` exigem motivo não vazio com até 2.000 caracteres. As operações em lote usam `sign-multiple` e `decline-multiple`.
|
|
314
314
|
|
|
315
315
|
Para certificados A1/A3, use a página de assinatura Assinafy ou integre o Web PKI com o SDK. Após apresentar o documento e aceitar os termos, `signer certificate-start --json` retorna `{ "token": "..." }`. O navegador assina essa operação no dispositivo do signatário. Defina `ASSINAFY_CERTIFICATE_TOKEN` com o mesmo token e execute `signer certificate-complete --json`, que retorna `{ "signerName": "..." }`. A chave privada e a senha/PIN permanecem no dispositivo. Aguarde o documento ficar `certificated` e baixe `--artifact pades` ou `bundle`; o comando comum `sign` não substitui esse fluxo.
|
|
316
316
|
|
|
317
|
-
O SDK remove credenciais do proprietário das chamadas públicas e do signatário. O download público de artefato do signatário aceita opcionalmente um código para uma verificação prévia de identidade.
|
|
317
|
+
O SDK remove credenciais do proprietário das chamadas públicas e do signatário. O download público de artefato do signatário aceita opcionalmente um código para uma verificação prévia de identidade. `--email` é um alias de `--recipient` em `send-token`. `signer documents <signerId>` e `signer search <signerId> <texto>` também funcionam sem `--access-code`, usando a chave de API ou o token do workspace ao qual o signatário pertence.
|
|
318
318
|
|
|
319
319
|
Verificação, confirmação de dados e envio da imagem de assinatura podem retornar `[]` em caso de sucesso. Consulte `signer self` para obter o perfil atualizado e confirme o progresso e os artefatos certificados após assinar. Os exemplos completos de requisição e resposta estão na [referência do SDK para signatários](docs/sdk-reference.md#signer-side-flows-clientsignerdocuments).
|
|
320
320
|
|
|
@@ -329,19 +329,38 @@ Os comandos de confirmação de dados, assinatura e recusa de um único document
|
|
|
329
329
|
|
|
330
330
|
## Eventos e webhooks
|
|
331
331
|
|
|
332
|
+
Cada workspace pode cadastrar 1 endpoint de webhook, ou até 3 nos planos pagos. Cada endpoint tem URL, eventos, estado e assinatura próprios, e todo endpoint ativo inscrito em um evento o recebe de forma independente.
|
|
333
|
+
|
|
332
334
|
```bash
|
|
333
335
|
assinafy webhooks event-types --json
|
|
334
|
-
assinafy webhooks
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
assinafy webhooks
|
|
336
|
+
assinafy webhooks endpoints create --url https://example.com/hooks/assinafy --email ops@example.com --name ERP --events document_ready,signer_signed_document,signer_rejected_document --signing --json
|
|
337
|
+
assinafy webhooks endpoints list
|
|
338
|
+
assinafy webhooks endpoints secret "$ENDPOINT_ID" # segredo whsec_ para o receptor
|
|
339
|
+
assinafy webhooks dispatches --endpoint "$ENDPOINT_ID" --delivered false --json
|
|
340
|
+
# confere uma entrega salva com ASSINAFY_WEBHOOK_SECRET (sai com código 1 se inválida)
|
|
341
|
+
assinafy webhooks verify corpo.json --id "$WEBHOOK_ID" --timestamp "$WEBHOOK_TIMESTAMP" --signature "$WEBHOOK_SIGNATURE"
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
Sem `--events`, o endpoint recebe `document_ready`, `document_prepared`, `signer_signed_document`, `signer_rejected_document` e `document_processing_failed`. `endpoints update <id>` altera apenas as opções informadas (`--active`/`--inactive`, `--signing`/`--no-signing`, `--url`, `--email`, `--name`, `--events`); desativar a assinatura descarta o segredo. `endpoints rotate-secret <id>` gera um novo segredo e invalida o anterior imediatamente. `endpoints delete <id>` remove o endpoint e libera a vaga. URLs repetidas no mesmo workspace retornam `400`; criar acima do limite do plano retorna `403`. A leitura e a rotação do segredo não estão disponíveis para aplicativos OAuth.
|
|
345
|
+
|
|
346
|
+
`webhooks register`, `webhooks get` e `webhooks inactivate` continuam disponíveis e atuam sobre o endpoint mais antigo do workspace.
|
|
347
|
+
|
|
348
|
+
Cada entrega é um `POST` JSON com os cabeçalhos `webhook-id` (igual em todas as tentativas do mesmo evento para o mesmo endpoint; use-o para eliminar duplicatas) e `webhook-timestamp`. Com a assinatura ativa, `webhook-signature` segue o padrão [Standard Webhooks](https://www.standardwebhooks.com). Valide o corpo bruto, antes de convertê-lo em JSON, com `WebhookVerifier`:
|
|
349
|
+
|
|
350
|
+
```ts
|
|
351
|
+
import { WebhookVerifier } from '@assinafy/cli/api';
|
|
352
|
+
|
|
353
|
+
const verifier = new WebhookVerifier(process.env.ASSINAFY_WEBHOOK_SECRET);
|
|
354
|
+
// rawBody: Buffer exatamente como recebido; headers: cabeçalhos da requisição
|
|
355
|
+
if (!verifier.verifyDelivery(rawBody, headers)) {
|
|
356
|
+
// responda 401 e descarte a entrega
|
|
357
|
+
}
|
|
358
|
+
const event = verifier.extractEvent(rawBody);
|
|
340
359
|
```
|
|
341
360
|
|
|
342
|
-
|
|
361
|
+
`verifyDelivery` compara em tempo constante o HMAC-SHA256 de `{webhook-id}.{webhook-timestamp}.{corpo}` e rejeita carimbos de tempo com mais de 5 minutos de diferença. Responda com `2xx` rapidamente; uma falha é tentada novamente uma vez após 3 segundos, e 10 eventos seguidos com falha pausam o endpoint até uma entrega funcionar. `webhooks retry <dispatchId>` reenvia uma entrega para o endpoint dela, desde que esteja ativo.
|
|
343
362
|
|
|
344
|
-
`
|
|
363
|
+
`document_ready` indica a assinatura pelo último signatário, não o término do processamento inicial do upload. Processe eventos de forma idempotente, consulte `event-types` para a lista vigente e confirme estado e artefatos pela API antes de ações irreversíveis.
|
|
345
364
|
|
|
346
365
|
## SDK Node.js
|
|
347
366
|
|
|
@@ -408,7 +427,7 @@ A listagem acima solicita uma página. Continue até `meta.last_page` quando pre
|
|
|
408
427
|
}
|
|
409
428
|
```
|
|
410
429
|
|
|
411
|
-
No SDK, `ValidationError` indica entrada inválida; `ApiError` carrega `statusCode`, `responseData`, `wwwAuthenticate` e `
|
|
430
|
+
No SDK, `ValidationError` indica entrada inválida; `ApiError` carrega `statusCode`, `responseData`, `wwwAuthenticate`, `retryAfter` e `rateLimit` (`X-Rate-Limit-Limit`, `-Remaining`, `-Reset`); em `429`, aguarde os segundos de `Retry-After` antes de repetir — o SDK não repete chamadas automaticamente; `NetworkError` indica falha de transporte; `PartialWorkflowError` preserva IDs existentes e a causa original. O SDK exige HTTPS, rejeita redirecionamentos e não inclui configurações Axios com credenciais nos erros. O uso de HTTP sem TLS é restrito a loopback com opt-in explícito no SDK.
|
|
412
431
|
|
|
413
432
|
## Referência de comandos
|
|
414
433
|
|
|
@@ -419,13 +438,13 @@ No SDK, `ValidationError` indica entrada inválida; `ApiError` carrega `statusCo
|
|
|
419
438
|
| [`assignments`](docs/assignments.md) | Solicitações, estimativas, vencimento, reenvios e notificações. |
|
|
420
439
|
| [`signer`](docs/signer.md) | Perfil, documentos, termos, verificação, assinatura e recusa. |
|
|
421
440
|
| [`oauth`](docs/oauth.md) | Conexão pelo navegador, discovery, autorização, exchange, refresh, UserInfo e revogação. |
|
|
422
|
-
| [`auth`](docs/auth.md) | Login de usuário, login social, senhas e chaves de API. |
|
|
441
|
+
| [`auth`](docs/auth.md) | Login de usuário com verificação em duas etapas, login social, senhas e chaves de API. |
|
|
423
442
|
| [`workspaces`](docs/workspaces.md) / `accounts` | Cadastro, consulta, tema, logo e estatísticas. |
|
|
424
443
|
| [`users`](docs/users.md) | Perfil, estatísticas e preferências de notificação. |
|
|
425
444
|
| [`templates`](docs/templates.md) | Listagem, detalhes e páginas de templates. |
|
|
426
445
|
| [`tags`](docs/tags.md) | Organização dos documentos por tags. |
|
|
427
446
|
| [`fields`](docs/fields.md) | Definições, tipos e validação de campos. |
|
|
428
|
-
| [`webhooks`](docs/webhooks.md) |
|
|
447
|
+
| [`webhooks`](docs/webhooks.md) | Endpoints de webhook, segredos de assinatura e acompanhamento das entregas. |
|
|
429
448
|
| [`config`](docs/config.md) | Perfis, credenciais e configuração efetiva. |
|
|
430
449
|
| [`send`](docs/send.md) | Upload e solicitação de assinaturas em um comando. |
|
|
431
450
|
|