@assinafy/cli 2.4.2 → 2.5.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.
Files changed (37) hide show
  1. package/.env.example +4 -2
  2. package/README.en.md +46 -21
  3. package/README.md +34 -15
  4. package/dist/api.cjs +295 -55
  5. package/dist/api.cjs.map +1 -1
  6. package/dist/api.js +295 -55
  7. package/dist/api.js.map +1 -1
  8. package/dist/cli.cjs +635 -100
  9. package/dist/types/api/errors.d.ts +9 -0
  10. package/dist/types/api/errors.d.ts.map +1 -1
  11. package/dist/types/api/index.d.ts +1 -1
  12. package/dist/types/api/index.d.ts.map +1 -1
  13. package/dist/types/api/resources/authentication.d.ts +33 -3
  14. package/dist/types/api/resources/authentication.d.ts.map +1 -1
  15. package/dist/types/api/resources/documents.d.ts +4 -3
  16. package/dist/types/api/resources/documents.d.ts.map +1 -1
  17. package/dist/types/api/resources/oauth.d.ts +1 -1
  18. package/dist/types/api/resources/oauth.d.ts.map +1 -1
  19. package/dist/types/api/resources/signer-documents.d.ts +9 -4
  20. package/dist/types/api/resources/signer-documents.d.ts.map +1 -1
  21. package/dist/types/api/resources/webhooks.d.ts +39 -6
  22. package/dist/types/api/resources/webhooks.d.ts.map +1 -1
  23. package/dist/types/api/support/webhook-verifier.d.ts +31 -14
  24. package/dist/types/api/support/webhook-verifier.d.ts.map +1 -1
  25. package/dist/types/api/types.d.ts +110 -21
  26. package/dist/types/api/types.d.ts.map +1 -1
  27. package/dist/types/api/utils.d.ts.map +1 -1
  28. package/docs/README.md +1 -1
  29. package/docs/api-operations.json +105 -1
  30. package/docs/api-reference.md +2380 -2057
  31. package/docs/auth.md +125 -4
  32. package/docs/documents.md +5 -6
  33. package/docs/migration-v2.md +1 -1
  34. package/docs/sdk-reference.md +84 -23
  35. package/docs/signer.md +4 -2
  36. package/docs/webhooks.md +185 -20
  37. package/package.json +2 -2
package/docs/auth.md CHANGED
@@ -11,8 +11,9 @@ Options:
11
11
  -h, --help display help for command
12
12
 
13
13
  Commands:
14
- login [options] <email> Exchange email + password for a JWT access
15
- token (no existing credentials required)
14
+ login [options] <email> Exchange email + password (and a two-factor
15
+ code when enabled) for a JWT access token (no
16
+ existing credentials required)
16
17
  social-login [options] Exchange a provider token for an Assinafy JWT
17
18
  (no existing credentials required)
18
19
  link-social-login [options] Link a Google identity to the authenticated
@@ -23,6 +24,8 @@ Commands:
23
24
  reset-password [options] Complete a password reset with the emailed
24
25
  token (no existing credentials required)
25
26
  api-keys Manage the current user personal API key
27
+ mfa Two-factor authentication: login verification,
28
+ enrollment, and recovery codes
26
29
  help [command] display help for command
27
30
  ```
28
31
 
@@ -31,14 +34,16 @@ Commands:
31
34
  ```text
32
35
  Usage: assinafy auth login [options] <email>
33
36
 
34
- Exchange email + password for a JWT access token (no existing credentials
35
- required)
37
+ Exchange email + password (and a two-factor code when enabled) for a JWT access
38
+ token (no existing credentials required)
36
39
 
37
40
  Arguments:
38
41
  email Account email
39
42
 
40
43
  Options:
41
44
  --password <password> Password (prompted if omitted) (env: ASSINAFY_PASSWORD)
45
+ --mfa-code <code> Authenticator or recovery code (prompted if required
46
+ and omitted) (env: ASSINAFY_MFA_CODE)
42
47
  -h, --help display help for command
43
48
  ```
44
49
 
@@ -167,3 +172,119 @@ Options:
167
172
  -y, --yes Skip the confirmation prompt
168
173
  -h, --help display help for command
169
174
  ```
