@assinafy/cli 2.1.1 → 2.1.3

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/README.en.md CHANGED
@@ -124,6 +124,8 @@ assinafy workspaces list --json
124
124
 
125
125
  The command opens the system browser and waits for consent. The HTTPS return page forwards the authorization response to a temporary listener on `127.0.0.1`. The CLI validates state and issuer, closes the listener, and exchanges the code using its local PKCE verifier. Use a browser on the same computer as the CLI. Tokens travel directly between the CLI and Assinafy.
126
126
 
127
+ Return pages use the visual identity hosted at `integrations.assinafy.com.br` and distinguish a received response, failed authorization, and an invalid return. Check the final result in your terminal. If it reports `invalid_scope`, verify the application's registered permissions, including `offline_access`.
128
+
127
129
  Use `--no-browser` to open the URL printed to stderr manually while keeping automatic callback reception. `--timeout` sets the browser wait from 1 to 600 seconds (default 180), `--scope` selects permissions, and `--redirect-uri` selects another registered HTTPS page implementing the relay protocol. Ctrl+C cancels the wait. Token JSON goes to stdout; protect it from logs. `connect` does not modify a profile or automatically refresh tokens.
128
130
 
129
131
  Select the single workspace returned and set `ASSINAFY_ACCOUNT_ID`. Keep refreshes serialized per connection and store each rotated result atomically. The existing `oauth authorize` and `oauth exchange` commands also support applications with their own callbacks and confidential server credentials. The [OAuth guide](./docs/oauth-guide.md#cli-flow) documents both flows, complete payloads, token rotation, identity validation, and disconnect behavior.
@@ -206,6 +208,8 @@ assinafy assignments create "$DOCUMENT_ID" --signers '[
206
208
 
207
209
  Steps must form a contiguous sequence starting at `1`, and a `DigitalCertificate` signer must be alone in its step — both are validated locally before the request is sent. `--copy-receivers` takes **signer IDs** (people who only receive a copy of the finished document), not arbitrary email addresses.
208
210
 
211
+ In production, `notification_methods: []` defaults to `['Email']` and sends an invitation. Select the intended channel explicitly; an empty array does not disable notifications.
212
+
209
213
  To start from a saved template instead of a PDF:
210
214
 
211
215
  ```bash
@@ -221,10 +225,10 @@ Keep the certified PDF, the certificate page, the bundle, and the `documents act
221
225
 
222
226
  ## The signer side
223
227
 
224
- Signers do not use your API key. Each invitation carries a one-time **access code**, and the `assinafy signer` commands act as that signer:
228
+ 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 email; an invitation containing only a document ID and recipient does not contain this credential. Confirm the signer and document before submitting a decision:
225
229
 
226
230
  ```bash
227
- export ASSINAFY_SIGNER_ACCESS_CODE=<code-from-the-invitation>
231
+ export ASSINAFY_SIGNER_ACCESS_CODE=<code-from-the-verification-link>
228
232
 
229
233
  assinafy signer self # who the code belongs to
230
234
  assinafy signer assignment # the document as the signer sees it
@@ -235,7 +239,18 @@ assinafy signer sign <documentId> <assignmentId> --entries '[
235
239
  ]'
236
240
  ```
237
241
 
238
- Where email or WhatsApp verification is configured, the signer also confirms a 6-digit code: `documents send-token <documentId> --email <email>` issues it and `signer verify-email --code <otp>` redeems it. `signer decline` (or `decline-multiple`) rejects with a reason, and `sign-multiple` completes several documents in one call.
242
+ Where email or WhatsApp verification is configured, the signer also confirms a 6-digit code: `documents send-token <documentId> --recipient <email> --channel email` issues it and `signer verify-email --code <otp>` redeems it. `signer decline` (or `decline-multiple`) rejects with a reason, and `sign-multiple` completes several documents in one call.
243
+
244
+ 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).
245
+
246
+ For a virtual assignment, confirm the signer's data and submit an empty entry array:
247
+
248
+ ```bash
249
+ assinafy signer confirm-data <documentId> --full-name 'Ana Lima' --email ana@example.com
250
+ assinafy signer sign <documentId> <assignmentId> --entries '[]'
251
+ ```
252
+
253
+ Single-document confirmation, signing, and decline commands verify that the access code matches the requested document and assignment before writing.
239
254
 
