@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.js CHANGED
@@ -158,7 +158,7 @@ var ApiError = class _ApiError extends AssinafyError {
158
158
  const data = responseData ?? {};
159
159
  const rawMessage = data["message"];
160
160
  const rawError = data["error"];
161
- const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : FALLBACK_MESSAGE;
161
+ const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" && rawError.length > 0 ? rawError : FALLBACK_MESSAGE;
162
162
  return new _ApiError(message, statusCode, responseData);
163
163
  }
164
164
  };
@@ -455,15 +455,16 @@ function assertDocumentArtifactName(value) {
455
455
  }
456
456
  function serializeJsonRecord(value, label) {
457
457
  assertRecord(value, label);
458
+ let serialized;
458
459
  try {
459
- const serialized = JSON.stringify(value);
460
- if (typeof serialized !== "string" || !serialized.startsWith("{")) {
461
- throw new ValidationError(`${label} must serialize to a JSON object`);
462
- }
463
- return serialized;
460
+ serialized = JSON.stringify(value);
464
461
  } catch {
465
462
  throw new ValidationError(`${label} must be JSON-serializable`);
466
463
  }
464
+ if (typeof serialized !== "string" || !serialized.startsWith("{")) {
465
+ throw new ValidationError(`${label} must serialize to a JSON object`);
466
+ }
467
+ return serialized;
467
468
  }
