@assinafy/cli 2.4.1 → 2.5.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/.env.example +4 -2
- package/README.en.md +52 -27
- package/README.md +40 -14
- package/dist/api.cjs +238 -18
- package/dist/api.cjs.map +1 -1
- package/dist/api.js +238 -18
- package/dist/api.js.map +1 -1
- package/dist/cli.cjs +559 -52
- 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/oauth.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 +87 -2
- package/dist/types/api/types.d.ts.map +1 -1
- package/docs/README.md +1 -1
- package/docs/api-operations.json +105 -1
- package/docs/api-reference.md +2309 -2025
- package/docs/auth.md +125 -4
- package/docs/migration-v2.md +4 -3
- package/docs/oauth-guide.md +4 -4
- package/docs/oauth.md +4 -4
- package/docs/sdk-reference.md +74 -12
- package/docs/signers.md +1 -1
- package/docs/webhooks.md +157 -15
- package/install.ps1 +10 -0
- package/install.sh +3 -0
- package/package.json +1 -1
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
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
*[Leia em português](README.md) · English*
|
|
4
4
|
|
|
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
|
|
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
|
|
|
@@ -32,7 +32,7 @@ This document reads top to bottom: install, authenticate, send your first signat
|
|
|
32
32
|
|
|
33
33
|
- Node.js `>=22.12.0`. Node.js 24 LTS is recommended and is what CI publishes with; CI also tests 22 and 26.
|
|
34
34
|
- HTTPS with TLS 1.2 or higher to reach the Assinafy API; supported Node.js versions use that minimum by default.
|
|
35
|
-
- An Assinafy account and an API key (see [Authentication](#authentication)).
|
|
35
|
+
- An Assinafy account and an API key or consented OAuth connection (see [Authentication](#authentication)).
|
|
36
36
|
- Linux, macOS, or Windows. Release archives ship for `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `windows-x64`, and `windows-arm64`.
|
|
37
37
|
|
|
38
38
|
## Installation
|
|
@@ -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
|
|
@@ -111,7 +113,7 @@ The CLI includes the official application's public client ID and uses PKCE S256
|
|
|
111
113
|
https://integrations.assinafy.com.br/assinafy-cli/oauth-callback
|
|
112
114
|
```
|
|
113
115
|
|
|
114
|
-
The CLI requests
|
|
116
|
+
The CLI requests the seven scopes registered for its official application by default: `account:read documents:read documents:write templates:read templates:write webhooks:write offline_access`, including template read/write access and `webhooks:write` for webhook write commands. Existing connections need fresh consent to gain additional permissions. An explicit `--scope` selects another set. `openid`, `profile`, and `email` are excluded from the default; request them only with an application registered for those scopes to obtain OpenID Connect identity and UserInfo.
|
|
115
117
|
|
|
116
118
|
No `ASSINAFY_OAUTH_CLIENT_ID` configuration is needed for the official application. For your own application or another environment, use `--client-id` or that variable; the flag takes precedence. Register the callback URI and scopes for the selected application. In a private directory outside the repository:
|
|
117
119
|
|
|
@@ -228,14 +230,14 @@ Keep the certified PDF, the certificate page, the bundle, and the `documents act
|
|
|
228
230
|
|
|
229
231
|
## The signer side
|
|
230
232
|
|
|
231
|
-
Signers do not use your API key. The `assinafy signer` commands use a private **access code** from the signing verification link. For email verification, use the link and six-digit code from the same
|
|
233
|
+
Signers do not use your API key. The `assinafy signer` commands use a private **access code** from the signing verification link. For email or WhatsApp verification, use the link and six-digit code from the same message; an invitation containing only a document ID and recipient does not contain this credential. Set `ASSINAFY_SIGNER_ACCESS_CODE` and `ASSINAFY_VERIFICATION_CODE` privately. Confirm the signer and document before submitting a decision:
|
|
232
234
|
|
|
233
235
|
```bash
|
|
234
|
-
export ASSINAFY_SIGNER_ACCESS_CODE=<code-from-the-verification-link>
|
|
235
|
-
|
|
236
236
|
assinafy signer self # who the code belongs to
|
|
237
237
|
assinafy signer assignment # the document as the signer sees it
|
|
238
238
|
assinafy signer accept-terms
|
|
239
|
+
assinafy signer verify-code
|
|
240
|
+
assinafy signer confirm-data <documentId> --full-name 'Ana Lima' --email ana@example.com
|
|
239
241
|
assinafy signer upload-signature --file signature.png
|
|
240
242
|
assinafy signer sign <documentId> <assignmentId> --entries '[
|
|
241
243
|
{"itemId":"item_1","fieldId":"field_1","pageId":"page_1","value":"..."}
|
|
@@ -246,6 +248,8 @@ Where email or WhatsApp verification is configured, the signer also confirms a 6
|
|
|
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
|
|
|
251
|
+
Before estimating or creating a certificate assignment, set the signer's CPF/CNPJ with `signers.update(signerId, { government_id })`, or `assinafy signers update <signerId> --cpf '<signer-CPF-or-CNPJ>'`. The update command sends `government_id`. Creating a signer by email may reuse an existing record without updating it. Each certificate signer needs a matching certificate and an individual signing step.
|
|
252
|
+
|
|
249
253
|
Verification, data confirmation, and signature upload may return `[]` on success. Fetch `signer self` for the updated profile and check document progress and certified artifacts after signing. Full request and response examples are in the [signer SDK reference](docs/sdk-reference.md#signer-side-flows-clientsignerdocuments).
|
|
250
254
|
|
|
251
255
|
For a virtual assignment, confirm the signer's data and submit an empty entry array:
|
|
@@ -261,24 +265,44 @@ Owner API credentials are stripped from every public and signer-side request, so
|
|
|
261
265
|
|
|
262
266
|
## Webhooks
|
|
263
267
|
|
|
264
|
-
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.
|
|
265
269
|
|
|
266
270
|
```bash
|
|
267
271
|
assinafy webhooks event-types # what the platform can send
|
|
268
|
-
assinafy webhooks
|
|
272
|
+
assinafy webhooks endpoints create \
|
|
269
273
|
--url https://example.com/hooks/assinafy \
|
|
270
274
|
--email ops@example.com \
|
|
271
|
-
--
|
|
272
|
-
|
|
273
|
-
|
|
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
|
|
274
285
|
assinafy webhooks retry <dispatchId> # redeliver one event
|
|
275
|
-
assinafy webhooks get # current subscription
|
|
276
|
-
assinafy webhooks inactivate # stop deliveries
|
|
277
286
|
```
|
|
278
287
|
|
|
279
|
-
|
|
288
|
+
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.
|
|
289
|
+
|
|
290
|
+
`webhooks register`, `webhooks get`, and `webhooks inactivate` remain and act on the workspace's oldest endpoint.
|
|
280
291
|
|
|
281
|
-
|
|
292
|
+
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:
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
import { WebhookVerifier } from '@assinafy/cli/api';
|
|
296
|
+
|
|
297
|
+
const verifier = new WebhookVerifier(process.env.ASSINAFY_WEBHOOK_SECRET);
|
|
298
|
+
// rawBody: the Buffer exactly as received; headers: the request headers
|
|
299
|
+
if (!verifier.verifyDelivery(rawBody, headers)) {
|
|
300
|
+
// answer 401 and drop the delivery
|
|
301
|
+
}
|
|
302
|
+
const event = verifier.extractEvent(rawBody);
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
`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.
|
|
282
306
|
|
|
283
307
|
## Output and scripting
|
|
284
308
|
|
|
@@ -299,9 +323,8 @@ assinafy documents list --page 2 --per-page 50 --json | jq '.meta'
|
|
|
299
323
|
# Upload and capture the new document ID
|
|
300
324
|
DOC=$(assinafy documents upload contract.pdf --json | jq -r '.id')
|
|
301
325
|
|
|
302
|
-
# Attach
|
|
303
|
-
|
|
304
|
-
assinafy documents tags-add "$DOC" "$TAG_ID"
|
|
326
|
+
# Attach a tag by name; production creates it if missing
|
|
327
|
+
assinafy documents tags-add "$DOC" legal
|
|
305
328
|
```
|
|
306
329
|
|
|
307
330
|
JSON errors carry a stable shape:
|
|
@@ -325,6 +348,8 @@ Destructive commands prompt for confirmation and refuse to run unattended unless
|
|
|
325
348
|
|
|
326
349
|
Every setting resolves as **CLI flag → environment variable → config-file profile → built-in default**. Credentials are selected together from the first level that supplies either type; an API key wins only when both types are supplied at that same level. Saving one credential type with `config set` clears the other from that profile. The CLI reads process environment variables; it does not automatically load `.env` files. The OAuth variables are listed in [.env.example](./.env.example).
|
|
327
350
|
|
|
351
|
+
Empty optional settings are ignored, including `.env.example` defaults. Configurations with invalid profile field types are ignored for reads and rejected by mutations.
|
|
352
|
+
|
|
328
353
|
| What | Flag | Environment variable |
|
|
329
354
|
| --- | --- | --- |
|
|
330
355
|
| API key (sent as `X-Api-Key`) | `--api-key` | `ASSINAFY_API_KEY` |
|
|
@@ -333,7 +358,7 @@ Every setting resolves as **CLI flag → environment variable → config-file pr
|
|
|
333
358
|
| API base URL | `--base-url` | `ASSINAFY_BASE_URL` |
|
|
334
359
|
| Config profile | `-p, --profile` | `ASSINAFY_PROFILE` |
|
|
335
360
|
| Config directory | — | `ASSINAFY_CONFIG_DIR` |
|
|
336
|
-
|
|
|
361
|
+
| Webhook endpoint signing secret (`whsec_`) | _(config only)_ | `ASSINAFY_WEBHOOK_SECRET` |
|
|
337
362
|
| Password / new password | `--password` / `--new-password` | `ASSINAFY_PASSWORD` / `ASSINAFY_NEW_PASSWORD` |
|
|
338
363
|
| Social provider / reset token | `--provider-token` / `--reset-token` | `ASSINAFY_PROVIDER_TOKEN` / `ASSINAFY_RESET_TOKEN` |
|
|
339
364
|
| Signer access code / email or WhatsApp OTP | `--access-code` / `--code` | `ASSINAFY_SIGNER_ACCESS_CODE` / `ASSINAFY_VERIFICATION_CODE` |
|
|
@@ -345,7 +370,7 @@ Public document verification and lookup, password reset, login and social login,
|
|
|
345
370
|
|
|
346
371
|
### Config file and profiles
|
|
347
372
|
|
|
348
|
-
`assinafy login` and `assinafy config set` write a JSON config file with owner-only (`0600`)
|
|
373
|
+
`assinafy login` and `assinafy config set` write a JSON config file with owner-only POSIX permissions (`0600` for the file and `0700` for its directory), including existing files and directories:
|
|
349
374
|
|
|
350
375
|
- Linux / macOS: `~/.config/assinafy/config.json` (honours `XDG_CONFIG_HOME`)
|
|
351
376
|
- Windows: `%APPDATA%\assinafy\config.json`
|
|
@@ -455,7 +480,7 @@ Field definitions are what `--method collect` assignments gather. Run `fields ty
|
|
|
455
480
|
|
|
456
481
|
### `webhooks`
|
|
457
482
|
|
|
458
|
-
`register --url --email [--events] [--inactive]` · `get` · `inactivate` · `event-types` · `dispatches [--event] [--delivered] [--from] [--to] [--page] [--per-page] [--sort]` · `retry <dispatchId>`
|
|
483
|
+
`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>`
|
|
459
484
|
|
|
460
485
|
### `workspaces` (alias `accounts`)
|
|
461
486
|
|
|
@@ -475,9 +500,9 @@ Every signer command except the public artifact `download` requires `--access-co
|
|
|
475
500
|
|
|
476
501
|
### `auth`
|
|
477
502
|
|
|
478
|
-
`login <email
|
|
503
|
+
`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]`
|
|
479
504
|
|
|
480
|
-
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.
|
|
505
|
+
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.
|
|
481
506
|
|
|
482
507
|
### `oauth`
|
|
483
508
|
|
|
@@ -569,11 +594,11 @@ The [release runbook](./docs/releasing.md) covers tags, trusted publishing, and
|
|
|
569
594
|
|
|
570
595
|
## Contract boundaries
|
|
571
596
|
|
|
572
|
-
- The production OpenAPI publishes
|
|
597
|
+
- 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.
|
|
573
598
|
- 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.
|
|
574
|
-
- 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
|
|
599
|
+
- 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.
|
|
575
600
|
- Both the published and legacy `send-token` payloads are supported for compatible deployments.
|
|
576
|
-
-
|
|
601
|
+
- 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.
|
|
577
602
|
|
|
578
603
|
## License
|
|
579
604
|
|
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
|
|
|
@@ -94,7 +94,7 @@ A CLI já inclui o ID público da aplicação oficial e usa PKCE S256, sem segre
|
|
|
94
94
|
https://integrations.assinafy.com.br/assinafy-cli/oauth-callback
|
|
95
95
|
```
|
|
96
96
|
|
|
97
|
-
A CLI solicita por padrão os
|
|
97
|
+
A CLI solicita por padrão os sete escopos cadastrados na aplicação oficial: `account:read documents:read documents:write templates:read templates:write webhooks:write offline_access`, incluindo leitura e alteração de templates e `webhooks:write` para os comandos que alteram webhooks. Uma conexão existente precisa de novo consentimento para obter permissões adicionais. `--scope` permite escolher outro conjunto. `openid`, `profile` e `email` não fazem parte do padrão; use-os apenas com uma aplicação cadastrada para esses escopos, para obter identidade OpenID Connect e UserInfo.
|
|
98
98
|
|
|
99
99
|
Não é necessário configurar `ASSINAFY_OAUTH_CLIENT_ID` para usar a aplicação oficial. Para uma aplicação própria ou outro ambiente, use `--client-id` ou essa variável; a flag tem precedência. A aplicação escolhida precisa ter a URI de retorno e os escopos cadastrados. Em um diretório privado fora do repositório:
|
|
100
100
|
|
|
@@ -120,6 +120,8 @@ Os comandos `oauth authorize` e `oauth exchange` continuam disponíveis para apl
|
|
|
120
120
|
|
|
121
121
|
A precedência é **flag → ambiente → perfil → padrão**. As credenciais são escolhidas juntas no primeiro nível que fornecer uma delas; nesse mesmo nível, a chave de API prevalece sobre o token. Assim, `--token` substitui uma chave existente no ambiente ou perfil. Salvar somente um tipo de credencial com `config set` remove o outro tipo daquele perfil.
|
|
122
122
|
|
|
123
|
+
Valores vazios de configurações opcionais são ignorados, inclusive os padrões de `.env.example`. Perfis com tipos de campos inválidos não são usados nem sobrescritos por comandos de configuração.
|
|
124
|
+
|
|
123
125
|
| Configuração | Flag | Variável |
|
|
124
126
|
| --- | --- | --- |
|
|
125
127
|
| Chave de API | `--api-key` | `ASSINAFY_API_KEY` |
|
|
@@ -263,6 +265,12 @@ assinafy assignments create "$DOCUMENT_ID" --signers '[
|
|
|
263
265
|
|
|
264
266
|
Passos explícitos devem ser contíguos a partir de `1`. Um signatário `DigitalCertificate` deve estar sozinho no seu passo, ter CPF/CNPJ em `government_id` e usar um certificado correspondente. A conta precisa do recurso Digital Certificate e dos créditos indicados pela estimativa. A1 e A3 usam o mesmo fluxo: `startCertificate`, assinatura local pelo Web PKI e `completeCertificate`. As chamadas seguem os payloads da aplicação Assinafy em produção; essas duas rotas ainda não constam como paths no OpenAPI. Veja [requisições, respostas e sequência completa](docs/sdk-reference.md#icp-brasil-a1a3-certificates).
|
|
265
267
|
|
|
268
|
+
Antes de estimar ou criar um assignment com certificado, atualize o CPF/CNPJ do signatário. O cadastro por e-mail pode reutilizar um registro sem atualizar seus dados. A opção `--cpf` de atualização envia `government_id` e aceita CPF ou CNPJ:
|
|
269
|
+
|
|
270
|
+
```bash
|
|
271
|
+
assinafy signers update "$SIGNER_ID" --cpf '<CPF-ou-CNPJ-do-signatário>' --json
|
|
272
|
+
```
|
|
273
|
+
|
|
266
274
|
Verificação `Email` usa notificação `["Email"]`; `Whatsapp` usa `["Whatsapp"]`. `DigitalCertificate` permite um desses dois canais. Escolha apenas um canal por signatário; os mesmos campos são aceitos em documentos gerados de templates.
|
|
267
275
|
|
|
268
276
|
Em produção, `notification_methods: []` assume `['Email']` e envia o convite. Para escolher o canal, informe-o explicitamente; o array vazio não desativa notificações.
|
|
@@ -287,12 +295,13 @@ Para organizar documentos, `documents tags-set <id> Contratos` substitui as tags
|
|
|
287
295
|
|
|
288
296
|
## Fluxo do signatário
|
|
289
297
|
|
|
290
|
-
Os comandos `signer` usam o código privado do link de verificação, separado da credencial do proprietário. Na verificação por e-mail, use o link e o código de seis dígitos da mesma mensagem; um convite que contém apenas o ID do documento e o destinatário não contém essa credencial. Configure `ASSINAFY_SIGNER_ACCESS_CODE` de forma privada e confirme o signatário e o documento. A aplicação deve apresentar termos, dados e documento à pessoa antes de enviar suas decisões:
|
|
298
|
+
Os comandos `signer` usam o código privado do link de verificação, separado da credencial do proprietário. Na verificação por e-mail ou WhatsApp, use o link e o código de seis dígitos da mesma mensagem; um convite que contém apenas o ID do documento e o destinatário não contém essa credencial. Configure `ASSINAFY_SIGNER_ACCESS_CODE` e `ASSINAFY_VERIFICATION_CODE` de forma privada e confirme o signatário e o documento. A aplicação deve apresentar termos, dados e documento à pessoa antes de enviar suas decisões:
|
|
291
299
|
|
|
292
300
|
```bash
|
|
293
301
|
assinafy signer self --json
|
|
294
302
|
assinafy signer document example_signer --json
|
|
295
303
|
assinafy signer accept-terms --json
|
|
304
|
+
assinafy signer verify-code --json
|
|
296
305
|
assinafy signer confirm-data "$DOCUMENT_ID" --full-name 'Ana Lima' --email ana@example.com --json
|
|
297
306
|
assinafy signer assignment --json
|
|
298
307
|
assinafy signer upload-signature --file assinatura.png --json
|
|
@@ -320,19 +329,36 @@ Os comandos de confirmação de dados, assinatura e recusa de um único document
|
|
|
320
329
|
|
|
321
330
|
## Eventos e webhooks
|
|
322
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
|
+
|
|
323
334
|
```bash
|
|
324
335
|
assinafy webhooks event-types --json
|
|
325
|
-
assinafy webhooks
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
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
|
+
```
|
|
341
|
+
|
|
342
|
+
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.
|
|
343
|
+
|
|
344
|
+
`webhooks register`, `webhooks get` e `webhooks inactivate` continuam disponíveis e atuam sobre o endpoint mais antigo do workspace.
|
|
345
|
+
|
|
346
|
+
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`:
|
|
347
|
+
|
|
348
|
+
```ts
|
|
349
|
+
import { WebhookVerifier } from '@assinafy/cli/api';
|
|
350
|
+
|
|
351
|
+
const verifier = new WebhookVerifier(process.env.ASSINAFY_WEBHOOK_SECRET);
|
|
352
|
+
// rawBody: Buffer exatamente como recebido; headers: cabeçalhos da requisição
|
|
353
|
+
if (!verifier.verifyDelivery(rawBody, headers)) {
|
|
354
|
+
// responda 401 e descarte a entrega
|
|
355
|
+
}
|
|
356
|
+
const event = verifier.extractEvent(rawBody);
|
|
331
357
|
```
|
|
332
358
|
|
|
333
|
-
|
|
359
|
+
`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.
|
|
334
360
|
|
|
335
|
-
`
|
|
361
|
+
`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.
|
|
336
362
|
|
|
337
363
|
## SDK Node.js
|
|
338
364
|
|
|
@@ -410,13 +436,13 @@ No SDK, `ValidationError` indica entrada inválida; `ApiError` carrega `statusCo
|
|
|
410
436
|
| [`assignments`](docs/assignments.md) | Solicitações, estimativas, vencimento, reenvios e notificações. |
|
|
411
437
|
| [`signer`](docs/signer.md) | Perfil, documentos, termos, verificação, assinatura e recusa. |
|
|
412
438
|
| [`oauth`](docs/oauth.md) | Conexão pelo navegador, discovery, autorização, exchange, refresh, UserInfo e revogação. |
|
|
413
|
-
| [`auth`](docs/auth.md) | Login de usuário, login social, senhas e chaves de API. |
|
|
439
|
+
| [`auth`](docs/auth.md) | Login de usuário com verificação em duas etapas, login social, senhas e chaves de API. |
|
|
414
440
|
| [`workspaces`](docs/workspaces.md) / `accounts` | Cadastro, consulta, tema, logo e estatísticas. |
|
|
415
441
|
| [`users`](docs/users.md) | Perfil, estatísticas e preferências de notificação. |
|
|
416
442
|
| [`templates`](docs/templates.md) | Listagem, detalhes e páginas de templates. |
|
|
417
443
|
| [`tags`](docs/tags.md) | Organização dos documentos por tags. |
|
|
418
444
|
| [`fields`](docs/fields.md) | Definições, tipos e validação de campos. |
|
|
419
|
-
| [`webhooks`](docs/webhooks.md) |
|
|
445
|
+
| [`webhooks`](docs/webhooks.md) | Endpoints de webhook, segredos de assinatura e acompanhamento das entregas. |
|
|
420
446
|
| [`config`](docs/config.md) | Perfis, credenciais e configuração efetiva. |
|
|
421
447
|
| [`send`](docs/send.md) | Upload e solicitação de assinaturas em um comando. |
|
|
422
448
|
|