175
+
176
+ ### `assinafy auth mfa`
177
+
178
+ ```text
179
+ Usage: assinafy auth mfa [options] [command]
180
+
181
+ Two-factor authentication: login verification, enrollment, and recovery codes
182
+
183
+ Options:
184
+ -h, --help display help for command
185
+
186
+ Commands:
187
+ verify [options] Complete a two-factor login with the mfa_token
188
+ from login (no existing credentials required)
189
+ list|ls List enrolled two-factor methods and remaining
190
+ recovery codes
191
+ enroll [options] Start authenticator enrollment; prints the
192
+ one-time secret and provisioning URI
193
+ confirm [options] <methodId> Activate an enrolled authenticator and print
194
+ the one-time recovery codes
195
+ recovery-codes [options] Issue ten new recovery codes and invalidate
196
+ the previous set
197
+ remove|rm [options] <methodId> Remove a two-factor method (the last one also
198
+ discards recovery codes)
199
+ help [command] display help for command
200
+ ```
201
+
202
+ #### `assinafy auth mfa verify`
203
+
204
+ ```text
205
+ Usage: assinafy auth mfa verify [options]
206
+
207
+ Complete a two-factor login with the mfa_token from login (no existing
208
+ credentials required)
209
+
210
+ Options:
211
+ --mfa-token <token> Challenge token returned by login (env:
212
+ ASSINAFY_MFA_TOKEN)
213
+ --mfa-code <code> Authenticator or recovery code (prompted if required and
214
+ omitted) (env: ASSINAFY_MFA_CODE)
215
+ -h, --help display help for command
216
+ ```
217
+
218
+ #### `assinafy auth mfa list`
219
+
220
+ ```text
221
+ Usage: assinafy auth mfa list|ls [options]
222
+
223
+ List enrolled two-factor methods and remaining recovery codes
224
+
225
+ Options:
226
+ -h, --help display help for command
227
+ ```
228
+
229
+ #### `assinafy auth mfa enroll`
230
+
231
+ ```text
232
+ Usage: assinafy auth mfa enroll [options]
233
+
234
+ Start authenticator enrollment; prints the one-time secret and provisioning URI
235
+
236
+ Options:
237
+ --label <label> Name for the authenticator
238
+ -h, --help display help for command
239
+ ```
240
+
241
+ #### `assinafy auth mfa confirm`
242
+
243
+ ```text
244
+ Usage: assinafy auth mfa confirm [options] <methodId>
245
+
246
+ Activate an enrolled authenticator and print the one-time recovery codes
247
+
248
+ Arguments:
249
+ methodId Method ID returned by enroll
250
+
251
+ Options:
252
+ --code <code> Live code from the new authenticator
253
+ --password <password> Current password (only when replacing a confirmed
254
+ method) (env: ASSINAFY_PASSWORD)
255
+ --reauth-code <code> Code from the current authenticator or a recovery code
256
+ (only when replacing)
257
+ -h, --help display help for command
258
+ ```
259
+
260
+ #### `assinafy auth mfa recovery-codes`
261
+
262
+ ```text
263
+ Usage: assinafy auth mfa recovery-codes [options]
264
+
265
+ Issue ten new recovery codes and invalidate the previous set
266
+
267
+ Options:
268
+ --password <password> Current password (env: ASSINAFY_PASSWORD)
269
+ --mfa-code <code> Authenticator or recovery code (prompted if required
270
+ and omitted) (env: ASSINAFY_MFA_CODE)
271
+ -h, --help display help for command
272
+ ```
273
+
274
+ #### `assinafy auth mfa remove`
275
+
276
+ ```text
277
+ Usage: assinafy auth mfa remove|rm [options] <methodId>
278
+
279
+ Remove a two-factor method (the last one also discards recovery codes)
280
+
281
+ Arguments:
282
+ methodId Method ID
283
+
284
+ Options:
285
+ --password <password> Current password (env: ASSINAFY_PASSWORD)
286
+ --mfa-code <code> Authenticator or recovery code (prompted if required
287
+ and omitted) (env: ASSINAFY_MFA_CODE)
288
+ -y, --yes Skip the confirmation prompt
289
+ -h, --help display help for command
290
+ ```
package/docs/documents.md CHANGED
@@ -30,7 +30,7 @@ Commands:
30
30
  verify <hash> Verify a document by its signature hash
31
31
  statuses List every possible document status
32
32
  public <id> Public (unauthenticated) lookup of basic document info
33
- send-token [options] <id> Send a 6-digit verification token to a signer
33
+ send-token [options] <id> Email a one-time access token to a signer of a pending document
34
34
  progress <id> Show signing progress for a document
35
35
  wait [options] <id> Poll a document until it is ready (or fails / times out)
36
36
  help [command] display help for command
@@ -339,16 +339,15 @@ Options:
339
339
  ```text
340
340
  Usage: assinafy documents send-token [options] <id>
341
341
 
342
- Send a 6-digit verification token to a signer
342
+ Email a one-time access token to a signer of a pending document
343
343
 
344
344
  Arguments:
345
345
  id Document ID
346
346
 
347
347
  Options:
348
- --email <email> Email address (compatibility overload for older
349
- deployments)
350
- --recipient <value> Email address or phone number (production payload)
351
- --channel <channel> email or whatsapp (default: "email")
348
+ --recipient <email> Email of a signer who has not signed yet
349
+ --email <email> Alias of --recipient
350
+ --channel <channel> Delivery channel (choices: "email", default: "email")
352
351
  -h, --help display help for command
353
352
  ```
354
353
 
