@assinafy/cli 2.5.3 → 2.6.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 CHANGED
@@ -36,7 +36,7 @@ ASSINAFY_MFA_CODE=
36
36
  ASSINAFY_MFA_TOKEN=
37
37
 
38
38
  # Endpoint signing secret (whsec_...) used by the SDK WebhookVerifier.
39
- # Read it with `assinafy webhooks endpoints secret <endpointId>`.
39
+ # Save it from signed endpoint creation; owner clients can also use `webhooks endpoints secret`.
40
40
  ASSINAFY_WEBHOOK_SECRET=
41
41
 
42
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 106 published API operations.
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 112 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
 
@@ -215,6 +215,8 @@ Email verification uses `["Email"]` notifications; WhatsApp uses `["Whatsapp"]`.
215
215
 
216
216
  In production, `notification_methods: []` defaults to `['Email']` and sends an invitation. Select the intended channel explicitly; an empty array does not disable notifications.
217
217
 
218
+ Biometric verification uses `IdDocumentFaceMatchBasic`, either notification channel, a valid CPF in `government_id`, and the ID Document + Face Match workspace feature. Signer creation and updates accept `--government-id` for CPF or numeric/alphanumeric CNPJ and forward it unchanged for server normalization; the legacy `--cpf` alias retains digit-only normalization.
219
+
218
220
  To start from a saved template instead of a PDF:
219
221
 
220
222
  ```bash
@@ -250,6 +252,23 @@ For A1/A3 certificates, use Assinafy's hosted signing page or integrate Web PKI
250
252
 
251
253
  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
254
 
255
+ For biometrics, create or explicitly update the signer with a valid CPF, estimate cost and create an `IdDocumentFaceMatchBasic` assignment. Present the document, terms and biometric-processing consent, then use the signer's private access code:
256
+
257
+ ```bash
258
+ assinafy signer identity-status --json
259
+ assinafy signer identity-start --consent --json
260
+ ```
261
+
262
+ Open the returned `url` unchanged, including any `#t=` fragment, and read status after capture. This is a private bearer link; keep it out of logs and browser storage. Start only when `can_start` is true. Only an `Expired` session can be replaced; `Declined` or `Abandoned` require a new document and assignment. `Approved` and `InReview` let the signer continue with data confirmation and signing. Review holds certification: after everyone signs, the document stays `pending_identity_review` until the account decides.
263
+
264
+ ```bash
265
+ assinafy assignments identity-verification <documentId> <assignmentId> <signerId> --json
266
+ assinafy assignments identity-image <documentId> <assignmentId> <signerId> --name face --output evidence.bin
267
+ assinafy assignments review-identity <documentId> <assignmentId> <signerId> --decision Approved --note 'Reviewed by the team'
268
+ ```
269
+
270
+ Evidence images are available only while the review is open. Approval releases certification after all signatures and reviews finish; `--decision Rejected` cancels the document and notifies signers and copy receivers. Decisions require confirmation or `--yes`; the private note allows at most 2,000 characters. See [complete biometric payloads and states](docs/sdk-reference.md#biometric-identity-verification).
271
+
253
272
  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).
254
273
 
255
274
  For a virtual assignment, confirm the signer's data and submit an empty entry array:
@@ -289,6 +308,8 @@ assinafy webhooks verify body.json --id <webhook-id> --timestamp <webhook-timest
289
308
 
290
309
  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
310
 
311
+ Creating a signed endpoint returns `secret` once, including through OAuth; store it securely. The CLI prints it in human and JSON output. OAuth applications that lose it must delete and recreate the endpoint. `endpoints list --url <url>` filters by the exact registered URL; `endpoints delete-by-url --url <url>` deletes by that URL and requires confirmation or `--yes`.
312
+
292
313
  `webhooks register`, `webhooks get`, and `webhooks inactivate` remain and act on the workspace's oldest endpoint.
293
314
 
294
315
  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:
@@ -596,9 +617,9 @@ The [release runbook](./docs/releasing.md) covers tags, trusted publishing, and
596
617
 
597
618
  ## Contract boundaries
