@assinafy/sdk 2.5.2 → 2.7.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
@@ -98,7 +98,7 @@ var ApiError = class _ApiError extends AssinafyError {
98
98
  const data = responseData ?? {};
99
99
  const rawMessage = data["message"];
100
100
  const rawError = data["error"];
101
- const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : FALLBACK_MESSAGE;
101
+ const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" && rawError.length > 0 ? rawError : FALLBACK_MESSAGE;
102
102
  return new _ApiError(message, statusCode, responseData);
103
103
  }
104
104
  };
@@ -395,15 +395,16 @@ function assertDocumentArtifactName(value) {
395
395
  }
396
396
  function serializeJsonRecord(value, label) {
397
397
  assertRecord(value, label);
398
+ let serialized;
398
399
  try {
399
- const serialized = JSON.stringify(value);
400
- if (typeof serialized !== "string" || !serialized.startsWith("{")) {
401
- throw new ValidationError(`${label} must serialize to a JSON object`);
402
- }
403
- return serialized;
400
+ serialized = JSON.stringify(value);
404
401
  } catch {
405
402
  throw new ValidationError(`${label} must be JSON-serializable`);
406
403
  }
404
+ if (typeof serialized !== "string" || !serialized.startsWith("{")) {
405
+ throw new ValidationError(`${label} must serialize to a JSON object`);
406
+ }
407
+ return serialized;
407
408
  }
