@assinafy/cli 2.5.3 → 2.6.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 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) {
@@ -516,6 +517,53 @@ function normaliseSignerRef(ref, options) {
516
517
  throw new ValidationError("Invalid signer reference", { ref });
517
518
  }
518
519
  var AssignmentResource = class extends BaseResource {
520
+ /** Fetch an account review and available evidence for a signer's identity verification. */
521
+ async getIdentityVerification(documentId, assignmentId, signerId) {
522
+ const docId = this.requireId(documentId, "Document ID");
523
+ const asgId = this.requireId(assignmentId, "Assignment ID");
524
+ const sid = this.requireId(signerId, "Signer ID");
525
+ return this.call(
526
+ "Failed to fetch signer identity review",
527
+ () => this.http.get(
528
+ `/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification`
529
+ )
530
+ );
531
+ }
532
+ /** Download JPEG/PNG evidence or the document PDF, available only while the review is open. */
533
+ async downloadIdentityVerificationImage(documentId, assignmentId, signerId, name) {
534
+ const docId = this.requireId(documentId, "Document ID");
535
+ const asgId = this.requireId(assignmentId, "Assignment ID");
536
+ const sid = this.requireId(signerId, "Signer ID");
537
+ if (!["document_front", "document_back", "document_pdf", "face"].includes(name)) {
538
+ throw new ValidationError("Unknown identity verification image name");
539
+ }
540
+ return this.callBinary(
541
+ "Failed to download identity review image",
542
+ () => this.http.get(
543
+ `/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification/images/${name}`,
544
+ { responseType: "arraybuffer" }
545
+ )
546
+ );
547
+ }
548
+ /** Approve certification or reject/cancel the document; the optional note is private to reviewers. */
549
+ async reviewIdentityVerification(documentId, assignmentId, signerId, payload) {
550
+ const docId = this.requireId(documentId, "Document ID");
551
+ const asgId = this.requireId(assignmentId, "Assignment ID");
552
+ const sid = this.requireId(signerId, "Signer ID");
553
+ if (!payload || !["Approved", "Rejected"].includes(payload.decision)) {
554
+ throw new ValidationError("decision must be Approved or Rejected");
555
+ }
556
+ if (payload.note != null && (typeof payload.note !== "string" || [...payload.note].length > 2e3)) {
557
+ throw new ValidationError("note must contain at most 2000 characters");
558
+ }
559
+ return this.call(
560
+ "Failed to decide signer identity review",
561
+ () => this.http.post(
562
+ `/documents/${docId}/assignments/${asgId}/signers/${sid}/identity-verification/review`,
563
+ { decision: payload.decision, note: payload.note }
564
+ )
565
+ );
566
+ }
519
567
  /**
520
568
  * List assignments across the account (`GET /assignments`).
521
569
  *
@@ -770,6 +818,7 @@ var DOCUMENT_SORTS = ["name", "-name", "updated_at", "-updated_at"];
770
818
  var READY_STATUSES = /* @__PURE__ */ new Set([
771
819
  "metadata_ready",
772
820
  "pending_signature",
821
+ "pending_identity_review",
773
822
  "certificated"
774
823
  ]);
775
824
  var FAILED_STATUSES = /* @__PURE__ */ new Set([
@@ -1613,6 +1662,25 @@ var SignerDocumentsResource = class extends BaseResource {
1613
1662
  () => this.http.get("/signers/self", signerAccessConfig(code))
1614
1663
  );
1615
1664
  }
1665
+ /** `GET /signers/identity-verification` — session status, capture URL and restart eligibility. */
1666
+ async getIdentityVerification(signerAccessCode) {
1667
+ const code = this.requireId(signerAccessCode, "signer-access-code");
1668
+ return this.call(
1669
+ "Failed to fetch identity verification",
1670
+ () => this.http.get("/signers/identity-verification", signerAccessConfig(code))
1671
+ );
1672
+ }
1673
+ /** `POST /signers/identity-verification` — open a hosted session after the signer's explicit consent. */
1674
+ async startIdentityVerification(signerAccessCode, payload) {
1675
+ const code = this.requireId(signerAccessCode, "signer-access-code");
1676
+ if (payload?.consent !== true) {
1677
+ throw new ValidationError("Explicit biometric-processing consent is required");
1678
+ }
1679
+ return this.call(
1680
+ "Failed to start identity verification",
1681
+ () => this.http.post("/signers/identity-verification", { consent: true }, signerAccessConfig(code))
1682
+ );
1683
+ }
1616
1684
  /**
1617
1685
  * `PUT /signers/accept-terms?signer-access-code=…` — accept the platform
1618
1686
  * terms as the signer.
@@ -1916,9 +1984,10 @@ function normaliseSignerPayload(payload, useGovernmentId = false) {
1916
1984
  email: payload.email,
1917
1985
  whatsapp_phone_number: payload.whatsapp_phone_number ?? payload.phone
1918
1986
  };
1919
- const governmentId = "government_id" in payload ? payload.government_id ?? payload.cpf : payload.cpf;
1920
- if (governmentId) {
1921
- const digits = governmentId.replace(/\D/g, "");
1987
+ if (payload.government_id !== void 0) {
1988
+ normalised.government_id = payload.government_id;
1989
+ } else if (payload.cpf) {
1990
+ const digits = payload.cpf.replace(/\D/g, "");
1922
1991
  if (digits) normalised[useGovernmentId ? "government_id" : "cpf"] = digits;
1923
1992
  }
1924
1993
  if ("metadata" in payload && payload.metadata !== void 0) {
@@ -2157,19 +2226,21 @@ var WebhookResource = class extends BaseResource {
2157
2226
  () => this.http.put(`/accounts/${id}/webhooks/inactivate`)
2158
2227
  );
2159
2228
  }
2160
- /** `GET /accounts/{accountId}/webhooks/endpoints` — list webhook endpoints, oldest first. */
2161
- async listEndpoints(accountId) {
2229
+ /** List webhook endpoints, oldest first; `url` matches the registered value exactly. */
2230
+ async listEndpoints(accountId, params = {}) {
2162
2231
  const id = this.accountId(accountId);
2232
+ validateWebhookFields(params);
2163
2233
  return this.call(
2164
2234
  "Failed to list webhook endpoints",
2165
- () => this.http.get(`/accounts/${id}/webhooks/endpoints`)
2235
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints`, { params: cleanParams({ ...params }) })
2166
2236
  );
2167
2237
  }
2168
2238
  /**
2169
2239
  * `POST /accounts/{accountId}/webhooks/endpoints` — register another
2170
2240
  * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past
2171
2241
  * the limit); URLs must be unique per workspace. Omitted `events` uses the
2172
- * same default set as {@link register}.
2242
+ * same default set as {@link register}. Signed creation returns `secret`
2243
+ * once, including to OAuth applications; save it securely.
2173
2244
  */
2174
2245
  async createEndpoint(payload, accountId) {
2175
2246
  if (!payload.url) throw new ValidationError("Webhook URL is required");
@@ -2217,6 +2288,16 @@ var WebhookResource = class extends BaseResource {
2217
2288
  () => this.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`)
2218
2289
  );
2219
2290
  }
2291
+ /** Delete the endpoint whose URL exactly matches `url`; returns 404 when none matches. */
2292
+ async deleteEndpointByUrl(url, accountId) {
2293
+ if (!url) throw new ValidationError("Webhook URL is required");
2294
+ validateWebhookFields({ url });
2295
+ const id = this.accountId(accountId);
2296
+ return this.call(
2297
+ "Failed to delete webhook endpoint by URL",
2298
+ () => this.http.delete(`/accounts/${id}/webhooks/endpoints`, { params: { url } })
2299
+ );
2300
+ }
2220
2301
  /**
2221
2302
  * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.
2222
2303
  * Returns `400` when signing is disabled. Not available to OAuth applications.
@@ -2374,12 +2455,10 @@ function readHeader(headers, name) {
2374
2455
  if (typeof headers.get === "function") {
2375
2456
  return headers.get(name) ?? void 0;
2376
2457
  }
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;
2458
+ const matches = Object.entries(headers).filter(([key]) => key.toLowerCase() === name);
2459
+ if (matches.length !== 1) return void 0;
2460
+ const value = matches[0]?.[1];
2461
+ return Array.isArray(value) ? value.length === 1 ? value[0] : void 0 : value;
2383
2462
  }
2384
2463
  var WebhookVerifier = class {
2385
2464
  constructor(webhookSecret, options = {}) {
@@ -2404,7 +2483,8 @@ var WebhookVerifier = class {
2404
2483
  if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
2405
2484
  const tolerance = options.toleranceSeconds ?? 300;
2406
2485
  const now = Math.floor((options.now ?? Date.now()) / 1e3);
2407
- if (Math.abs(now - Number(timestamp)) > tolerance) return false;
2486
+ if (!Number.isFinite(tolerance) || tolerance < 0 || !Number.isSafeInteger(now) || now < 0 || !Number.isSafeInteger(Number(timestamp)) || Math.abs(now - Number(timestamp)) > tolerance)
2487
+ return false;
2408
2488
  const secret = this.webhookSecret.startsWith("whsec_") ? this.webhookSecret.slice("whsec_".length) : this.webhookSecret;
2409
2489
  const key = Buffer.from(secret, "base64");
2410
2490
  if (key.length === 0) return false;
@@ -2412,8 +2492,8 @@ var WebhookVerifier = class {
2412
2492
  (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`).update(typeof payload === "string" ? Buffer.from(payload, "utf8") : payload).digest("base64")
2413
2493
  );
2414
2494
  return signatures.split(" ").some((entry) => {
2415
- const [version, value] = entry.split(",", 2);
2416
- if (version !== "v1" || !value) return false;
2495
+ const [version, value, extra] = entry.split(",");
2496
+ if (version !== "v1" || !value || extra !== void 0) return false;
2417
2497
  const provided = Buffer.from(value);
2418
2498
  return provided.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(provided, expected);
2419
2499
  });
@@ -2618,6 +2698,7 @@ var AssinafyClient = class _AssinafyClient {
2618
2698
  const phone = signer.whatsapp_phone_number ?? signer.phone;
2619
2699
  if (phone !== void 0) payload.whatsapp_phone_number = phone;
2620
2700
  if (signer.cpf !== void 0) payload.cpf = signer.cpf;
2701
+ if (signer.government_id !== void 0) payload.government_id = signer.government_id;
2621
2702
  if (signer.metadata !== void 0) payload.metadata = signer.metadata;
2622
2703
  validateCreateSignerPayload(payload);
2623
2704
  return { signer, payload, phone };