598
619
 
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.
620
+ - The production OpenAPI publishes 112 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.
600
621
  - 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.
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.
622
+ - 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 112 OpenAPI operations.
602
623
  - `send-token` sends the email-only body `{ "channel": "email", "recipient": "..." }`; WhatsApp and the older `{ "email" }` body are rejected by the API with `400`.
603
624
  - `signer documents` and `signer search` accept the workspace API key or token when `--access-code` is omitted.
604
625
  - 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.
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 106 operações publicadas.
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 112 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
 
@@ -253,6 +253,7 @@ Thumbnails e páginas individuais são JPEG. Downloads não sobrescrevem arquivo
253
253
  | `Email` | Verificação por código enviado por e-mail. |
254
254
  | `Whatsapp` | Verificação por WhatsApp; notificações dependem dos recursos e créditos da conta. |
255
255
  | `DigitalCertificate` | Assinatura com certificado ICP-Brasil A1/A3 e fluxo Web PKI. |
256
+ | `IdDocumentFaceMatchBasic` | Verificação biométrica com documento, foto segurando o documento e prova de vida; exige CPF válido e o recurso ID Document + Face Match. |
256
257
 
257
258
  Use os endpoints de estimativa para obter os valores atuais. Verificação e notificação seguem combinações definidas pela API. Para selecionar explicitamente métodos e ordem:
258
259
 
@@ -271,7 +272,7 @@ Antes de estimar ou criar um assignment com certificado, atualize o CPF/CNPJ do
271
272
  assinafy signers update "$SIGNER_ID" --cpf '<CPF-ou-CNPJ-do-signatário>' --json
272
273
  ```
273
274
 
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.
275
+ Verificação `Email` usa notificação `["Email"]`; `Whatsapp` usa `["Whatsapp"]`. `DigitalCertificate` e `IdDocumentFaceMatchBasic` permitem um desses dois canais. Escolha apenas um canal por signatário; os mesmos campos são aceitos em documentos gerados de templates. `signers create` e `signers update` aceitam `--government-id` para CPF ou CNPJ numérico/alfanumérico, preservando o valor para normalização pelo servidor; `--cpf` mantém a compatibilidade e remove caracteres não numéricos.
275
276
 
276
277
  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.
277
278
 
@@ -314,6 +315,23 @@ Os IDs e valores de campos vêm do assignment apresentado ao signatário. Na ver
314
315
 
315
316
  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
317
 
318
+ Para biometria, cadastre ou atualize o CPF válido em `government_id`, estime o custo e crie o assignment com `verification_method: "IdDocumentFaceMatchBasic"`. A pessoa precisa consentir com o processamento biométrico antes de iniciar:
319
+
320
+ ```bash
321
+ assinafy signer identity-status --json
322
+ assinafy signer identity-start --consent --json
323
+ ```
324
+
325
+ Abra a `url` retornada exatamente como recebida, incluindo o fragmento `#t=`, e consulte o status após a captura. É um link privado: mantenha-o fora de logs e do armazenamento do navegador. Só inicie outra sessão quando `can_start` for verdadeiro; uma sessão `Expired` pode ser substituída, enquanto `Declined` ou `Abandoned` exigem novo documento e assignment. Em `Approved` ou `InReview`, a pessoa continua com confirmação de dados e assinatura. `InReview` segura a certificação: após todas as assinaturas, o documento fica `pending_identity_review` até a decisão da conta.
326
+
327
+ ```bash
328
+ assinafy assignments identity-verification "$DOCUMENT_ID" example_assignment example_signer --json
329
+ assinafy assignments identity-image "$DOCUMENT_ID" example_assignment example_signer --name face --output evidencia.bin
330
+ assinafy assignments review-identity "$DOCUMENT_ID" example_assignment example_signer --decision Approved --note 'Conferido pela equipe'
331
+ ```
332
+
333
+ As imagens ficam disponíveis somente durante a revisão. Aprovar libera a certificação quando todas as assinaturas e revisões terminarem; `--decision Rejected` cancela o documento e notifica signatários e destinatários de cópia. A decisão pede confirmação ou `--yes`; a nota privada aceita até 2.000 caracteres. Veja os [payloads completos e estados](docs/sdk-reference.md#biometric-identity-verification).
334
+
317
335
  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
336
 
319
337
  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).