240
255
  Owner API credentials are stripped from every public and signer-side request, so an access-code flow can never leak your workspace key. The published signer artifact download is public; passing `--access-code` adds an identity preflight that confirms the code belongs to the signer being downloaded for.
241
256
 
@@ -383,15 +398,15 @@ assinafy send contract.pdf \
383
398
  | `documents activities <id>` | Activity log |
384
399
  | `documents delete <id> [-y]` | Delete a document |
385
400
  | `documents tags <id>` | List attached tags |
386
- | `documents tags-set <id> [tagIds...]` | Replace the tag set by ID (none detaches all) |
387
- | `documents tags-add <id> <tagIds...>` | Attach tags by ID |
401
+ | `documents tags-set <id> [tags...]` | Replace the tag set by name (none detaches all) |
402
+ | `documents tags-add <id> <tags...>` | Attach tags by name |
388
403
  | `documents tags-remove <id> <tagId>` | Detach one tag |
389
404
  | `documents create-from-template <templateId> --signers <json> [...]` | Create from a template |
390
405
  | `documents estimate-template-cost <templateId> --signers <json>` | Estimate template cost |
391
406
  | `documents verify <hash>` | Verify by signature hash (public) |
392
407
  | `documents statuses` | List every document status and whether it is deletable |
393
408
  | `documents public <id>` | Public unauthenticated lookup |
394
- | `documents send-token <id> --email <email>` | Send a verification token (`--recipient`/`--channel` remains for the live legacy form) |
409
+ | `documents send-token <id> --recipient <email> --channel email` | Send a verification token in production |
395
410
  | `documents progress <id>` | Signing progress |
396
411
  | `documents wait <id> [--timeout] [--interval]` | Poll until ready, failed, or timed out |
397
412
 
package/README.md CHANGED
@@ -108,6 +108,8 @@ assinafy workspaces list --json
108
108
 
109
109
  A CLI abre o navegador e aguarda o consentimento. A página HTTPS encaminha a resposta para uma porta temporária em `127.0.0.1`; a CLI valida `state` e o emissor, fecha a porta e troca o código usando o verificador PKCE mantido localmente. Não é necessário copiar um código. Use o navegador no mesmo computador da CLI. O site recebe a resposta de autorização; a troca de tokens ocorre diretamente entre a CLI e a Assinafy.
110
110
 
111
+ As telas de retorno usam a identidade visual de `integrations.assinafy.com.br` e distinguem resposta recebida, autorização não concluída e retorno inválido. Confira o resultado final no terminal. Se aparecer `invalid_scope`, verifique as permissões cadastradas para a aplicação, incluindo `offline_access`.
112
+
111
113
  `--no-browser` permite abrir manualmente a URL exibida no stderr e mantém o retorno automático. `--timeout` controla a espera pelo navegador (180 segundos por padrão, de 1 a 600); `--scope` seleciona as permissões e `--redirect-uri` permite uma página HTTPS com o mesmo protocolo. Ctrl+C cancela a espera. A saída JSON contém tokens sensíveis; não a envie para logs. O comando não altera o perfil nem renova tokens automaticamente.
112
114
 
113
115
  Selecione o único workspace retornado e configure `ASSINAFY_ACCOUNT_ID`. Tokens OAuth não autorizam cobrança, criação/exclusão de workspaces nem administração de credenciais. Cada refresh consome o token anterior: serialize a operação por conexão e salve o novo par de tokens atomicamente.
@@ -261,6 +263,8 @@ assinafy assignments create "$DOCUMENT_ID" --signers '[
261
263
 
262
264
  Passos explícitos devem ser contíguos a partir de `1`. Um signatário `DigitalCertificate` deve estar sozinho no seu passo e ter os dados exigidos pela plataforma. O fluxo normal de `sign` não executa o handshake Web PKI. As rotas de certificado citadas na descrição da API não têm contratos OpenAPI publicados; o SDK não fornece chamadas especulativas para elas.
263
265
 