408
409
  function assertDateTime(value, label) {
409
410
  if (typeof value !== "string") throw new ValidationError(`${label} must be an ISO-8601 date-time`);
@@ -591,7 +592,7 @@ import axios2 from "axios";
591
592
  // package.json
592
593
  var package_default = {
593
594
  name: "@assinafy/sdk",
594
- version: "2.5.2",
595
+ version: "2.7.0",
595
596
  packageManager: "bun@1.4.0",
596
597
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
597
598
  type: "commonjs",
@@ -1485,9 +1486,10 @@ var AssignmentResource = class extends BaseResource {
1485
1486
  * Update the expiration date of an existing assignment
1486
1487
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
1487
1488
  *
1488
- * Sends `{ expires_at }` verbatim. Use an ISO-8601 date/time string; `null`
1489
- * is retained as a compatibility value and, unlike ordinary nullable
1490
- * inputs, is intentionally not stripped from the body.
1489
+ * Sends `{ expires_at }` verbatim; the key itself is required by the
1490
+ * contract. Use an ISO-8601 date/time string, or `null` to remove the
1491
+ * expiration — `null` is the documented clear mechanism and, unlike
1492
+ * ordinary nullable inputs, is intentionally not stripped from the body.
1491
1493
  *
1492
1494
  * Request body (`application/json`):
1493
1495
  * ```jsonc
@@ -1498,8 +1500,8 @@ var AssignmentResource = class extends BaseResource {
1498
1500
  *
1499
1501
  * @param documentId - The document the assignment belongs to.
1500
1502
  * @param assignmentId - The assignment to update.
1501
- * @param expiresAt - New expiry as an ISO-8601 date/time string. `null` is
1502
- * a compatibility value intended to clear it.
1503
+ * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
1504
+ * to remove the expiration.
1503
1505
  * @returns The updated {@link IAssignment} — the same full shape
1504
1506
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
1505
1507
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -2971,7 +2973,7 @@ var SignerResource = class extends BaseResource {
2971
2973
  * "full_name": "Example Signer",
2972
2974
  * "email": "signer@example.com",
2973
2975
  * "whatsapp_phone_number": "+5548999990000",
2974
- * "cpf": "39053344705",
2976
+ * "government_id": "390.533.447-05",
2975
2977
  * "metadata": {
2976
2978
  * "reference": "customer_example"
2977
2979
  * }
@@ -2979,12 +2981,13 @@ var SignerResource = class extends BaseResource {
2979
2981
  * ```
2980
2982
  *
2981
2983
  * @param payload - The signer to create. The official fields are required
2982
- * `full_name` plus optional `email` and E.164 `whatsapp_phone_number`.
2983
- * `phone`, `cpf`, and `metadata` are compatibility extensions; the SDK
2984
- * normalizes the phone alias and strips non-digits from CPF before sending.
2984
+ * `full_name` plus optional `email`, E.164 `whatsapp_phone_number` and
2985
+ * `government_id` (CPF, or a CNPJ that may contain letters; the API strips
2986
+ * formatting). `phone`, `cpf`, and `metadata` are compatibility extensions;
2987
+ * the SDK normalizes the phone alias and strips non-digits from CPF.
2985
2988
  * @param accountId - Override the client's default account ID.
2986
- * @returns The created (or reused) signer. Note the response **never echoes
2987
- * `cpf` back**, even when one was sent:
2989
+ * @returns The created (or reused) signer. `government_id` comes back
2990
+ * normalized; `cpf` is **never echoed back**:
2988
2991
  * ```jsonc
2989
2992
  * {
2990
2993
  * "resource": "signer",
@@ -2992,6 +2995,7 @@ var SignerResource = class extends BaseResource {
2992
2995
  * "full_name": "Ana Souza",
2993
2996
  * "email": "ana@example.com",
2994
2997
  * "whatsapp_phone_number": null,
2998
+ * "government_id": "39053344705",
2995
2999
  * "has_accepted_terms": false
2996
3000
  * }
2997
3001
  * ```
@@ -3005,7 +3009,7 @@ var SignerResource = class extends BaseResource {
3005
3009
  * const signer = await client.signers.create({
3006
3010
  * full_name: 'Ana Souza',
3007
3011
  * email: 'ana@example.com',
3008
- * cpf: '390.533.447-05', // sent as '39053344705', never echoed back
3012
+ * government_id: '390.533.447-05', // returned as '39053344705'
3009
3013
  * });
3010
3014
  *
3011
3015
  * // A whatsapp-only signer (no email):
@@ -3064,6 +3068,7 @@ var SignerResource = class extends BaseResource {
3064
3068
  * "full_name": "Example Signer",
3065
3069
  * "email": "signer@example.com",
3066
3070
  * "whatsapp_phone_number": null,
3071
+ * "government_id": "12ABC34501DE35",
3067
3072
  * "has_accepted_terms": false
3068
3073
  * }
3069
3074
  * ```
@@ -3135,13 +3140,14 @@ var SignerResource = class extends BaseResource {
3135
3140
  * "full_name": "Example Signer",
3136
3141
  * "email": "signer@example.com",
3137
3142
  * "whatsapp_phone_number": "+5548999990000",
3138
- * "government_id": "39053344705"
3143
+ * "government_id": "12.ABC.345/01DE-35"
3139
3144
  * }
3140
3145
  * ```
3141
3146
  *
3142
3147
  * @param signerId - The signer to update.
3143
- * @param payload - Fields to change. The official `government_id` field and
3144
- * legacy `cpf` extension are stripped to digits before sending.
3148
+ * @param payload - Fields to change. `government_id` is sent as given (the
3149
+ * API normalizes it and keeps CNPJ letters); the legacy `cpf` extension is
3150
+ * stripped to digits.
3145
3151
  * @param accountId - Override the client's default account ID.
3146
3152
  * @returns The updated signer (as with create, `cpf` is never echoed back):
3147
3153
  * ```jsonc
@@ -3151,6 +3157,7 @@ var SignerResource = class extends BaseResource {
3151
3157
  * "full_name": "Ana Souza Lima",
3152
3158
  * "email": "ana@example.com",
3153
3159
  * "whatsapp_phone_number": null,
3160
+ * "government_id": "12ABC34501DE35",
3154
3161
  * "has_accepted_terms": false
3155
3162
  * }
3156
3163
  * ```
@@ -3277,6 +3284,7 @@ function validateCreateSignerPayload(payload) {
3277
3284
  validateOptionalPhone(phone);
3278
3285
  if (payload.metadata !== void 0) serializeJsonRecord(payload.metadata, "metadata");
3279
3286
  validateOptionalDigits(payload.cpf, "cpf");
3287
+ validateOptionalDigits(payload.government_id, "government_id");
3280
3288
  }
3281
3289
  function validateUpdateSignerPayload(payload) {
3282
3290
  if (!payload || typeof payload !== "object") {
@@ -3325,8 +3333,8 @@ function normaliseSignerPayload(payload) {
3325
3333
  if (payload.cpf) {
3326
3334
  normalised["cpf"] = payload.cpf.replace(/\D/g, "");
3327
3335
  }
3328
- if ("government_id" in payload && payload.government_id) {
3329
- normalised["government_id"] = payload.government_id.replace(/\D/g, "");
3336
+ if (payload.government_id) {
3337
+ normalised["government_id"] = payload.government_id.trim();
3330
3338
  }
3331
3339
  if ("metadata" in payload && payload.metadata !== void 0) {
3332
3340
  normalised["metadata"] = payload.metadata;
@@ -3786,9 +3794,9 @@ var DEFAULT_WEBHOOK_EVENTS = Object.freeze([
3786
3794
  ]);
3787
3795
  var WebhookResource = class extends BaseResource {
3788
3796
  /**
3789
- * Register (or replace) the workspace's single webhook subscription
3790
- * (`PUT /accounts/{accountId}/webhooks/subscriptions`). There is exactly one
3791
- * subscription per workspace, keyed by URL.
3797
+ * Update the account's oldest webhook endpoint, creating it if the account
3798
+ * has none (`PUT /accounts/{accountId}/webhooks/subscriptions`). Accounts
3799
+ * with several endpoints should use {@link WebhookResource.updateEndpoint}.
3792
3800
  *
3793
3801
  * When `events` is omitted or empty, {@link DEFAULT_WEBHOOK_EVENTS} is used
3794
3802
  * (`document_ready`, `document_prepared`, `signer_signed_document`,
@@ -3847,26 +3855,12 @@ var WebhookResource = class extends BaseResource {
3847
3855
  * ```
3848
3856
  */
3849
3857
  async register(payload, accountId) {
3850
- if (!payload || typeof payload !== "object") {
3851
- throw new ValidationError("Webhook subscription payload is required");
3852
- }
3853
- validateWebhookUrl(payload.url);
3854
- if (!isEmail(payload.email)) {
3855
- throw new ValidationError("Webhook email must be a valid email address", {
3856
- email: payload.email
3857
- });
3858
- }
3859
- if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event.trim()))) {
3860
- throw new ValidationError("Webhook events must be an array of non-empty strings");
3861
- }
3862
- if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
3863
- throw new ValidationError("Webhook is_active must be a boolean");
3864
- }
3858
+ validateWebhookFields(payload, true);
3865
3859
  const id = this.accountId(accountId);
3866
3860
  const body = {
3867
3861
  url: payload.url,
3868
3862
  email: payload.email,
3869
- events: [...payload.events && payload.events.length > 0 ? payload.events : DEFAULT_WEBHOOK_EVENTS],
3863
+ events: withDefaultEvents(payload.events),
3870
3864
  is_active: payload.is_active ?? true
3871
3865
  };
3872
3866
  this.logger.info("Registering webhook");
@@ -3879,8 +3873,9 @@ var WebhookResource = class extends BaseResource {
3879
3873
  );
3880
3874
  }
3881
3875
  /**
3882
- * Fetch the current webhook subscription
3883
- * (`GET /accounts/{accountId}/webhooks/subscriptions`).
3876
+ * Fetch the account's oldest webhook endpoint in the legacy subscription
3877
+ * shape (`GET /accounts/{accountId}/webhooks/subscriptions`). Accounts with
3878
+ * several endpoints should use {@link WebhookResource.listEndpoints}.
3884
3879
  *
3885
3880
  * @param accountId - Override the client's default account ID.
3886
3881
  * @returns The subscription, or `null` when the workspace has none (the API
@@ -3922,13 +3917,14 @@ var WebhookResource = class extends BaseResource {
3922
3917
  );
3923
3918
  }
3924
3919
  /**
3925
- * Inactivate the current webhook subscription
3926
- * (`PUT /accounts/{accountId}/webhooks/inactivate`).
3920
+ * Deactivate the account's oldest webhook endpoint
3921
+ * (`PUT /accounts/{accountId}/webhooks/inactivate`). Other endpoints are
3922
+ * unaffected; use {@link WebhookResource.updateEndpoint} with
3923
+ * `is_active: false` to target a specific one.
3927
3924
  *
3928
- * This is the only supported way to stop deliveries — the API has no
3929
- * subscription-delete route. The subscription is retained (with its `url`
3930
- * and `events`) and simply stops firing; re-enable it by calling
3931
- * {@link WebhookResource.register} again with `is_active: true`.
3925
+ * The endpoint is retained (with its `url` and `events`) and simply stops
3926
+ * firing; re-enable it by calling {@link WebhookResource.register} again
3927
+ * with `is_active: true`.
3932
3928
  * OAuth tokens need the `webhooks:write` scope.
3933
3929
  *
3934
3930
  * @param accountId - Override the client's default account ID.
@@ -4013,6 +4009,7 @@ var WebhookResource = class extends BaseResource {
4013
4009
  * truncated to 2,000 characters.
4014
4010
  *
4015
4011
  * @param params - Optional filters and pagination:
4012
+ * - `endpoint_id` — only deliveries to this webhook endpoint.
4016
4013
  * - `event` — restrict to a single {@link WebhookEventType}
4017
4014
  * (e.g. `'signer_signed_document'`).
4018
4015
  * - `delivered` — `true`/`false` to filter by delivery success.
@@ -4027,6 +4024,7 @@ var WebhookResource = class extends BaseResource {
4027
4024
  * "id": "103a09cfce51319dd3b3f72ffcdf",
4028
4025
  * "event": "signature_requested",
4029
4026
  * "activity_id": 8629,
4027
+ * "endpoint_id": "65f1c2a9b3e4d5f60718293a4b5c6d7e", // null once the endpoint is deleted
4030
4028
  * "endpoint": "https://example.com/hook",
4031
4029
  * "payload": {
4032
4030
  * // the full event body that was POSTed to `endpoint`:
@@ -4069,7 +4067,7 @@ var WebhookResource = class extends BaseResource {
4069
4067
  /**
4070
4068
  * Retry delivery of a specific webhook dispatch
4071
4069
  * (`POST /accounts/{accountId}/webhooks/{historyId}/retry`). Re-sends the
4072
- * original payload to the subscription's endpoint.
4070
+ * original payload to the endpoint that received it.
4073
4071
  *
4074
4072
  * @param dispatchId - The dispatch (delivery history) ID to re-send, as
4075
4073
  * returned by {@link WebhookResource.listDispatches}.
@@ -4083,6 +4081,7 @@ var WebhookResource = class extends BaseResource {
4083
4081
  * "id": "103a09cfce51319dd3b3f72ffcdf",
4084
4082
  * "event": "signature_requested",
4085
4083
  * "activity_id": 8629,
4084
+ * "endpoint_id": "65f1c2a9b3e4d5f60718293a4b5c6d7e", // null once the endpoint is deleted
4086
4085
  * "endpoint": "https://example.com/hook",
4087
4086
  * "payload": { }, // the original event body that was re-POSTed
4088
4087
  * "delivered": true,
@@ -4113,11 +4112,320 @@ var WebhookResource = class extends BaseResource {
4113
4112
  )
4114
4113
  );
4115
4114
  }
4115
+ /**
4116
+ * List the account's webhook endpoints, oldest first
4117
+ * (`GET /accounts/{accountId}/webhooks/endpoints`). OAuth tokens need the
4118
+ * `account:read` scope.
4119
+ *
4120
+ * @param accountId - Override the client's default account ID.
4121
+ * @returns Every endpoint (1 on free plans, up to 3 on paid plans):
4122
+ * ```jsonc
4123
+ * [
4124
+ * {
4125
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4126
+ * "name": "ERP",
4127
+ * "url": "https://example.com/webhooks/assinafy",
4128
+ * "email": "ops@example.com",
4129
+ * "events": ["document_ready", "signer_signed_document"],
4130
+ * "is_active": true,
4131
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4132
+ * "created_at": "2026-10-01T12:00:00Z",
4133
+ * "updated_at": "2026-10-01T12:00:00Z"
4134
+ * }
4135
+ * ]
4136
+ * ```
4137
+ * @throws {ValidationError} If no account ID is available.
4138
+ * @throws {ApiError} If the API rejects the request.
4139
+ *
4140
+ * @example
4141
+ * ```ts
4142
+ * const endpoints = await client.webhooks.listEndpoints();
4143
+ * const signed = endpoints.filter((endpoint) => endpoint.signing_enabled);
4144
+ * ```
4145
+ */
4146
+ async listEndpoints(accountId) {
4147
+ const path2 = this.endpointsPath(accountId);
4148
+ return this.call("Failed to list webhook endpoints", () => this.http.get(path2));
4149
+ }
4150
+ /**
4151
+ * Register a URL to receive the account's webhook events
4152
+ * (`POST /accounts/{accountId}/webhooks/endpoints`).
4153
+ *
4154
+ * An account can have 1 endpoint, or up to 3 on paid plans. Each endpoint
4155
+ * of a workspace needs a different `url`. With `signing_enabled: true` the
4156
+ * API generates a signing secret; read it with
4157
+ * {@link WebhookResource.getEndpointSecret}. When `events` is omitted or
4158
+ * empty, {@link DEFAULT_WEBHOOK_EVENTS} is sent. OAuth tokens need the
4159
+ * `webhooks:write` scope.
4160
+ *
4161
+ * Request body (`application/json`):
4162
+ * ```jsonc
4163
+ * {
4164
+ * "url": "https://example.com/webhooks/assinafy",
4165
+ * "email": "ops@example.com",
4166
+ * "events": ["document_ready", "signer_signed_document"],
4167
+ * "name": "ERP", // optional label
4168
+ * "is_active": true, // defaults to true
4169
+ * "signing_enabled": true // defaults to false
4170
+ * }
4171
+ * ```
4172
+ *
4173
+ * @param payload - Endpoint details. `url` (absolute HTTP(S)) and `email`
4174
+ * are required; `events`, `name`, `is_active` and `signing_enabled` are
4175
+ * optional.
4176
+ * @param accountId - Override the client's default account ID.
4177
+ * @returns The created endpoint:
4178
+ * ```jsonc
4179
+ * {
4180
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4181
+ * "name": "ERP",
4182
+ * "url": "https://example.com/webhooks/assinafy",
4183
+ * "email": "ops@example.com",
4184
+ * "events": ["document_ready", "signer_signed_document"],
4185
+ * "is_active": true,
4186
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4187
+ * "created_at": "2026-10-01T12:00:00Z",
4188
+ * "updated_at": "2026-10-01T12:00:00Z"
4189
+ * }
4190
+ * ```
4191
+ * @throws {ValidationError} If a field is malformed or no account ID is
4192
+ * available.
4193
+ * @throws {ApiError} `400` if another endpoint already uses `url`; `403`
4194
+ * when the plan's endpoint limit is reached or an OAuth token lacks
4195
+ * `webhooks:write`.
4196
+ *
4197
+ * @example
4198
+ * ```ts
4199
+ * const endpoint = await client.webhooks.createEndpoint({
4200
+ * name: 'ERP',
4201
+ * url: 'https://example.com/webhooks/assinafy',
4202
+ * email: 'ops@example.com',
4203
+ * events: ['document_ready', 'signer_signed_document'],
4204
+ * signing_enabled: true,
4205
+ * });
4206
+ * const { secret } = await client.webhooks.getEndpointSecret(endpoint.id);
4207
+ * ```
4208
+ */
4209
+ async createEndpoint(payload, accountId) {
4210
+ validateWebhookFields(payload, true);
4211
+ const path2 = this.endpointsPath(accountId);
4212
+ this.logger.info("Creating webhook endpoint");
4213
+ return this.call(
4214
+ "Failed to create webhook endpoint",
4215
+ () => this.http.post(path2, { ...payload, events: withDefaultEvents(payload.events) })
4216
+ );
4217
+ }
4218
+ /**
4219
+ * Retrieve one webhook endpoint
4220
+ * (`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}`). OAuth
4221
+ * tokens need the `account:read` scope.
4222
+ *
4223
+ * @param endpointId - The endpoint ID.
4224
+ * @param accountId - Override the client's default account ID.
4225
+ * @returns The endpoint:
4226
+ * ```jsonc
4227
+ * {
4228
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4229
+ * "name": "ERP",
4230
+ * "url": "https://example.com/webhooks/assinafy",
4231
+ * "email": "ops@example.com",
4232
+ * "events": ["document_ready", "signer_signed_document"],
4233
+ * "is_active": true,
4234
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4235
+ * "created_at": "2026-10-01T12:00:00Z",
4236
+ * "updated_at": "2026-10-01T12:00:00Z"
4237
+ * }
4238
+ * ```
4239
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4240
+ * available.
4241
+ * @throws {ApiError} `404` if the endpoint does not exist.
4242
+ *
4243
+ * @example
4244
+ * ```ts
4245
+ * const endpoint = await client.webhooks.getEndpoint('65f1c2a9b3e4d5f60718293a4b5c6d7e');
4246
+ * ```
4247
+ */
4248
+ async getEndpoint(endpointId, accountId) {
4249
+ const path2 = this.endpointPath(endpointId, accountId);
4250
+ return this.call("Failed to fetch webhook endpoint", () => this.http.get(path2));
4251
+ }
4252
+ /**
4253
+ * Change a webhook endpoint
4254
+ * (`PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}`). Only the
4255
+ * fields sent are updated; `url` cannot be one another endpoint of the
4256
+ * workspace already uses.
4257
+ *
4258
+ * `signing_enabled: true` generates a secret if the endpoint has none and
4259
+ * keeps the current one otherwise; `false` discards the secret. OAuth
4260
+ * tokens need the `webhooks:write` scope.
4261
+ *
4262
+ * Request body (`application/json`, every field optional):
4263
+ * ```jsonc
4264
+ * {
4265
+ * "url": "https://example.com/webhooks/assinafy",
4266
+ * "email": "ops@example.com",
4267
+ * "events": ["document_ready"],
4268
+ * "name": "ERP",
4269
+ * "is_active": false,
4270
+ * "signing_enabled": true
4271
+ * }
4272
+ * ```
4273
+ *
4274
+ * @param endpointId - The endpoint ID.
4275
+ * @param payload - Fields to change; at least one is required.
4276
+ * @param accountId - Override the client's default account ID.
4277
+ * @returns The updated endpoint:
4278
+ * ```jsonc
4279
+ * {
4280
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4281
+ * "name": "ERP",
4282
+ * "url": "https://example.com/webhooks/assinafy",
4283
+ * "email": "ops@example.com",
4284
+ * "events": ["document_ready", "signer_signed_document"],
4285
+ * "is_active": true,
4286
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4287
+ * "created_at": "2026-10-01T12:00:00Z",
4288
+ * "updated_at": "2026-10-01T12:00:00Z"
4289
+ * }
4290
+ * ```
4291
+ * @throws {ValidationError} If `endpointId` is empty, the payload is empty
4292
+ * or malformed, or no account ID is available.
4293
+ * @throws {ApiError} `400` if another endpoint already uses `url`; `404` if
4294
+ * the endpoint does not exist.
4295
+ *
4296
+ * @example
4297
+ * ```ts
4298
+ * // Pause one endpoint without touching the others:
4299
+ * await client.webhooks.updateEndpoint(endpoint.id, { is_active: false });
4300
+ * ```
4301
+ */
4302
+ async updateEndpoint(endpointId, payload, accountId) {
4303
+ validateWebhookFields(payload, false);
4304
+ const path2 = this.endpointPath(endpointId, accountId);
4305
+ this.logger.info("Updating webhook endpoint");
4306
+ return this.call("Failed to update webhook endpoint", () => this.http.put(path2, payload));
4307
+ }
4308
+ /**
4309
+ * Stop delivering events to an endpoint and free its plan slot
4310
+ * (`DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}`). Its
4311
+ * delivery history is kept with `endpoint_id: null`. OAuth tokens need the
4312
+ * `webhooks:write` scope.
4313
+ *
4314
+ * @param endpointId - The endpoint ID.
4315
+ * @param accountId - Override the client's default account ID.
4316
+ * @returns Resolves once deleted (the API answers `{ "data": [] }`).
4317
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4318
+ * available.
4319
+ * @throws {ApiError} `404` if the endpoint does not exist.
4320
+ *
4321
+ * @example
4322
+ * ```ts
4323
+ * await client.webhooks.deleteEndpoint('65f1c2a9b3e4d5f60718293a4b5c6d7e');
4324
+ * ```
4325
+ */
4326
+ async deleteEndpoint(endpointId, accountId) {
4327
+ const path2 = this.endpointPath(endpointId, accountId);
4328
+ this.logger.info("Deleting webhook endpoint");
4329
+ await this.callVoid("Failed to delete webhook endpoint", () => this.http.delete(path2));
4330
+ }
4331
+ /**
4332
+ * Return the secret that signs deliveries to an endpoint
4333
+ * (`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret`).
4334
+ * Pass it to {@link AssinafyClient} as `webhookSecret` to verify deliveries
4335
+ * with `webhookVerifier.verifySignature()`. Not available to OAuth
4336
+ * applications; use an API key.
4337
+ *
4338
+ * @param endpointId - The endpoint ID.
4339
+ * @param accountId - Override the client's default account ID.
4340
+ * @returns The Standard Webhooks secret:
4341
+ * ```jsonc
4342
+ * { "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw" }
4343
+ * ```
4344
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4345
+ * available.
4346
+ * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4347
+ * if it does not exist.
4348
+ *
4349
+ * @example
4350
+ * ```ts
4351
+ * const { secret } = await client.webhooks.getEndpointSecret(endpoint.id);
4352
+ * // store `secret` with your other credentials, never in source control
4353
+ * ```
4354
+ */
4355
+ async getEndpointSecret(endpointId, accountId) {
4356
+ const path2 = `${this.endpointPath(endpointId, accountId)}/secret`;
4357
+ return this.call("Failed to fetch webhook endpoint secret", () => this.http.get(path2));
4358
+ }
4359
+ /**
4360
+ * Replace an endpoint's signing secret and return the new one
4361
+ * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`).
4362
+ * The old secret stops working immediately: deliveries sent after the
4363
+ * rotation are signed only with the new secret, so update the receiver at
4364
+ * once. Not available to OAuth applications; use an API key.
4365
+ *
4366
+ * @param endpointId - The endpoint ID.
4367
+ * @param accountId - Override the client's default account ID.
4368
+ * @returns The new secret:
4369
+ * ```jsonc
4370
+ * { "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==" }
4371
+ * ```
4372
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4373
+ * available.
4374
+ * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4375
+ * if it does not exist.
4376
+ *
4377
+ * @example
4378
+ * ```ts
4379
+ * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id);
4380
+ * await secretStore.put('assinafy-webhook-secret', secret);
4381
+ * ```
4382
+ */
4383
+ async rotateEndpointSecret(endpointId, accountId) {
4384
+ const path2 = `${this.endpointPath(endpointId, accountId)}/secret/rotate`;
4385
+ this.logger.info("Rotating webhook endpoint secret");
4386
+ return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2));
4387
+ }
4388
+ endpointsPath(accountId) {
4389
+ const id = this.pathSegment(this.accountId(accountId), "Account ID");
4390
+ return `/accounts/${id}/webhooks/endpoints`;
4391
+ }
4392
+ endpointPath(endpointId, accountId) {
4393
+ const eid = this.pathSegment(endpointId, "Endpoint ID");
4394
+ return `${this.endpointsPath(accountId)}/${eid}`;
4395
+ }
4116
4396
  };
4397
+ function withDefaultEvents(events) {
4398
+ return [...events && events.length > 0 ? events : DEFAULT_WEBHOOK_EVENTS];
4399
+ }
4400
+ function validateWebhookFields(payload, required) {
4401
+ if (!payload || typeof payload !== "object") {
4402
+ throw new ValidationError("Webhook payload is required");
4403
+ }
4404
+ if (!required && Object.values(payload).every((value) => value === void 0)) {
4405
+ throw new ValidationError("Webhook endpoint update must include at least one field");
4406
+ }
4407
+ if (required || payload.url !== void 0) validateWebhookUrl(payload.url);
4408
+ if ((required || payload.email !== void 0) && !isEmail(payload.email)) {
4409
+ throw new ValidationError("Webhook email must be a valid email address", {
4410
+ email: payload.email
4411
+ });
4412
+ }
4413
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event.trim()))) {
4414
+ throw new ValidationError("Webhook events must be an array of non-empty strings");
4415
+ }
4416
+ for (const key of ["is_active", "signing_enabled"]) {
4417
+ if (payload[key] !== void 0 && typeof payload[key] !== "boolean") {
4418
+ throw new ValidationError(`Webhook ${key} must be a boolean`);
4419
+ }
4420
+ }
4421
+ if (payload.name !== void 0 && typeof payload.name !== "string") {
4422
+ throw new ValidationError("Webhook name must be a string");
4423
+ }
4424
+ }
4117
4425
  function validateWebhookUrl(value) {
4118
4426
  let url;
4119
4427
  try {
4120
- url = new URL(value);
4428
+ url = new URL(value ?? "");
4121
4429
  } catch {
4122
4430
  throw new ValidationError("Webhook URL must be an absolute HTTP(S) URL", { url: value });
4123
4431
  }
@@ -4442,7 +4750,7 @@ var TemplateResource = class extends BaseResource {
4442
4750
  * ```ts
4443
4751
  * const tmpl = await client.templates.get('103ad2171db7979468c3e97eb067');
4444
4752
  * const jpeg = await client.templates.downloadPage(tmpl.id, tmpl.pages[0].id);
4445
- * await fs.writeFile('page-1.jpg', jpeg);
4753
+ * await fs.promises.writeFile('page-1.jpg', jpeg);
4446
4754
  * ```
4447
4755
  */
4448
4756
  async downloadPage(templateId, pageId, accountId) {
@@ -4779,6 +5087,9 @@ var AuthenticationResource = class extends BaseResource {
4779
5087
  * ]
4780
5088
  * }
4781
5089
  * ```
5090
+ * When the user has two-factor authentication enabled the response carries
5091
+ * an `mfa_token` instead of a usable session; finish with
5092
+ * {@link AuthenticationResource.verifyMfa}.
4782
5093
  * @throws {ValidationError} If `email` or `password` is missing.
4783
5094
  * @throws {ApiError} `400` if the credentials are rejected.
4784
5095
  *
@@ -4798,6 +5109,52 @@ var AuthenticationResource = class extends BaseResource {
4798
5109
  () => this.publicHttp.post("/login", { email, password })
4799
5110
  );
4800
5111
  }
5112
+ /**
5113
+ * Complete a two-factor login (`POST /authentication/mfa/verify`). Sent
5114
+ * without credentials.
5115
+ *
5116
+ * When the user has two-factor authentication enabled, `login()` returns
5117
+ * an `mfa_token`; exchange it here, within 5 minutes, for the session. The
5118
+ * challenge is single-use.
5119
+ *
5120
+ * Request body (`application/json`):
5121
+ * ```jsonc
5122
+ * {
5123
+ * "mfa_token": "<token from login>",
5124
+ * "code": "123456" // authenticator code, or a recovery code such as "ABCD-EFGH-JKMN"
5125
+ * }
5126
+ * ```
5127
+ *
5128
+ * @param mfaToken - The `mfa_token` returned by {@link AuthenticationResource.login}.
5129
+ * @param code - A 6-digit authenticator code or an unused recovery code.
5130
+ * @returns The same session as a password-only login:
5131
+ * ```jsonc
5132
+ * {
5133
+ * "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…",
5134
+ * "user": { "id": "md3j6p9w8b7y6qvqaoy5er42", "email": "user@example.com" },
5135
+ * "accounts": [{ "id": "acc_example", "name": "Empresa Exemplo", "roles": ["Owner"] }]
5136
+ * }
5137
+ * ```
5138
+ * @throws {ValidationError} If either argument is empty.
5139
+ * @throws {ApiError} `400` for an invalid or used code; `401` when the
5140
+ * challenge expired, was used, or too many codes were tried.
5141
+ *
5142
+ * @example
5143
+ * ```ts
5144
+ * let session = await client.auth.login('user@example.com', password);
5145
+ * if (session.mfa_token) {
5146
+ * session = await client.auth.verifyMfa(session.mfa_token, await promptForCode());
5147
+ * }
5148
+ * ```
5149
+ */
5150
+ async verifyMfa(mfaToken, code) {
5151
+ assertNonEmptyString(mfaToken, "mfa_token");
5152
+ assertNonEmptyString(code, "code");
5153
+ return this.call(
5154
+ "Two-factor verification failed",
5155
+ () => this.publicHttp.post("/authentication/mfa/verify", { mfa_token: mfaToken, code })
5156
+ );
5157
+ }
4801
5158
  /**
4802
5159
  * Log in with a social provider (`POST /authentication/social-login`).
4803
5160
  *
@@ -4881,13 +5238,6 @@ var AuthenticationResource = class extends BaseResource {
4881
5238
  * Link a Google identity to the authenticated user
4882
5239
  * (`POST /auth/link-social-login`).
4883
5240
  *
4884
- * Request body:
4885
- * ```jsonc
4886
- * { "provider": "google", "token": "provider-issued-token" }
4887
- * ```
4888
- * The response is the standard status/message acknowledgement with no data,
4889
- * so this method resolves to `void`.
4890
- *
4891
5241
  * Request body (`application/json`):
4892
5242
  * ```jsonc
4893
5243
  * {
@@ -4895,6 +5245,8 @@ var AuthenticationResource = class extends BaseResource {
4895
5245
  * "token": "provider_token_example"
4896
5246
  * }
4897
5247
  * ```
5248
+ * The response is the standard status/message acknowledgement with no data,
5249
+ * so this method resolves to `void`.
4898
5250
  *
4899
5251
  * @param payload - Social provider and provider-issued access/ID token.
4900
5252
  * @returns Resolves when the API acknowledges that the identity was linked.
@@ -5651,6 +6003,11 @@ var OAuthResource = class extends BaseResource {
5651
6003
  * already-revoked included — so the endpoint cannot be used to probe
5652
6004
  * whether a token exists. Only failed client authentication returns `401`.
5653
6005
  *
6006
+ * Request body (`application/x-www-form-urlencoded`):
6007
+ * ```text
6008
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
6009
+ * ```
6010
+ *
5654
6011
  * @param options - Revocation options.
5655
6012
  * @param options.token - The access or refresh token to revoke.
5656
6013
  * @param options.clientId - The application's `client_id`.
@@ -5659,10 +6016,6 @@ var OAuthResource = class extends BaseResource {
5659
6016
  * @param options.tokenTypeHint - Optional `access_token` or
5660
6017
  * `refresh_token` hint that lets the server skip a lookup.
5661
6018
  * @returns Nothing; resolves once the API acknowledges the request.
5662
- * Request body (`application/x-www-form-urlencoded`):
5663
- * ```text
5664
- * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
5665
- * ```
5666
6019
  * @throws {ValidationError} If `token` or `clientId` is missing, or
5667
6020
  * `tokenTypeHint` is not one of the two documented values.
5668
6021
  * @throws {OAuthError} `invalid_client` when client authentication fails.
@@ -6517,7 +6870,7 @@ var SignerDocumentsResource = class extends BaseResource {
6517
6870
  * documentId,
6518
6871
  * 'original',
6519
6872
  * );
6520
- * await fs.writeFile('to-sign.pdf', pdf);
6873
+ * await fs.promises.writeFile('to-sign.pdf', pdf);
6521
6874
  * ```
6522
6875
  */
6523
6876
  async download(signerId, documentId, artifactName, signerAccessCode) {
@@ -6824,7 +7177,7 @@ var SignerDocumentsResource = class extends BaseResource {
6824
7177
  * @example
6825
7178
  * ```ts
6826
7179
  * const png = await client.signerDocuments.downloadSignature(accessCode, 'signature');
6827
- * await fs.writeFile('signature.png', png);
7180
+ * await fs.promises.writeFile('signature.png', png);
6828
7181
  * ```
6829
7182
  */
6830
7183
  async downloadSignature(signerAccessCode, imageType = "signature") {
@@ -7261,7 +7614,186 @@ var UserResource = class extends BaseResource {
7261
7614
  () => this.http.put("/users/self/notification-preferences", preferences)
7262
7615
  );
7263
7616
  }
7617
+ /**
7618
+ * List the user's enrolled two-factor methods (`GET /users/self/mfa`).
7619
+ *
7620
+ * @returns Methods and unused recovery-code count:
7621
+ * ```jsonc
7622
+ * {
7623
+ * "methods": [
7624
+ * {
7625
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7626
+ * "type": "Totp",
7627
+ * "label": "My phone",
7628
+ * "confirmed_at": "2026-09-09T14:21:03Z",
7629
+ * "last_used_at": "2026-09-09T18:02:44Z"
7630
+ * }
7631
+ * ],
7632
+ * "recovery_codes_remaining": 8
7633
+ * }
7634
+ * ```
7635
+ * @throws {ApiError} `401` when credentials are missing or invalid.
7636
+ *
7637
+ * @example
7638
+ * ```ts
7639
+ * const { methods } = await client.users.getMfa();
7640
+ * const enabled = methods.some((method) => method.confirmed_at !== null);
7641
+ * ```
7642
+ */
7643
+ async getMfa() {
7644
+ return this.call(
7645
+ "Failed to fetch two-factor methods",
7646
+ () => this.http.get("/users/self/mfa")
7647
+ );
7648
+ }
7649
+ /**
7650
+ * Start authenticator-app enrollment (`POST /users/self/mfa/totp`).
7651
+ * Two-factor authentication is not active until
7652
+ * {@link UserResource.confirmTotpEnrollment} succeeds.
7653
+ *
7654
+ * Request body (`application/json`): `{ "label": "My phone" }` (optional).
7655
+ *
7656
+ * @param label - Optional name for the device.
7657
+ * @returns The pending enrollment. `secret` is returned only here:
7658
+ * ```jsonc
7659
+ * {
7660
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7661
+ * "secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
7662
+ * "provisioning_uri": "otpauth://totp/user%40example.com?issuer=Assinafy&secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
7663
+ * }
7664
+ * ```
7665
+ * @throws {ValidationError} If `label` is not a string.
7666
+ * @throws {ApiError} `401` when credentials are missing or invalid.
7667
+ *
7668
+ * @example
7669
+ * ```ts
7670
+ * const enrollment = await client.users.startTotpEnrollment('My phone');
7671
+ * showQrCode(enrollment.provisioning_uri);
7672
+ * ```
7673
+ */
7674
+ async startTotpEnrollment(label) {
7675
+ if (label !== void 0 && typeof label !== "string") {
7676
+ throw new ValidationError("label must be a string");
7677
+ }
7678
+ return this.call(
7679
+ "Failed to start authenticator enrollment",
7680
+ () => this.http.post("/users/self/mfa/totp", label === void 0 ? {} : { label })
7681
+ );
7682
+ }
7683
+ /**
7684
+ * Activate an authenticator with a live code from the new device
7685
+ * (`PUT /users/self/mfa/totp/confirm`). From then on every login needs a
7686
+ * second factor.
7687
+ *
7688
+ * Replacing an already confirmed authenticator soft-deletes the old one,
7689
+ * reissues recovery codes, and additionally requires `password` or
7690
+ * `reauth_code`. First-time enrollment needs neither.
7691
+ *
7692
+ * Request body (`application/json`):
7693
+ * ```jsonc
7694
+ * {
7695
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7696
+ * "code": "123456", // from the NEW device
7697
+ * "password": "example-pass", // only when replacing; or:
7698
+ * "reauth_code": "654321" // code from the CURRENT device, or a recovery code
7699
+ * }
7700
+ * ```
7701
+ *
7702
+ * @param payload - Enrollment `id`, new-device `code`, and re-authentication
7703
+ * when replacing a method.
7704
+ * @returns The recovery codes, shown only once:
7705
+ * ```jsonc
7706
+ * {
7707
+ * "recovery_codes": ["ABCD-EFGH-JKMN", "PQRS-TUVW-XYZ2"] // ten in total
7708
+ * }
7709
+ * ```
7710
+ * @throws {ValidationError} If `id` or `code` is empty.
7711
+ * @throws {ApiError} `400` for a wrong code or missing re-authentication;
7712
+ * `404` for an unknown enrollment.
7713
+ *
7714
+ * @example
7715
+ * ```ts
7716
+ * const { recovery_codes } = await client.users.confirmTotpEnrollment({
7717
+ * id: enrollment.id,
7718
+ * code: '123456',
7719
+ * });
7720
+ * ```
7721
+ */
7722
+ async confirmTotpEnrollment(payload) {
7723
+ assertRecord(payload, "payload");
7724
+ assertNonEmptyString(payload.id, "id");
7725
+ assertNonEmptyString(payload.code, "code");
7726
+ return this.call(
7727
+ "Failed to confirm authenticator enrollment",
7728
+ () => this.http.put("/users/self/mfa/totp/confirm", payload)
7729
+ );
7730
+ }
7731
+ /**
7732
+ * Issue ten fresh recovery codes and invalidate the previous set
7733
+ * (`POST /users/self/mfa/recovery-codes`).
7734
+ *
7735
+ * Request body (`application/json`): `{ "password": "…" }` or
7736
+ * `{ "code": "123456" }`.
7737
+ *
7738
+ * @param proof - Current password, or a live authenticator / recovery code.
7739
+ * @returns The new codes, shown only once:
7740
+ * ```jsonc
7741
+ * {
7742
+ * "recovery_codes": ["ABCD-EFGH-JKMN", "PQRS-TUVW-XYZ2"] // ten in total
7743
+ * }
7744
+ * ```
7745
+ * @throws {ValidationError} If neither `password` nor `code` is given.
7746
+ * @throws {ApiError} `400` when the proof is rejected.
7747
+ *
7748
+ * @example
7749
+ * ```ts
7750
+ * const { recovery_codes } = await client.users.regenerateRecoveryCodes({ code: '123456' });
7751
+ * ```
7752
+ */
7753
+ async regenerateRecoveryCodes(proof) {
7754
+ validateReauth(proof);
7755
+ return this.call(
7756
+ "Failed to regenerate recovery codes",
7757
+ () => this.http.post("/users/self/mfa/recovery-codes", proof)
7758
+ );
7759
+ }
7760
+ /**
7761
+ * Remove an enrolled two-factor method (`DELETE /users/self/mfa/{id}`).
7762
+ * Removing the last method also discards the recovery codes.
7763
+ *
7764
+ * Request body (`application/json`): `{ "password": "…" }` or
7765
+ * `{ "code": "123456" }`.
7766
+ *
7767
+ * @param methodId - The method ID from {@link UserResource.getMfa}.
7768
+ * @param proof - Current password, or a live authenticator / recovery code.
7769
+ * @returns Whether two-factor authentication is still on:
7770
+ * ```jsonc
7771
+ * { "is_mfa_enabled": false }
7772
+ * ```
7773
+ * @throws {ValidationError} If `methodId` is empty or no proof is given.
7774
+ * @throws {ApiError} `400` when the proof is rejected; `404` for an unknown
7775
+ * method.
7776
+ *
7777
+ * @example
7778
+ * ```ts
7779
+ * await client.users.deleteMfaMethod(method.id, { password });
7780
+ * ```
7781
+ */
7782
+ async deleteMfaMethod(methodId, proof) {
7783
+ const id = this.pathSegment(methodId, "Method ID");
7784
+ validateReauth(proof);
7785
+ return this.call(
7786
+ "Failed to remove two-factor method",
7787
+ () => this.http.delete(`/users/self/mfa/${id}`, { data: proof })
7788
+ );
7789
+ }
7264
7790
  };
7791
+ function validateReauth(proof) {
7792
+ assertRecord(proof, "proof");
7793
+ if (![proof.password, proof.code].some((value) => typeof value === "string" && value.trim())) {
7794
+ throw new ValidationError("password or code is required");
7795
+ }
7796
+ }
7265
7797
  var NOTIFICATION_PREFERENCE_KEYS = /* @__PURE__ */ new Set([
7266
7798
  "DocumentCompleted",
7267
7799
  "SignerDeclined",
@@ -7291,24 +7823,73 @@ function validateNotificationPreferences(preferences) {
7291
7823
 
7292
7824
  // src/support/webhook-verifier.ts
7293
7825
  import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
7826
+ var DEFAULT_TOLERANCE_SECONDS = 300;
7294
7827
  var WebhookVerifier = class {
7295
7828
  webhookSecret;
7296
7829
  /**
7297
- * Create an opt-in verifier for a gateway-defined HMAC convention.
7298
- *
7299
- * @param webhookSecret - Shared secret configured in both the trusted
7300
- * gateway and this process. Omit it to keep verification disabled.
7830
+ * @param webhookSecret - The endpoint's `whsec_…` secret from
7831
+ * `webhooks.getEndpointSecret()`. Omit it to keep verification disabled
7832
+ * (every check returns `false`).
7301
7833
  *
7302
7834
  * @example
7303
7835
  * ```ts
7304
- * const verifier = new WebhookVerifier(process.env.WEBHOOK_SHARED_SECRET);
7836
+ * const verifier = new WebhookVerifier(process.env.ASSINAFY_WEBHOOK_SECRET);
7305
7837
  * ```
7306
7838
  */
7307
7839
  constructor(webhookSecret) {
7308
7840
  this.webhookSecret = webhookSecret;
7309
7841
  }
7310
7842
  /**
7311
- * Compare a hexadecimal HMAC-SHA256 digest with the raw request body.
7843
+ * Verify a signed delivery: the Standard Webhooks signature over the raw
7844
+ * body, and a `webhook-timestamp` within `toleranceSeconds` of this
7845
+ * machine's clock (replay protection).
7846
+ *
7847
+ * @param payload - Exact, unparsed request bytes (or their UTF-8 string).
7848
+ * Re-serialized JSON will not match.
7849
+ * @param headers - Request headers: a Node/Express header object
7850
+ * (lowercase keys) or a Fetch `Headers`. Reads `webhook-id`,
7851
+ * `webhook-timestamp` and `webhook-signature`.
7852
+ * @param toleranceSeconds - Accepted clock distance. Defaults to `300`.
7853
+ * @returns `true` only when a signature entry matches (constant-time) and
7854
+ * the timestamp is fresh; `false` when verification is disabled, a header
7855
+ * is missing, or anything does not match.
7856
+ *
7857
+ * @example
7858
+ * ```ts
7859
+ * app.post('/webhooks/assinafy', express.raw({ type: 'application/json' }), (req, res) => {
7860
+ * if (!client.webhookVerifier.verifySignature(req.body, req.headers)) {
7861
+ * return res.status(401).end();
7862
+ * }
7863
+ * const event = client.webhookVerifier.extractEvent(req.body);
7864
+ * // deduplicate on req.headers['webhook-id'], then process
7865
+ * res.status(204).end();
7866
+ * });
7867
+ * ```
7868
+ */
7869
+ verifySignature(payload, headers, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS) {
7870
+ const key = decodeSecret(this.webhookSecret);
7871
+ if (!key || typeof payload !== "string" && !Buffer.isBuffer(payload) || !headers) {
7872
+ return false;
7873
+ }
7874
+ const id = header(headers, "webhook-id");
7875
+ const timestamp = header(headers, "webhook-timestamp");
7876
+ const signatures = header(headers, "webhook-signature");
7877
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
7878
+ if (Math.abs(Date.now() / 1e3 - Number(timestamp)) > toleranceSeconds) return false;
7879
+ const expected = createHmac("sha256", key).update(`${id}.${timestamp}.`).update(payload).digest();
7880
+ return signatures.split(" ").some((entry) => {
7881
+ const [version, signature] = entry.split(",", 2);
7882
+ if (version !== "v1" || !signature) return false;
7883
+ const actual = Buffer.from(signature, "base64");
7884
+ return actual.length === expected.length && timingSafeEqual2(actual, expected);
7885
+ });
7886
+ }
7887
+ /**
7888
+ * Compare a hexadecimal HMAC-SHA256 digest of the raw body, keyed with the
7889
+ * secret string as-is.
7890
+ *
7891
+ * @deprecated For gateways that apply their own HMAC convention. Assinafy's
7892
+ * own signatures are verified with {@link WebhookVerifier.verifySignature}.
7312
7893
  *
7313
7894
  * @param payload - Exact, unparsed request bytes (or their UTF-8 string).
7314
7895
  * @param signature - 64-character hexadecimal SHA-256 digest supplied by
@@ -7397,6 +7978,16 @@ var WebhookVerifier = class {
7397
7978
  return {};
7398
7979
  }
7399
7980
  };
7981
+ function decodeSecret(secret) {
7982
+ if (typeof secret !== "string" || !secret) return null;
7983
+ const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
7984
+ return key.length > 0 ? key : null;
7985
+ }
7986
+ function header(headers, name) {
7987
+ const value = typeof headers.get === "function" ? headers.get(name) : headers[name];
7988
+ const first = Array.isArray(value) ? value[0] : value;
7989
+ return typeof first === "string" ? first.trim() : void 0;
7990
+ }
7400
7991
  function isRecord(value) {
7401
7992
  return typeof value === "object" && value !== null && !Array.isArray(value);
7402
7993
  }
@@ -7602,7 +8193,7 @@ var AssinafyClient = class _AssinafyClient {
7602
8193
  if (baseUrl !== void 0) opts.baseUrl = baseUrl;
7603
8194
  if (webhookSecret !== void 0) opts.webhookSecret = webhookSecret;
7604
8195
  if (config.timeout !== void 0) opts.timeout = config.timeout;
7605
- const maxRetries = config.maxRetries ?? config.max_retries;
8196
+ const maxRetries = config.max_retries ?? config.maxRetries;
7606
8197
  if (maxRetries !== void 0) opts.maxRetries = maxRetries;
7607
8198
  if (config.logger !== void 0) opts.logger = config.logger;
7608
8199
  return new _AssinafyClient(opts);