@@ -343,6 +361,8 @@ assinafy webhooks verify corpo.json --id "$WEBHOOK_ID" --timestamp "$WEBHOOK_TIM
343
361
 
344
362
  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
363
 
364
+ Com `--signing`, a criação retorna `secret` uma vez, inclusive via OAuth; armazene-o com segurança. A CLI o mostra em texto e em JSON. Aplicativos OAuth que perderem esse segredo precisam excluir e recriar o endpoint. `endpoints list --url <url>` filtra pela URL exata; `endpoints delete-by-url --url <url>` remove por essa mesma URL e pede confirmação ou `--yes`.
365
+
346
366
  `webhooks register`, `webhooks get` e `webhooks inactivate` continuam disponíveis e atuam sobre o endpoint mais antigo do workspace.
347
367
 
348
368
  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`:
package/dist/api.cjs CHANGED
@@ -157,7 +157,8 @@ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
157
157
  var VERIFICATION_METHODS = [
158
158
  "Email",
159
159
  "Whatsapp",
160
- "DigitalCertificate"
160
+ "DigitalCertificate",
161
+ "IdDocumentFaceMatchBasic"
161
162
  ];
162
163
  var NOTIFICATION_METHODS = ["Email", "Whatsapp"];
163
164
  function handleAssinafyResponse(response) {
@@ -283,6 +284,13 @@ function validateSignerOptions(input) {
283
284
  throw new ValidationError("step must be an integer");
284
285
  }
285
286
  }
287
+ function validateDigitalCertificateMethod(method, signers) {
288
+ if (method !== "virtual" && signers.some((signer) => signer.verification_method === "DigitalCertificate")) {
289
+ throw new ValidationError("DigitalCertificate signers require method: virtual", {
290
+ code: "digital_certificate_requires_virtual"
291
+ });
292
+ }
293
+ }
286
294
  function validateSigningSteps(signers) {
287
295
  const withSteps = signers.filter((signer) => signer.step !== void 0);
288
296
  if (withSteps.length > 0) {
@@ -459,15 +467,17 @@ function buildAssignmentPayload(payload, options = {}) {
459
467
  signers: payload.signers ?? payload.signer_ids ?? payload.signerIds
460
468
  });
461
469
  }
462
- if (payload.method === "collect" && !Array.isArray(payload.entries)) {
470
+ const method = payload.method ?? "virtual";
471
+ const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
472
+ validateDigitalCertificateMethod(method, normalisedSigners);
473
+ if (method === "collect" && !Array.isArray(payload.entries)) {
463
474
  throw new ValidationError("entries are required for collect assignments");
464
475
  }
465
- const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
466
476
  if (!options.skipDigitalCertificateStepValidation) {
467
477
  validateSigningSteps(normalisedSigners);
468
478
  }
469
479
  return stripEmpty({
470
- method: payload.method ?? "virtual",
480
+ method,
471
481
  signers: normalisedSigners,
472
482
  message: payload.message,
473
483
  expires_at: payload.expires_at === void 0 ? void 0 : requireIso8601(payload.expires_at, "expires_at"),
@@ -516,6 +526,53 @@ function normaliseSignerRef(ref, options) {
516
526
  throw new ValidationError("Invalid signer reference", { ref });
517
527
  }
518
528
  var AssignmentResource = class extends BaseResource {
529
+ /** Fetch an account review and available evidence for a signer's identity verification. */
530
+ async getIdentityVerification(documentId, assignmentId, signerId) {
531
+ const docId = this.requireId(documentId, "Document ID");
532
+ const asgId = this.requireId(assignmentId, "Assignment ID");
533
+ const sid = this.requireId(signerId, "Signer ID");
534
+ return this.call(
535
+ "Failed to fetch signer identity review",
536
+ () => this.http.get(
537
+ `/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification`
538
+ )
539
+ );
540
+ }
541
+ /** Download JPEG/PNG evidence or the document PDF, available only while the review is open. */
542
+ async downloadIdentityVerificationImage(documentId, assignmentId, signerId, name) {
543
+ const docId = this.requireId(documentId, "Document ID");
544
+ const asgId = this.requireId(assignmentId, "Assignment ID");
545
+ const sid = this.requireId(signerId, "Signer ID");
546
+ if (!["document_front", "document_back", "document_pdf", "face"].includes(name)) {
547
+ throw new ValidationError("Unknown identity verification image name");
548
+ }
549
+ return this.callBinary(
550
+ "Failed to download identity review image",
551
+ () => this.http.get(
552
+ `/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification/images/${name}`,
553
+ { responseType: "arraybuffer" }
554
+ )
555
+ );
556
+ }
557
+ /** Approve certification or reject/cancel the document; the optional note is private to reviewers. */
558
+ async reviewIdentityVerification(documentId, assignmentId, signerId, payload) {
559
+ const docId = this.requireId(documentId, "Document ID");
560
+ const asgId = this.requireId(assignmentId, "Assignment ID");
561
+ const sid = this.requireId(signerId, "Signer ID");
562
+ if (!payload || !["Approved", "Rejected"].includes(payload.decision)) {
563
+ throw new ValidationError("decision must be Approved or Rejected");
564
+ }
565
+ if (payload.note != null && (typeof payload.note !== "string" || [...payload.note].length > 2e3)) {
566
+ throw new ValidationError("note must contain at most 2000 characters");
567
+ }
568
+ return this.call(
569
+ "Failed to decide signer identity review",
570
+ () => this.http.post(
571
+ `/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification/review`,
572
+ { decision: payload.decision, note: payload.note }
573
+ )
574
+ );
575
+ }
519
576
  /**
520
577
  * List assignments across the account (`GET /assignments`).
521
578
  *
@@ -770,6 +827,7 @@ var DOCUMENT_SORTS = ["name", "-name", "updated_at", "-updated_at"];
770
827
  var READY_STATUSES = /* @__PURE__ */ new Set([
771
828
  "metadata_ready",
772
829
  "pending_signature",
830
+ "pending_identity_review",
773
831
  "certificated"
774
832
  ]);
775
833
  var FAILED_STATUSES = /* @__PURE__ */ new Set([
@@ -1023,6 +1081,7 @@ var DocumentResource = class extends BaseResource {
1023
1081
  if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !tag))) {
1024
1082
  throw new ValidationError("tags must contain non-empty tag names");
1025
1083
  }
1084
+ await this.validateCertificateTemplateMethod(tmplId, accId, signers);
1026
1085
  const body = { ...options, signers };
1027
1086
  this.logger.info("Creating document from template", { templateId: tmplId, accountId: accId });
1028
1087
  return this.call(
@@ -1035,6 +1094,7 @@ var DocumentResource = class extends BaseResource {
1035
1094
  const tmplId = this.requireId(templateId, "Template ID");
1036
1095
  const accId = this.accountId(accountId);
1037
1096
  validateTemplateSigners(signers, { requireId: false });
1097
+ await this.validateCertificateTemplateMethod(tmplId, accId, signers);
1038
1098
  return this.call(
1039
1099
  "Failed to estimate cost from template",
1040
1100
  () => this.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers })
@@ -1113,6 +1173,15 @@ var DocumentResource = class extends BaseResource {
1113
1173
  const percentage = total > 0 ? Math.round(signed / total * 1e4) / 100 : 0;
1114
1174
  return { signed, total, pending, percentage };
1115
1175
  }
1176
+ async validateCertificateTemplateMethod(templateId, accountId, signers) {
1177
+ if (!signers.some((signer) => signer.verification_method === "DigitalCertificate")) return;
1178
+ const template = await this.call(
1179
+ "Failed to fetch template",
1180
+ () => this.http.get(`/accounts/${accountId}/templates/${templateId}`)
1181
+ );
1182
+ const method = template.pages?.some((page) => page.fields.length > 0) ? "collect" : "virtual";
1183
+ validateDigitalCertificateMethod(method, signers);
1184
+ }
1116
1185
  };
1117
1186
  function validateTemplateSigners(signers, options) {
1118
1187
  if (!Array.isArray(signers)) throw new ValidationError("signers must be an array");
@@ -1613,6 +1682,25 @@ var SignerDocumentsResource = class extends BaseResource {
1613
1682
  () => this.http.get("/signers/self", signerAccessConfig(code))
1614
1683
  );
1615
1684
  }
1685
+ /** `GET /signers/identity-verification` — session status, capture URL and restart eligibility. */
1686
+ async getIdentityVerification(signerAccessCode) {
1687
+ const code = this.requireId(signerAccessCode, "signer-access-code");
1688
+ return this.call(
1689
+ "Failed to fetch identity verification",
1690
+ () => this.http.get("/signers/identity-verification", signerAccessConfig(code))
1691
+ );
1692
+ }
1693
+ /** `POST /signers/identity-verification` — open a hosted session after the signer's explicit consent. */
1694
+ async startIdentityVerification(signerAccessCode, payload) {
1695
+ const code = this.requireId(signerAccessCode, "signer-access-code");
1696
+ if (payload?.consent !== true) {
1697
+ throw new ValidationError("Explicit biometric-processing consent is required");
1698
+ }
1699
+ return this.call(
1700
+ "Failed to start identity verification",
1701
+ () => this.http.post("/signers/identity-verification", { consent: true }, signerAccessConfig(code))
1702
+ );
1703
+ }
1616
1704
  /**
1617
1705
  * `PUT /signers/accept-terms?signer-access-code=…` — accept the platform
1618
1706
  * terms as the signer.
@@ -1916,9 +2004,10 @@ function normaliseSignerPayload(payload, useGovernmentId = false) {
1916
2004
  email: payload.email,
1917
2005
  whatsapp_phone_number: payload.whatsapp_phone_number ?? payload.phone
1918
2006
  };
1919
- const governmentId = "government_id" in payload ? payload.government_id ?? payload.cpf : payload.cpf;
1920
- if (governmentId) {
1921
- const digits = governmentId.replace(/\D/g, "");
2007
+ if (payload.government_id !== void 0) {
2008
+ normalised.government_id = payload.government_id;
2009
+ } else if (payload.cpf) {
2010
+ const digits = payload.cpf.replace(/\D/g, "");
1922
2011
  if (digits) normalised[useGovernmentId ? "government_id" : "cpf"] = digits;
1923
2012
  }
1924
2013
  if ("metadata" in payload && payload.metadata !== void 0) {
@@ -2157,19 +2246,21 @@ var WebhookResource = class extends BaseResource {
2157
2246
  () => this.http.put(`/accounts/${id}/webhooks/inactivate`)
2158
2247
  );
2159
2248
  }
2160
- /** `GET /accounts/{accountId}/webhooks/endpoints` — list webhook endpoints, oldest first. */
2161
- async listEndpoints(accountId) {
2249
+ /** List webhook endpoints, oldest first; `url` matches the registered value exactly. */
2250
+ async listEndpoints(accountId, params = {}) {
2162
2251
  const id = this.accountId(accountId);
2252
+ validateWebhookFields(params);
2163
2253
  return this.call(
2164
2254
  "Failed to list webhook endpoints",
2165
- () => this.http.get(`/accounts/${id}/webhooks/endpoints`)
2255
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints`, { params: cleanParams({ ...params }) })
2166
2256
  );
