@assinafy/sdk 2.5.1 → 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/dist/index.mjs CHANGED
@@ -153,12 +153,14 @@ var OAuthError = class _OAuthError extends ApiError {
153
153
  const code = body["error"];
154
154
  if (typeof code !== "string" || code.length === 0) return error;
155
155
  const description = body["error_description"];
156
- return new _OAuthError(
156
+ const upgraded = new _OAuthError(
157
157
  code,
158
158
  typeof description === "string" && description.length > 0 ? description : null,
159
159
  error.statusCode,
160
160
  body
161
161
  );
162
+ if (error.challenge !== void 0) upgraded.challenge = error.challenge;
163
+ return upgraded;
162
164
  }
163
165
  };
164
166
  var ValidationError = class extends AssinafyError {
@@ -462,6 +464,9 @@ function nextRetryDelayMs(headers, attempt, maxDelayMs = 3e4) {
462
464
  return Math.min(backoffMs(attempt), maxDelayMs);
463
465
  }
464
466
 
467
+ // src/resources/base.ts
468
+ import { AxiosError } from "axios";
469
+
465
470
  // src/support/path.ts
466
471
  function encodePathSegment(value) {
467
472
  return encodeURIComponent(value).replace(
@@ -586,7 +591,7 @@ import axios2 from "axios";
586
591
  // package.json
587
592
  var package_default = {
588
593
  name: "@assinafy/sdk",
589
- version: "2.5.1",
594
+ version: "2.6.0",
590
595
  packageManager: "bun@1.4.0",
591
596
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
592
597
  type: "commonjs",
@@ -667,7 +672,7 @@ var package_default = {
667
672
  },
668
673
  overrides: {
669
674
  esbuild: "0.28.2",
670
- "brace-expansion": "5.0.9"
675
+ "brace-expansion": "5.0.12"
671
676
  },
672
677
  files: [
673
678
  "dist",
@@ -892,7 +897,10 @@ var BaseResource = class {
892
897
  };
893
898
  function assertSuccessful(response) {
894
899
  if (response.status < 200 || response.status >= 300) {
895
- throw ApiError.fromResponse(response.status, response.data);
900
+ throw toSdkError(
901
+ new AxiosError("Request failed", void 0, response.config, void 0, response),
902
+ "API request failed"
903
+ );
896
904
  }
897
905
  return response;
898
906
  }
@@ -1271,6 +1279,28 @@ var AssignmentResource = class extends BaseResource {
1271
1279
  * `DigitalCertificate` costs two credits, requires the feature plus a
1272
1280
  * signer `government_id`, and that signer must be alone in its step.
1273
1281
  *
1282
+ * Request body (`application/json`):
1283
+ * ```jsonc
1284
+ * {
1285
+ * "method": "virtual",
1286
+ * "signers": [
1287
+ * {
1288
+ * "id": "signer_example",
1289
+ * "verification_method": "Email",
1290
+ * "notification_methods": [
1291
+ * "Email"
1292
+ * ],
1293
+ * "step": 1
1294
+ * }
1295
+ * ],
1296
+ * "message": "Please sign this document.",
1297
+ * "expires_at": "2027-12-31T23:59:59Z",
1298
+ * "copy_receivers": [
1299
+ * "copy_signer_example"
1300
+ * ]
1301
+ * }
1302
+ * ```
1303
+ *
1274
1304
  * @param documentId - The document to request signatures on.
1275
1305
  * @param payload - Signers plus optional `method` (defaults to `virtual`),
1276
1306
  * `message`, `expires_at`, `copy_receivers` (existing signer IDs, not
@@ -1389,6 +1419,21 @@ var AssignmentResource = class extends BaseResource {
1389
1419
  * email notification, and 0.45 for WhatsApp notification; a digital
1390
1420
  * certificate charge is added on top of its notification cost.
1391
1421
  *
1422
+ * Request body (`application/json`):
1423
+ * ```jsonc
1424
+ * {
1425
+ * "method": "virtual",
1426
+ * "signers": [
1427
+ * {
1428
+ * "verification_method": "Email",
1429
+ * "notification_methods": [
1430
+ * "Email"
1431
+ * ]
1432
+ * }
1433
+ * ]
1434
+ * }
1435
+ * ```
1436
+ *
1392
1437
  * @param documentId - The document the assignment would be created on.
1393
1438
  * @param payload - `method` plus channel-only signer descriptors and/or
1394
1439
  * `collect`-mode `entries`. Create-only fields and signer IDs are not part
@@ -1444,6 +1489,13 @@ var AssignmentResource = class extends BaseResource {
1444
1489
  * is retained as a compatibility value and, unlike ordinary nullable
1445
1490
  * inputs, is intentionally not stripped from the body.
1446
1491
  *
1492
+ * Request body (`application/json`):
1493
+ * ```jsonc
1494
+ * {
1495
+ * "expires_at": "2027-12-31T23:59:59Z"
1496
+ * }
1497
+ * ```
1498
+ *
1447
1499
  * @param documentId - The document the assignment belongs to.
1448
1500
  * @param assignmentId - The assignment to update.
1449
1501
  * @param expiresAt - New expiry as an ISO-8601 date/time string. `null` is
@@ -1859,6 +1911,13 @@ var DocumentResource = class extends BaseResource {
1859
1911
  * {@link DocumentResource.upload} — that avoids the extra round-trip and
1860
1912
  * the processing race entirely.
1861
1913
  *
1914
+ * Request body (`application/json`):
1915
+ * ```jsonc
1916
+ * {
1917
+ * "name": "Service agreement.pdf"
1918
+ * }
1919
+ * ```
1920
+ *
1862
1921
  * @param documentId - The document to rename.
1863
1922
  * @param name - The new display name (max 255 chars), e.g.
1864
1923
  * `'Service agreement.pdf'`. The API removes diacritics and replaces
@@ -2269,6 +2328,15 @@ var DocumentResource = class extends BaseResource {
2269
2328
  * overwrites the existing set — use
2270
2329
  * {@link DocumentResource.addTags} to append.
2271
2330
  *
2331
+ * Request body (`application/json`):
2332
+ * ```jsonc
2333
+ * {
2334
+ * "tags": [
2335
+ * "tag_example"
2336
+ * ]
2337
+ * }
2338
+ * ```
2339
+ *
2272
2340
  * @param documentId - The document to retag.
2273
2341
  * @param tags - The complete desired set of tag IDs (`[]` clears all).
2274
2342
  * @param accountId - Override the client's default account ID.
@@ -2311,6 +2379,15 @@ var DocumentResource = class extends BaseResource {
2311
2379
  * present is a no-op. To replace the whole set instead, use
2312
2380
  * {@link DocumentResource.replaceTags}.
2313
2381
  *
2382
+ * Request body (`application/json`):
2383
+ * ```jsonc
2384
+ * {
2385
+ * "tags": [
2386
+ * "tag_example"
2387
+ * ]
2388
+ * }
2389
+ * ```
2390
+ *
2314
2391
  * @param documentId - The document to tag.
2315
2392
  * @param tags - Tag IDs to attach (must be non-empty).
2316
2393
  * @param accountId - Override the client's default account ID.
@@ -2386,6 +2463,35 @@ var DocumentResource = class extends BaseResource {
2386
2463
  * `options` may add `name`, `message`, `expires_at`, `editor_fields`, and
2387
2464
  * tag names in `tags` (unknown names are created automatically).
2388
2465
  *
2466
+ * Request body (`application/json`):
2467
+ * ```jsonc
2468
+ * {
2469
+ * "signers": [
2470
+ * {
2471
+ * "role_id": "signing_role_example",
2472
+ * "id": "signer_example",
2473
+ * "verification_method": "Email",
2474
+ * "notification_methods": [
2475
+ * "Email"
2476
+ * ],
2477
+ * "step": 1
2478
+ * }
2479
+ * ],
2480
+ * "name": "Service agreement.pdf",
2481
+ * "message": "Please sign this document.",
2482
+ * "expires_at": "2027-12-31T23:59:59Z",
2483
+ * "editor_fields": [
2484
+ * {
2485
+ * "field_id": "editor_field_example",
2486
+ * "value": "Example Company"
2487
+ * }
2488
+ * ],
2489
+ * "tags": [
2490
+ * "Contracts"
2491
+ * ]
2492
+ * }
2493
+ * ```
2494
+ *
2389
2495
  * @param templateId - The template to instantiate.
2390
2496
  * @param signers - Role-to-signer bindings (each with `role_id` and `id`,
2391
2497
  * plus optional `verification_method`, `notification_methods`, `step`).
@@ -2469,6 +2575,21 @@ var DocumentResource = class extends BaseResource {
2469
2575
  * `DigitalCertificate` adds two credits per signer and has the same feature,
2470
2576
  * `government_id`, and signing-step prerequisites as document creation.
2471
2577
  *
2578
+ * Request body (`application/json`):
2579
+ * ```jsonc
2580
+ * {
2581
+ * "signers": [
2582
+ * {
2583
+ * "role_id": "signing_role_example",
2584
+ * "verification_method": "Email",
2585
+ * "notification_methods": [
2586
+ * "Email"
2587
+ * ]
2588
+ * }
2589
+ * ]
2590
+ * }
2591
+ * ```
2592
+ *
2472
2593
  * @param templateId - The template that would be instantiated.
2473
2594
  * @param signers - One channel descriptor per template role. Cost requests
2474
2595
  * use only `role_id`, `verification_method`, and `notification_methods`;
@@ -2844,13 +2965,27 @@ var SignerResource = class extends BaseResource {
2844
2965
  * A reused signer is returned unchanged; this method does not overwrite its
2845
2966
  * existing name, phone, CPF, or metadata with the create payload.
2846
2967
  *
2968
+ * Request body (`application/json`):
2969
+ * ```jsonc
2970
+ * {
2971
+ * "full_name": "Example Signer",
2972
+ * "email": "signer@example.com",
2973
+ * "whatsapp_phone_number": "+5548999990000",
2974
+ * "government_id": "390.533.447-05",
2975
+ * "metadata": {
2976
+ * "reference": "customer_example"
2977
+ * }
2978
+ * }
2979
+ * ```
2980
+ *
2847
2981
  * @param payload - The signer to create. The official fields are required
2848
- * `full_name` plus optional `email` and E.164 `whatsapp_phone_number`.
2849
- * `phone`, `cpf`, and `metadata` are compatibility extensions; the SDK
2850
- * normalizes the phone alias and strips non-digits from CPF before sending.
2982
+ * `full_name` plus optional `email`, E.164 `whatsapp_phone_number` and
2983
+ * `government_id` (CPF, or a CNPJ that may contain letters; the API strips
2984
+ * formatting). `phone`, `cpf`, and `metadata` are compatibility extensions;
2985
+ * the SDK normalizes the phone alias and strips non-digits from CPF.
2851
2986
  * @param accountId - Override the client's default account ID.
2852
- * @returns The created (or reused) signer. Note the response **never echoes
2853
- * `cpf` back**, even when one was sent:
2987
+ * @returns The created (or reused) signer. `government_id` comes back
2988
+ * normalized; `cpf` is **never echoed back**:
2854
2989
  * ```jsonc
2855
2990
  * {
2856
2991
  * "resource": "signer",
@@ -2858,6 +2993,7 @@ var SignerResource = class extends BaseResource {
2858
2993
  * "full_name": "Ana Souza",
2859
2994
  * "email": "ana@example.com",
2860
2995
  * "whatsapp_phone_number": null,
2996
+ * "government_id": "39053344705",
2861
2997
  * "has_accepted_terms": false
2862
2998
  * }
2863
2999
  * ```
@@ -2871,7 +3007,7 @@ var SignerResource = class extends BaseResource {
2871
3007
  * const signer = await client.signers.create({
2872
3008
  * full_name: 'Ana Souza',
2873
3009
  * email: 'ana@example.com',
2874
- * cpf: '390.533.447-05', // sent as '39053344705', never echoed back
3010
+ * government_id: '390.533.447-05', // returned as '39053344705'
2875
3011
  * });
2876
3012
  *
2877
3013
  * // A whatsapp-only signer (no email):
@@ -2930,6 +3066,7 @@ var SignerResource = class extends BaseResource {
2930
3066
  * "full_name": "Example Signer",
2931
3067
  * "email": "signer@example.com",
2932
3068
  * "whatsapp_phone_number": null,
3069
+ * "government_id": "12ABC34501DE35",
2933
3070
  * "has_accepted_terms": false
2934
3071
  * }
2935
3072
  * ```
@@ -2995,9 +3132,20 @@ var SignerResource = class extends BaseResource {
2995
3132
  * while it belongs to an in-flight document; changing an unverified channel
2996
3133
  * rotates its access/verification codes, so resend the notification.
2997
3134
  *
3135
+ * Request body (`application/json`):
3136
+ * ```jsonc
3137
+ * {
3138
+ * "full_name": "Example Signer",
3139
+ * "email": "signer@example.com",
3140
+ * "whatsapp_phone_number": "+5548999990000",
3141
+ * "government_id": "12.ABC.345/01DE-35"
3142
+ * }
3143
+ * ```
3144
+ *
2998
3145
  * @param signerId - The signer to update.
2999
- * @param payload - Fields to change. The official `government_id` field and
3000
- * legacy `cpf` extension are stripped to digits before sending.
3146
+ * @param payload - Fields to change. `government_id` is sent as given (the
3147
+ * API normalizes it and keeps CNPJ letters); the legacy `cpf` extension is
3148
+ * stripped to digits.
3001
3149
  * @param accountId - Override the client's default account ID.
3002
3150
  * @returns The updated signer (as with create, `cpf` is never echoed back):
3003
3151
  * ```jsonc
@@ -3007,6 +3155,7 @@ var SignerResource = class extends BaseResource {
3007
3155
  * "full_name": "Ana Souza Lima",
3008
3156
  * "email": "ana@example.com",
3009
3157
  * "whatsapp_phone_number": null,
3158
+ * "government_id": "12ABC34501DE35",
3010
3159
  * "has_accepted_terms": false
3011
3160
  * }
3012
3161
  * ```
@@ -3133,6 +3282,7 @@ function validateCreateSignerPayload(payload) {
3133
3282
  validateOptionalPhone(phone);
3134
3283
  if (payload.metadata !== void 0) serializeJsonRecord(payload.metadata, "metadata");
3135
3284
  validateOptionalDigits(payload.cpf, "cpf");
3285
+ validateOptionalDigits(payload.government_id, "government_id");
3136
3286
  }
3137
3287
  function validateUpdateSignerPayload(payload) {
3138
3288
  if (!payload || typeof payload !== "object") {
@@ -3181,8 +3331,8 @@ function normaliseSignerPayload(payload) {
3181
3331
  if (payload.cpf) {
3182
3332
  normalised["cpf"] = payload.cpf.replace(/\D/g, "");
3183
3333
  }
3184
- if ("government_id" in payload && payload.government_id) {
3185
- normalised["government_id"] = payload.government_id.replace(/\D/g, "");
3334
+ if (payload.government_id) {
3335
+ normalised["government_id"] = payload.government_id.trim();
3186
3336
  }
3187
3337
  if ("metadata" in payload && payload.metadata !== void 0) {
3188
3338
  normalised["metadata"] = payload.metadata;
@@ -3214,6 +3364,16 @@ var WorkspaceResource = class extends BaseResource {
3214
3364
  /**
3215
3365
  * Create a new workspace (`POST /accounts`).
3216
3366
  *
3367
+ * Request body (`application/json`):
3368
+ * ```jsonc
3369
+ * {
3370
+ * "name": "Example Workspace",
3371
+ * "notification_sender_type": "Account",
3372
+ * "primary_color": "336699",
3373
+ * "secondary_color": "ffffff"
3374
+ * }
3375
+ * ```
3376
+ *
3217
3377
  * @param payload - Official fields are workspace `name` (required) and
3218
3378
  * optional `notification_sender_type` (`User` or `Account`). Optional brand
3219
3379
  * colours use six hex characters without
@@ -3494,6 +3654,16 @@ var WorkspaceResource = class extends BaseResource {
3494
3654
  /**
3495
3655
  * Update a workspace (`PUT /accounts/{accountId}`).
3496
3656
  *
3657
+ * Request body (`application/json`):
3658
+ * ```jsonc
3659
+ * {
3660
+ * "name": "Example Workspace",
3661
+ * "notification_sender_type": "Account",
3662
+ * "primary_color": "336699",
3663
+ * "secondary_color": null
3664
+ * }
3665
+ * ```
3666
+ *
3497
3667
  * @param accountId - The workspace to update.
3498
3668
  * @param payload - Official fields are `name` and
3499
3669
  * `notification_sender_type` (`User` or `Account`). Brand colours use six
@@ -3554,6 +3724,13 @@ var WorkspaceResource = class extends BaseResource {
3554
3724
  * proceeds with deletion; it is not documented as a blanket override for
3555
3725
  * unrelated restrictions. The flag is sent in the request body.
3556
3726
  *
3727
+ * Request body (`application/json`):
3728
+ * ```jsonc
3729
+ * {
3730
+ * "force": true
3731
+ * }
3732
+ * ```
3733
+ *
3557
3734
  * @param accountId - The workspace to delete.
3558
3735
  * @param options - Set `force: true` to cancel an active paid subscription
3559
3736
  * and proceed with deletion.
@@ -3615,15 +3792,28 @@ var DEFAULT_WEBHOOK_EVENTS = Object.freeze([
3615
3792
  ]);
3616
3793
  var WebhookResource = class extends BaseResource {
3617
3794
  /**
3618
- * Register (or replace) the workspace's single webhook subscription
3619
- * (`PUT /accounts/{accountId}/webhooks/subscriptions`). There is exactly one
3620
- * subscription per workspace, keyed by URL.
3795
+ * Update the account's oldest webhook endpoint, creating it if the account
3796
+ * has none (`PUT /accounts/{accountId}/webhooks/subscriptions`). Accounts
3797
+ * with several endpoints should use {@link WebhookResource.updateEndpoint}.
3621
3798
  *
3622
3799
  * When `events` is omitted or empty, {@link DEFAULT_WEBHOOK_EVENTS} is used
3623
3800
  * (`document_ready`, `document_prepared`, `signer_signed_document`,
3624
3801
  * `signer_rejected_document`, `document_processing_failed`).
3625
3802
  * OAuth tokens need the `webhooks:write` scope.
3626
3803
  *
3804
+ * Request body (`application/json`):
3805
+ * ```jsonc
3806
+ * {
3807
+ * "events": [
3808
+ * "document_ready",
3809
+ * "document_prepared"
3810
+ * ],
3811
+ * "is_active": true,
3812
+ * "url": "https://myapp.example.com/webhooks/assinafy",
3813
+ * "email": "operations@example.com"
3814
+ * }
3815
+ * ```
3816
+ *
3627
3817
  * @param payload - Subscription details. `url` and `email` are required;
3628
3818
  * `events` defaults to {@link DEFAULT_WEBHOOK_EVENTS} and `is_active`
3629
3819
  * defaults to `true`.
@@ -3663,26 +3853,12 @@ var WebhookResource = class extends BaseResource {
3663
3853
  * ```
3664
3854
  */
3665
3855
  async register(payload, accountId) {
3666
- if (!payload || typeof payload !== "object") {
3667
- throw new ValidationError("Webhook subscription payload is required");
3668
- }
3669
- validateWebhookUrl(payload.url);
3670
- if (!isEmail(payload.email)) {
3671
- throw new ValidationError("Webhook email must be a valid email address", {
3672
- email: payload.email
3673
- });
3674
- }
3675
- if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event.trim()))) {
3676
- throw new ValidationError("Webhook events must be an array of non-empty strings");
3677
- }
3678
- if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
3679
- throw new ValidationError("Webhook is_active must be a boolean");
3680
- }
3856
+ validateWebhookFields(payload, true);
3681
3857
  const id = this.accountId(accountId);
3682
3858
  const body = {
3683
3859
  url: payload.url,
3684
3860
  email: payload.email,
3685
- events: [...payload.events && payload.events.length > 0 ? payload.events : DEFAULT_WEBHOOK_EVENTS],
3861
+ events: withDefaultEvents(payload.events),
3686
3862
  is_active: payload.is_active ?? true
3687
3863
  };
3688
3864
  this.logger.info("Registering webhook");
@@ -3695,8 +3871,9 @@ var WebhookResource = class extends BaseResource {
3695
3871
  );
3696
3872
  }
3697
3873
  /**
3698
- * Fetch the current webhook subscription
3699
- * (`GET /accounts/{accountId}/webhooks/subscriptions`).
3874
+ * Fetch the account's oldest webhook endpoint in the legacy subscription
3875
+ * shape (`GET /accounts/{accountId}/webhooks/subscriptions`). Accounts with
3876
+ * several endpoints should use {@link WebhookResource.listEndpoints}.
3700
3877
  *
3701
3878
  * @param accountId - Override the client's default account ID.
3702
3879
  * @returns The subscription, or `null` when the workspace has none (the API
@@ -3738,13 +3915,14 @@ var WebhookResource = class extends BaseResource {
3738
3915
  );
3739
3916
  }
3740
3917
  /**
3741
- * Inactivate the current webhook subscription
3742
- * (`PUT /accounts/{accountId}/webhooks/inactivate`).
3918
+ * Deactivate the account's oldest webhook endpoint
3919
+ * (`PUT /accounts/{accountId}/webhooks/inactivate`). Other endpoints are
3920
+ * unaffected; use {@link WebhookResource.updateEndpoint} with
3921
+ * `is_active: false` to target a specific one.
3743
3922
  *
3744
- * This is the only supported way to stop deliveries — the API has no
3745
- * subscription-delete route. The subscription is retained (with its `url`
3746
- * and `events`) and simply stops firing; re-enable it by calling
3747
- * {@link WebhookResource.register} again with `is_active: true`.
3923
+ * The endpoint is retained (with its `url` and `events`) and simply stops
3924
+ * firing; re-enable it by calling {@link WebhookResource.register} again
3925
+ * with `is_active: true`.
3748
3926
  * OAuth tokens need the `webhooks:write` scope.
3749
3927
  *
3750
3928
  * @param accountId - Override the client's default account ID.
@@ -3829,6 +4007,7 @@ var WebhookResource = class extends BaseResource {
3829
4007
  * truncated to 2,000 characters.
3830
4008
  *
3831
4009
  * @param params - Optional filters and pagination:
4010
+ * - `endpoint_id` — only deliveries to this webhook endpoint.
3832
4011
  * - `event` — restrict to a single {@link WebhookEventType}
3833
4012
  * (e.g. `'signer_signed_document'`).
3834
4013
  * - `delivered` — `true`/`false` to filter by delivery success.
@@ -3843,6 +4022,7 @@ var WebhookResource = class extends BaseResource {
3843
4022
  * "id": "103a09cfce51319dd3b3f72ffcdf",
3844
4023
  * "event": "signature_requested",
3845
4024
  * "activity_id": 8629,
4025
+ * "endpoint_id": "65f1c2a9b3e4d5f60718293a4b5c6d7e", // null once the endpoint is deleted
3846
4026
  * "endpoint": "https://example.com/hook",
3847
4027
  * "payload": {
3848
4028
  * // the full event body that was POSTed to `endpoint`:
@@ -3885,7 +4065,7 @@ var WebhookResource = class extends BaseResource {
3885
4065
  /**
3886
4066
  * Retry delivery of a specific webhook dispatch
3887
4067
  * (`POST /accounts/{accountId}/webhooks/{historyId}/retry`). Re-sends the
3888
- * original payload to the subscription's endpoint.
4068
+ * original payload to the endpoint that received it.
3889
4069
  *
3890
4070
  * @param dispatchId - The dispatch (delivery history) ID to re-send, as
3891
4071
  * returned by {@link WebhookResource.listDispatches}.
@@ -3899,6 +4079,7 @@ var WebhookResource = class extends BaseResource {
3899
4079
  * "id": "103a09cfce51319dd3b3f72ffcdf",
3900
4080
  * "event": "signature_requested",
3901
4081
  * "activity_id": 8629,
4082
+ * "endpoint_id": "65f1c2a9b3e4d5f60718293a4b5c6d7e", // null once the endpoint is deleted
3902
4083
  * "endpoint": "https://example.com/hook",
3903
4084
  * "payload": { }, // the original event body that was re-POSTed
3904
4085
  * "delivered": true,
@@ -3929,11 +4110,320 @@ var WebhookResource = class extends BaseResource {
3929
4110
  )
3930
4111
  );
3931
4112
  }
4113
+ /**
4114
+ * List the account's webhook endpoints, oldest first
4115
+ * (`GET /accounts/{accountId}/webhooks/endpoints`). OAuth tokens need the
4116
+ * `account:read` scope.
4117
+ *
4118
+ * @param accountId - Override the client's default account ID.
4119
+ * @returns Every endpoint (1 on free plans, up to 3 on paid plans):
4120
+ * ```jsonc
4121
+ * [
4122
+ * {
4123
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4124
+ * "name": "ERP",
4125
+ * "url": "https://example.com/webhooks/assinafy",
4126
+ * "email": "ops@example.com",
4127
+ * "events": ["document_ready", "signer_signed_document"],
4128
+ * "is_active": true,
4129
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4130
+ * "created_at": "2026-10-01T12:00:00Z",
4131
+ * "updated_at": "2026-10-01T12:00:00Z"
4132
+ * }
4133
+ * ]
4134
+ * ```
4135
+ * @throws {ValidationError} If no account ID is available.
4136
+ * @throws {ApiError} If the API rejects the request.
4137
+ *
4138
+ * @example
4139
+ * ```ts
4140
+ * const endpoints = await client.webhooks.listEndpoints();
4141
+ * const signed = endpoints.filter((endpoint) => endpoint.signing_enabled);
4142
+ * ```
4143
+ */
4144
+ async listEndpoints(accountId) {
4145
+ const path2 = this.endpointsPath(accountId);
4146
+ return this.call("Failed to list webhook endpoints", () => this.http.get(path2));
4147
+ }
4148
+ /**
4149
+ * Register a URL to receive the account's webhook events
4150
+ * (`POST /accounts/{accountId}/webhooks/endpoints`).
4151
+ *
4152
+ * An account can have 1 endpoint, or up to 3 on paid plans. Each endpoint
4153
+ * of a workspace needs a different `url`. With `signing_enabled: true` the
4154
+ * API generates a signing secret; read it with
4155
+ * {@link WebhookResource.getEndpointSecret}. When `events` is omitted or
4156
+ * empty, {@link DEFAULT_WEBHOOK_EVENTS} is sent. OAuth tokens need the
4157
+ * `webhooks:write` scope.
4158
+ *
4159
+ * Request body (`application/json`):
4160
+ * ```jsonc
4161
+ * {
4162
+ * "url": "https://example.com/webhooks/assinafy",
4163
+ * "email": "ops@example.com",
4164
+ * "events": ["document_ready", "signer_signed_document"],
4165
+ * "name": "ERP", // optional label
4166
+ * "is_active": true, // defaults to true
4167
+ * "signing_enabled": true // defaults to false
4168
+ * }
4169
+ * ```
4170
+ *
4171
+ * @param payload - Endpoint details. `url` (absolute HTTP(S)) and `email`
4172
+ * are required; `events`, `name`, `is_active` and `signing_enabled` are
4173
+ * optional.
4174
+ * @param accountId - Override the client's default account ID.
4175
+ * @returns The created endpoint:
4176
+ * ```jsonc
4177
+ * {
4178
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4179
+ * "name": "ERP",
4180
+ * "url": "https://example.com/webhooks/assinafy",
4181
+ * "email": "ops@example.com",
4182
+ * "events": ["document_ready", "signer_signed_document"],
4183
+ * "is_active": true,
4184
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4185
+ * "created_at": "2026-10-01T12:00:00Z",
4186
+ * "updated_at": "2026-10-01T12:00:00Z"
4187
+ * }
4188
+ * ```
4189
+ * @throws {ValidationError} If a field is malformed or no account ID is
4190
+ * available.
4191
+ * @throws {ApiError} `400` if another endpoint already uses `url`; `403`
4192
+ * when the plan's endpoint limit is reached or an OAuth token lacks
4193
+ * `webhooks:write`.
4194
+ *
4195
+ * @example
4196
+ * ```ts
4197
+ * const endpoint = await client.webhooks.createEndpoint({
4198
+ * name: 'ERP',
4199
+ * url: 'https://example.com/webhooks/assinafy',
4200
+ * email: 'ops@example.com',
4201
+ * events: ['document_ready', 'signer_signed_document'],
4202
+ * signing_enabled: true,
4203
+ * });
4204
+ * const { secret } = await client.webhooks.getEndpointSecret(endpoint.id);
4205
+ * ```
4206
+ */
4207
+ async createEndpoint(payload, accountId) {
4208
+ validateWebhookFields(payload, true);
4209
+ const path2 = this.endpointsPath(accountId);
4210
+ this.logger.info("Creating webhook endpoint");
4211
+ return this.call(
4212
+ "Failed to create webhook endpoint",
4213
+ () => this.http.post(path2, { ...payload, events: withDefaultEvents(payload.events) })
4214
+ );
4215
+ }
4216
+ /**
4217
+ * Retrieve one webhook endpoint
4218
+ * (`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}`). OAuth
4219
+ * tokens need the `account:read` scope.
4220
+ *
4221
+ * @param endpointId - The endpoint ID.
4222
+ * @param accountId - Override the client's default account ID.
4223
+ * @returns The endpoint:
4224
+ * ```jsonc
4225
+ * {
4226
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4227
+ * "name": "ERP",
4228
+ * "url": "https://example.com/webhooks/assinafy",
4229
+ * "email": "ops@example.com",
4230
+ * "events": ["document_ready", "signer_signed_document"],
4231
+ * "is_active": true,
4232
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4233
+ * "created_at": "2026-10-01T12:00:00Z",
4234
+ * "updated_at": "2026-10-01T12:00:00Z"
4235
+ * }
4236
+ * ```
4237
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4238
+ * available.
4239
+ * @throws {ApiError} `404` if the endpoint does not exist.
4240
+ *
4241
+ * @example
4242
+ * ```ts
4243
+ * const endpoint = await client.webhooks.getEndpoint('65f1c2a9b3e4d5f60718293a4b5c6d7e');
4244
+ * ```
4245
+ */
4246
+ async getEndpoint(endpointId, accountId) {
4247
+ const path2 = this.endpointPath(endpointId, accountId);
4248
+ return this.call("Failed to fetch webhook endpoint", () => this.http.get(path2));
4249
+ }
4250
+ /**
4251
+ * Change a webhook endpoint
4252
+ * (`PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}`). Only the
4253
+ * fields sent are updated; `url` cannot be one another endpoint of the
4254
+ * workspace already uses.
4255
+ *
4256
+ * `signing_enabled: true` generates a secret if the endpoint has none and
4257
+ * keeps the current one otherwise; `false` discards the secret. OAuth
4258
+ * tokens need the `webhooks:write` scope.
4259
+ *
4260
+ * Request body (`application/json`, every field optional):
4261
+ * ```jsonc
4262
+ * {
4263
+ * "url": "https://example.com/webhooks/assinafy",
4264
+ * "email": "ops@example.com",
4265
+ * "events": ["document_ready"],
4266
+ * "name": "ERP",
4267
+ * "is_active": false,
4268
+ * "signing_enabled": true
4269
+ * }
4270
+ * ```
4271
+ *
4272
+ * @param endpointId - The endpoint ID.
4273
+ * @param payload - Fields to change; at least one is required.
4274
+ * @param accountId - Override the client's default account ID.
4275
+ * @returns The updated endpoint:
4276
+ * ```jsonc
4277
+ * {
4278
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4279
+ * "name": "ERP",
4280
+ * "url": "https://example.com/webhooks/assinafy",
4281
+ * "email": "ops@example.com",
4282
+ * "events": ["document_ready", "signer_signed_document"],
4283
+ * "is_active": true,
4284
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4285
+ * "created_at": "2026-10-01T12:00:00Z",
4286
+ * "updated_at": "2026-10-01T12:00:00Z"
4287
+ * }
4288
+ * ```
4289
+ * @throws {ValidationError} If `endpointId` is empty, the payload is empty
4290
+ * or malformed, or no account ID is available.
4291
+ * @throws {ApiError} `400` if another endpoint already uses `url`; `404` if
4292
+ * the endpoint does not exist.
4293
+ *
4294
+ * @example
4295
+ * ```ts
4296
+ * // Pause one endpoint without touching the others:
4297
+ * await client.webhooks.updateEndpoint(endpoint.id, { is_active: false });
4298
+ * ```
4299
+ */
4300
+ async updateEndpoint(endpointId, payload, accountId) {
4301
+ validateWebhookFields(payload, false);
4302
+ const path2 = this.endpointPath(endpointId, accountId);
4303
+ this.logger.info("Updating webhook endpoint");
4304
+ return this.call("Failed to update webhook endpoint", () => this.http.put(path2, payload));
4305
+ }
4306
+ /**
4307
+ * Stop delivering events to an endpoint and free its plan slot
4308
+ * (`DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}`). Its
4309
+ * delivery history is kept with `endpoint_id: null`. OAuth tokens need the
4310
+ * `webhooks:write` scope.
4311
+ *
4312
+ * @param endpointId - The endpoint ID.
4313
+ * @param accountId - Override the client's default account ID.
4314
+ * @returns Resolves once deleted (the API answers `{ "data": [] }`).
4315
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4316
+ * available.
4317
+ * @throws {ApiError} `404` if the endpoint does not exist.
4318
+ *
4319
+ * @example
4320
+ * ```ts
4321
+ * await client.webhooks.deleteEndpoint('65f1c2a9b3e4d5f60718293a4b5c6d7e');
4322
+ * ```
4323
+ */
4324
+ async deleteEndpoint(endpointId, accountId) {
4325
+ const path2 = this.endpointPath(endpointId, accountId);
4326
+ this.logger.info("Deleting webhook endpoint");
4327
+ await this.callVoid("Failed to delete webhook endpoint", () => this.http.delete(path2));
4328
+ }
4329
+ /**
4330
+ * Return the secret that signs deliveries to an endpoint
4331
+ * (`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret`).
4332
+ * Pass it to {@link AssinafyClient} as `webhookSecret` to verify deliveries
4333
+ * with `webhookVerifier.verifySignature()`. Not available to OAuth
4334
+ * applications; use an API key.
4335
+ *
4336
+ * @param endpointId - The endpoint ID.
4337
+ * @param accountId - Override the client's default account ID.
4338
+ * @returns The Standard Webhooks secret:
4339
+ * ```jsonc
4340
+ * { "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw" }
4341
+ * ```
4342
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4343
+ * available.
4344
+ * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4345
+ * if it does not exist.
4346
+ *
4347
+ * @example
4348
+ * ```ts
4349
+ * const { secret } = await client.webhooks.getEndpointSecret(endpoint.id);
4350
+ * // store `secret` with your other credentials, never in source control
4351
+ * ```
4352
+ */
4353
+ async getEndpointSecret(endpointId, accountId) {
4354
+ const path2 = `${this.endpointPath(endpointId, accountId)}/secret`;
4355
+ return this.call("Failed to fetch webhook endpoint secret", () => this.http.get(path2));
4356
+ }
4357
+ /**
4358
+ * Replace an endpoint's signing secret and return the new one
4359
+ * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`).
4360
+ * The old secret stops working immediately: deliveries sent after the
4361
+ * rotation are signed only with the new secret, so update the receiver at
4362
+ * once. Not available to OAuth applications; use an API key.
4363
+ *
4364
+ * @param endpointId - The endpoint ID.
4365
+ * @param accountId - Override the client's default account ID.
4366
+ * @returns The new secret:
4367
+ * ```jsonc
4368
+ * { "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==" }
4369
+ * ```
4370
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4371
+ * available.
4372
+ * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4373
+ * if it does not exist.
4374
+ *
4375
+ * @example
4376
+ * ```ts
4377
+ * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id);
4378
+ * await secretStore.put('assinafy-webhook-secret', secret);
4379
+ * ```
4380
+ */
4381
+ async rotateEndpointSecret(endpointId, accountId) {
4382
+ const path2 = `${this.endpointPath(endpointId, accountId)}/secret/rotate`;
4383
+ this.logger.info("Rotating webhook endpoint secret");
4384
+ return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2));
4385
+ }
4386
+ endpointsPath(accountId) {
4387
+ const id = this.pathSegment(this.accountId(accountId), "Account ID");
4388
+ return `/accounts/${id}/webhooks/endpoints`;
4389
+ }
4390
+ endpointPath(endpointId, accountId) {
4391
+ const eid = this.pathSegment(endpointId, "Endpoint ID");
4392
+ return `${this.endpointsPath(accountId)}/${eid}`;
4393
+ }
3932
4394
  };
4395
+ function withDefaultEvents(events) {
4396
+ return [...events && events.length > 0 ? events : DEFAULT_WEBHOOK_EVENTS];
4397
+ }
4398
+ function validateWebhookFields(payload, required) {
4399
+ if (!payload || typeof payload !== "object") {
4400
+ throw new ValidationError("Webhook payload is required");
4401
+ }
4402
+ if (!required && Object.values(payload).every((value) => value === void 0)) {
4403
+ throw new ValidationError("Webhook endpoint update must include at least one field");
4404
+ }
4405
+ if (required || payload.url !== void 0) validateWebhookUrl(payload.url);
4406
+ if ((required || payload.email !== void 0) && !isEmail(payload.email)) {
4407
+ throw new ValidationError("Webhook email must be a valid email address", {
4408
+ email: payload.email
4409
+ });
4410
+ }
4411
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event.trim()))) {
4412
+ throw new ValidationError("Webhook events must be an array of non-empty strings");
4413
+ }
4414
+ for (const key of ["is_active", "signing_enabled"]) {
4415
+ if (payload[key] !== void 0 && typeof payload[key] !== "boolean") {
4416
+ throw new ValidationError(`Webhook ${key} must be a boolean`);
4417
+ }
4418
+ }
4419
+ if (payload.name !== void 0 && typeof payload.name !== "string") {
4420
+ throw new ValidationError("Webhook name must be a string");
4421
+ }
4422
+ }
3933
4423
  function validateWebhookUrl(value) {
3934
4424
  let url;
3935
4425
  try {
3936
- url = new URL(value);
4426
+ url = new URL(value ?? "");
3937
4427
  } catch {
3938
4428
  throw new ValidationError("Webhook URL must be an absolute HTTP(S) URL", { url: value });
3939
4429
  }
@@ -4147,6 +4637,14 @@ var TemplateResource = class extends BaseResource {
4147
4637
  * `undefined` keys before sending. Unlike uploads, `name` here is a plain
4148
4638
  * display name and is **not** forced to end in `.pdf`.
4149
4639
  *
4640
+ * Request body (`application/json`):
4641
+ * ```jsonc
4642
+ * {
4643
+ * "name": "Service agreement.pdf",
4644
+ * "message": "Please sign this document."
4645
+ * }
4646
+ * ```
4647
+ *
4150
4648
  * @param templateId - The template to update.
4151
4649
  * @param payload - `name` and/or `message`; both optional.
4152
4650
  * @param accountId - Override the client's default account ID.
@@ -4327,6 +4825,14 @@ var TagResource = class extends BaseResource {
4327
4825
  * and `'ff8800'` both persist as `'ff8800'`. Omit `color`
4328
4826
  * (or pass `null`) for no color.
4329
4827
  *
4828
+ * Request body (`application/json`):
4829
+ * ```jsonc
4830
+ * {
4831
+ * "name": "Contracts",
4832
+ * "color": "ff8800"
4833
+ * }
4834
+ * ```
4835
+ *
4330
4836
  * @param payload - `name` (required, max 64 characters; trimmed with
4331
4837
  * internal whitespace collapsed) and optional `color`.
4332
4838
  * @param accountId - Override the client's default account ID.
@@ -4376,6 +4882,14 @@ var TagResource = class extends BaseResource {
4376
4882
  * leading `#` on `color` is accepted and stripped by the API
4377
4883
  * (`'#112233'` → `'112233'`).
4378
4884
  *
4885
+ * Request body (`application/json`):
4886
+ * ```jsonc
4887
+ * {
4888
+ * "name": "Signed contracts",
4889
+ * "color": null
4890
+ * }
4891
+ * ```
4892
+ *
4379
4893
  * @param tagId - The tag to update.
4380
4894
  * @param payload - `name` and/or `color`. `color: null` clears the color;
4381
4895
  * omit a field to leave it unchanged.
@@ -4534,6 +5048,14 @@ var AuthenticationResource = class extends BaseResource {
4534
5048
  * `X-Api-Key` (see {@link AuthenticationResource.createApiKey}) instead of
4535
5049
  * storing a password.
4536
5050
  *
5051
+ * Request body (`application/json`):
5052
+ * ```jsonc
5053
+ * {
5054
+ * "email": "user@example.com",
5055
+ * "password": "example-password"
5056
+ * }
5057
+ * ```
5058
+ *
4537
5059
  * @param email - The user's email address, e.g. `'user@example.com'`.
4538
5060
  * @param password - The user's password.
4539
5061
  * @returns An {@link ILoginResponse} with the access token, user, and
@@ -4564,6 +5086,9 @@ var AuthenticationResource = class extends BaseResource {
4564
5086
  * }
4565
5087
  * ```
4566
5088
  * @throws {ValidationError} If `email` or `password` is missing.
5089
+ * When the user has two-factor authentication enabled the response carries
5090
+ * an `mfa_token` instead of a usable session; finish with
5091
+ * {@link AuthenticationResource.verifyMfa}.
4567
5092
  * @throws {ApiError} `400` if the credentials are rejected.
4568
5093
  *
4569
5094
  * @example
@@ -4582,6 +5107,52 @@ var AuthenticationResource = class extends BaseResource {
4582
5107
  () => this.publicHttp.post("/login", { email, password })
4583
5108
  );
4584
5109
  }
5110
+ /**
5111
+ * Complete a two-factor login (`POST /authentication/mfa/verify`). Sent
5112
+ * without credentials.
5113
+ *
5114
+ * When the user has two-factor authentication enabled, `login()` returns
5115
+ * an `mfa_token`; exchange it here, within 5 minutes, for the session. The
5116
+ * challenge is single-use.
5117
+ *
5118
+ * Request body (`application/json`):
5119
+ * ```jsonc
5120
+ * {
5121
+ * "mfa_token": "<token from login>",
5122
+ * "code": "123456" // authenticator code, or a recovery code such as "ABCD-EFGH-JKMN"
5123
+ * }
5124
+ * ```
5125
+ *
5126
+ * @param mfaToken - The `mfa_token` returned by {@link AuthenticationResource.login}.
5127
+ * @param code - A 6-digit authenticator code or an unused recovery code.
5128
+ * @returns The same session as a password-only login:
5129
+ * ```jsonc
5130
+ * {
5131
+ * "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…",
5132
+ * "user": { "id": "md3j6p9w8b7y6qvqaoy5er42", "email": "user@example.com" },
5133
+ * "accounts": [{ "id": "acc_example", "name": "Empresa Exemplo", "roles": ["Owner"] }]
5134
+ * }
5135
+ * ```
5136
+ * @throws {ValidationError} If either argument is empty.
5137
+ * @throws {ApiError} `400` for an invalid or used code; `401` when the
5138
+ * challenge expired, was used, or too many codes were tried.
5139
+ *
5140
+ * @example
5141
+ * ```ts
5142
+ * let session = await client.auth.login('user@example.com', password);
5143
+ * if (session.mfa_token) {
5144
+ * session = await client.auth.verifyMfa(session.mfa_token, await promptForCode());
5145
+ * }
5146
+ * ```
5147
+ */
5148
+ async verifyMfa(mfaToken, code) {
5149
+ assertNonEmptyString(mfaToken, "mfa_token");
5150
+ assertNonEmptyString(code, "code");
5151
+ return this.call(
5152
+ "Two-factor verification failed",
5153
+ () => this.publicHttp.post("/authentication/mfa/verify", { mfa_token: mfaToken, code })
5154
+ );
5155
+ }
4585
5156
  /**
4586
5157
  * Log in with a social provider (`POST /authentication/social-login`).
4587
5158
  *
@@ -4589,6 +5160,15 @@ var AuthenticationResource = class extends BaseResource {
4589
5160
  * Assinafy JWT. Returns the same {@link ILoginResponse} shape as
4590
5161
  * {@link AuthenticationResource.login}.
4591
5162
  *
5163
+ * Request body (`application/json`):
5164
+ * ```jsonc
5165
+ * {
5166
+ * "provider": "google",
5167
+ * "token": "provider_token_example",
5168
+ * "has_accepted_terms": true
5169
+ * }
5170
+ * ```
5171
+ *
4592
5172
  * @param payload - The social-login body.
4593
5173
  * @param payload.provider - OAuth provider; currently exactly `'google'`.
4594
5174
  * @param payload.token - The provider-issued OAuth/ID token.
@@ -4663,6 +5243,14 @@ var AuthenticationResource = class extends BaseResource {
4663
5243
  * The response is the standard status/message acknowledgement with no data,
4664
5244
  * so this method resolves to `void`.
4665
5245
  *
5246
+ * Request body (`application/json`):
5247
+ * ```jsonc
5248
+ * {
5249
+ * "provider": "google",
5250
+ * "token": "provider_token_example"
5251
+ * }
5252
+ * ```
5253
+ *
4666
5254
  * @param payload - Social provider and provider-issued access/ID token.
4667
5255
  * @returns Resolves when the API acknowledges that the identity was linked.
4668
5256
  * @throws {ValidationError} If `provider` is not `google` or `token` is empty.
@@ -4699,6 +5287,13 @@ var AuthenticationResource = class extends BaseResource {
4699
5287
  * a masked value. Calling this again rotates the key, invalidating the
4700
5288
  * previous one.
4701
5289
  *
5290
+ * Request body (`application/json`):
5291
+ * ```jsonc
5292
+ * {
5293
+ * "password": "example-password"
5294
+ * }
5295
+ * ```
5296
+ *
4702
5297
  * @param password - The current user's password, required to authorize
4703
5298
  * key generation.
4704
5299
  * @returns An {@link IApiKeyResponse} containing the new key. Response
@@ -4786,6 +5381,15 @@ var AuthenticationResource = class extends BaseResource {
4786
5381
  * Requires the current password as a confirmation. On success the API
4787
5382
  * echoes back the affected `email`.
4788
5383
  *
5384
+ * Request body (`application/json`):
5385
+ * ```jsonc
5386
+ * {
5387
+ * "email": "user@example.com",
5388
+ * "password": "example-password",
5389
+ * "new_password": "new-example-password"
5390
+ * }
5391
+ * ```
5392
+ *
4789
5393
  * @param payload - The change-password body.
4790
5394
  * @param payload.email - The user's email address.
4791
5395
  * @param payload.password - The current password.
@@ -4832,6 +5436,13 @@ var AuthenticationResource = class extends BaseResource {
4832
5436
  * Triggers Assinafy to email a reset link/token to the given address.
4833
5437
  * Complete the flow with {@link AuthenticationResource.resetPassword}.
4834
5438
  *
5439
+ * Request body (`application/json`):
5440
+ * ```jsonc
5441
+ * {
5442
+ * "email": "user@example.com"
5443
+ * }
5444
+ * ```
5445
+ *
4835
5446
  * @param email - The email address to send the reset link to.
4836
5447
  * @returns `{ email }` — the address the reset link was sent to. Response
4837
5448
  * shape:
@@ -4863,6 +5474,15 @@ var AuthenticationResource = class extends BaseResource {
4863
5474
  * {@link AuthenticationResource.requestPasswordReset} and sets the new
4864
5475
  * password. On success the API echoes back the affected `email`.
4865
5476
  *
5477
+ * Request body (`application/json`):
5478
+ * ```jsonc
5479
+ * {
5480
+ * "email": "user@example.com",
5481
+ * "token": "reset_token_example",
5482
+ * "new_password": "new-example-password"
5483
+ * }
5484
+ * ```
5485
+ *
4866
5486
  * @param payload - The reset-password body.
4867
5487
  * @param payload.email - The user's email address.
4868
5488
  * @param payload.token - The reset token from the emailed link. The current
@@ -5085,8 +5705,8 @@ var OAuthResource = class extends BaseResource {
5085
5705
  * ```ts
5086
5706
  * const request = await client.oauth.createAuthorizationUrl({
5087
5707
  * clientId: process.env.ASSINAFY_CLIENT_ID!,
5088
- * redirectUri: 'https://myapp.com/oauth/callback',
5089
- * scopes: ['documents:read', 'documents:write', 'offline_access'],
5708
+ * redirectUri: 'https://myapp.example.com/oauth/callback',
5709
+ * scopes: ['documents:read', 'documents:write', 'account:read', 'offline_access'],
5090
5710
  * });
5091
5711
  * session.oauth = request;
5092
5712
  * response.redirect(request.url);
@@ -5173,8 +5793,8 @@ var OAuthResource = class extends BaseResource {
5173
5793
  * ```
5174
5794
  * @throws {ValidationError} If `state` is missing or does not match, `iss`
5175
5795
  * is absent or disagrees with the expected issuer, or a successful response
5176
- * carries no `code`. In every case the response is not yours — stop, do not
5177
- * exchange.
5796
+ * carries no `code`, or a protocol parameter appears more than once.
5797
+ * Reject such responses without exchanging the code.
5178
5798
  * @throws {OAuthError} If the server returned `error` (e.g.
5179
5799
  * `access_denied`, `invalid_scope`, `invalid_request`,
5180
5800
  * `unsupported_response_type`, `invalid_target`).
@@ -5187,9 +5807,9 @@ var OAuthResource = class extends BaseResource {
5187
5807
  * const tokens = await client.oauth.exchangeCode({
5188
5808
  * code,
5189
5809
  * codeVerifier: stored.codeVerifier,
5190
- * redirectUri: 'https://myapp.com/oauth/callback',
5810
+ * redirectUri: 'https://myapp.example.com/oauth/callback',
5191
5811
  * clientId: process.env.ASSINAFY_CLIENT_ID!,
5192
- * clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
5812
+ * clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
5193
5813
  * });
5194
5814
  * });
5195
5815
  * ```
@@ -5198,6 +5818,11 @@ var OAuthResource = class extends BaseResource {
5198
5818
  assertRecord(expected, "expected authorization request");
5199
5819
  assertNonEmptyString(expected.state, "expected.state");
5200
5820
  const query = toSearchParams(params);
5821
+ for (const key of ["state", "iss", "code", "error", "error_description"]) {
5822
+ if (query.getAll(key).length > 1) {
5823
+ throw new ValidationError(`OAuth callback must not repeat ${key}`);
5824
+ }
5825
+ }
5201
5826
  const state = query.get("state");
5202
5827
  if (state === null || !constantTimeEquals(state, expected.state)) {
5203
5828
  throw new ValidationError(
@@ -5234,6 +5859,12 @@ var OAuthResource = class extends BaseResource {
5234
5859
  * a browser. Every value must match the authorization request exactly, or
5235
5860
  * the API answers `invalid_grant`.
5236
5861
  *
5862
+ * Request body (`application/x-www-form-urlencoded`; omit `client_secret`
5863
+ * for public applications):
5864
+ * ```text
5865
+ * grant_type=authorization_code&code=code_example&redirect_uri=https%3A%2F%2Fmyapp.example.com%2Foauth%2Fcallback&client_id=client_example&client_secret=secret_example&code_verifier=dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk&resource=https%3A%2F%2Fapi.assinafy.com.br
5866
+ * ```
5867
+ *
5237
5868
  * @param options - Exchange options.
5238
5869
  * @param options.code - The code from
5239
5870
  * {@link OAuthResource.readAuthorizationCallback}.
@@ -5269,9 +5900,9 @@ var OAuthResource = class extends BaseResource {
5269
5900
  * const tokens = await client.oauth.exchangeCode({
5270
5901
  * code,
5271
5902
  * codeVerifier: session.oauth.codeVerifier,
5272
- * redirectUri: 'https://myapp.com/oauth/callback',
5903
+ * redirectUri: 'https://myapp.example.com/oauth/callback',
5273
5904
  * clientId: process.env.ASSINAFY_CLIENT_ID!,
5274
- * clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
5905
+ * clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
5275
5906
  * });
5276
5907
  * ```
5277
5908
  */
@@ -5307,6 +5938,12 @@ var OAuthResource = class extends BaseResource {
5307
5938
  * only expires if it goes 30 days without a refresh; after that the user
5308
5939
  * has to reconnect.
5309
5940
  *
5941
+ * Request body (`application/x-www-form-urlencoded`; omit `client_secret`
5942
+ * for public applications):
5943
+ * ```text
5944
+ * grant_type=refresh_token&refresh_token=refresh_token_example&client_id=client_example&client_secret=secret_example&resource=https%3A%2F%2Fapi.assinafy.com.br
5945
+ * ```
5946
+ *
5310
5947
  * @param options - Refresh options.
5311
5948
  * @param options.refreshToken - The current refresh token.
5312
5949
  * @param options.clientId - The application's `client_id`.
@@ -5337,7 +5974,7 @@ var OAuthResource = class extends BaseResource {
5337
5974
  * const tokens = await client.oauth.refreshToken({
5338
5975
  * refreshToken: connection.refreshToken,
5339
5976
  * clientId: process.env.ASSINAFY_CLIENT_ID!,
5340
- * clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
5977
+ * clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
5341
5978
  * });
5342
5979
  * await connection.save({ refreshToken: tokens.refresh_token });
5343
5980
  * ```
@@ -5391,7 +6028,7 @@ var OAuthResource = class extends BaseResource {
5391
6028
  * token: connection.refreshToken,
5392
6029
  * tokenTypeHint: 'refresh_token',
5393
6030
  * clientId: process.env.ASSINAFY_CLIENT_ID!,
5394
- * clientSecret: process.env.ASSINAFY_CLIENT_SECRET,
6031
+ * clientSecret: process.env.ASSINAFY_CLIENT_SECRET!,
5395
6032
  * });
5396
6033
  * ```
5397
6034
  */
@@ -5434,8 +6071,8 @@ var OAuthResource = class extends BaseResource {
5434
6071
  * "email_verified": true
5435
6072
  * }
5436
6073
  * ```
5437
- * `sub` is the stable user identifier; the rest are `null` when their scope
5438
- * was not granted.
6074
+ * `sub` is the stable user identifier; other claims may be omitted or
6075
+ * `null` when their scope was not granted.
5439
6076
  * @throws {ValidationError} If `accessToken` is supplied but empty.
5440
6077
  * @throws {ApiError} `401` when the token is missing, expired or revoked;
5441
6078
  * `403` when the `openid` scope was not granted — its `WWW-Authenticate`
@@ -5605,8 +6242,9 @@ function toSearchParams(params) {
5605
6242
  assertRecord(params, "callback parameters");
5606
6243
  const search = new URLSearchParams();
5607
6244
  for (const [key, value] of Object.entries(params)) {
5608
- const first = Array.isArray(value) ? value[0] : value;
5609
- if (typeof first === "string") search.set(key, first);
6245
+ for (const item of Array.isArray(value) ? value : [value]) {
6246
+ if (typeof item === "string") search.append(key, item);
6247
+ }
5610
6248
  }
5611
6249
  return search;
5612
6250
  }
@@ -5616,6 +6254,17 @@ var FieldsResource = class extends BaseResource {
5616
6254
  /**
5617
6255
  * Create a field definition (`POST /accounts/{accountId}/fields`).
5618
6256
  *
6257
+ * Request body (`application/json`):
6258
+ * ```jsonc
6259
+ * {
6260
+ * "type": "text",
6261
+ * "name": "Reference",
6262
+ * "regex": null,
6263
+ * "is_required": true,
6264
+ * "is_active": true
6265
+ * }
6266
+ * ```
6267
+ *
5619
6268
  * @param payload - The field to create. `type` and `name` are required;
5620
6269
  * `type` must be one of the platform field types (see
5621
6270
  * {@link FieldsResource.listTypes}); `regex` may be a string or `null`,
@@ -5760,6 +6409,15 @@ var FieldsResource = class extends BaseResource {
5760
6409
  * Update a field definition
5761
6410
  * (`PUT /accounts/{accountId}/fields/{fieldId}`).
5762
6411
  *
6412
+ * Request body (`application/json`):
6413
+ * ```jsonc
6414
+ * {
6415
+ * "name": "Customer reference",
6416
+ * "regex": null,
6417
+ * "is_active": true
6418
+ * }
6419
+ * ```
6420
+ *
5763
6421
  * @param fieldId - The field definition to update.
5764
6422
  * @param payload - Fields are `name`, nullable `regex`, and `is_active`;
5765
6423
  * `type` and `is_required` are compatibility extensions.
@@ -5848,6 +6506,13 @@ var FieldsResource = class extends BaseResource {
5848
6506
  * `signerAccessCode` is a compatibility query and is sent as
5849
6507
  * `signer-access-code` when supplied.
5850
6508
  *
6509
+ * Request body (`application/json`):
6510
+ * ```jsonc
6511
+ * {
6512
+ * "value": "Example value"
6513
+ * }
6514
+ * ```
6515
+ *
5851
6516
  * @param fieldId - The field definition to validate against.
5852
6517
  * @param value - The value to check (validated against the field's
5853
6518
  * type/regex). Sent as `{ value }` in the request body.
@@ -5900,6 +6565,16 @@ var FieldsResource = class extends BaseResource {
5900
6565
  * same compatibility extension described on
5901
6566
  * {@link FieldsResource.validate}.
5902
6567
  *
6568
+ * Request body (`application/json`):
6569
+ * ```jsonc
6570
+ * [
6571
+ * {
6572
+ * "field_id": "field_example",
6573
+ * "value": "Example value"
6574
+ * }
6575
+ * ]
6576
+ * ```
6577
+ *
5903
6578
  * @param entries - Non-empty array of `{ field_id, value }` pairs.
5904
6579
  * @param options - Account override and optional legacy `signerAccessCode`.
5905
6580
  * @returns One validation result per entry. Response shape:
@@ -6227,6 +6902,15 @@ var SignerDocumentsResource = class extends BaseResource {
6227
6902
  * The `document_ids` array goes in the request body; the access code
6228
6903
  * authenticates via the `signer-access-code` query param.
6229
6904
  *
6905
+ * Request body (`application/json`):
6906
+ * ```jsonc
6907
+ * {
6908
+ * "document_ids": [
6909
+ * "document_example"
6910
+ * ]
6911
+ * }
6912
+ * ```
6913
+ *
6230
6914
  * @param documentIds - Non-empty array of document IDs to sign.
6231
6915
  * @param signerAccessCode - The signer's access code, from their signing link.
6232
6916
  * @returns Resolves when the API acknowledges the operation. The documented
@@ -6266,6 +6950,16 @@ var SignerDocumentsResource = class extends BaseResource {
6266
6950
  * Both `document_ids` and `decline_reason` go in the request body; the access
6267
6951
  * code authenticates via the `signer-access-code` query param.
6268
6952
  *
6953
+ * Request body (`application/json`):
6954
+ * ```jsonc
6955
+ * {
6956
+ * "document_ids": [
6957
+ * "document_example"
6958
+ * ],
6959
+ * "decline_reason": "The document needs a correction."
6960
+ * }
6961
+ * ```
6962
+ *
6269
6963
  * @param documentIds - Non-empty array of document IDs to decline.
6270
6964
  * @param declineReason - Free-text reason shown to the sender (required).
6271
6965
  * @param signerAccessCode - The signer's access code, from their signing link.
@@ -6381,6 +7075,13 @@ var SignerDocumentsResource = class extends BaseResource {
6381
7075
  * **body carries only `verification-code`** (putting the access code in the
6382
7076
  * body leaves the request unauthenticated → `401`).
6383
7077
  *
7078
+ * Request body (`application/json`):
7079
+ * ```jsonc
7080
+ * {
7081
+ * "verification-code": "123456"
7082
+ * }
7083
+ * ```
7084
+ *
6384
7085
  * @param payload - `signerAccessCode` (the signing-link code) and
6385
7086
  * `verificationCode` (the OTP the signer received).
6386
7087
  * @returns Resolves when the API acknowledges the operation. The response
@@ -6599,6 +7300,18 @@ var SignerDocumentsResource = class extends BaseResource {
6599
7300
  * first. Digital Certificate signers cannot use this endpoint; use the
6600
7301
  * certificate start/complete API flow instead.
6601
7302
  *
7303
+ * Request body (`application/json`):
7304
+ * ```jsonc
7305
+ * [
7306
+ * {
7307
+ * "itemId": "item_example",
7308
+ * "fieldId": "field_example",
7309
+ * "pageId": "page_example",
7310
+ * "value": "Example Signer"
7311
+ * }
7312
+ * ]
7313
+ * ```
7314
+ *
6602
7315
  * @param documentId - The document being signed.
6603
7316
  * @param assignmentId - The assignment within that document.
6604
7317
  * @param signerAccessCode - The signer's access code, from their signing link.
@@ -6656,6 +7369,13 @@ var SignerDocumentsResource = class extends BaseResource {
6656
7369
  * delete the document via `documents.delete`; there is no workspace "cancel"
6657
7370
  * endpoint.)
6658
7371
  *
7372
+ * Request body (`application/json`):
7373
+ * ```jsonc
7374
+ * {
7375
+ * "decline_reason": "The document needs a correction."
7376
+ * }
7377
+ * ```
7378
+ *
6659
7379
  * @param documentId - The document being declined.
6660
7380
  * @param assignmentId - The assignment within that document.
6661
7381
  * @param signerAccessCode - The signer's access code, from their signing link.
@@ -6842,6 +7562,21 @@ var UserResource = class extends BaseResource {
6842
7562
  * (`PUT /users/self/notification-preferences`). Omitted keys retain their
6843
7563
  * current values; account/security e-mails are not configurable here.
6844
7564
  *
7565
+ * Request body (`application/json`):
7566
+ * ```jsonc
7567
+ * {
7568
+ * "DocumentCompleted": true,
7569
+ * "SignerDeclined": true,
7570
+ * "DocumentCancelled": true,
7571
+ * "DocumentAboutToExpire": true,
7572
+ * "DocumentExpired": true,
7573
+ * "DocumentExpirationReset": true,
7574
+ * "DocumentProcessingFailed": true,
7575
+ * "TemplateProcessingFailed": true,
7576
+ * "SignerWhatsappFailed": true
7577
+ * }
7578
+ * ```
7579
+ *
6845
7580
  * @param preferences - One or more of the nine documented keys, each with
6846
7581
  * a boolean value. Request example:
6847
7582
  * ```json
@@ -6881,7 +7616,186 @@ var UserResource = class extends BaseResource {
6881
7616
  () => this.http.put("/users/self/notification-preferences", preferences)
6882
7617
  );
6883
7618
  }
7619
+ /**
7620
+ * List the user's enrolled two-factor methods (`GET /users/self/mfa`).
7621
+ *
7622
+ * @returns Methods and unused recovery-code count:
7623
+ * ```jsonc
7624
+ * {
7625
+ * "methods": [
7626
+ * {
7627
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7628
+ * "type": "Totp",
7629
+ * "label": "My phone",
7630
+ * "confirmed_at": "2026-09-09T14:21:03Z",
7631
+ * "last_used_at": "2026-09-09T18:02:44Z"
7632
+ * }
7633
+ * ],
7634
+ * "recovery_codes_remaining": 8
7635
+ * }
7636
+ * ```
7637
+ * @throws {ApiError} `401` when credentials are missing or invalid.
7638
+ *
7639
+ * @example
7640
+ * ```ts
7641
+ * const { methods } = await client.users.getMfa();
7642
+ * const enabled = methods.some((method) => method.confirmed_at !== null);
7643
+ * ```
7644
+ */
7645
+ async getMfa() {
7646
+ return this.call(
7647
+ "Failed to fetch two-factor methods",
7648
+ () => this.http.get("/users/self/mfa")
7649
+ );
7650
+ }
7651
+ /**
7652
+ * Start authenticator-app enrollment (`POST /users/self/mfa/totp`).
7653
+ * Two-factor authentication is not active until
7654
+ * {@link UserResource.confirmTotpEnrollment} succeeds.
7655
+ *
7656
+ * Request body (`application/json`): `{ "label": "My phone" }` (optional).
7657
+ *
7658
+ * @param label - Optional name for the device.
7659
+ * @returns The pending enrollment. `secret` is returned only here:
7660
+ * ```jsonc
7661
+ * {
7662
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7663
+ * "secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
7664
+ * "provisioning_uri": "otpauth://totp/user%40example.com?issuer=Assinafy&secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
7665
+ * }
7666
+ * ```
7667
+ * @throws {ValidationError} If `label` is not a string.
7668
+ * @throws {ApiError} `401` when credentials are missing or invalid.
7669
+ *
7670
+ * @example
7671
+ * ```ts
7672
+ * const enrollment = await client.users.startTotpEnrollment('My phone');
7673
+ * showQrCode(enrollment.provisioning_uri);
7674
+ * ```
7675
+ */
7676
+ async startTotpEnrollment(label) {
7677
+ if (label !== void 0 && typeof label !== "string") {
7678
+ throw new ValidationError("label must be a string");
7679
+ }
7680
+ return this.call(
7681
+ "Failed to start authenticator enrollment",
7682
+ () => this.http.post("/users/self/mfa/totp", label === void 0 ? {} : { label })
7683
+ );
7684
+ }
7685
+ /**
7686
+ * Activate an authenticator with a live code from the new device
7687
+ * (`PUT /users/self/mfa/totp/confirm`). From then on every login needs a
7688
+ * second factor.
7689
+ *
7690
+ * Replacing an already confirmed authenticator soft-deletes the old one,
7691
+ * reissues recovery codes, and additionally requires `password` or
7692
+ * `reauth_code`. First-time enrollment needs neither.
7693
+ *
7694
+ * Request body (`application/json`):
7695
+ * ```jsonc
7696
+ * {
7697
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7698
+ * "code": "123456", // from the NEW device
7699
+ * "password": "example-pass", // only when replacing; or:
7700
+ * "reauth_code": "654321" // code from the CURRENT device, or a recovery code
7701
+ * }
7702
+ * ```
7703
+ *
7704
+ * @param payload - Enrollment `id`, new-device `code`, and re-authentication
7705
+ * when replacing a method.
7706
+ * @returns The recovery codes, shown only once:
7707
+ * ```jsonc
7708
+ * {
7709
+ * "recovery_codes": ["ABCD-EFGH-JKMN", "PQRS-TUVW-XYZ2"] // ten in total
7710
+ * }
7711
+ * ```
7712
+ * @throws {ValidationError} If `id` or `code` is empty.
7713
+ * @throws {ApiError} `400` for a wrong code or missing re-authentication;
7714
+ * `404` for an unknown enrollment.
7715
+ *
7716
+ * @example
7717
+ * ```ts
7718
+ * const { recovery_codes } = await client.users.confirmTotpEnrollment({
7719
+ * id: enrollment.id,
7720
+ * code: '123456',
7721
+ * });
7722
+ * ```
7723
+ */
7724
+ async confirmTotpEnrollment(payload) {
7725
+ assertRecord(payload, "payload");
7726
+ assertNonEmptyString(payload.id, "id");
7727
+ assertNonEmptyString(payload.code, "code");
7728
+ return this.call(
7729
+ "Failed to confirm authenticator enrollment",
7730
+ () => this.http.put("/users/self/mfa/totp/confirm", payload)
7731
+ );
7732
+ }
7733
+ /**
7734
+ * Issue ten fresh recovery codes and invalidate the previous set
7735
+ * (`POST /users/self/mfa/recovery-codes`).
7736
+ *
7737
+ * Request body (`application/json`): `{ "password": "…" }` or
7738
+ * `{ "code": "123456" }`.
7739
+ *
7740
+ * @param proof - Current password, or a live authenticator / recovery code.
7741
+ * @returns The new codes, shown only once:
7742
+ * ```jsonc
7743
+ * {
7744
+ * "recovery_codes": ["ABCD-EFGH-JKMN", "PQRS-TUVW-XYZ2"] // ten in total
7745
+ * }
7746
+ * ```
7747
+ * @throws {ValidationError} If neither `password` nor `code` is given.
7748
+ * @throws {ApiError} `400` when the proof is rejected.
7749
+ *
7750
+ * @example
7751
+ * ```ts
7752
+ * const { recovery_codes } = await client.users.regenerateRecoveryCodes({ code: '123456' });
7753
+ * ```
7754
+ */
7755
+ async regenerateRecoveryCodes(proof) {
7756
+ validateReauth(proof);
7757
+ return this.call(
7758
+ "Failed to regenerate recovery codes",
7759
+ () => this.http.post("/users/self/mfa/recovery-codes", proof)
7760
+ );
7761
+ }
7762
+ /**
7763
+ * Remove an enrolled two-factor method (`DELETE /users/self/mfa/{id}`).
7764
+ * Removing the last method also discards the recovery codes.
7765
+ *
7766
+ * Request body (`application/json`): `{ "password": "…" }` or
7767
+ * `{ "code": "123456" }`.
7768
+ *
7769
+ * @param methodId - The method ID from {@link UserResource.getMfa}.
7770
+ * @param proof - Current password, or a live authenticator / recovery code.
7771
+ * @returns Whether two-factor authentication is still on:
7772
+ * ```jsonc
7773
+ * { "is_mfa_enabled": false }
7774
+ * ```
7775
+ * @throws {ValidationError} If `methodId` is empty or no proof is given.
7776
+ * @throws {ApiError} `400` when the proof is rejected; `404` for an unknown
7777
+ * method.
7778
+ *
7779
+ * @example
7780
+ * ```ts
7781
+ * await client.users.deleteMfaMethod(method.id, { password });
7782
+ * ```
7783
+ */
7784
+ async deleteMfaMethod(methodId, proof) {
7785
+ const id = this.pathSegment(methodId, "Method ID");
7786
+ validateReauth(proof);
7787
+ return this.call(
7788
+ "Failed to remove two-factor method",
7789
+ () => this.http.delete(`/users/self/mfa/${id}`, { data: proof })
7790
+ );
7791
+ }
6884
7792
  };
7793
+ function validateReauth(proof) {
7794
+ assertRecord(proof, "proof");
7795
+ if (![proof.password, proof.code].some((value) => typeof value === "string" && value.trim())) {
7796
+ throw new ValidationError("password or code is required");
7797
+ }
7798
+ }
6885
7799
  var NOTIFICATION_PREFERENCE_KEYS = /* @__PURE__ */ new Set([
6886
7800
  "DocumentCompleted",
6887
7801
  "SignerDeclined",
@@ -6911,24 +7825,73 @@ function validateNotificationPreferences(preferences) {
6911
7825
 
6912
7826
  // src/support/webhook-verifier.ts
6913
7827
  import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
7828
+ var DEFAULT_TOLERANCE_SECONDS = 300;
6914
7829
  var WebhookVerifier = class {
6915
7830
  webhookSecret;
6916
7831
  /**
6917
- * Create an opt-in verifier for a gateway-defined HMAC convention.
6918
- *
6919
- * @param webhookSecret - Shared secret configured in both the trusted
6920
- * gateway and this process. Omit it to keep verification disabled.
7832
+ * @param webhookSecret - The endpoint's `whsec_…` secret from
7833
+ * `webhooks.getEndpointSecret()`. Omit it to keep verification disabled
7834
+ * (every check returns `false`).
6921
7835
  *
6922
7836
  * @example
6923
7837
  * ```ts
6924
- * const verifier = new WebhookVerifier(process.env.WEBHOOK_SHARED_SECRET);
7838
+ * const verifier = new WebhookVerifier(process.env.ASSINAFY_WEBHOOK_SECRET);
6925
7839
  * ```
6926
7840
  */
6927
7841
  constructor(webhookSecret) {
6928
7842
  this.webhookSecret = webhookSecret;
6929
7843
  }
6930
7844
  /**
6931
- * Compare a hexadecimal HMAC-SHA256 digest with the raw request body.
7845
+ * Verify a signed delivery: the Standard Webhooks signature over the raw
7846
+ * body, and a `webhook-timestamp` within `toleranceSeconds` of this
7847
+ * machine's clock (replay protection).
7848
+ *
7849
+ * @param payload - Exact, unparsed request bytes (or their UTF-8 string).
7850
+ * Re-serialized JSON will not match.
7851
+ * @param headers - Request headers: a Node/Express header object
7852
+ * (lowercase keys) or a Fetch `Headers`. Reads `webhook-id`,
7853
+ * `webhook-timestamp` and `webhook-signature`.
7854
+ * @param toleranceSeconds - Accepted clock distance. Defaults to `300`.
7855
+ * @returns `true` only when a signature entry matches (constant-time) and
7856
+ * the timestamp is fresh; `false` when verification is disabled, a header
7857
+ * is missing, or anything does not match.
7858
+ *
7859
+ * @example
7860
+ * ```ts
7861
+ * app.post('/webhooks/assinafy', express.raw({ type: 'application/json' }), (req, res) => {
7862
+ * if (!client.webhookVerifier.verifySignature(req.body, req.headers)) {
7863
+ * return res.status(401).end();
7864
+ * }
7865
+ * const event = client.webhookVerifier.extractEvent(req.body);
7866
+ * // deduplicate on req.headers['webhook-id'], then process
7867
+ * res.status(204).end();
7868
+ * });
7869
+ * ```
7870
+ */
7871
+ verifySignature(payload, headers, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS) {
7872
+ const key = decodeSecret(this.webhookSecret);
7873
+ if (!key || typeof payload !== "string" && !Buffer.isBuffer(payload) || !headers) {
7874
+ return false;
7875
+ }
7876
+ const id = header(headers, "webhook-id");
7877
+ const timestamp = header(headers, "webhook-timestamp");
7878
+ const signatures = header(headers, "webhook-signature");
7879
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
7880
+ if (Math.abs(Date.now() / 1e3 - Number(timestamp)) > toleranceSeconds) return false;
7881
+ const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(payload).digest();
7882
+ return signatures.split(" ").some((entry) => {
7883
+ const [version, signature] = entry.split(",", 2);
7884
+ if (version !== "v1" || !signature) return false;
7885
+ const actual = Buffer.from(signature, "base64");
7886
+ return actual.length === expected.length && timingSafeEqual2(actual, expected);
7887
+ });
7888
+ }
7889
+ /**
7890
+ * Compare a hexadecimal HMAC-SHA256 digest of the raw body, keyed with the
7891
+ * secret string as-is.
7892
+ *
7893
+ * @deprecated For gateways that apply their own HMAC convention. Assinafy's
7894
+ * own signatures are verified with {@link WebhookVerifier.verifySignature}.
6932
7895
  *
6933
7896
  * @param payload - Exact, unparsed request bytes (or their UTF-8 string).
6934
7897
  * @param signature - 64-character hexadecimal SHA-256 digest supplied by
@@ -7017,6 +7980,16 @@ var WebhookVerifier = class {
7017
7980
  return {};
7018
7981
  }
7019
7982
  };
7983
+ function decodeSecret(secret) {
7984
+ if (typeof secret !== "string" || !secret) return null;
7985
+ const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
7986
+ return key.length > 0 ? key : null;
7987
+ }
7988
+ function header(headers, name) {
7989
+ const value = typeof headers.get === "function" ? headers.get(name) : headers[name];
7990
+ const first = Array.isArray(value) ? value[0] : value;
7991
+ return typeof first === "string" ? first.trim() : void 0;
7992
+ }
7020
7993
  function isRecord(value) {
7021
7994
  return typeof value === "object" && value !== null && !Array.isArray(value);
7022
7995
  }