468
469
  function assertDateTime(value, label) {
469
470
  if (typeof value !== "string") throw new ValidationError(`${label} must be an ISO-8601 date-time`);
@@ -651,7 +652,7 @@ var import_axios2 = __toESM(require("axios"));
651
652
  // package.json
652
653
  var package_default = {
653
654
  name: "@assinafy/sdk",
654
- version: "2.5.2",
655
+ version: "2.7.0",
655
656
  packageManager: "bun@1.4.0",
656
657
  description: "TypeScript SDK for Assinafy API - Digital signature platform",
657
658
  type: "commonjs",
@@ -1545,9 +1546,10 @@ var AssignmentResource = class extends BaseResource {
1545
1546
  * Update the expiration date of an existing assignment
1546
1547
  * (`PUT /documents/{documentId}/assignments/{assignmentId}/reset-expiration`).
1547
1548
  *
1548
- * Sends `{ expires_at }` verbatim. Use an ISO-8601 date/time string; `null`
1549
- * is retained as a compatibility value and, unlike ordinary nullable
1550
- * inputs, is intentionally not stripped from the body.
1549
+ * Sends `{ expires_at }` verbatim; the key itself is required by the
1550
+ * contract. Use an ISO-8601 date/time string, or `null` to remove the
1551
+ * expiration — `null` is the documented clear mechanism and, unlike
1552
+ * ordinary nullable inputs, is intentionally not stripped from the body.
1551
1553
  *
1552
1554
  * Request body (`application/json`):
1553
1555
  * ```jsonc
@@ -1558,8 +1560,8 @@ var AssignmentResource = class extends BaseResource {
1558
1560
  *
1559
1561
  * @param documentId - The document the assignment belongs to.
1560
1562
  * @param assignmentId - The assignment to update.
1561
- * @param expiresAt - New expiry as an ISO-8601 date/time string. `null` is
1562
- * a compatibility value intended to clear it.
1563
+ * @param expiresAt - New expiry as an ISO-8601 date/time string, or `null`
1564
+ * to remove the expiration.
1563
1565
  * @returns The updated {@link IAssignment} — the same full shape
1564
1566
  * {@link AssignmentResource.create} returns (`signers`, `items`, `summary`,
1565
1567
  * `signing_urls`), with `expires_at` reflecting the new value:
@@ -3031,7 +3033,7 @@ var SignerResource = class extends BaseResource {
3031
3033
  * "full_name": "Example Signer",
3032
3034
  * "email": "signer@example.com",
3033
3035
  * "whatsapp_phone_number": "+5548999990000",
3034
- * "cpf": "39053344705",
3036
+ * "government_id": "390.533.447-05",
3035
3037
  * "metadata": {
3036
3038
  * "reference": "customer_example"
3037
3039
  * }
@@ -3039,12 +3041,13 @@ var SignerResource = class extends BaseResource {
3039
3041
  * ```
3040
3042
  *
3041
3043
  * @param payload - The signer to create. The official fields are required
3042
- * `full_name` plus optional `email` and E.164 `whatsapp_phone_number`.
3043
- * `phone`, `cpf`, and `metadata` are compatibility extensions; the SDK
3044
- * normalizes the phone alias and strips non-digits from CPF before sending.
3044
+ * `full_name` plus optional `email`, E.164 `whatsapp_phone_number` and
3045
+ * `government_id` (CPF, or a CNPJ that may contain letters; the API strips
3046
+ * formatting). `phone`, `cpf`, and `metadata` are compatibility extensions;
3047
+ * the SDK normalizes the phone alias and strips non-digits from CPF.
3045
3048
  * @param accountId - Override the client's default account ID.
3046
- * @returns The created (or reused) signer. Note the response **never echoes
3047
- * `cpf` back**, even when one was sent:
3049
+ * @returns The created (or reused) signer. `government_id` comes back
3050
+ * normalized; `cpf` is **never echoed back**:
3048
3051
  * ```jsonc
3049
3052
  * {
3050
3053
  * "resource": "signer",
@@ -3052,6 +3055,7 @@ var SignerResource = class extends BaseResource {
3052
3055
  * "full_name": "Ana Souza",
3053
3056
  * "email": "ana@example.com",
3054
3057
  * "whatsapp_phone_number": null,
3058
+ * "government_id": "39053344705",
3055
3059
  * "has_accepted_terms": false
3056
3060
  * }
3057
3061
  * ```
@@ -3065,7 +3069,7 @@ var SignerResource = class extends BaseResource {
3065
3069
  * const signer = await client.signers.create({
3066
3070
  * full_name: 'Ana Souza',
3067
3071
  * email: 'ana@example.com',
3068
- * cpf: '390.533.447-05', // sent as '39053344705', never echoed back
3072
+ * government_id: '390.533.447-05', // returned as '39053344705'
3069
3073
  * });
3070
3074
  *
3071
3075
  * // A whatsapp-only signer (no email):
@@ -3124,6 +3128,7 @@ var SignerResource = class extends BaseResource {
3124
3128
  * "full_name": "Example Signer",
3125
3129
  * "email": "signer@example.com",
3126
3130
  * "whatsapp_phone_number": null,
3131
+ * "government_id": "12ABC34501DE35",
3127
3132
  * "has_accepted_terms": false
3128
3133
  * }
3129
3134
  * ```
@@ -3195,13 +3200,14 @@ var SignerResource = class extends BaseResource {
3195
3200
  * "full_name": "Example Signer",
3196
3201
  * "email": "signer@example.com",
3197
3202
  * "whatsapp_phone_number": "+5548999990000",
3198
- * "government_id": "39053344705"
3203
+ * "government_id": "12.ABC.345/01DE-35"
3199
3204
  * }
3200
3205
  * ```
3201
3206
  *
3202
3207
  * @param signerId - The signer to update.
3203
- * @param payload - Fields to change. The official `government_id` field and
3204
- * legacy `cpf` extension are stripped to digits before sending.
3208
+ * @param payload - Fields to change. `government_id` is sent as given (the
3209
+ * API normalizes it and keeps CNPJ letters); the legacy `cpf` extension is
3210
+ * stripped to digits.
3205
3211
  * @param accountId - Override the client's default account ID.
3206
3212
  * @returns The updated signer (as with create, `cpf` is never echoed back):
3207
3213
  * ```jsonc
@@ -3211,6 +3217,7 @@ var SignerResource = class extends BaseResource {
3211
3217
  * "full_name": "Ana Souza Lima",
3212
3218
  * "email": "ana@example.com",
3213
3219
  * "whatsapp_phone_number": null,
3220
+ * "government_id": "12ABC34501DE35",
3214
3221
  * "has_accepted_terms": false
3215
3222
  * }
3216
3223
  * ```
@@ -3337,6 +3344,7 @@ function validateCreateSignerPayload(payload) {
3337
3344
  validateOptionalPhone(phone);
3338
3345
  if (payload.metadata !== void 0) serializeJsonRecord(payload.metadata, "metadata");
3339
3346
  validateOptionalDigits(payload.cpf, "cpf");
3347
+ validateOptionalDigits(payload.government_id, "government_id");
3340
3348
  }
3341
3349
  function validateUpdateSignerPayload(payload) {
3342
3350
  if (!payload || typeof payload !== "object") {
@@ -3385,8 +3393,8 @@ function normaliseSignerPayload(payload) {
3385
3393
  if (payload.cpf) {
3386
3394
  normalised["cpf"] = payload.cpf.replace(/\D/g, "");
3387
3395
  }
3388
- if ("government_id" in payload && payload.government_id) {
3389
- normalised["government_id"] = payload.government_id.replace(/\D/g, "");
3396
+ if (payload.government_id) {
3397
+ normalised["government_id"] = payload.government_id.trim();
3390
3398
  }
3391
3399
  if ("metadata" in payload && payload.metadata !== void 0) {
3392
3400
  normalised["metadata"] = payload.metadata;
@@ -3846,9 +3854,9 @@ var DEFAULT_WEBHOOK_EVENTS = Object.freeze([
3846
3854
  ]);
3847
3855
  var WebhookResource = class extends BaseResource {
3848
3856
  /**
3849
- * Register (or replace) the workspace's single webhook subscription
3850
- * (`PUT /accounts/{accountId}/webhooks/subscriptions`). There is exactly one
3851
- * subscription per workspace, keyed by URL.
3857
+ * Update the account's oldest webhook endpoint, creating it if the account
3858
+ * has none (`PUT /accounts/{accountId}/webhooks/subscriptions`). Accounts
3859
+ * with several endpoints should use {@link WebhookResource.updateEndpoint}.
3852
3860
  *
3853
3861
  * When `events` is omitted or empty, {@link DEFAULT_WEBHOOK_EVENTS} is used
3854
3862
  * (`document_ready`, `document_prepared`, `signer_signed_document`,
@@ -3907,26 +3915,12 @@ var WebhookResource = class extends BaseResource {
3907
3915
  * ```
3908
3916
  */
3909
3917
  async register(payload, accountId) {
3910
- if (!payload || typeof payload !== "object") {
3911
- throw new ValidationError("Webhook subscription payload is required");
3912
- }
3913
- validateWebhookUrl(payload.url);
3914
- if (!isEmail(payload.email)) {
3915
- throw new ValidationError("Webhook email must be a valid email address", {
3916
- email: payload.email
3917
- });
3918
- }
3919
- if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event.trim()))) {
3920
- throw new ValidationError("Webhook events must be an array of non-empty strings");
3921
- }
3922
- if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
3923
- throw new ValidationError("Webhook is_active must be a boolean");
3924
- }
3918
+ validateWebhookFields(payload, true);
3925
3919
  const id = this.accountId(accountId);
3926
3920
  const body = {
3927
3921
  url: payload.url,
3928
3922
  email: payload.email,
3929
- events: [...payload.events && payload.events.length > 0 ? payload.events : DEFAULT_WEBHOOK_EVENTS],
3923
+ events: withDefaultEvents(payload.events),
3930
3924
  is_active: payload.is_active ?? true
3931
3925
  };
3932
3926
  this.logger.info("Registering webhook");
@@ -3939,8 +3933,9 @@ var WebhookResource = class extends BaseResource {
3939
3933
  );
3940
3934
  }
3941
3935
  /**
3942
- * Fetch the current webhook subscription
3943
- * (`GET /accounts/{accountId}/webhooks/subscriptions`).
3936
+ * Fetch the account's oldest webhook endpoint in the legacy subscription
3937
+ * shape (`GET /accounts/{accountId}/webhooks/subscriptions`). Accounts with
3938
+ * several endpoints should use {@link WebhookResource.listEndpoints}.
3944
3939
  *
3945
3940
  * @param accountId - Override the client's default account ID.
3946
3941
  * @returns The subscription, or `null` when the workspace has none (the API
@@ -3982,13 +3977,14 @@ var WebhookResource = class extends BaseResource {
3982
3977
  );
3983
3978
  }
3984
3979
  /**
3985
- * Inactivate the current webhook subscription
3986
- * (`PUT /accounts/{accountId}/webhooks/inactivate`).
3980
+ * Deactivate the account's oldest webhook endpoint
3981
+ * (`PUT /accounts/{accountId}/webhooks/inactivate`). Other endpoints are
3982
+ * unaffected; use {@link WebhookResource.updateEndpoint} with
3983
+ * `is_active: false` to target a specific one.
3987
3984
  *
3988
- * This is the only supported way to stop deliveries — the API has no
3989
- * subscription-delete route. The subscription is retained (with its `url`
3990
- * and `events`) and simply stops firing; re-enable it by calling
3991
- * {@link WebhookResource.register} again with `is_active: true`.
3985
+ * The endpoint is retained (with its `url` and `events`) and simply stops
3986
+ * firing; re-enable it by calling {@link WebhookResource.register} again
3987
+ * with `is_active: true`.
3992
3988
  * OAuth tokens need the `webhooks:write` scope.
3993
3989
  *
3994
3990
  * @param accountId - Override the client's default account ID.
@@ -4073,6 +4069,7 @@ var WebhookResource = class extends BaseResource {
4073
4069
  * truncated to 2,000 characters.
4074
4070
  *
4075
4071
  * @param params - Optional filters and pagination:
4072
+ * - `endpoint_id` — only deliveries to this webhook endpoint.
4076
4073
  * - `event` — restrict to a single {@link WebhookEventType}
4077
4074
  * (e.g. `'signer_signed_document'`).
4078
4075
  * - `delivered` — `true`/`false` to filter by delivery success.
@@ -4087,6 +4084,7 @@ var WebhookResource = class extends BaseResource {
4087
4084
  * "id": "103a09cfce51319dd3b3f72ffcdf",
4088
4085
  * "event": "signature_requested",
4089
4086
  * "activity_id": 8629,
4087
+ * "endpoint_id": "65f1c2a9b3e4d5f60718293a4b5c6d7e", // null once the endpoint is deleted
4090
4088
  * "endpoint": "https://example.com/hook",
4091
4089
  * "payload": {
4092
4090
  * // the full event body that was POSTed to `endpoint`:
@@ -4129,7 +4127,7 @@ var WebhookResource = class extends BaseResource {
4129
4127
  /**
4130
4128
  * Retry delivery of a specific webhook dispatch
4131
4129
  * (`POST /accounts/{accountId}/webhooks/{historyId}/retry`). Re-sends the
4132
- * original payload to the subscription's endpoint.
4130
+ * original payload to the endpoint that received it.
4133
4131
  *
4134
4132
  * @param dispatchId - The dispatch (delivery history) ID to re-send, as
4135
4133
  * returned by {@link WebhookResource.listDispatches}.
@@ -4143,6 +4141,7 @@ var WebhookResource = class extends BaseResource {
4143
4141
  * "id": "103a09cfce51319dd3b3f72ffcdf",
4144
4142
  * "event": "signature_requested",
4145
4143
  * "activity_id": 8629,
4144
+ * "endpoint_id": "65f1c2a9b3e4d5f60718293a4b5c6d7e", // null once the endpoint is deleted
4146
4145
  * "endpoint": "https://example.com/hook",
4147
4146
  * "payload": { }, // the original event body that was re-POSTed
4148
4147
  * "delivered": true,
@@ -4173,11 +4172,320 @@ var WebhookResource = class extends BaseResource {
4173
4172
  )
4174
4173
  );
4175
4174
  }
4175
+ /**
4176
+ * List the account's webhook endpoints, oldest first
4177
+ * (`GET /accounts/{accountId}/webhooks/endpoints`). OAuth tokens need the
4178
+ * `account:read` scope.
4179
+ *
4180
+ * @param accountId - Override the client's default account ID.
4181
+ * @returns Every endpoint (1 on free plans, up to 3 on paid plans):
4182
+ * ```jsonc
4183
+ * [
4184
+ * {
4185
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4186
+ * "name": "ERP",
4187
+ * "url": "https://example.com/webhooks/assinafy",
4188
+ * "email": "ops@example.com",
4189
+ * "events": ["document_ready", "signer_signed_document"],
4190
+ * "is_active": true,
4191
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4192
+ * "created_at": "2026-10-01T12:00:00Z",
4193
+ * "updated_at": "2026-10-01T12:00:00Z"
4194
+ * }
4195
+ * ]
4196
+ * ```
4197
+ * @throws {ValidationError} If no account ID is available.
4198
+ * @throws {ApiError} If the API rejects the request.
4199
+ *
4200
+ * @example
4201
+ * ```ts
4202
+ * const endpoints = await client.webhooks.listEndpoints();
4203
+ * const signed = endpoints.filter((endpoint) => endpoint.signing_enabled);
4204
+ * ```
4205
+ */
4206
+ async listEndpoints(accountId) {
4207
+ const path2 = this.endpointsPath(accountId);
4208
+ return this.call("Failed to list webhook endpoints", () => this.http.get(path2));
4209
+ }
4210
+ /**
4211
+ * Register a URL to receive the account's webhook events
4212
+ * (`POST /accounts/{accountId}/webhooks/endpoints`).
4213
+ *
4214
+ * An account can have 1 endpoint, or up to 3 on paid plans. Each endpoint
4215
+ * of a workspace needs a different `url`. With `signing_enabled: true` the
4216
+ * API generates a signing secret; read it with
4217
+ * {@link WebhookResource.getEndpointSecret}. When `events` is omitted or
4218
+ * empty, {@link DEFAULT_WEBHOOK_EVENTS} is sent. OAuth tokens need the
4219
+ * `webhooks:write` scope.
4220
+ *
4221
+ * Request body (`application/json`):
4222
+ * ```jsonc
4223
+ * {
4224
+ * "url": "https://example.com/webhooks/assinafy",
4225
+ * "email": "ops@example.com",
4226
+ * "events": ["document_ready", "signer_signed_document"],
4227
+ * "name": "ERP", // optional label
4228
+ * "is_active": true, // defaults to true
4229
+ * "signing_enabled": true // defaults to false
4230
+ * }
4231
+ * ```
4232
+ *
4233
+ * @param payload - Endpoint details. `url` (absolute HTTP(S)) and `email`
4234
+ * are required; `events`, `name`, `is_active` and `signing_enabled` are
4235
+ * optional.
4236
+ * @param accountId - Override the client's default account ID.
4237
+ * @returns The created endpoint:
4238
+ * ```jsonc
4239
+ * {
4240
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4241
+ * "name": "ERP",
4242
+ * "url": "https://example.com/webhooks/assinafy",
4243
+ * "email": "ops@example.com",
4244
+ * "events": ["document_ready", "signer_signed_document"],
4245
+ * "is_active": true,
4246
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4247
+ * "created_at": "2026-10-01T12:00:00Z",
4248
+ * "updated_at": "2026-10-01T12:00:00Z"
4249
+ * }
4250
+ * ```
4251
+ * @throws {ValidationError} If a field is malformed or no account ID is
4252
+ * available.
4253
+ * @throws {ApiError} `400` if another endpoint already uses `url`; `403`
4254
+ * when the plan's endpoint limit is reached or an OAuth token lacks
4255
+ * `webhooks:write`.
4256
+ *
4257
+ * @example
4258
+ * ```ts
4259
+ * const endpoint = await client.webhooks.createEndpoint({
4260
+ * name: 'ERP',
4261
+ * url: 'https://example.com/webhooks/assinafy',
4262
+ * email: 'ops@example.com',
4263
+ * events: ['document_ready', 'signer_signed_document'],
4264
+ * signing_enabled: true,
4265
+ * });
4266
+ * const { secret } = await client.webhooks.getEndpointSecret(endpoint.id);
4267
+ * ```
4268
+ */
4269
+ async createEndpoint(payload, accountId) {
4270
+ validateWebhookFields(payload, true);
4271
+ const path2 = this.endpointsPath(accountId);
4272
+ this.logger.info("Creating webhook endpoint");
4273
+ return this.call(
4274
+ "Failed to create webhook endpoint",
4275
+ () => this.http.post(path2, { ...payload, events: withDefaultEvents(payload.events) })
4276
+ );
4277
+ }
4278
+ /**
4279
+ * Retrieve one webhook endpoint
4280
+ * (`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}`). OAuth
4281
+ * tokens need the `account:read` scope.
4282
+ *
4283
+ * @param endpointId - The endpoint ID.
4284
+ * @param accountId - Override the client's default account ID.
4285
+ * @returns The endpoint:
4286
+ * ```jsonc
4287
+ * {
4288
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4289
+ * "name": "ERP",
4290
+ * "url": "https://example.com/webhooks/assinafy",
4291
+ * "email": "ops@example.com",
4292
+ * "events": ["document_ready", "signer_signed_document"],
4293
+ * "is_active": true,
4294
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4295
+ * "created_at": "2026-10-01T12:00:00Z",
4296
+ * "updated_at": "2026-10-01T12:00:00Z"
4297
+ * }
4298
+ * ```
4299
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4300
+ * available.
4301
+ * @throws {ApiError} `404` if the endpoint does not exist.
4302
+ *
4303
+ * @example
4304
+ * ```ts
4305
+ * const endpoint = await client.webhooks.getEndpoint('65f1c2a9b3e4d5f60718293a4b5c6d7e');
4306
+ * ```
4307
+ */
4308
+ async getEndpoint(endpointId, accountId) {
4309
+ const path2 = this.endpointPath(endpointId, accountId);
4310
+ return this.call("Failed to fetch webhook endpoint", () => this.http.get(path2));
4311
+ }
4312
+ /**
4313
+ * Change a webhook endpoint
4314
+ * (`PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}`). Only the
4315
+ * fields sent are updated; `url` cannot be one another endpoint of the
4316
+ * workspace already uses.
4317
+ *
4318
+ * `signing_enabled: true` generates a secret if the endpoint has none and
4319
+ * keeps the current one otherwise; `false` discards the secret. OAuth
4320
+ * tokens need the `webhooks:write` scope.
4321
+ *
4322
+ * Request body (`application/json`, every field optional):
4323
+ * ```jsonc
4324
+ * {
4325
+ * "url": "https://example.com/webhooks/assinafy",
4326
+ * "email": "ops@example.com",
4327
+ * "events": ["document_ready"],
4328
+ * "name": "ERP",
4329
+ * "is_active": false,
4330
+ * "signing_enabled": true
4331
+ * }
4332
+ * ```
4333
+ *
4334
+ * @param endpointId - The endpoint ID.
4335
+ * @param payload - Fields to change; at least one is required.
4336
+ * @param accountId - Override the client's default account ID.
4337
+ * @returns The updated endpoint:
4338
+ * ```jsonc
4339
+ * {
4340
+ * "id": "65f1c2a9b3e4d5f60718293a4b5c6d7e",
4341
+ * "name": "ERP",
4342
+ * "url": "https://example.com/webhooks/assinafy",
4343
+ * "email": "ops@example.com",
4344
+ * "events": ["document_ready", "signer_signed_document"],
4345
+ * "is_active": true,
4346
+ * "signing_enabled": true, // deliveries carry a `webhook-signature` header
4347
+ * "created_at": "2026-10-01T12:00:00Z",
4348
+ * "updated_at": "2026-10-01T12:00:00Z"
4349
+ * }
4350
+ * ```
4351
+ * @throws {ValidationError} If `endpointId` is empty, the payload is empty
4352
+ * or malformed, or no account ID is available.
4353
+ * @throws {ApiError} `400` if another endpoint already uses `url`; `404` if
4354
+ * the endpoint does not exist.
4355
+ *
4356
+ * @example
4357
+ * ```ts
4358
+ * // Pause one endpoint without touching the others:
4359
+ * await client.webhooks.updateEndpoint(endpoint.id, { is_active: false });
4360
+ * ```
4361
+ */
4362
+ async updateEndpoint(endpointId, payload, accountId) {
4363
+ validateWebhookFields(payload, false);
4364
+ const path2 = this.endpointPath(endpointId, accountId);
4365
+ this.logger.info("Updating webhook endpoint");
4366
+ return this.call("Failed to update webhook endpoint", () => this.http.put(path2, payload));
4367
+ }
4368
+ /**
4369
+ * Stop delivering events to an endpoint and free its plan slot
4370
+ * (`DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}`). Its
4371
+ * delivery history is kept with `endpoint_id: null`. OAuth tokens need the
4372
+ * `webhooks:write` scope.
4373
+ *
4374
+ * @param endpointId - The endpoint ID.
4375
+ * @param accountId - Override the client's default account ID.
4376
+ * @returns Resolves once deleted (the API answers `{ "data": [] }`).
4377
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4378
+ * available.
4379
+ * @throws {ApiError} `404` if the endpoint does not exist.
4380
+ *
4381
+ * @example
4382
+ * ```ts
4383
+ * await client.webhooks.deleteEndpoint('65f1c2a9b3e4d5f60718293a4b5c6d7e');
4384
+ * ```
4385
+ */
4386
+ async deleteEndpoint(endpointId, accountId) {
4387
+ const path2 = this.endpointPath(endpointId, accountId);
4388
+ this.logger.info("Deleting webhook endpoint");
4389
+ await this.callVoid("Failed to delete webhook endpoint", () => this.http.delete(path2));
4390
+ }
4391
+ /**
4392
+ * Return the secret that signs deliveries to an endpoint
4393
+ * (`GET /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret`).
4394
+ * Pass it to {@link AssinafyClient} as `webhookSecret` to verify deliveries
4395
+ * with `webhookVerifier.verifySignature()`. Not available to OAuth
4396
+ * applications; use an API key.
4397
+ *
4398
+ * @param endpointId - The endpoint ID.
4399
+ * @param accountId - Override the client's default account ID.
4400
+ * @returns The Standard Webhooks secret:
4401
+ * ```jsonc
4402
+ * { "secret": "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw" }
4403
+ * ```
4404
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4405
+ * available.
4406
+ * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4407
+ * if it does not exist.
4408
+ *
4409
+ * @example
4410
+ * ```ts
4411
+ * const { secret } = await client.webhooks.getEndpointSecret(endpoint.id);
4412
+ * // store `secret` with your other credentials, never in source control
4413
+ * ```
4414
+ */
4415
+ async getEndpointSecret(endpointId, accountId) {
4416
+ const path2 = `${this.endpointPath(endpointId, accountId)}/secret`;
4417
+ return this.call("Failed to fetch webhook endpoint secret", () => this.http.get(path2));
4418
+ }
4419
+ /**
4420
+ * Replace an endpoint's signing secret and return the new one
4421
+ * (`POST /accounts/{accountId}/webhooks/endpoints/{endpointId}/secret/rotate`).
4422
+ * The old secret stops working immediately: deliveries sent after the
4423
+ * rotation are signed only with the new secret, so update the receiver at
4424
+ * once. Not available to OAuth applications; use an API key.
4425
+ *
4426
+ * @param endpointId - The endpoint ID.
4427
+ * @param accountId - Override the client's default account ID.
4428
+ * @returns The new secret:
4429
+ * ```jsonc
4430
+ * { "secret": "whsec_bmV3LWtleS1iYXNlNjQtZW5jb2RlZA==" }
4431
+ * ```
4432
+ * @throws {ValidationError} If `endpointId` is empty or no account ID is
4433
+ * available.
4434
+ * @throws {ApiError} `400` when signing is disabled on the endpoint; `404`
4435
+ * if it does not exist.
4436
+ *
4437
+ * @example
4438
+ * ```ts
4439
+ * const { secret } = await client.webhooks.rotateEndpointSecret(endpoint.id);
4440
+ * await secretStore.put('assinafy-webhook-secret', secret);
4441
+ * ```
4442
+ */
4443
+ async rotateEndpointSecret(endpointId, accountId) {
4444
+ const path2 = `${this.endpointPath(endpointId, accountId)}/secret/rotate`;
4445
+ this.logger.info("Rotating webhook endpoint secret");
4446
+ return this.call("Failed to rotate webhook endpoint secret", () => this.http.post(path2));
4447
+ }
4448
+ endpointsPath(accountId) {
4449
+ const id = this.pathSegment(this.accountId(accountId), "Account ID");
4450
+ return `/accounts/${id}/webhooks/endpoints`;
4451
+ }
4452
+ endpointPath(endpointId, accountId) {
4453
+ const eid = this.pathSegment(endpointId, "Endpoint ID");
4454
+ return `${this.endpointsPath(accountId)}/${eid}`;
4455
+ }
4176
4456
  };
4457
+ function withDefaultEvents(events) {
4458
+ return [...events && events.length > 0 ? events : DEFAULT_WEBHOOK_EVENTS];
4459
+ }
4460
+ function validateWebhookFields(payload, required) {
4461
+ if (!payload || typeof payload !== "object") {
4462
+ throw new ValidationError("Webhook payload is required");
4463
+ }
4464
+ if (!required && Object.values(payload).every((value) => value === void 0)) {
4465
+ throw new ValidationError("Webhook endpoint update must include at least one field");
4466
+ }
4467
+ if (required || payload.url !== void 0) validateWebhookUrl(payload.url);
4468
+ if ((required || payload.email !== void 0) && !isEmail(payload.email)) {
4469
+ throw new ValidationError("Webhook email must be a valid email address", {
4470
+ email: payload.email
4471
+ });
4472
+ }
4473
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event.trim()))) {
4474
+ throw new ValidationError("Webhook events must be an array of non-empty strings");
4475
+ }
4476
+ for (const key of ["is_active", "signing_enabled"]) {
4477
+ if (payload[key] !== void 0 && typeof payload[key] !== "boolean") {
4478
+ throw new ValidationError(`Webhook ${key} must be a boolean`);
4479
+ }
4480
+ }
4481
+ if (payload.name !== void 0 && typeof payload.name !== "string") {
4482
+ throw new ValidationError("Webhook name must be a string");
4483
+ }
4484
+ }
4177
4485
  function validateWebhookUrl(value) {
4178
4486
  let url;
4179
4487
  try {
4180
- url = new URL(value);
4488
+ url = new URL(value ?? "");
4181
4489
  } catch {
4182
4490
  throw new ValidationError("Webhook URL must be an absolute HTTP(S) URL", { url: value });
4183
4491
  }
@@ -4502,7 +4810,7 @@ var TemplateResource = class extends BaseResource {
4502
4810
  * ```ts
4503
4811
  * const tmpl = await client.templates.get('103ad2171db7979468c3e97eb067');
4504
4812
  * const jpeg = await client.templates.downloadPage(tmpl.id, tmpl.pages[0].id);
4505
- * await fs.writeFile('page-1.jpg', jpeg);
4813
+ * await fs.promises.writeFile('page-1.jpg', jpeg);
4506
4814
  * ```
4507
4815
  */
4508
4816
  async downloadPage(templateId, pageId, accountId) {
@@ -4839,6 +5147,9 @@ var AuthenticationResource = class extends BaseResource {
4839
5147
  * ]
4840
5148
  * }
4841
5149
  * ```
5150
+ * When the user has two-factor authentication enabled the response carries
5151
+ * an `mfa_token` instead of a usable session; finish with
5152
+ * {@link AuthenticationResource.verifyMfa}.
4842
5153
  * @throws {ValidationError} If `email` or `password` is missing.
4843
5154
  * @throws {ApiError} `400` if the credentials are rejected.
4844
5155
  *
@@ -4858,6 +5169,52 @@ var AuthenticationResource = class extends BaseResource {
4858
5169
  () => this.publicHttp.post("/login", { email, password })
4859
5170
  );
4860
5171
  }
5172
+ /**
5173
+ * Complete a two-factor login (`POST /authentication/mfa/verify`). Sent
5174
+ * without credentials.
5175
+ *
5176
+ * When the user has two-factor authentication enabled, `login()` returns
5177
+ * an `mfa_token`; exchange it here, within 5 minutes, for the session. The
5178
+ * challenge is single-use.
5179
+ *
5180
+ * Request body (`application/json`):
5181
+ * ```jsonc
5182
+ * {
5183
+ * "mfa_token": "<token from login>",
5184
+ * "code": "123456" // authenticator code, or a recovery code such as "ABCD-EFGH-JKMN"
5185
+ * }
5186
+ * ```
5187
+ *
5188
+ * @param mfaToken - The `mfa_token` returned by {@link AuthenticationResource.login}.
5189
+ * @param code - A 6-digit authenticator code or an unused recovery code.
5190
+ * @returns The same session as a password-only login:
5191
+ * ```jsonc
5192
+ * {
5193
+ * "access_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9…",
5194
+ * "user": { "id": "md3j6p9w8b7y6qvqaoy5er42", "email": "user@example.com" },
5195
+ * "accounts": [{ "id": "acc_example", "name": "Empresa Exemplo", "roles": ["Owner"] }]
5196
+ * }
5197
+ * ```
5198
+ * @throws {ValidationError} If either argument is empty.
5199
+ * @throws {ApiError} `400` for an invalid or used code; `401` when the
5200
+ * challenge expired, was used, or too many codes were tried.
5201
+ *
5202
+ * @example
5203
+ * ```ts
5204
+ * let session = await client.auth.login('user@example.com', password);
5205
+ * if (session.mfa_token) {
5206
+ * session = await client.auth.verifyMfa(session.mfa_token, await promptForCode());
5207
+ * }
5208
+ * ```
5209
+ */
5210
+ async verifyMfa(mfaToken, code) {
5211
+ assertNonEmptyString(mfaToken, "mfa_token");
5212
+ assertNonEmptyString(code, "code");
5213
+ return this.call(
5214
+ "Two-factor verification failed",
5215
+ () => this.publicHttp.post("/authentication/mfa/verify", { mfa_token: mfaToken, code })
5216
+ );
5217
+ }
4861
5218
  /**
4862
5219
  * Log in with a social provider (`POST /authentication/social-login`).
4863
5220
  *
@@ -4941,13 +5298,6 @@ var AuthenticationResource = class extends BaseResource {
4941
5298
  * Link a Google identity to the authenticated user
4942
5299
  * (`POST /auth/link-social-login`).
4943
5300
  *
4944
- * Request body:
4945
- * ```jsonc
4946
- * { "provider": "google", "token": "provider-issued-token" }
4947
- * ```
4948
- * The response is the standard status/message acknowledgement with no data,
4949
- * so this method resolves to `void`.
4950
- *
4951
5301
  * Request body (`application/json`):
4952
5302
  * ```jsonc
4953
5303
  * {
@@ -4955,6 +5305,8 @@ var AuthenticationResource = class extends BaseResource {
4955
5305
  * "token": "provider_token_example"
4956
5306
  * }
4957
5307
  * ```
5308
+ * The response is the standard status/message acknowledgement with no data,
5309
+ * so this method resolves to `void`.
4958
5310
  *
4959
5311
  * @param payload - Social provider and provider-issued access/ID token.
4960
5312
  * @returns Resolves when the API acknowledges that the identity was linked.
@@ -5711,6 +6063,11 @@ var OAuthResource = class extends BaseResource {
5711
6063
  * already-revoked included — so the endpoint cannot be used to probe
5712
6064
  * whether a token exists. Only failed client authentication returns `401`.
5713
6065
  *
6066
+ * Request body (`application/x-www-form-urlencoded`):
6067
+ * ```text
6068
+ * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
6069
+ * ```
6070
+ *
5714
6071
  * @param options - Revocation options.
5715
6072
  * @param options.token - The access or refresh token to revoke.
5716
6073
  * @param options.clientId - The application's `client_id`.
@@ -5719,10 +6076,6 @@ var OAuthResource = class extends BaseResource {
5719
6076
  * @param options.tokenTypeHint - Optional `access_token` or
5720
6077
  * `refresh_token` hint that lets the server skip a lookup.
5721
6078
  * @returns Nothing; resolves once the API acknowledges the request.
5722
- * Request body (`application/x-www-form-urlencoded`):
5723
- * ```text
5724
- * token=def50200f1e2…&token_type_hint=refresh_token&client_id=cli_1a2b3c&client_secret=…
5725
- * ```
5726
6079
  * @throws {ValidationError} If `token` or `clientId` is missing, or
5727
6080
  * `tokenTypeHint` is not one of the two documented values.
5728
6081
  * @throws {OAuthError} `invalid_client` when client authentication fails.
@@ -6577,7 +6930,7 @@ var SignerDocumentsResource = class extends BaseResource {
6577
6930
  * documentId,
6578
6931
  * 'original',
6579
6932
  * );
6580
- * await fs.writeFile('to-sign.pdf', pdf);
6933
+ * await fs.promises.writeFile('to-sign.pdf', pdf);
6581
6934
  * ```
6582
6935
  */
6583
6936
  async download(signerId, documentId, artifactName, signerAccessCode) {
@@ -6884,7 +7237,7 @@ var SignerDocumentsResource = class extends BaseResource {
6884
7237
  * @example
6885
7238
  * ```ts
6886
7239
  * const png = await client.signerDocuments.downloadSignature(accessCode, 'signature');
6887
- * await fs.writeFile('signature.png', png);
7240
+ * await fs.promises.writeFile('signature.png', png);
6888
7241
  * ```
6889
7242
  */
6890
7243
  async downloadSignature(signerAccessCode, imageType = "signature") {
@@ -7321,7 +7674,186 @@ var UserResource = class extends BaseResource {
7321
7674
  () => this.http.put("/users/self/notification-preferences", preferences)
7322
7675
  );
7323
7676
  }
7677
+ /**
7678
+ * List the user's enrolled two-factor methods (`GET /users/self/mfa`).
7679
+ *
7680
+ * @returns Methods and unused recovery-code count:
7681
+ * ```jsonc
7682
+ * {
7683
+ * "methods": [
7684
+ * {
7685
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7686
+ * "type": "Totp",
7687
+ * "label": "My phone",
7688
+ * "confirmed_at": "2026-09-09T14:21:03Z",
7689
+ * "last_used_at": "2026-09-09T18:02:44Z"
7690
+ * }
7691
+ * ],
7692
+ * "recovery_codes_remaining": 8
7693
+ * }
7694
+ * ```
7695
+ * @throws {ApiError} `401` when credentials are missing or invalid.
7696
+ *
7697
+ * @example
7698
+ * ```ts
7699
+ * const { methods } = await client.users.getMfa();
7700
+ * const enabled = methods.some((method) => method.confirmed_at !== null);
7701
+ * ```
7702
+ */
7703
+ async getMfa() {
7704
+ return this.call(
7705
+ "Failed to fetch two-factor methods",
7706
+ () => this.http.get("/users/self/mfa")
7707
+ );
7708
+ }
7709
+ /**
7710
+ * Start authenticator-app enrollment (`POST /users/self/mfa/totp`).
7711
+ * Two-factor authentication is not active until
7712
+ * {@link UserResource.confirmTotpEnrollment} succeeds.
7713
+ *
7714
+ * Request body (`application/json`): `{ "label": "My phone" }` (optional).
7715
+ *
7716
+ * @param label - Optional name for the device.
7717
+ * @returns The pending enrollment. `secret` is returned only here:
7718
+ * ```jsonc
7719
+ * {
7720
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7721
+ * "secret": "GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ",
7722
+ * "provisioning_uri": "otpauth://totp/user%40example.com?issuer=Assinafy&secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ"
7723
+ * }
7724
+ * ```
7725
+ * @throws {ValidationError} If `label` is not a string.
7726
+ * @throws {ApiError} `401` when credentials are missing or invalid.
7727
+ *
7728
+ * @example
7729
+ * ```ts
7730
+ * const enrollment = await client.users.startTotpEnrollment('My phone');
7731
+ * showQrCode(enrollment.provisioning_uri);
7732
+ * ```
7733
+ */
7734
+ async startTotpEnrollment(label) {
7735
+ if (label !== void 0 && typeof label !== "string") {
7736
+ throw new ValidationError("label must be a string");
7737
+ }
7738
+ return this.call(
7739
+ "Failed to start authenticator enrollment",
7740
+ () => this.http.post("/users/self/mfa/totp", label === void 0 ? {} : { label })
7741
+ );
7742
+ }
7743
+ /**
7744
+ * Activate an authenticator with a live code from the new device
7745
+ * (`PUT /users/self/mfa/totp/confirm`). From then on every login needs a
7746
+ * second factor.
7747
+ *
7748
+ * Replacing an already confirmed authenticator soft-deletes the old one,
7749
+ * reissues recovery codes, and additionally requires `password` or
7750
+ * `reauth_code`. First-time enrollment needs neither.
7751
+ *
7752
+ * Request body (`application/json`):
7753
+ * ```jsonc
7754
+ * {
7755
+ * "id": "a1b2c3d4e5f60718293a4b5c6d7e8f90",
7756
+ * "code": "123456", // from the NEW device
7757
+ * "password": "example-pass", // only when replacing; or:
7758
+ * "reauth_code": "654321" // code from the CURRENT device, or a recovery code
7759
+ * }
7760
+ * ```
7761
+ *
7762
+ * @param payload - Enrollment `id`, new-device `code`, and re-authentication
7763
+ * when replacing a method.
7764
+ * @returns The recovery codes, shown only once:
7765
+ * ```jsonc
7766
+ * {
7767
+ * "recovery_codes": ["ABCD-EFGH-JKMN", "PQRS-TUVW-XYZ2"] // ten in total
7768
+ * }
7769
+ * ```
7770
+ * @throws {ValidationError} If `id` or `code` is empty.
7771
+ * @throws {ApiError} `400` for a wrong code or missing re-authentication;
7772
+ * `404` for an unknown enrollment.
7773
+ *
7774
+ * @example
7775
+ * ```ts
7776
+ * const { recovery_codes } = await client.users.confirmTotpEnrollment({
7777
+ * id: enrollment.id,
7778
+ * code: '123456',
7779
+ * });
7780
+ * ```
7781
+ */
7782
+ async confirmTotpEnrollment(payload) {
7783
+ assertRecord(payload, "payload");
7784
+ assertNonEmptyString(payload.id, "id");
7785
+ assertNonEmptyString(payload.code, "code");
7786
+ return this.call(
7787
+ "Failed to confirm authenticator enrollment",
7788
+ () => this.http.put("/users/self/mfa/totp/confirm", payload)
7789
+ );
7790
+ }
7791
+ /**
7792
+ * Issue ten fresh recovery codes and invalidate the previous set
7793
+ * (`POST /users/self/mfa/recovery-codes`).
7794
+ *
7795
+ * Request body (`application/json`): `{ "password": "…" }` or
7796
+ * `{ "code": "123456" }`.
7797
+ *
7798
+ * @param proof - Current password, or a live authenticator / recovery code.
7799
+ * @returns The new codes, shown only once:
7800
+ * ```jsonc
7801
+ * {
7802
+ * "recovery_codes": ["ABCD-EFGH-JKMN", "PQRS-TUVW-XYZ2"] // ten in total
7803
+ * }
7804
+ * ```
7805
+ * @throws {ValidationError} If neither `password` nor `code` is given.
7806
+ * @throws {ApiError} `400` when the proof is rejected.
7807
+ *
7808
+ * @example
7809
+ * ```ts
7810
+ * const { recovery_codes } = await client.users.regenerateRecoveryCodes({ code: '123456' });
7811
+ * ```
7812
+ */
7813
+ async regenerateRecoveryCodes(proof) {
7814
+ validateReauth(proof);
7815
+ return this.call(
7816
+ "Failed to regenerate recovery codes",
7817
+ () => this.http.post("/users/self/mfa/recovery-codes", proof)
7818
+ );
7819
+ }
7820
+ /**
7821
+ * Remove an enrolled two-factor method (`DELETE /users/self/mfa/{id}`).
7822
+ * Removing the last method also discards the recovery codes.
7823
+ *
7824
+ * Request body (`application/json`): `{ "password": "…" }` or
7825
+ * `{ "code": "123456" }`.
7826
+ *
7827
+ * @param methodId - The method ID from {@link UserResource.getMfa}.
7828
+ * @param proof - Current password, or a live authenticator / recovery code.
7829
+ * @returns Whether two-factor authentication is still on:
7830
+ * ```jsonc
7831
+ * { "is_mfa_enabled": false }
7832
+ * ```
7833
+ * @throws {ValidationError} If `methodId` is empty or no proof is given.
7834
+ * @throws {ApiError} `400` when the proof is rejected; `404` for an unknown
7835
+ * method.
7836
+ *
7837
+ * @example
7838
+ * ```ts
7839
+ * await client.users.deleteMfaMethod(method.id, { password });
7840
+ * ```
7841
+ */
7842
+ async deleteMfaMethod(methodId, proof) {
7843
+ const id = this.pathSegment(methodId, "Method ID");
7844
+ validateReauth(proof);
7845
+ return this.call(
7846
+ "Failed to remove two-factor method",
7847
+ () => this.http.delete(`/users/self/mfa/${id}`, { data: proof })
7848
+ );
7849
+ }
7324
7850
  };
7851
+ function validateReauth(proof) {
7852
+ assertRecord(proof, "proof");
7853
+ if (![proof.password, proof.code].some((value) => typeof value === "string" && value.trim())) {
7854
+ throw new ValidationError("password or code is required");
7855
+ }
7856
+ }
7325
7857
  var NOTIFICATION_PREFERENCE_KEYS = /* @__PURE__ */ new Set([
7326
7858
  "DocumentCompleted",
7327
7859
  "SignerDeclined",
@@ -7351,24 +7883,73 @@ function validateNotificationPreferences(preferences) {
7351
7883
 
7352
7884
  // src/support/webhook-verifier.ts
7353
7885
  var import_node_crypto2 = require("crypto");
7886
+ var DEFAULT_TOLERANCE_SECONDS = 300;
7354
7887
  var WebhookVerifier = class {
7355
7888
  webhookSecret;
7356
7889
  /**
7357
- * Create an opt-in verifier for a gateway-defined HMAC convention.
7358
- *
7359
- * @param webhookSecret - Shared secret configured in both the trusted
7360
- * gateway and this process. Omit it to keep verification disabled.
7890
+ * @param webhookSecret - The endpoint's `whsec_…` secret from
7891
+ * `webhooks.getEndpointSecret()`. Omit it to keep verification disabled
7892
+ * (every check returns `false`).
7361
7893
  *
7362
7894
  * @example
7363
7895
  * ```ts
7364
- * const verifier = new WebhookVerifier(process.env.WEBHOOK_SHARED_SECRET);
7896
+ * const verifier = new WebhookVerifier(process.env.ASSINAFY_WEBHOOK_SECRET);
7365
7897
  * ```
7366
7898
  */
7367
7899
  constructor(webhookSecret) {
7368
7900
  this.webhookSecret = webhookSecret;
7369
7901
  }
7370
7902
  /**
7371
- * Compare a hexadecimal HMAC-SHA256 digest with the raw request body.
7903
+ * Verify a signed delivery: the Standard Webhooks signature over the raw
7904
+ * body, and a `webhook-timestamp` within `toleranceSeconds` of this
7905
+ * machine's clock (replay protection).
7906
+ *
7907
+ * @param payload - Exact, unparsed request bytes (or their UTF-8 string).
7908
+ * Re-serialized JSON will not match.
7909
+ * @param headers - Request headers: a Node/Express header object
7910
+ * (lowercase keys) or a Fetch `Headers`. Reads `webhook-id`,
7911
+ * `webhook-timestamp` and `webhook-signature`.
7912
+ * @param toleranceSeconds - Accepted clock distance. Defaults to `300`.
7913
+ * @returns `true` only when a signature entry matches (constant-time) and
7914
+ * the timestamp is fresh; `false` when verification is disabled, a header
7915
+ * is missing, or anything does not match.
7916
+ *
7917
+ * @example
7918
+ * ```ts
7919
+ * app.post('/webhooks/assinafy', express.raw({ type: 'application/json' }), (req, res) => {
7920
+ * if (!client.webhookVerifier.verifySignature(req.body, req.headers)) {
7921
+ * return res.status(401).end();
7922
+ * }
7923
+ * const event = client.webhookVerifier.extractEvent(req.body);
7924
+ * // deduplicate on req.headers['webhook-id'], then process
7925
+ * res.status(204).end();
7926
+ * });
7927
+ * ```
7928
+ */
7929
+ verifySignature(payload, headers, toleranceSeconds = DEFAULT_TOLERANCE_SECONDS) {
7930
+ const key = decodeSecret(this.webhookSecret);
7931
+ if (!key || typeof payload !== "string" && !Buffer.isBuffer(payload) || !headers) {
7932
+ return false;
7933
+ }
7934
+ const id = header(headers, "webhook-id");
7935
+ const timestamp = header(headers, "webhook-timestamp");
7936
+ const signatures = header(headers, "webhook-signature");
7937
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
7938
+ if (Math.abs(Date.now() / 1e3 - Number(timestamp)) > toleranceSeconds) return false;
7939
+ const expected = (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`).update(payload).digest();
7940
+ return signatures.split(" ").some((entry) => {
7941
+ const [version, signature] = entry.split(",", 2);
7942
+ if (version !== "v1" || !signature) return false;
7943
+ const actual = Buffer.from(signature, "base64");
7944
+ return actual.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(actual, expected);
7945
+ });
7946
+ }
7947
+ /**
7948
+ * Compare a hexadecimal HMAC-SHA256 digest of the raw body, keyed with the
7949
+ * secret string as-is.
7950
+ *
7951
+ * @deprecated For gateways that apply their own HMAC convention. Assinafy's
7952
+ * own signatures are verified with {@link WebhookVerifier.verifySignature}.
7372
7953
  *
7373
7954
  * @param payload - Exact, unparsed request bytes (or their UTF-8 string).
7374
7955
  * @param signature - 64-character hexadecimal SHA-256 digest supplied by
@@ -7457,6 +8038,16 @@ var WebhookVerifier = class {
7457
8038
  return {};
7458
8039
  }
7459
8040
  };
8041
+ function decodeSecret(secret) {
8042
+ if (typeof secret !== "string" || !secret) return null;
8043
+ const key = Buffer.from(secret.replace(/^whsec_/, ""), "base64");
8044
+ return key.length > 0 ? key : null;
8045
+ }
8046
+ function header(headers, name) {
8047
+ const value = typeof headers.get === "function" ? headers.get(name) : headers[name];
8048
+ const first = Array.isArray(value) ? value[0] : value;
8049
+ return typeof first === "string" ? first.trim() : void 0;
8050
+ }
7460
8051
  function isRecord(value) {
7461
8052
  return typeof value === "object" && value !== null && !Array.isArray(value);
7462
8053
  }
@@ -7662,7 +8253,7 @@ var AssinafyClient = class _AssinafyClient {
7662
8253
  if (baseUrl !== void 0) opts.baseUrl = baseUrl;
7663
8254
  if (webhookSecret !== void 0) opts.webhookSecret = webhookSecret;
7664
8255
  if (config.timeout !== void 0) opts.timeout = config.timeout;
7665
- const maxRetries = config.maxRetries ?? config.max_retries;
8256
+ const maxRetries = config.max_retries ?? config.maxRetries;
7666
8257
  if (maxRetries !== void 0) opts.maxRetries = maxRetries;
7667
8258
  if (config.logger !== void 0) opts.logger = config.logger;
7668
8259
  return new _AssinafyClient(opts);