@@ -21,5 +21,5 @@ Version 2 publishes the Node.js SDK at `@assinafy/cli/api` and requires Node.js
21
21
  access code adds an identity preflight before downloading.
22
22
 
23
23
  Legacy signer aliases (`phone`, `cpf`, and assignment `signer_ids`/`signerIds`),
24
- both public `sendToken` request forms, and existing CLI functionality remain
24
+ both `sendToken` call forms (each sends the email-only production body), and existing CLI functionality remain
25
25
  available. See the [SDK reference](./sdk-reference.md) for exact method signatures.
@@ -1,6 +1,6 @@
1
1
  # TypeScript SDK reference
2
2
 
3
- The Node.js SDK is published with the CLI and requires Node.js `>=22.12.0` (Node.js 24 LTS is recommended). Responses containing Assinafy's `{ status, message, data }` envelope resolve to `data`; operations with empty result data resolve to `IEmptyResult` (`unknown[]`). Responses without `data` remain unchanged, including direct `IStatusResponse` (`{ status, message }`) bodies. `sendToken` preserves either that published body or the production `{ document, channel, recipient }` body.
3
+ The Node.js SDK is published with the CLI and requires Node.js `>=22.12.0` (Node.js 24 LTS is recommended). Responses containing Assinafy's `{ status, message, data }` envelope resolve to `data`; operations with empty result data resolve to `IEmptyResult` (`unknown[]`). Responses without `data` remain unchanged, including direct `IStatusResponse` (`{ status, message }`) bodies. `sendToken` resolves to `{ document, channel, recipient }`.
4
4
 
5
5
  The [API request/response reference](./api-reference.md) is the canonical source for every published HTTP payload and example. Complete TypeScript declarations are exported and packaged with `@assinafy/cli/api`.
6
6
 
@@ -52,7 +52,7 @@ const publicClient = new AssinafyClient({ allowUnauthenticated: true });
52
52
  | `timeout` | `number` | Request timeout in milliseconds; default `30_000`. |
53
53
  | `logger` | `Logger` | Optional `debug`/`info`/`warn`/`error` functions; otherwise no-op. |
54
54
  | `allowUnauthenticated` | `boolean` | Permit construction without `apiKey`/`token`; use only for public, OAuth bootstrap, and signer-code flows. |