266
+ 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.
267
+
264
268
  `--copy-receivers` recebe IDs de signatários que receberão uma cópia final. Para coletar campos, use `assignments create --method collect --entries ...` com páginas, campos e signatários do documento; os formatos completos estão em [assignments](docs/assignments.md) e [SDK](docs/sdk-reference.md#assignments-clientassignments).
265
269
 
266
270
  Para iniciar a partir de um template:
@@ -277,9 +281,11 @@ assinafy documents create-from-template example_template --name 'Contrato' --sig
277
281
 
278
282
  Cada papel deve corresponder ao template escolhido. Campos de editor, tags, mensagem e vencimento são opcionais. Use IDs reais obtidos na sua conta ao executar os exemplos.
279
283
 
284
+ Para organizar documentos, `documents tags-set <id> Contratos` substitui as tags e `documents tags-add <id> Contratos` acrescenta nomes. Nomes inexistentes são criados. `documents tags-remove <id> <tagId>` e o filtro `documents list --tags <ids>` usam IDs obtidos em `documents tags <id>`.
285
+
280
286
  ## Fluxo do signatário
281
287
 
282
- Os comandos `signer` usam o código do convite, separado da credencial do proprietário. Configure `ASSINAFY_SIGNER_ACCESS_CODE` de forma privada. A aplicação deve apresentar termos, dados e documento à pessoa antes de enviar suas decisões:
288
+ 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:
283
289
 
284
290
  ```bash
285
291
  assinafy signer self --json
@@ -293,9 +299,20 @@ assinafy signer sign "$DOCUMENT_ID" example_assignment --entries '[
293
299
  ]' --json
294
300
  ```
295
301
 
296
- Os IDs e valores de campos vêm do assignment apresentado ao signatário. Quando for exigida verificação de e-mail, `documents send-token <id> --email <email>` envia o código e `signer verify-email --code <otp>` confirma; a variável `ASSINAFY_VERIFICATION_CODE` evita colocar o código nos argumentos. `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`.
302
+ Os IDs e valores de campos vêm do assignment apresentado ao signatário. Quando for exigida verificação de e-mail, `documents send-token <id> --recipient <email> --channel email` envia o código e `signer verify-email --code <otp>` confirma; a variável `ASSINAFY_VERIFICATION_CODE` evita colocar o código nos argumentos. `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`.
303
+
304
+ 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. Em produção, `send-token` usa `--recipient` e `--channel`; `--email` mantém o formato publicado para deployments que o aceitam.
305
+
306
+ 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).
307
+
308
+ Para um assignment virtual, confirme os dados do signatário e envie um array vazio:
309
+
310
+ ```bash
311
+ assinafy signer confirm-data "$DOCUMENT_ID" --full-name 'Ana Lima' --email ana@example.com
312
+ assinafy signer sign "$DOCUMENT_ID" example_assignment --entries '[]'
313
+ ```
297
314
 
298
- 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. A sobrecarga de `send-token` com `--recipient` e `--channel` permanece disponível para deployments que usam esse formato.
315
+ Os comandos de confirmação de dados, assinatura e recusa de um único documento verificam se o código de acesso corresponde ao documento e ao assignment antes de enviar a alteração.
299
316
 
300
317
  ## Eventos e webhooks
301
318
 
package/dist/api.cjs CHANGED
@@ -860,24 +860,24 @@ var DocumentResource = class extends BaseResource {
860
860
  );
861
861
  }
862
862
  /**
863
- * Replace the document's tag set with tag IDs. An empty array detaches all tags.
864
- * Values are forwarded unchanged for compatibility with deployments that also accept names.
863
+ * Replace the document's tag set. Production accepts tag names and creates missing tags.
864
+ * An empty array detaches all tags. Values are forwarded unchanged.
865
865
  */
866
866
  async replaceTags(documentId, tags, accountId) {
867
867
  const accId = this.accountId(accountId);
868
868
  const docId = this.requireId(documentId, "Document ID");
869
- if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag IDs");
869
+ if (!Array.isArray(tags)) throw new ValidationError("tags must be an array");
870
870
  return this.call(
871
871
  "Failed to replace document tags",
872
872
  () => this.http.put(`/accounts/${accId}/documents/${docId}/tags`, { tags })
873
873
  );
874
874
  }
