@assinafy/cli 2.4.2 → 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 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
- # Experimental verifier only: Assinafy does not publish its webhook signing scheme.
37
- # Do not treat WebhookVerifier as a production trust boundary without independent validation.
38
+ # Endpoint signing secret (whsec_...) used by the SDK WebhookVerifier.
39
+ # Read it with `assinafy webhooks endpoints secret <endpointId>`.
38
40
  ASSINAFY_WEBHOOK_SECRET=
39
41
 
40
42
  # Named profile to select from the config file (~/.config/assinafy/config.json).
package/README.en.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  The official command-line interface and Node.js SDK for the [Assinafy API](https://api.assinafy.com.br/v1/docs), a Brazilian digital-signature platform. Upload PDFs, manage signers, request signatures, track activity history, and download certified documents — from a terminal, a shell script, or an application.
6
6
 
7
- The CLI is a single self-contained executable. It prints human-readable tables by default and structured JSON with `--json`, so the same commands serve both interactive use and automation. The same package exposes a fully typed SDK at `@assinafy/cli/api` covering all 93 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 106 published API operations.
8
8
 
9
9
  This document reads top to bottom: install, authenticate, send your first signature request, then understand the model well enough to automate it. The [command reference](#command-reference) and [SDK](#nodejs-sdk) sections near the end are lookup tables you can jump to once the flow makes sense.
10
10
 
@@ -92,6 +92,8 @@ assinafy auth login you@example.com # returns a JWT
92
92
  assinafy auth api-keys create --token <jwt> # generates (and rotates) the key
93
93
  ```
94
94
 
95
+ When two-factor authentication is enabled, `auth login` asks for an authenticator or recovery code (or reads `--mfa-code` / `ASSINAFY_MFA_CODE`); the challenge is single-use and expires after 5 minutes. `auth mfa enroll`, `confirm`, `list`, `recovery-codes`, and `remove` manage the authenticator and recovery codes.
96
+
95
97
  Store the key once, then confirm it works:
96
98
 
97
99
  ```bash
@@ -263,24 +265,44 @@ Owner API credentials are stripped from every public and signer-side request, so
263
265
 
264
266
  ## Webhooks
265
267
 
266
- Polling works, but webhooks are the right way to react to signing events:
268
+ Polling works, but webhooks are the right way to react to signing events. A workspace can register 1 webhook endpoint, or up to 3 on paid plans. Each endpoint has its own URL, events, active flag, and signing setting, and every active endpoint subscribed to an event receives it independently.
267
269
 
268
270
  ```bash
269
271
  assinafy webhooks event-types # what the platform can send
270
- assinafy webhooks register \
272
+ assinafy webhooks endpoints create \
271
273
  --url https://example.com/hooks/assinafy \
272
274
  --email ops@example.com \
273
- --events document_ready,signer_signed_document,signer_rejected_document
274
-
275
- assinafy webhooks dispatches --delivered false # what failed to deliver
275
+ --name ERP \
276
+ --events document_ready,signer_signed_document,signer_rejected_document \
277
+ --signing # sign deliveries
278
+ assinafy webhooks endpoints list
279
+ assinafy webhooks endpoints secret <endpointId> # whsec_ secret for your receiver
280
+ assinafy webhooks endpoints update <endpointId> --inactive
281
+ assinafy webhooks endpoints rotate-secret <endpointId>
282
+ assinafy webhooks endpoints delete <endpointId>
283
+
284
+ assinafy webhooks dispatches --endpoint <endpointId> --delivered false
276
285
  assinafy webhooks retry <dispatchId> # redeliver one event
277
- assinafy webhooks get # current subscription
278
- assinafy webhooks inactivate # stop deliveries
279
286
  ```
280
287
 
281
- One subscription exists per workspace; `register` replaces it. Omitting `--events` subscribes to `document_ready`, `document_prepared`, `signer_signed_document`, `signer_rejected_document`, and `document_processing_failed`. The API has no delete-subscription operation — use `inactivate` to stop deliveries, and note that `retry` only works while the subscription is active.
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.
291
+
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
+ ```
282
304
 
283
- Assinafy does not publish a webhook signing scheme, so the SDK's `WebhookVerifier` is experimental. See [Contract boundaries](#contract-boundaries).
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.
284
306
 
285
307
  ## Output and scripting
286
308
 
@@ -336,7 +358,7 @@ Empty optional settings are ignored, including `.env.example` defaults. Configur
336
358
  | API base URL | `--base-url` | `ASSINAFY_BASE_URL` |
337
359
  | Config profile | `-p, --profile` | `ASSINAFY_PROFILE` |
338
360
  | Config directory | — | `ASSINAFY_CONFIG_DIR` |
339
- | Experimental webhook-verifier secret | _(config only)_ | `ASSINAFY_WEBHOOK_SECRET` |
361
+ | Webhook endpoint signing secret (`whsec_`) | _(config only)_ | `ASSINAFY_WEBHOOK_SECRET` |
340
362
  | Password / new password | `--password` / `--new-password` | `ASSINAFY_PASSWORD` / `ASSINAFY_NEW_PASSWORD` |
341
363
  | Social provider / reset token | `--provider-token` / `--reset-token` | `ASSINAFY_PROVIDER_TOKEN` / `ASSINAFY_RESET_TOKEN` |
342
364
  | Signer access code / email or WhatsApp OTP | `--access-code` / `--code` | `ASSINAFY_SIGNER_ACCESS_CODE` / `ASSINAFY_VERIFICATION_CODE` |
@@ -458,7 +480,7 @@ Field definitions are what `--method collect` assignments gather. Run `fields ty
458
480
 
459
481
  ### `webhooks`
460
482
 
461
- `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>`
462
484
 
463
485
  ### `workspaces` (alias `accounts`)
464
486
 
@@ -478,9 +500,9 @@ Every signer command except the public artifact `download` requires `--access-co
478
500
 
479
501
  ### `auth`
480
502
 
481
- `login <email>` · `social-login` · `link-social-login` · `change-password` · `request-password-reset <email>` · `reset-password --reset-token` · `api-keys create|get|delete`
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]`
482
504
 
483
- For server-to-server use, prefer an API key (`assinafy login` or `--api-key`) and skip this group. `auth login`, `auth social-login`, `auth request-password-reset`, and `auth reset-password` run without stored credentials; the rest accept the API key or JWT documented for their endpoint.
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.
484
506
 
485
507
  ### `oauth`
486
508
 
@@ -572,11 +594,11 @@ The [release runbook](./docs/releasing.md) covers tags, trusted publishing, and
572
594
 
573
595
  ## Contract boundaries
574
596
 
575
- - The production OpenAPI publishes 93 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.
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.
576
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.
577
- - Certificate start/complete are deployed production extensions of the public signing frontend, exposed as `signerDocuments.startCertificate(accessCode)` and `signerDocuments.completeCertificate(accessCode, token)`. Start posts `{ "signer-access-code": code }` and returns `{ token }`; complete posts `{ "signer-access-code": code, token }` and returns `{ signerName }`. Both also carry the access code in the query string and strip owner credentials. They supplement, but are not part of, the 93 OpenAPI operations.
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.
578
600
  - Both the published and legacy `send-token` payloads are supported for compatible deployments.
579
- - `WebhookVerifier` is **experimental**. Assinafy does not publish the signature header, algorithm, encoding, timestamp, or replay-protection scheme, so it is not a production trust boundary until the exact scheme is published or independently verified against real deliveries.
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.
580
602
 
581
603
  ## License
582
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 93 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 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
 
@@ -329,19 +329,36 @@ Os comandos de confirmação de dados, assinatura e recusa de um único document
329
329
 
330
330
  ## Eventos e webhooks
331
331
 
332
+ Cada workspace pode cadastrar 1 endpoint de webhook, ou até 3 nos planos pagos. Cada endpoint tem URL, eventos, estado e assinatura próprios, e todo endpoint ativo inscrito em um evento o recebe de forma independente.
333
+
332
334
  ```bash
333
335
  assinafy webhooks event-types --json
334
- assinafy webhooks register \
335
- --url https://example.com/hooks/assinafy \
336
- --email ops@example.com \
337
- --events document_ready,signer_signed_document,signer_rejected_document \
338
- --json
339
- assinafy webhooks dispatches --delivered false --json
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);
340
357
  ```
341
358
 
342
- Há uma assinatura de webhook por workspace; `register` substitui sua configuração. `document_ready` indica a assinatura pelo último signatário, não o término do processamento inicial do upload. Confirme estado e artefatos pela API antes de baixar o resultado. Processe eventos de forma idempotente e consulte `event-types` para a lista vigente.
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.
343
360
 
344
- `webhooks retry <dispatchId>` solicita uma nova entrega. `webhooks inactivate` desativa a assinatura, sem excluí-la. A Assinafy não publica um esquema de assinatura criptográfica de webhooks: `WebhookVerifier` é experimental e não deve autenticar eventos de produção sem validação independente do protocolo. Trate notificações como sinais para consultar o estado autorizado pela API.
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.
345
362
 
346
363
  ## SDK Node.js
347
364
 
@@ -419,13 +436,13 @@ No SDK, `ValidationError` indica entrada inválida; `ApiError` carrega `statusCo
419
436
  | [`assignments`](docs/assignments.md) | Solicitações, estimativas, vencimento, reenvios e notificações. |
420
437
  | [`signer`](docs/signer.md) | Perfil, documentos, termos, verificação, assinatura e recusa. |
421
438
  | [`oauth`](docs/oauth.md) | Conexão pelo navegador, discovery, autorização, exchange, refresh, UserInfo e revogação. |
422
- | [`auth`](docs/auth.md) | Login de usuário, login social, senhas e chaves de API. |
439
+ | [`auth`](docs/auth.md) | Login de usuário com verificação em duas etapas, login social, senhas e chaves de API. |
423
440
  | [`workspaces`](docs/workspaces.md) / `accounts` | Cadastro, consulta, tema, logo e estatísticas. |
424
441
  | [`users`](docs/users.md) | Perfil, estatísticas e preferências de notificação. |
425
442
  | [`templates`](docs/templates.md) | Listagem, detalhes e páginas de templates. |
426
443
  | [`tags`](docs/tags.md) | Organização dos documentos por tags. |
427
444
  | [`fields`](docs/fields.md) | Definições, tipos e validação de campos. |
428
- | [`webhooks`](docs/webhooks.md) | Assinatura de eventos e acompanhamento das entregas. |
445
+ | [`webhooks`](docs/webhooks.md) | Endpoints de webhook, segredos de assinatura e acompanhamento das entregas. |
429
446
  | [`config`](docs/config.md) | Perfis, credenciais e configuração efetiva. |
430
447
  | [`send`](docs/send.md) | Upload e solicitação de assinaturas em um comando. |
431
448
 
package/dist/api.cjs CHANGED
@@ -589,6 +589,12 @@ var AssignmentResource = class extends BaseResource {
589
589
  };
590
590
 
591
591
  // src/api/resources/authentication.ts
592
+ function requireReauth(payload) {
593
+ if (!payload?.password && !payload?.code) {
594
+ throw new ValidationError("password or code is required");
595
+ }
596
+ return payload;
597
+ }
592
598
  var AuthenticationResource = class extends BaseResource {
593
599
  /** `POST /login` — exchange email + password for a JWT access token. */
594
600
  async login(email, password) {
@@ -599,6 +605,70 @@ var AuthenticationResource = class extends BaseResource {
599
605
  () => this.http.post("/login", { email, password }, publicRequestConfig())
600
606
  );
601
607
  }
608
+ /**
609
+ * `POST /authentication/mfa/verify` — exchange the login `mfa_token` and an
610
+ * authenticator or recovery code for an access token. The challenge is
611
+ * single-use and expires 5 minutes after login.
612
+ */
613
+ async verifyMfa(payload) {
614
+ if (!payload?.mfa_token) throw new ValidationError("mfa_token is required");
615
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
616
+ return this.call(
617
+ "Two-factor verification failed",
618
+ () => this.http.post(
619
+ "/authentication/mfa/verify",
620
+ { mfa_token: payload.mfa_token, code: payload.code.trim() },
621
+ publicRequestConfig()
622
+ )
623
+ );
624
+ }
625
+ /** `GET /users/self/mfa` — enrolled two-factor methods and remaining recovery codes. */
626
+ async listMfaMethods() {
627
+ return this.call("Failed to list two-factor methods", () => this.http.get("/users/self/mfa"));
628
+ }
629
+ /**
630
+ * `POST /users/self/mfa/totp` — start authenticator enrollment. The secret
631
+ * and provisioning URI are returned only once; two-factor stays inactive
632
+ * until {@link confirmTotpEnrollment}.
633
+ */
634
+ async startTotpEnrollment(label) {
635
+ return this.call(
636
+ "Failed to start authenticator enrollment",
637
+ () => this.http.post("/users/self/mfa/totp", label ? { label } : {})
638
+ );
639
+ }
640
+ /**
641
+ * `PUT /users/self/mfa/totp/confirm` — activate the method with a live code
642
+ * and receive one-time recovery codes. Replacing a confirmed method also
643
+ * requires `password` or `reauth_code`.
644
+ */
645
+ async confirmTotpEnrollment(payload) {
646
+ if (!payload?.id) throw new ValidationError("id is required");
647
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
648
+ return this.call(
649
+ "Failed to confirm authenticator enrollment",
650
+ () => this.http.put("/users/self/mfa/totp/confirm", payload)
651
+ );
652
+ }
653
+ /** `POST /users/self/mfa/recovery-codes` — issue ten new recovery codes, invalidating the old set. */
654
+ async regenerateRecoveryCodes(payload) {
655
+ return this.call(
656
+ "Failed to regenerate recovery codes",
657
+ () => this.http.post("/users/self/mfa/recovery-codes", requireReauth(payload))
658
+ );
659
+ }
660
+ /**
661
+ * `DELETE /users/self/mfa/{methodId}` — remove a method. Removing the last
662
+ * one also discards the recovery codes.
663
+ */
664
+ async removeMfaMethod(methodId, payload) {
665
+ const id = this.requireId(methodId, "Method ID");
666
+ const data = requireReauth(payload);
667
+ return this.call(
668
+ "Failed to remove two-factor method",
669
+ () => this.http.delete(`/users/self/mfa/${id}`, { data })
670
+ );
671
+ }
602
672
  /** `POST /authentication/social-login` — exchange a provider token for an Assinafy JWT. */
603
673
  async socialLogin(payload) {
604
674
  if (payload.provider !== "google") throw new ValidationError("provider must be google");
@@ -1980,10 +2050,8 @@ var DEFAULT_EVENTS = [
1980
2050
  "signer_rejected_document",
1981
2051
  "document_processing_failed"
1982
2052
  ];
1983
- var WebhookResource = class extends BaseResource {
1984
- /** Register (or replace) the webhook subscription for the workspace. */
1985
- async register(payload, accountId) {
1986
- if (!payload.url) throw new ValidationError("Webhook URL is required");
2053
+ function validateWebhookFields(payload) {
2054
+ if (payload.url !== void 0) {
1987
2055
  let webhookUrl;
1988
2056
  try {
1989
2057
  webhookUrl = new URL(payload.url);
@@ -1993,13 +2061,29 @@ var WebhookResource = class extends BaseResource {
1993
2061
  if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
1994
2062
  throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1995
2063
  }
1996
- requireEmail(payload.email);
1997
- if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
1998
- throw new ValidationError("Webhook events must contain non-empty strings");
1999
- }
2000
- if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
2001
- throw new ValidationError("Webhook is_active must be a boolean");
2064
+ }
2065
+ if (payload.email !== void 0) requireEmail(payload.email);
2066
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
2067
+ throw new ValidationError("Webhook events must contain non-empty strings");
2068
+ }
2069
+ if (payload.name !== void 0 && typeof payload.name !== "string") {
2070
+ throw new ValidationError("Webhook name must be a string");
2071
+ }
2072
+ for (const key of ["is_active", "signing_enabled"]) {
2073
+ if (payload[key] !== void 0 && typeof payload[key] !== "boolean") {
2074
+ throw new ValidationError(`Webhook ${key} must be a boolean`);
2002
2075
  }
2076
+ }
2077
+ }
2078
+ var WebhookResource = class extends BaseResource {
2079
+ /**
2080
+ * `PUT /accounts/{accountId}/webhooks/subscriptions` — create or replace the
2081
+ * account's oldest webhook endpoint. Use the endpoint methods for accounts
2082
+ * with several endpoints or for signed deliveries.
2083
+ */
2084
+ async register(payload, accountId) {
2085
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
2086
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
2003
2087
  const id = this.accountId(accountId);
2004
2088
  const body = {
2005
2089
  url: payload.url,
@@ -2015,7 +2099,7 @@ var WebhookResource = class extends BaseResource {
2015
2099
  () => this.http.put(`/accounts/${id}/webhooks/subscriptions`, body)
2016
2100
  );
2017
2101
  }
2018
- /** Fetch the current webhook subscription. Returns `null` if none exists. */
2102
+ /** Fetch the account's oldest webhook endpoint. Returns `null` if none exists. */
2019
2103
  async get(accountId) {
2020
2104
  const id = this.accountId(accountId);
2021
2105
  return this.callOptional(
@@ -2023,7 +2107,7 @@ var WebhookResource = class extends BaseResource {
2023
2107
  () => this.http.get(`/accounts/${id}/webhooks/subscriptions`)
2024
2108
  );
2025
2109
  }
2026
- /** Inactivate the current webhook subscription without deleting it. */
2110
+ /** Inactivate the account's oldest webhook endpoint without deleting it. */
2027
2111
  async inactivate(accountId) {
2028
2112
  const id = this.accountId(accountId);
2029
2113
  this.logger.info("Inactivating webhook subscription");
@@ -2032,6 +2116,91 @@ var WebhookResource = class extends BaseResource {
2032
2116
  () => this.http.put(`/accounts/${id}/webhooks/inactivate`)
2033
2117
  );
2034
2118
  }
2119
+ /** `GET /accounts/{accountId}/webhooks/endpoints` — list webhook endpoints, oldest first. */
2120
+ async listEndpoints(accountId) {
2121
+ const id = this.accountId(accountId);
2122
+ return this.call(
2123
+ "Failed to list webhook endpoints",
2124
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints`)
2125
+ );
2126
+ }
2127
+ /**
2128
+ * `POST /accounts/{accountId}/webhooks/endpoints` — register another
2129
+ * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past
2130
+ * the limit); URLs must be unique per workspace. Omitted `events` uses the
2131
+ * same default set as {@link register}.
2132
+ */
2133
+ async createEndpoint(payload, accountId) {
2134
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
2135
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
2136
+ const id = this.accountId(accountId);
2137
+ const body = { ...payload, events: payload.events ?? DEFAULT_EVENTS };
2138
+ this.logger.info("Creating webhook endpoint", { eventCount: body.events.length });
2139
+ return this.call(
2140
+ "Failed to create webhook endpoint",
2141
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints`, body)
2142
+ );
2143
+ }
2144
+ /** `GET /accounts/{accountId}/webhooks/endpoints/{endpointId}` — fetch one endpoint. */
2145
+ async getEndpoint(endpointId, accountId) {
2146
+ const id = this.accountId(accountId);
2147
+ const eid = this.requireId(endpointId, "Endpoint ID");
2148
+ return this.call(
2149
+ "Failed to fetch webhook endpoint",
2150
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}`)
2151
+ );
2152
+ }
2153
+ /**
2154
+ * `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` — update only
2155
+ * the fields sent. Enabling signing creates a secret when none exists;
2156
+ * disabling it discards the secret.
2157
+ */
2158
+ async updateEndpoint(endpointId, payload, accountId) {
2159
+ const id = this.accountId(accountId);
2160
+ const eid = this.requireId(endpointId, "Endpoint ID");
2161
+ if (!payload || typeof payload !== "object" || Object.keys(payload).length === 0) {
2162
+ throw new ValidationError("At least one webhook endpoint field is required");
2163
+ }
2164
+ validateWebhookFields(payload);
2165
+ return this.call(
2166
+ "Failed to update webhook endpoint",
2167
+ () => this.http.put(`/accounts/${id}/webhooks/endpoints/${eid}`, payload)
2168
+ );
2169
+ }
2170
+ /** `DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}` — delete an endpoint and free its slot. */
2171
+ async deleteEndpoint(endpointId, accountId) {
2172
+ const id = this.accountId(accountId);
2173
+ const eid = this.requireId(endpointId, "Endpoint ID");
2174
+ return this.call(
2175
+ "Failed to delete webhook endpoint",
2176
+ () => this.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`)
2177
+ );
2178
+ }
2179
+ /**
2180
+ * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.
2181
+ * Returns `400` when signing is disabled. Not available to OAuth applications.
2182
+ */
2183
+ async getEndpointSecret(endpointId, accountId) {
2184
+ const id = this.accountId(accountId);
2185
+ const eid = this.requireId(endpointId, "Endpoint ID");
2186
+ return this.call(
2187
+ "Failed to fetch webhook endpoint secret",
2188
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}/secret`)
2189
+ );
2190
+ }
2191
+ /**
2192
+ * `POST …/endpoints/{endpointId}/secret/rotate` — replace the signing secret.
2193
+ * The old secret stops working immediately. Not available to OAuth applications.
2194
+ */
2195
+ async rotateEndpointSecret(endpointId, accountId) {
2196
+ const id = this.accountId(accountId);
2197
+ const eid = this.requireId(endpointId, "Endpoint ID");
2198
+ this.logger.info("Rotating webhook endpoint secret");
2199
+ return this.call(
2200
+ "Failed to rotate webhook endpoint secret",
2201
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints/${eid}/secret/rotate`)
2202
+ );
2203
+ }
2035
2204
  /** List currently supported webhook event types. */
2036
2205
  async listEventTypes() {
2037
2206
  return this.call(
@@ -2039,7 +2208,7 @@ var WebhookResource = class extends BaseResource {
2039
2208
  () => this.http.get("/webhooks/event-types")
2040
2209
  );
2041
2210
  }
2042
- /** List webhook delivery history for the workspace. */
2211
+ /** List webhook delivery history for the workspace, optionally for one endpoint. */
2043
2212
  async listDispatches(params = {}, accountId) {
2044
2213
  const id = this.accountId(accountId);
2045
2214
  if ("search" in params) throw new ValidationError("webhook dispatch search is not supported");
@@ -2051,7 +2220,7 @@ var WebhookResource = class extends BaseResource {
2051
2220
  })
2052
2221
  );
2053
2222
  }
2054
- /** Retry delivery of a specific webhook dispatch. */
2223
+ /** Retry delivery of a specific webhook dispatch to that entry's endpoint. */
2055
2224
  async retryDispatch(dispatchId, accountId) {
2056
2225
  const id = this.accountId(accountId);
2057
2226
  const did = this.requireId(dispatchId, "Dispatch ID");
@@ -2160,6 +2329,17 @@ function validateNotificationSender(value) {
2160
2329
 
2161
2330
  // src/api/support/webhook-verifier.ts
2162
2331
  var import_node_crypto2 = require("crypto");
2332
+ function readHeader(headers, name) {
2333
+ if (typeof headers.get === "function") {
2334
+ return headers.get(name) ?? void 0;
2335
+ }
2336
+ for (const [key, value] of Object.entries(headers)) {
2337
+ if (key.toLowerCase() !== name) continue;
2338
+ if (Array.isArray(value)) return value.length === 1 ? value[0] : void 0;
2339
+ return value;
2340
+ }
2341
+ return void 0;
2342
+ }
2163
2343
  var WebhookVerifier = class {
2164
2344
  constructor(webhookSecret, options = {}) {
2165
2345
  this.webhookSecret = webhookSecret;
@@ -2169,15 +2349,48 @@ var WebhookVerifier = class {
2169
2349
  webhookSecret;
2170
2350
  algorithm;
2171
2351
  encoding;
2172
- /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
2352
+ /**
2353
+ * Returns `true` when `headers` carry a Standard Webhooks signature that
2354
+ * matches the raw `payload` under this verifier's `whsec_` secret and the
2355
+ * `webhook-timestamp` is within the tolerance window. Pass the body exactly
2356
+ * as received; re-serialized JSON does not verify.
2357
+ */
2358
+ verifyDelivery(payload, headers, options = {}) {
2359
+ if (!this.webhookSecret || !headers) return false;
2360
+ const id = readHeader(headers, "webhook-id");
2361
+ const timestamp = readHeader(headers, "webhook-timestamp");
2362
+ const signatures = readHeader(headers, "webhook-signature");
2363
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
2364
+ const tolerance = options.toleranceSeconds ?? 300;
2365
+ const now = Math.floor((options.now ?? Date.now()) / 1e3);
2366
+ if (Math.abs(now - Number(timestamp)) > tolerance) return false;
2367
+ const secret = this.webhookSecret.startsWith("whsec_") ? this.webhookSecret.slice("whsec_".length) : this.webhookSecret;
2368
+ const key = Buffer.from(secret, "base64");
2369
+ if (key.length === 0) return false;
2370
+ const expected = Buffer.from(
2371
+ (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`).update(typeof payload === "string" ? Buffer.from(payload, "utf8") : payload).digest("base64")
2372
+ );
2373
+ return signatures.split(" ").some((entry) => {
2374
+ const [version, value] = entry.split(",", 2);
2375
+ if (version !== "v1" || !value) return false;
2376
+ const provided = Buffer.from(value);
2377
+ return provided.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(provided, expected);
2378
+ });
2379
+ }
2380
+ /**
2381
+ * Returns `true` if `signature` is an HMAC of `payload` keyed with the raw
2382
+ * secret string under the configured algorithm/encoding.
2383
+ *
2384
+ * @deprecated Assinafy signs deliveries with Standard Webhooks headers; use
2385
+ * {@link verifyDelivery}. Retained for existing callers.
2386
+ */
2173
2387
  verify(payload, signature) {
2174
2388
  if (!this.webhookSecret || !signature) return false;
2175
2389
  try {
2176
2390
  const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
2177
2391
  const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
2178
- const provided = signature.trim();
2179
2392
  const a = Buffer.from(expected, "utf8");
2180
- const b = Buffer.from(provided, "utf8");
2393
+ const b = Buffer.from(signature.trim(), "utf8");
2181
2394
  if (a.length !== b.length) return false;
2182
2395
  return (0, import_node_crypto2.timingSafeEqual)(a, b);
2183
2396
  } catch {