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