@assinafy/sdk 2.5.2 → 2.6.0

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