2167
2257
  }
2168
2258
  /**
2169
2259
  * `POST /accounts/{accountId}/webhooks/endpoints` — register another
2170
2260
  * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past
2171
2261
  * the limit); URLs must be unique per workspace. Omitted `events` uses the
2172
- * same default set as {@link register}.
2262
+ * same default set as {@link register}. Signed creation returns `secret`
2263
+ * once, including to OAuth applications; save it securely.
2173
2264
  */
2174
2265
  async createEndpoint(payload, accountId) {
2175
2266
  if (!payload.url) throw new ValidationError("Webhook URL is required");
@@ -2217,6 +2308,16 @@ var WebhookResource = class extends BaseResource {
2217
2308
  () => this.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`)
2218
2309
  );
2219
2310
  }
2311
+ /** Delete the endpoint whose URL exactly matches `url`; returns 404 when none matches. */
2312
+ async deleteEndpointByUrl(url, accountId) {
2313
+ if (!url) throw new ValidationError("Webhook URL is required");
2314
+ validateWebhookFields({ url });
2315
+ const id = this.accountId(accountId);
2316
+ return this.call(
2317
+ "Failed to delete webhook endpoint by URL",
2318
+ () => this.http.delete(`/accounts/${id}/webhooks/endpoints`, { params: { url } })
2319
+ );
2320
+ }
2220
2321
  /**
2221
2322
  * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.
2222
2323
  * Returns `400` when signing is disabled. Not available to OAuth applications.
@@ -2374,12 +2475,10 @@ function readHeader(headers, name) {
2374
2475
  if (typeof headers.get === "function") {
2375
2476
  return headers.get(name) ?? void 0;
2376
2477
  }
2377
- for (const [key, value] of Object.entries(headers)) {
2378
- if (key.toLowerCase() !== name) continue;
2379
- if (Array.isArray(value)) return value.length === 1 ? value[0] : void 0;
2380
- return value;
2381
- }
2382
- return void 0;
2478
+ const matches = Object.entries(headers).filter(([key]) => key.toLowerCase() === name);
2479
+ if (matches.length !== 1) return void 0;
2480
+ const value = matches[0]?.[1];
2481
+ return Array.isArray(value) ? value.length === 1 ? value[0] : void 0 : value;
2383
2482
  }
2384
2483
  var WebhookVerifier = class {
2385
2484
  constructor(webhookSecret, options = {}) {
@@ -2404,7 +2503,8 @@ var WebhookVerifier = class {
2404
2503
  if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
2405
2504
  const tolerance = options.toleranceSeconds ?? 300;
2406
2505
  const now = Math.floor((options.now ?? Date.now()) / 1e3);
2407
- if (Math.abs(now - Number(timestamp)) > tolerance) return false;
2506
+ if (!Number.isFinite(tolerance) || tolerance < 0 || !Number.isSafeInteger(now) || now < 0 || !Number.isSafeInteger(Number(timestamp)) || Math.abs(now - Number(timestamp)) > tolerance)
2507
+ return false;
2408
2508
  const secret = this.webhookSecret.startsWith("whsec_") ? this.webhookSecret.slice("whsec_".length) : this.webhookSecret;
2409
2509
  const key = Buffer.from(secret, "base64");
2410
2510
  if (key.length === 0) return false;
@@ -2412,8 +2512,8 @@ var WebhookVerifier = class {
2412
2512
  (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`).update(typeof payload === "string" ? Buffer.from(payload, "utf8") : payload).digest("base64")
2413
2513
  );
2414
2514
  return signatures.split(" ").some((entry) => {
2415
- const [version, value] = entry.split(",", 2);
2416
- if (version !== "v1" || !value) return false;
2515
+ const [version, value, extra] = entry.split(",");
2516
+ if (version !== "v1" || !value || extra !== void 0) return false;
2417
2517
  const provided = Buffer.from(value);
2418
2518
  return provided.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(provided, expected);
2419
2519
  });
@@ -2618,6 +2718,7 @@ var AssinafyClient = class _AssinafyClient {
2618
2718
  const phone = signer.whatsapp_phone_number ?? signer.phone;
2619
2719
  if (phone !== void 0) payload.whatsapp_phone_number = phone;
2620
2720
  if (signer.cpf !== void 0) payload.cpf = signer.cpf;
2721
+ if (signer.government_id !== void 0) payload.government_id = signer.government_id;
2621
2722
  if (signer.metadata !== void 0) payload.metadata = signer.metadata;
2622
2723
  validateCreateSignerPayload(payload);
2623
2724
  return { signer, payload, phone };