875
- /** Attach additional tag IDs without removing existing ones. */
875
+ /** Attach additional tag names without removing existing ones. Production creates missing tags. */
876
876
  async addTags(documentId, tags, accountId) {
877
877
  const accId = this.accountId(accountId);
878
878
  const docId = this.requireId(documentId, "Document ID");
879
879
  if (!Array.isArray(tags) || tags.length === 0) {
880
- throw new ValidationError("tags must be a non-empty array of tag IDs");
880
+ throw new ValidationError("tags must be a non-empty array");
881
881
  }
882
882
  return this.call(
883
883
  "Failed to add document tags",
@@ -1291,7 +1291,11 @@ var OAuthResource = class extends BaseResource {
1291
1291
  throw new ValidationError("OAuth issuer mismatch");
1292
1292
  }
1293
1293
  if (callback.searchParams.has("error")) {
1294
- throw new ValidationError("OAuth authorization was declined or failed");
1294
+ const error = callback.searchParams.get("error");
1295
+ const oauthError = error.length > 0 && error.length <= 64 && !/[^a-z_]/.test(error) ? error : "unknown_error";
1296
+ throw new ValidationError(`OAuth authorization was declined or failed: ${oauthError}`, {
1297
+ oauthError
1298
+ });
1295
1299
  }
1296
1300
  return this.token({
1297
1301
  grant_type: "authorization_code",
@@ -1496,6 +1500,7 @@ var SignerDocumentsResource = class extends BaseResource {
1496
1500
  for (const [key, value] of Object.entries(payload)) {
1497
1501
  if (value !== void 0) body[key] = value;
1498
1502
  }
1503
+ await this.requireDocumentAccess(did, code);
1499
1504
  return this.call(
1500
1505
  "Failed to confirm signer data",
1501
1506
  () => this.http.put(`/documents/${did}/signers/confirm-data`, body, signerAccessConfig(code))
@@ -1548,13 +1553,20 @@ var SignerDocumentsResource = class extends BaseResource {
1548
1553
  () => this.http.get("/sign", signerAccessConfig(code, { has_accepted_terms: hasAcceptedTerms }))
1549
1554
  );
1550
1555
  }
1551
- /** `POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…` — sign. */
1556
+ /**
1557
+ * `POST /documents/{documentId}/assignments/{assignmentId}?signer-access-code=…` — sign.
1558
+ * Virtual assignments accept `[]` after the signer confirms their data.
1559
+ */
1552
1560
  async sign(documentId, assignmentId, signerAccessCode, entries) {
1553
1561
  const did = this.requireId(documentId, "Document ID");
1554
1562
  const aid = this.requireId(assignmentId, "Assignment ID");
1555
1563
  const code = this.requireId(signerAccessCode, "signer-access-code");
1556
- if (!Array.isArray(entries) || entries.length === 0) {
1557
- throw new ValidationError("entries must be a non-empty array");
1564
+ if (!Array.isArray(entries)) {
1565
+ throw new ValidationError("entries must be an array");
1566
+ }
1567
+ const document = await this.requireDocumentAccess(did, code, aid);
1568
+ if (document.assignment?.method === "collect" && entries.length === 0) {
1569
+ throw new ValidationError("entries must be non-empty for collect assignments");
1558
1570
  }
1559
1571
  return this.call(
1560
1572
  "Failed to sign document",
@@ -1570,6 +1582,7 @@ var SignerDocumentsResource = class extends BaseResource {
1570
1582
  const aid = this.requireId(assignmentId, "Assignment ID");
1571
1583
  const code = this.requireId(signerAccessCode, "signer-access-code");
1572
1584
  validateDeclineReason(declineReason);
1585
+ await this.requireDocumentAccess(did, code, aid);
1573
1586
  return this.call(
1574
1587
  "Failed to decline assignment",
1575
1588
  () => this.http.put(
@@ -1579,6 +1592,13 @@ var SignerDocumentsResource = class extends BaseResource {
1579
1592
  )
1580
1593
  );
1581
1594
  }
1595
+ async requireDocumentAccess(documentId, signerAccessCode, assignmentId) {
1596
+ const document = await this.getAssignment(signerAccessCode);
1597
+ if (document.id !== documentId || assignmentId !== void 0 && document.assignment?.id !== assignmentId) {
1598
+ throw new ValidationError("Signer access code does not match the document or assignment");
1599
+ }
1600
+ return document;
1601
+ }
1582
1602
  };
1583
1603
  function validateDeclineReason(value) {
1584
1604
  if (typeof value !== "string" || !value.trim()) {