55
- | `webhookSecret` | `string` | Used only by the experimental `webhookVerifier`; see [Webhook verification](#webhook-verification-experimental). |
55
+ | `webhookSecret` | `string` | Endpoint `whsec_` signing secret used by `client.webhookVerifier`; see [Webhook verification](#webhook-verification). |
56
56
 
57
57
  | API | Result |
58
58
  | --- | --- |
@@ -131,7 +131,7 @@ try {
131
131
  | `verify(hash)` | [`GET /documents/{signatureHash}/verify`](./api-reference.md#verify-a-signed-document) | `IDocumentVerifyResponse` |
132
132
  | `statuses()` | [`GET /documents/statuses`](./api-reference.md#list-document-statuses) | `IDocumentStatusInfo[]` |
133
133
  | `getPublic(documentId)` | [`GET /public/documents/{documentId}`](./api-reference.md#view-public-document) | `IPublicDocumentInfo` |
134
- | `sendToken(documentId, { email })` or `sendToken(documentId, recipient, channel?)` | [`PUT /public/documents/{documentId}/send-token`](./api-reference.md#send-access-token-for-public-document) | `ISendTokenResponse` (`{ status; message }` or `{ document; channel; recipient }`) |
134
+ | `sendToken(documentId, email, channel?)` or `sendToken(documentId, { email })` | [`PUT /public/documents/{documentId}/send-token`](./api-reference.md#send-access-token-for-public-document) | `ISendTokenResponse` (`{ document; channel; recipient }`) |
135
135
  | `isFullySigned(documentId)` | SDK helper over `details` | `boolean` |
136
136
  | `getSigningProgress(documentId)` | SDK helper over `details` | `{ signed; total; pending; percentage }` |
137
137
 
@@ -149,7 +149,7 @@ interface IDocumentUploadOptions {
149
149
  }
150
150
  ```
151
151
 
152
- Uploads must be non-empty PDFs up to 25 MiB. `DocumentArtifactName` is `original | certificated | certificate-page | pades | bundle`; `bundle` is ZIP and the other document artifacts are PDF. For production email delivery, use `sendToken(documentId, 'signer@example.com', 'email')`, which sends `{ recipient, channel }`. The `{ email }` overload preserves the published request form for deployments that support it.
152
+ Uploads must be non-empty PDFs up to 25 MiB. `DocumentArtifactName` is `original | certificated | certificate-page | pades | bundle`; `bundle` is ZIP and the other document artifacts are PDF. `sendToken(documentId, 'signer@example.com')` emails a one-time access token to a signer who has not signed a pending document yet and sends `{ "channel": "email", "recipient": "signer@example.com" }`. Only the `email` channel is accepted; any other channel is rejected locally. The `{ email }` overload sends the same body.
153
153
 
154
154
  Template document creation sends `{ signers, name?, message?, expires_at?, editor_fields?, tags? }`. Each signer is `{ role_id, id, verification_method?, notification_methods?, step? }`; each editor field is `{ field_id, value: string }`. Template cost estimation publishes `{ signers: Array<{ role_id, verification_method?, notification_methods? }> }`. The optional cost-signer `id` and `step` properties remain compatibility extensions for existing integrations.
155
155
 
@@ -224,13 +224,13 @@ Create payload: `{ full_name: string; email?; whatsapp_phone_number?; phone?; cp
224
224
 
225
225
  ## Signer-side flows (`client.signerDocuments`)
226
226
 
227
- These methods use the private `signer-access-code`, not the workspace API key, except for the artifact download that the API publishes as a public route. For email or WhatsApp verification, obtain the access code from the verification link and the OTP from the same message. An invitation containing only a document ID and recipient is not an access code. Call `self` and `getAssignment` to confirm the signer and document before submitting a decision; keep each document's verification credentials together.
227
+ These methods use the private `signer-access-code`, not the workspace API key, except for the artifact download that the API publishes as a public route. `list` and `search` also accept the client's API key or bearer token when the access code is omitted; the signer must belong to that workspace. For email or WhatsApp verification, obtain the access code from the verification link and the OTP from the same message. An invitation containing only a document ID and recipient is not an access code. Call `self` and `getAssignment` to confirm the signer and document before submitting a decision; keep each document's verification credentials together.
228
228
 
229
229
  | SDK method | HTTP operation | Resolves to |
230
230
  | --- | --- | --- |
231
231
  | `getCurrent(signerId, accessCode)` | [`GET /signers/{signerId}/document`](./api-reference.md#get-signers-document) | `IDocumentDetailsResponse` |
232
- | `list(signerId, accessCode, params?)` | [`GET /signers/{signerId}/documents`](./api-reference.md#list-signers-documents) | `IDocumentListResponse` |
233
- | `search(signerId, search, accessCode)` | [`GET /signers/{signerId}/documents/search`](./api-reference.md#search-signers-documents) | `IDocumentListResponse` |
232
+ | `list(signerId, accessCode?, params?)` | [`GET /signers/{signerId}/documents`](./api-reference.md#list-signers-documents) | `IDocumentListResponse` |
233
+ | `search(signerId, search, accessCode?)` | [`GET /signers/{signerId}/documents/search`](./api-reference.md#search-signers-documents) | `IDocumentListResponse` |
234
234
  | `download(signerId, documentId, artifact, accessCode?)` | [`GET /signers/{signerId}/documents/{documentId}/download/{artifact}`](./api-reference.md#download-signers-document-artifact) | `Buffer` |
235
235
  | `signMultiple(documentIds, accessCode)` | [`PUT /signers/documents/sign-multiple`](./api-reference.md#sign-multiple-documents) | `unknown[]` |
236
236
  | `declineMultiple(documentIds, reason, accessCode)` | [`PUT /signers/documents/decline-multiple`](./api-reference.md#decline-multiple-documents) | `unknown[]` |
@@ -279,9 +279,8 @@ Choose one notification channel. With neither field specified, the API defaults
279
279
  `IVerifySignerCodePayload` is `{ signerAccessCode: string; verificationCode: string }`. Keep the OTP as a string to preserve leading zeroes. Email and WhatsApp use the same verification endpoint and response; the access code identifies the channel and document.
280
280
 
281
281
  ```ts
282
- // Choose the channel configured for this signer; these calls send messages.
283
- await client.documents.sendToken('example_document', 'signer@example.com', 'email');
284
- await client.documents.sendToken('example_document', '+5500000000000', 'whatsapp');
282
+ // Optional: email a new one-time access token (email channel only; sends a message).
283
+ await client.documents.sendToken('example_document', 'signer@example.com');
285
284
 
286
285
  // Use the private link and OTP from the selected channel's same message.
287
286
  await client.signerDocuments.verifyCode({
@@ -290,7 +289,7 @@ await client.signerDocuments.verifyCode({
290
289
  }); // [] on production success
291
290
  ```
292
291
 
293
- The delivery request bodies are `{ "recipient": "signer@example.com", "channel": "email" }` and `{ "recipient": "+5500000000000", "channel": "whatsapp" }`. `sendToken` preserves the response forms documented in [Documents](#documents-clientdocuments). Verification sends `{ "verification-code": "012345" }` with `?signer-access-code=example_access_code`; a successful envelope `{ "status": 200, "message": "", "data": [] }` resolves to `[]`. Invalid codes surface as `ApiError` with the server's status and message. `verifyEmail` remains a compatible alias. Continue with data confirmation and virtual/collect signing as described above.
292
+ The token request body is `{ "channel": "email", "recipient": "signer@example.com" }` and the response data is `{ "document": { "resource": "document", "id": "example_document", "name": "Contract.pdf", "page_count": 3, "created_by": "Example User" }, "channel": "email", "recipient": "signer@example.com" }`. WhatsApp-verified signers receive their code in the WhatsApp invitation itself. Verification sends `{ "verification-code": "012345" }` with `?signer-access-code=example_access_code`; a successful envelope `{ "status": 200, "message": "", "data": [] }` resolves to `[]`. Invalid codes surface as `ApiError` with the server's status and message. `verifyEmail` remains a compatible alias. Continue with data confirmation and virtual/collect signing as described above.
294
293
 
295
294
  ### ICP-Brasil A1/A3 certificates
296
295
 
@@ -412,8 +411,27 @@ Notification counters can overlap when a request uses multiple delivery channels
412
411
  | `createApiKey(password)` | [`POST /users/api-keys`](./api-reference.md#create-api-key) | `IApiKeyResponse` |
413
412
  | `getApiKey()` | [`GET /users/api-keys`](./api-reference.md#get-api-key) | `IMaskedApiKeyResponse`; 404 means no key |
414
413
  | `deleteApiKey()` | [`DELETE /users/api-keys`](./api-reference.md#delete-api-key) | `IEmptyResult` (`unknown[]`) |
414
+ | `verifyMfa({ mfa_token, code })` | [`POST /authentication/mfa/verify`](./api-reference.md#complete-a-two-factor-login) | `IMfaVerifyPayload` → `ILoginResponse` |
415
+ | `listMfaMethods()` | [`GET /users/self/mfa`](./api-reference.md#list-two-factor-methods) | `IMfaStatus` (`{ methods, recovery_codes_remaining }`) |
416
+ | `startTotpEnrollment(label?)` | [`POST /users/self/mfa/totp`](./api-reference.md#start-authenticator-enrollment) | `{ label? }` → `ITotpEnrollment` (`{ id, secret, provisioning_uri }`) |
417
+ | `confirmTotpEnrollment({ id, code, password?, reauth_code? })` | [`PUT /users/self/mfa/totp/confirm`](./api-reference.md#confirm-authenticator-enrollment) | `ITotpConfirmPayload` → `IMfaRecoveryCodes` |
418
+ | `regenerateRecoveryCodes({ password?, code? })` | [`POST /users/self/mfa/recovery-codes`](./api-reference.md#regenerate-recovery-codes) | `IMfaReauthPayload` → `IMfaRecoveryCodes` |
419
+ | `removeMfaMethod(methodId, { password?, code? })` | [`DELETE /users/self/mfa/{methodId}`](./api-reference.md#remove-a-two-factor-method) | JSON body `IMfaReauthPayload` → `{ is_mfa_enabled }` |
415
420
 
416
- Login/social/reset bootstrap calls can use an unauthenticated client. The published authenticated user endpoints permit either a bearer JWT or `X-Api-Key`; use the credential type appropriate to the account and endpoint policy.
421
+ ### Two-factor authentication
422
+
423
+ When the user has a confirmed authenticator, `login` returns an `mfa_token` challenge instead of a session. Exchange it within 5 minutes, once, with a 6-digit authenticator code or a recovery code:
424
+
425
+ ```ts
426
+ let session = await client.auth.login('user@example.com', password);
427
+ if (!session.access_token && session.mfa_token) {
428
+ session = await client.auth.verifyMfa({ mfa_token: session.mfa_token, code: '123456' });
429
+ }
430
+ ```
431
+
432
+ Enrollment is `startTotpEnrollment` (show `provisioning_uri` as a QR code; the secret is returned only once) followed by `confirmTotpEnrollment({ id, code })`, which returns ten one-time recovery codes. Replacing a confirmed method also needs `password` or `reauth_code`. `regenerateRecoveryCodes` and `removeMfaMethod` require the current password or a live/recovery `code`; the SDK rejects a payload with neither before sending. `verifyMfa` strips owner credentials.
433
+
434
+ Login/social/reset/two-factor-verify bootstrap calls can use an unauthenticated client. The published authenticated user endpoints permit either a bearer JWT or `X-Api-Key`; use the credential type appropriate to the account and endpoint policy.
417
435
 
418
436
  ## OAuth (`client.oauth`)
419
437
 
@@ -504,16 +522,39 @@ Template list params support pagination, published `search`, and compatible `sor
504
522
 
505
523
  ## Webhooks (`client.webhooks`)
506
524
 
525
+ An account can register 1 webhook endpoint, or up to 3 on paid plans. Each endpoint has its own URL, events, active flag, and signing setting; every active endpoint subscribed to an event receives it independently. The `subscriptions` operations remain and act on the account's oldest endpoint.
526
+
507
527
  | SDK method | HTTP operation | Resolves to |
508
528
  | --- | --- | --- |
509
- | `register(payload, accountId?)` | [`PUT /accounts/{accountId}/webhooks/subscriptions`](./api-reference.md#update-webhook-subscription) | `IWebhookSubscription` |
529
+ | `listEndpoints(accountId?)` | [`GET /accounts/{accountId}/webhooks/endpoints`](./api-reference.md#list-webhook-endpoints) | `IWebhookEndpoint[]`, oldest first |
530
+ | `createEndpoint(payload, accountId?)` | [`POST /accounts/{accountId}/webhooks/endpoints`](./api-reference.md#create-webhook-endpoint) | `IWebhookEndpointCreatePayload` → `IWebhookEndpoint` |
531
+ | `getEndpoint(endpointId, accountId?)` | [`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}`](./api-reference.md#get-webhook-endpoint) | `IWebhookEndpoint` |
532
+ | `updateEndpoint(endpointId, payload, accountId?)` | [`PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}`](./api-reference.md#update-webhook-endpoint) | `IWebhookEndpointUpdatePayload` → `IWebhookEndpoint` |
533
+ | `deleteEndpoint(endpointId, accountId?)` | [`DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}`](./api-reference.md#delete-webhook-endpoint) | `IEmptyResult` (`[]`) |
534
+ | `getEndpointSecret(endpointId, accountId?)` | [`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret`](./api-reference.md#get-webhook-endpoint-signing-secret) | `IWebhookEndpointSecret` (`{ secret }`) |
535
+ | `rotateEndpointSecret(endpointId, accountId?)` | [`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`](./api-reference.md#rotate-webhook-endpoint-signing-secret) | `IWebhookEndpointSecret` |
536
+ | `register(payload, accountId?)` | [`PUT /accounts/{accountId}/webhooks/subscriptions`](./api-reference.md#update-webhook-subscription) | `IWebhookSubscription` (oldest endpoint) |
510
537
  | `get(accountId?)` | [`GET /accounts/{accountId}/webhooks/subscriptions`](./api-reference.md#get-webhook-subscription) | `IWebhookSubscription | null` |
511
538
  | `inactivate(accountId?)` | [`PUT /accounts/{accountId}/webhooks/inactivate`](./api-reference.md#inactivate-webhook-subscription) | `IWebhookSubscription` |
512
539
  | `listEventTypes()` | [`GET /webhooks/event-types`](./api-reference.md#list-webhook-event-types) | `IWebhookEventTypeInfo[]` |
513
540
  | `listDispatches(params?, accountId?)` | [`GET /accounts/{accountId}/webhooks`](./api-reference.md#list-webhook-deliveries) | `PaginatedResult<IWebhookDispatch>` |
514
541
  | `retryDispatch(dispatchId, accountId?)` | [`POST /accounts/{accountId}/webhooks/{dispatchId}/retry`](./api-reference.md#retry-webhook-delivery) | `IWebhookDispatch` |
515
542
 
516
- Registration payload: `{ url: string; email: string; events?: string[]; is_active?: boolean }`. When `events` is omitted the SDK uses `document_ready`, `document_prepared`, `signer_signed_document`, `signer_rejected_document`, and `document_processing_failed`; pass `[]` deliberately for none. Dispatch filters extend pagination with `{ event?, delivered?, from?, to?, sort?: 'created_at' | '-created_at' }`; sort is a compatibility extension. Dispatch `search` is unsupported and rejected locally. The API does not expose a delete-subscription operation; use `inactivate`.
543
+ Endpoint payload: `{ url: string; email: string; events?: string[]; name?: string; is_active?: boolean; signing_enabled?: boolean }`. Update sends only the given fields and requires at least one. URLs must be HTTP(S) and unique within the workspace (`400`); creating past the plan limit returns `403`. Enabling signing creates a `whsec_` secret if none exists; disabling it discards the secret. Secret read and rotation return `400` when signing is disabled and are not available to OAuth applications; rotation invalidates the previous secret immediately.
544
+
545
+ ```ts
546
+ const endpoint = await client.webhooks.createEndpoint({
547
+ url: 'https://example.com/assinafy/webhooks',
548
+ email: 'ops@example.com',
549
+ name: 'ERP',
550
+ events: ['document_ready', 'signer_signed_document'],
551
+ signing_enabled: true,
552
+ });
553
+ const { secret } = await client.webhooks.getEndpointSecret(endpoint.id);
554
+ // Store `secret` in your receiver's secret manager.
555
+ ```
556
+
557
+ Registration payload: `{ url: string; email: string; events?: string[]; is_active?: boolean }`. When `events` is omitted on `register` or `createEndpoint`, the SDK uses `document_ready`, `document_prepared`, `signer_signed_document`, `signer_rejected_document`, and `document_processing_failed`; pass `[]` deliberately for none. Dispatch filters extend pagination with `{ endpoint_id?, event?, delivered?, from?, to?, sort?: 'created_at' | '-created_at' }`; sort is a compatibility extension. Dispatch records include `endpoint_id`. Dispatch `search` is unsupported and rejected locally. Retrying re-sends only to that entry's endpoint and requires the endpoint to be active. There is no delete-subscription operation; delete a specific endpoint with `deleteEndpoint` or deactivate the oldest with `inactivate`.
517
558
 
518
559
  Decline operations require a non-empty reason of at most 2,000 Unicode characters. `signers.findByEmail` follows pagination metadata until an exact case-insensitive email match is found or the search is exhausted; when a response carries no pagination metadata a partial page ends the search, and the scan is bounded at 100 pages.
519
560
 
@@ -521,10 +562,10 @@ Decline operations require a non-empty reason of at most 2,000 Unicode character
521
562
 
522
563
  - JSON responses with `data` are unwrapped from the API envelope; direct status bodies remain `IStatusResponse`. Paginated calls resolve to `{ data: T[]; meta?: { current_page?, last_page?, per_page?, total? } }`; metadata comes from `X-Pagination-*` headers.
523
564
  - Binary methods resolve to Node.js `Buffer`; the SDK is not a browser package. It never writes downloaded data to disk.
524
- - `ValidationError` means local input validation failed before a request. `ApiError` exposes `statusCode`, `responseData`, `wwwAuthenticate` and `retryAfter`; binary JSON error bodies are decoded before normalization. OAuth responses are flat JSON, and OAuth revocation resolves to `undefined`. `NetworkError` covers timeout/DNS/transport failures. `PartialWorkflowError` reports `documents upload --wait` or a multi-step helper that failed after creating resources and exposes `documentId` and `signerIds`. All extend `AssinafyError`, which exposes `context` and preserves `cause` where available.
565
+ - `ValidationError` means local input validation failed before a request. `ApiError` exposes `statusCode`, `responseData`, `wwwAuthenticate`, `retryAfter` and `rateLimit` (`{ limit?, remaining?, reset? }` from `X-Rate-Limit-*`); a `429` carries `Retry-After` seconds to wait before retrying, and the SDK never retries automatically. OAuth errors use `error: error_description` as the message; binary JSON error bodies are decoded before normalization. OAuth responses are flat JSON, and OAuth revocation resolves to `undefined`. `NetworkError` covers timeout/DNS/transport failures. `PartialWorkflowError` reports `documents upload --wait` or a multi-step helper that failed after creating resources and exposes `documentId` and `signerIds`. All extend `AssinafyError`, which exposes `context` and preserves `cause` where available.
525
566
  - `normalizeBaseUrl(url)` is exported and removes one trailing slash. The CLI-facing guards `requireDocumentArtifactName(name)` and `requireSignerImageType(type)` are also exported.
526
567
 
527
- Exported error constructors/helpers are `new AssinafyError(message, context?, { cause? }?)`, `new ApiError(message, statusCode, responseData?, { cause?, wwwAuthenticate?, retryAfter? }?)`, `ApiError.fromResponse(statusCode, responseData, headers?)`, `new ValidationError(message?, errors?)`, `new NetworkError(message, { cause? }?)`, and `new PartialWorkflowError(message, { documentId?, signerIds? }, { cause? }?)`. Resource classes and all named request/response types are also exported for dependency injection and type annotations; normal applications should obtain resource instances from `AssinafyClient`.
568
+ Exported error constructors/helpers are `new AssinafyError(message, context?, { cause? }?)`, `new ApiError(message, statusCode, responseData?, { cause?, wwwAuthenticate?, retryAfter?, rateLimit? }?)`, `ApiError.fromResponse(statusCode, responseData, headers?)`, `new ValidationError(message?, errors?)`, `new NetworkError(message, { cause? }?)`, and `new PartialWorkflowError(message, { documentId?, signerIds? }, { cause? }?)`. Resource classes and all named request/response types are also exported for dependency injection and type annotations; normal applications should obtain resource instances from `AssinafyClient`.
528
569
 
529
570
  ```ts
530
571
  try {
@@ -536,21 +577,41 @@ try {
536
577
  }
537
578
  ```
538
579
 
539
- ## Webhook verification (experimental)
580
+ ## Webhook verification
581
+
582
+ Deliveries are `POST` requests with `Content-Type: application/json`, a `webhook-id` (stable across retries of the same event to the same endpoint; use it to deduplicate), a `webhook-timestamp` (Unix seconds), and, when the endpoint has `signing_enabled`, a `webhook-signature` following [Standard Webhooks](https://www.standardwebhooks.com). Any `2xx` is success; a failed delivery is retried once after 3 seconds. After 10 consecutive failed events the endpoint's delivery is paused and probed until one succeeds; use `retryDispatch` to force redelivery.
540
583
 
541
584
  | API | Result |
542
585
  | --- | --- |
543
- | `new WebhookVerifier(secret?, { algorithm?, encoding? }?)` | Compatibility verifier; defaults to `sha256` and `hex`. |
544
- | `verify(rawBody, signature)` | `boolean`; HMAC verification under the configured, assumed scheme. |
586
+ | `new WebhookVerifier(secret?, { algorithm?, encoding? }?)` | Verifier keyed with an endpoint's `whsec_` secret. The options apply only to the deprecated `verify`. |
587
+ | `verifyDelivery(rawBody, headers, { toleranceSeconds?, now? }?)` | `boolean`. Checks `v1` HMAC-SHA256 over `{webhook-id}.{webhook-timestamp}.{rawBody}` with the base64-decoded secret, constant-time, against every space-separated signature entry, and rejects timestamps more than `toleranceSeconds` (default 300) from `now` (ms, default `Date.now()`). `headers` may be Node `IncomingHttpHeaders`, a plain record (case-insensitive), or Fetch `Headers`; repeated headers are rejected. |
588
+ | `verify(rawBody, signature)` | Deprecated body-only HMAC kept for existing callers; Assinafy deliveries do not use it. |
545
589
  | `extractEvent(rawBody)` | Parsed `IWebhookPayload`, or `null` for invalid JSON/non-object data. |
546
590
  | `getEventType(event)` | `event`/`type` string, or `null`. |
547
591
  | `getEventData(event)` | First object found at `payload`, `data`, or `object`; otherwise `{}`. |
548
592
 
549
- Assinafy's published API does **not** define a signature header, algorithm, digest encoding, timestamp, or replay-protection scheme. Therefore this helper is experimental and unverified; do not use it as a production trust boundary until Assinafy publishes the scheme or you validate every detail against real deliveries. Preserve the exact raw request bytes for any future verification.
593
+ `client.webhookVerifier` uses the `webhookSecret` client option. Each endpoint has its own secret, so construct one verifier per signed endpoint.
594
+
595
+ ```ts
596
+ import express from 'express';
597
+ import { WebhookVerifier } from '@assinafy/cli/api';
598
+
599
+ const verifier = new WebhookVerifier(process.env.ASSINAFY_WEBHOOK_SECRET);
600
+ const app = express();
601
+
602
+ app.post('/assinafy/webhooks', express.raw({ type: 'application/json' }), (req, res) => {
603
+ if (!verifier.verifyDelivery(req.body, req.headers)) return res.sendStatus(401);
604
+ const event = verifier.extractEvent(req.body);
605
+ // Deduplicate by req.headers['webhook-id'], enqueue the work, and answer quickly.
606
+ res.sendStatus(204);
607
+ });
608
+ ```
609
+
610
+ Verify the raw bytes before parsing; re-serialized JSON does not match. The envelope is `{ id, event, message, payload, origin, created_at, subject, object, account_id }`; `subject` and `object` carry a `type` of `User`, `Signer`, `Account`, `Document`, or `Template`. Unknown fields are forward-compatible additions. Confirm business state (for example a document's status) through the API before irreversible actions.
550
611
 
551
612
  ## Contract boundaries
552
613
 
553
- - Production OpenAPI currently publishes 93 operations. Some sandbox deployments lag it; account/user statistics and user notification-preference routes may return route-level 404s even though production documentation includes them.
554
- - Certificate start/complete are deployed production extensions, exposed by `startCertificate` and `completeCertificate` with the signing application's payloads. They supplement the 93 OpenAPI operations; the API manifest contains only published paths.
555
- - The SDK retains the two template compatibility routes above and both published/legacy public `sendToken` payloads for compatible deployments.
614
+ - Production OpenAPI currently publishes 106 operations. Some sandbox deployments lag it; account/user statistics and user notification-preference routes may return route-level 404s even though production documentation includes them.
615
+ - Certificate start/complete are deployed production extensions, exposed by `startCertificate` and `completeCertificate` with the signing application's payloads. They supplement the 106 OpenAPI operations; the API manifest contains only published paths.
616
+ - The SDK retains the two template compatibility routes above. Both `sendToken` call forms send the email-only production body.
556
617
  - Signer artifact downloads are public in the published contract. Supplying a signer access code opts into an SDK identity preflight; it does not change the server route into a private endpoint.
package/docs/signer.md CHANGED
@@ -57,7 +57,8 @@ Arguments:
57
57
  signerId Signer ID
58
58
 
59
59
  Options:
60
- --access-code <code> Signer access code (env: ASSINAFY_SIGNER_ACCESS_CODE)
60
+ --access-code <code> Signer access code (omit to use your API key or token)
61
+ (env: ASSINAFY_SIGNER_ACCESS_CODE)
61
62
  --page <n> Page number to fetch
62
63
  --per-page <n> Items per page
63
64
  --search <query> Filter by a search query
@@ -77,7 +78,8 @@ Arguments:
77
78
  query Search text
78
79
 
79
80
  Options:
80
- --access-code <code> Signer access code (env: ASSINAFY_SIGNER_ACCESS_CODE)
81
+ --access-code <code> Signer access code (omit to use your API key or token)
82
+ (env: ASSINAFY_SIGNER_ACCESS_CODE)
81
83
  -h, --help display help for command
82
84
  ```
83
85