@assinafy/cli 2.4.2 → 2.5.1

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.
Files changed (37) hide show
  1. package/.env.example +4 -2
  2. package/README.en.md +46 -21
  3. package/README.md +34 -15
  4. package/dist/api.cjs +295 -55
  5. package/dist/api.cjs.map +1 -1
  6. package/dist/api.js +295 -55
  7. package/dist/api.js.map +1 -1
  8. package/dist/cli.cjs +635 -100
  9. package/dist/types/api/errors.d.ts +9 -0
  10. package/dist/types/api/errors.d.ts.map +1 -1
  11. package/dist/types/api/index.d.ts +1 -1
  12. package/dist/types/api/index.d.ts.map +1 -1
  13. package/dist/types/api/resources/authentication.d.ts +33 -3
  14. package/dist/types/api/resources/authentication.d.ts.map +1 -1
  15. package/dist/types/api/resources/documents.d.ts +4 -3
  16. package/dist/types/api/resources/documents.d.ts.map +1 -1
  17. package/dist/types/api/resources/oauth.d.ts +1 -1
  18. package/dist/types/api/resources/oauth.d.ts.map +1 -1
  19. package/dist/types/api/resources/signer-documents.d.ts +9 -4
  20. package/dist/types/api/resources/signer-documents.d.ts.map +1 -1
  21. package/dist/types/api/resources/webhooks.d.ts +39 -6
  22. package/dist/types/api/resources/webhooks.d.ts.map +1 -1
  23. package/dist/types/api/support/webhook-verifier.d.ts +31 -14
  24. package/dist/types/api/support/webhook-verifier.d.ts.map +1 -1
  25. package/dist/types/api/types.d.ts +110 -21
  26. package/dist/types/api/types.d.ts.map +1 -1
  27. package/dist/types/api/utils.d.ts.map +1 -1
  28. package/docs/README.md +1 -1
  29. package/docs/api-operations.json +105 -1
  30. package/docs/api-reference.md +2380 -2057
  31. package/docs/auth.md +125 -4
  32. package/docs/documents.md +5 -6
  33. package/docs/migration-v2.md +1 -1
  34. package/docs/sdk-reference.md +84 -23
  35. package/docs/signer.md +4 -2
  36. package/docs/webhooks.md +185 -20
  37. package/package.json +2 -2
package/dist/cli.cjs CHANGED
@@ -21093,6 +21093,8 @@ var ApiError = class _ApiError extends AssinafyError {
21093
21093
  wwwAuthenticate;
21094
21094
  /** Server retry delay (seconds or HTTP date), when provided. */
21095
21095
  retryAfter;
21096
+ /** Rate-limit window reported by the API, when the headers are present. */
21097
+ rateLimit;
21096
21098
  constructor(message, statusCode, responseData = null, options) {
21097
21099
  super(message, { statusCode, responseData }, options);
21098
21100
  this.name = "ApiError";
@@ -21100,6 +21102,7 @@ var ApiError = class _ApiError extends AssinafyError {
21100
21102
  this.responseData = responseData;
21101
21103
  this.wwwAuthenticate = options?.wwwAuthenticate;
21102
21104
  this.retryAfter = options?.retryAfter;
21105
+ this.rateLimit = options?.rateLimit;
21103
21106
  }
21104
21107
  static fromResponse(statusCode, responseData, headers = {}) {
21105
21108
  if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
@@ -21113,13 +21116,23 @@ var ApiError = class _ApiError extends AssinafyError {
21113
21116
  const data = responseData ?? {};
21114
21117
  const rawMessage = data.message;
21115
21118
  const rawError = data.error;
21116
- const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
21119
+ const description = data.error_description;
21120
+ const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? typeof description === "string" && description.length > 0 ? `${rawError}: ${description}` : rawError : "API request failed";
21117
21121
  return new _ApiError(message, statusCode, responseData, {
21118
21122
  wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
21119
- retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
21123
+ retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0,
21124
+ rateLimit: parseRateLimit(headers)
21120
21125
  });
21121
21126
  }
21122
21127
  };
21128
+ function parseRateLimit(headers) {
21129
+ const info = {};
21130
+ for (const key of ["limit", "remaining", "reset"]) {
21131
+ const value = Number.parseInt(String(headers[`x-rate-limit-${key}`]), 10);
21132
+ if (Number.isFinite(value)) info[key] = value;
21133
+ }
21134
+ return Object.keys(info).length > 0 ? info : void 0;
21135
+ }
21123
21136
  var ValidationError = class extends AssinafyError {
21124
21137
  errors;
21125
21138
  constructor(message = "Validation failed", errors = {}) {
@@ -21272,6 +21285,16 @@ function validateSignerOptions(input) {
21272
21285
  `notification_methods must contain only: ${NOTIFICATION_METHODS.join(", ")}`
21273
21286
  );
21274
21287
  }
21288
+ const notifications = input.notification_methods ?? [];
21289
+ if (notifications.length > 1) {
21290
+ throw new ValidationError("notification_methods accepts exactly one method per signer");
21291
+ }
21292
+ const [notification] = notifications;
21293
+ if (notification !== void 0 && (input.verification_method === "Email" || input.verification_method === "Whatsapp") && notification !== input.verification_method) {
21294
+ throw new ValidationError(
21295
+ `${input.verification_method} verification requires the ${input.verification_method} notification method`
21296
+ );
21297
+ }
21275
21298
  if (input.step !== void 0 && !Number.isInteger(input.step)) {
21276
21299
  throw new ValidationError("step must be an integer");
21277
21300
  }
@@ -21605,6 +21628,12 @@ var AssignmentResource = class extends BaseResource {
21605
21628
  };
21606
21629
 
21607
21630
  // src/api/resources/authentication.ts
21631
+ function requireReauth(payload) {
21632
+ if (!payload?.password && !payload?.code) {
21633
+ throw new ValidationError("password or code is required");
21634
+ }
21635
+ return payload;
21636
+ }
21608
21637
  var AuthenticationResource = class extends BaseResource {
21609
21638
  /** `POST /login` — exchange email + password for a JWT access token. */
21610
21639
  async login(email, password2) {
@@ -21615,6 +21644,70 @@ var AuthenticationResource = class extends BaseResource {
21615
21644
  () => this.http.post("/login", { email, password: password2 }, publicRequestConfig())
21616
21645
  );
21617
21646
  }
21647
+ /**
21648
+ * `POST /authentication/mfa/verify` — exchange the login `mfa_token` and an
21649
+ * authenticator or recovery code for an access token. The challenge is
21650
+ * single-use and expires 5 minutes after login.
21651
+ */
21652
+ async verifyMfa(payload) {
21653
+ if (!payload?.mfa_token) throw new ValidationError("mfa_token is required");
21654
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
21655
+ return this.call(
21656
+ "Two-factor verification failed",
21657
+ () => this.http.post(
21658
+ "/authentication/mfa/verify",
21659
+ { mfa_token: payload.mfa_token, code: payload.code.trim() },
21660
+ publicRequestConfig()
21661
+ )
21662
+ );
21663
+ }
21664
+ /** `GET /users/self/mfa` — enrolled two-factor methods and remaining recovery codes. */
21665
+ async listMfaMethods() {
21666
+ return this.call("Failed to list two-factor methods", () => this.http.get("/users/self/mfa"));
21667
+ }
21668
+ /**
21669
+ * `POST /users/self/mfa/totp` — start authenticator enrollment. The secret
21670
+ * and provisioning URI are returned only once; two-factor stays inactive
21671
+ * until {@link confirmTotpEnrollment}.
21672
+ */
21673
+ async startTotpEnrollment(label) {
21674
+ return this.call(
21675
+ "Failed to start authenticator enrollment",
21676
+ () => this.http.post("/users/self/mfa/totp", label ? { label } : {})
21677
+ );
21678
+ }
21679
+ /**
21680
+ * `PUT /users/self/mfa/totp/confirm` — activate the method with a live code
21681
+ * and receive one-time recovery codes. Replacing a confirmed method also
21682
+ * requires `password` or `reauth_code`.
21683
+ */
21684
+ async confirmTotpEnrollment(payload) {
21685
+ if (!payload?.id) throw new ValidationError("id is required");
21686
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
21687
+ return this.call(
21688
+ "Failed to confirm authenticator enrollment",
21689
+ () => this.http.put("/users/self/mfa/totp/confirm", payload)
21690
+ );
21691
+ }
21692
+ /** `POST /users/self/mfa/recovery-codes` — issue ten new recovery codes, invalidating the old set. */
21693
+ async regenerateRecoveryCodes(payload) {
21694
+ return this.call(
21695
+ "Failed to regenerate recovery codes",
21696
+ () => this.http.post("/users/self/mfa/recovery-codes", requireReauth(payload))
21697
+ );
21698
+ }
21699
+ /**
21700
+ * `DELETE /users/self/mfa/{methodId}` — remove a method. Removing the last
21701
+ * one also discards the recovery codes.
21702
+ */
21703
+ async removeMfaMethod(methodId, payload) {
21704
+ const id = this.requireId(methodId, "Method ID");
21705
+ const data = requireReauth(payload);
21706
+ return this.call(
21707
+ "Failed to remove two-factor method",
21708
+ () => this.http.delete(`/users/self/mfa/${id}`, { data })
21709
+ );
21710
+ }
21618
21711
  /** `POST /authentication/social-login` — exchange a provider token for an Assinafy JWT. */
21619
21712
  async socialLogin(payload) {
21620
21713
  if (payload.provider !== "google") throw new ValidationError("provider must be google");
@@ -21938,7 +22031,7 @@ var DocumentResource = class extends BaseResource {
21938
22031
  async createFromTemplate(templateId, signers, options = {}, accountId) {
21939
22032
  const tmplId = this.requireId(templateId, "Template ID");
21940
22033
  const accId = this.accountId(accountId);
21941
- validateTemplateSigners(signers, { requireId: true, singleNotification: true });
22034
+ validateTemplateSigners(signers, { requireId: true });
21942
22035
  if (options.expires_at !== void 0) requireIso8601(options.expires_at, "expires_at");
21943
22036
  if (options.editor_fields !== void 0 && (!Array.isArray(options.editor_fields) || options.editor_fields.some((field) => !field?.field_id || typeof field.value !== "string"))) {
21944
22037
  throw new ValidationError("editor_fields must contain field_id and value");
@@ -21957,7 +22050,7 @@ var DocumentResource = class extends BaseResource {
21957
22050
  async estimateCostFromTemplate(templateId, signers, accountId) {
21958
22051
  const tmplId = this.requireId(templateId, "Template ID");
21959
22052
  const accId = this.accountId(accountId);
21960
- validateTemplateSigners(signers, { requireId: false, singleNotification: false });
22053
+ validateTemplateSigners(signers, { requireId: false });
21961
22054
  return this.call(
21962
22055
  "Failed to estimate cost from template",
21963
22056
  () => this.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers })
@@ -21997,33 +22090,21 @@ var DocumentResource = class extends BaseResource {
21997
22090
  );
21998
22091
  }
21999
22092
  /**
22000
- * `PUT /public/documents/{document_id}/send-token` — send the 6-digit
22001
- * verification token to the signer's email / WhatsApp. Pass `{ email }` for
22002
- * the published OpenAPI body or a string plus channel for the live legacy body.
22093
+ * `PUT /public/documents/{document_id}/send-token` — email a one-time access
22094
+ * token to a signer who has not signed a pending document yet. The API sends
22095
+ * `{ channel: 'email', recipient }`; only the `email` channel is accepted.
22096
+ * The `{ email }` form is kept for existing callers and sends the same body.
22003
22097
  */
22004
22098
  async sendToken(documentId, recipient, channel = "email") {
22005
22099
  const id = this.requireId(documentId, "Document ID");
22006
- if (typeof recipient === "object") {
22007
- requireEmail(recipient?.email);
22008
- return this.call(
22009
- "Failed to send signing token",
22010
- () => this.http.put(
22011
- `/public/documents/${id}/send-token`,
22012
- { email: recipient.email },
22013
- publicRequestConfig()
22014
- )
22015
- );
22016
- }
22017
- if (!recipient) throw new ValidationError("recipient is required");
22018
- if (channel !== "email" && channel !== "whatsapp") {
22019
- throw new ValidationError("channel must be email or whatsapp");
22020
- }
22021
- if (channel === "email") requireEmail(recipient);
22100
+ const email = typeof recipient === "object" ? recipient?.email : recipient;
22101
+ if (channel !== "email") throw new ValidationError("channel must be email");
22102
+ requireEmail(email);
22022
22103
  return this.call(
22023
22104
  "Failed to send signing token",
22024
22105
  () => this.http.put(
22025
22106
  `/public/documents/${id}/send-token`,
22026
- { recipient, channel },
22107
+ { channel, recipient: email },
22027
22108
  publicRequestConfig()
22028
22109
  )
22029
22110
  );
@@ -22066,9 +22147,6 @@ function validateTemplateSigners(signers, options) {
22066
22147
  if (options.requireId && signer.step !== void 0 && Number(signer.step) < 1) {
22067
22148
  throw new ValidationError("template signer step must be a positive integer");
22068
22149
  }
22069
- if (options.singleNotification && Array.isArray(signer.notification_methods) && signer.notification_methods.length > 1) {
22070
- throw new ValidationError("template signers accept at most one notification method");
22071
- }
22072
22150
  }
22073
22151
  if (options.requireId) {
22074
22152
  validateSigningSteps(signers);
@@ -22353,7 +22431,7 @@ var OAuthResource = class extends BaseResource {
22353
22431
  });
22354
22432
  }
22355
22433
  /**
22356
- * `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body.
22434
+ * `POST /oauth/token` — code exchange, refresh, or RFC 8693 token exchange; returns the flat OAuth JSON body.
22357
22435
  * A refresh must return a new `refresh_token`; otherwise this throws `ValidationError`.
22358
22436
  */
22359
22437
  async token(payload) {
@@ -22370,8 +22448,20 @@ var OAuthResource = class extends BaseResource {
22370
22448
  }
22371
22449
  } else if (payload.grant_type === "refresh_token") {
22372
22450
  required(payload.refresh_token, "refresh_token");
22451
+ } else if (payload.grant_type === TOKEN_EXCHANGE) {
22452
+ required(payload.client_secret, "client_secret");
22453
+ httpsUrl(required(payload.resource, "resource"), "resource");
22454
+ required(payload.subject_token, "subject_token");
22455
+ for (const field of ["subject_token_type", "requested_token_type"]) {
22456
+ const value = payload[field];
22457
+ if ((value !== void 0 || field === "subject_token_type") && value !== ACCESS_TOKEN_TYPE) {
22458
+ throw new ValidationError(`${field} must be ${ACCESS_TOKEN_TYPE}`);
22459
+ }
22460
+ }
22373
22461
  } else {
22374
- throw new ValidationError("grant_type must be authorization_code or refresh_token");
22462
+ throw new ValidationError(
22463
+ `grant_type must be authorization_code, refresh_token or ${TOKEN_EXCHANGE}`
22464
+ );
22375
22465
  }
22376
22466
  const tokens = await this.call(
22377
22467
  "OAuth token request failed",
@@ -22404,6 +22494,8 @@ var OAuthResource = class extends BaseResource {
22404
22494
  return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
22405
22495
  }
22406
22496
  };
22497
+ var TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
22498
+ var ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
22407
22499
  function required(value, name) {
22408
22500
  if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
22409
22501
  return value;
@@ -22432,27 +22524,32 @@ var SignerDocumentsResource = class extends BaseResource {
22432
22524
  () => this.http.get(`/signers/${sid}/document`, signerAccessConfig(code))
22433
22525
  );
22434
22526
  }
22435
- /** `GET /signers/{signer_id}/documents?signer-access-code=…` */
22527
+ /**
22528
+ * `GET /signers/{signer_id}/documents` — with a signer access code, or with
22529
+ * the client's owner credentials when the code is omitted (the signer must
22530
+ * belong to that workspace).
22531
+ */
22436
22532
  async list(signerId, signerAccessCode, params = {}) {
22437
22533
  const sid = this.requireId(signerId, "Signer ID");
22438
- const code = this.requireId(signerAccessCode, "signer-access-code");
22534
+ const config = this.signerOrOwnerConfig(signerAccessCode, { ...params });
22439
22535
  return this.callList(
22440
22536
  "Failed to list signer documents",
22441
- () => this.http.get(
22442
- `/signers/${sid}/documents`,
22443
- signerAccessConfig(code, params)
22444
- )
22537
+ () => this.http.get(`/signers/${sid}/documents`, config)
22445
22538
  );
22446
22539
  }
22447
- /** `GET /signers/{signer_id}/documents/search?signer-access-code=…&search=…` */
22540
+ /** `GET /signers/{signer_id}/documents/search?search=…` — access code or owner credentials. */
22448
22541
  async search(signerId, search, signerAccessCode) {
22449
22542
  const sid = this.requireId(signerId, "Signer ID");
22450
- const code = this.requireId(signerAccessCode, "signer-access-code");
22543
+ const config = this.signerOrOwnerConfig(signerAccessCode, { search });
22451
22544
  return this.callList(
22452
22545
  "Failed to search signer documents",
22453
- () => this.http.get(`/signers/${sid}/documents/search`, signerAccessConfig(code, { search }))
22546
+ () => this.http.get(`/signers/${sid}/documents/search`, config)
22454
22547
  );
22455
22548
  }
22549
+ signerOrOwnerConfig(signerAccessCode, params) {
22550
+ if (signerAccessCode === void 0) return { params: cleanParams(params) };
22551
+ return signerAccessConfig(this.requireId(signerAccessCode, "signer-access-code"), params);
22552
+ }
22456
22553
  /**
22457
22554
  * Public `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`.
22458
22555
  * When an access code is supplied, the SDK first verifies that it belongs to
@@ -22996,10 +23093,8 @@ var DEFAULT_EVENTS = [
22996
23093
  "signer_rejected_document",
22997
23094
  "document_processing_failed"
22998
23095
  ];
22999
- var WebhookResource = class extends BaseResource {
23000
- /** Register (or replace) the webhook subscription for the workspace. */
23001
- async register(payload, accountId) {
23002
- if (!payload.url) throw new ValidationError("Webhook URL is required");
23096
+ function validateWebhookFields(payload) {
23097
+ if (payload.url !== void 0) {
23003
23098
  let webhookUrl;
23004
23099
  try {
23005
23100
  webhookUrl = new URL(payload.url);
@@ -23009,13 +23104,29 @@ var WebhookResource = class extends BaseResource {
23009
23104
  if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
23010
23105
  throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
23011
23106
  }
23012
- requireEmail(payload.email);
23013
- if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
23014
- throw new ValidationError("Webhook events must contain non-empty strings");
23015
- }
23016
- if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
23017
- throw new ValidationError("Webhook is_active must be a boolean");
23107
+ }
23108
+ if (payload.email !== void 0) requireEmail(payload.email);
23109
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
23110
+ throw new ValidationError("Webhook events must contain non-empty strings");
23111
+ }
23112
+ if (payload.name !== void 0 && typeof payload.name !== "string") {
23113
+ throw new ValidationError("Webhook name must be a string");
23114
+ }
23115
+ for (const key of ["is_active", "signing_enabled"]) {
23116
+ if (payload[key] !== void 0 && typeof payload[key] !== "boolean") {
23117
+ throw new ValidationError(`Webhook ${key} must be a boolean`);
23018
23118
  }
23119
+ }
23120
+ }
23121
+ var WebhookResource = class extends BaseResource {
23122
+ /**
23123
+ * `PUT /accounts/{accountId}/webhooks/subscriptions` — create or replace the
23124
+ * account's oldest webhook endpoint. Use the endpoint methods for accounts
23125
+ * with several endpoints or for signed deliveries.
23126
+ */
23127
+ async register(payload, accountId) {
23128
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
23129
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
23019
23130
  const id = this.accountId(accountId);
23020
23131
  const body = {
23021
23132
  url: payload.url,
@@ -23031,7 +23142,7 @@ var WebhookResource = class extends BaseResource {
23031
23142
  () => this.http.put(`/accounts/${id}/webhooks/subscriptions`, body)
23032
23143
  );
23033
23144
  }
23034
- /** Fetch the current webhook subscription. Returns `null` if none exists. */
23145
+ /** Fetch the account's oldest webhook endpoint. Returns `null` if none exists. */
23035
23146
  async get(accountId) {
23036
23147
  const id = this.accountId(accountId);
23037
23148
  return this.callOptional(
@@ -23039,7 +23150,7 @@ var WebhookResource = class extends BaseResource {
23039
23150
  () => this.http.get(`/accounts/${id}/webhooks/subscriptions`)
23040
23151
  );
23041
23152
  }
23042
- /** Inactivate the current webhook subscription without deleting it. */
23153
+ /** Inactivate the account's oldest webhook endpoint without deleting it. */
23043
23154
  async inactivate(accountId) {
23044
23155
  const id = this.accountId(accountId);
23045
23156
  this.logger.info("Inactivating webhook subscription");
@@ -23048,6 +23159,91 @@ var WebhookResource = class extends BaseResource {
23048
23159
  () => this.http.put(`/accounts/${id}/webhooks/inactivate`)
23049
23160
  );
23050
23161
  }
23162
+ /** `GET /accounts/{accountId}/webhooks/endpoints` — list webhook endpoints, oldest first. */
23163
+ async listEndpoints(accountId) {
23164
+ const id = this.accountId(accountId);
23165
+ return this.call(
23166
+ "Failed to list webhook endpoints",
23167
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints`)
23168
+ );
23169
+ }
23170
+ /**
23171
+ * `POST /accounts/{accountId}/webhooks/endpoints` — register another
23172
+ * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past
23173
+ * the limit); URLs must be unique per workspace. Omitted `events` uses the
23174
+ * same default set as {@link register}.
23175
+ */
23176
+ async createEndpoint(payload, accountId) {
23177
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
23178
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
23179
+ const id = this.accountId(accountId);
23180
+ const body = { ...payload, events: payload.events ?? DEFAULT_EVENTS };
23181
+ this.logger.info("Creating webhook endpoint", { eventCount: body.events.length });
23182
+ return this.call(
23183
+ "Failed to create webhook endpoint",
23184
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints`, body)
23185
+ );
23186
+ }
23187
+ /** `GET /accounts/{accountId}/webhooks/endpoints/{endpointId}` — fetch one endpoint. */
23188
+ async getEndpoint(endpointId, accountId) {
23189
+ const id = this.accountId(accountId);
23190
+ const eid = this.requireId(endpointId, "Endpoint ID");
23191
+ return this.call(
23192
+ "Failed to fetch webhook endpoint",
23193
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}`)
23194
+ );
23195
+ }
23196
+ /**
23197
+ * `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` — update only
23198
+ * the fields sent. Enabling signing creates a secret when none exists;
23199
+ * disabling it discards the secret.
23200
+ */
23201
+ async updateEndpoint(endpointId, payload, accountId) {
23202
+ const id = this.accountId(accountId);
23203
+ const eid = this.requireId(endpointId, "Endpoint ID");
23204
+ if (!payload || typeof payload !== "object" || Object.keys(payload).length === 0) {
23205
+ throw new ValidationError("At least one webhook endpoint field is required");
23206
+ }
23207
+ validateWebhookFields(payload);
23208
+ return this.call(
23209
+ "Failed to update webhook endpoint",
23210
+ () => this.http.put(`/accounts/${id}/webhooks/endpoints/${eid}`, payload)
23211
+ );
23212
+ }
23213
+ /** `DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}` — delete an endpoint and free its slot. */
23214
+ async deleteEndpoint(endpointId, accountId) {
23215
+ const id = this.accountId(accountId);
23216
+ const eid = this.requireId(endpointId, "Endpoint ID");
23217
+ return this.call(
23218
+ "Failed to delete webhook endpoint",
23219
+ () => this.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`)
23220
+ );
23221
+ }
23222
+ /**
23223
+ * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.
23224
+ * Returns `400` when signing is disabled. Not available to OAuth applications.
23225
+ */
23226
+ async getEndpointSecret(endpointId, accountId) {
23227
+ const id = this.accountId(accountId);
23228
+ const eid = this.requireId(endpointId, "Endpoint ID");
23229
+ return this.call(
23230
+ "Failed to fetch webhook endpoint secret",
23231
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}/secret`)
23232
+ );
23233
+ }
23234
+ /**
23235
+ * `POST …/endpoints/{endpointId}/secret/rotate` — replace the signing secret.
23236
+ * The old secret stops working immediately. Not available to OAuth applications.
23237
+ */
23238
+ async rotateEndpointSecret(endpointId, accountId) {
23239
+ const id = this.accountId(accountId);
23240
+ const eid = this.requireId(endpointId, "Endpoint ID");
23241
+ this.logger.info("Rotating webhook endpoint secret");
23242
+ return this.call(
23243
+ "Failed to rotate webhook endpoint secret",
23244
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints/${eid}/secret/rotate`)
23245
+ );
23246
+ }
23051
23247
  /** List currently supported webhook event types. */
23052
23248
  async listEventTypes() {
23053
23249
  return this.call(
@@ -23055,7 +23251,7 @@ var WebhookResource = class extends BaseResource {
23055
23251
  () => this.http.get("/webhooks/event-types")
23056
23252
  );
23057
23253
  }
23058
- /** List webhook delivery history for the workspace. */
23254
+ /** List webhook delivery history for the workspace, optionally for one endpoint. */
23059
23255
  async listDispatches(params = {}, accountId) {
23060
23256
  const id = this.accountId(accountId);
23061
23257
  if ("search" in params) throw new ValidationError("webhook dispatch search is not supported");
@@ -23067,7 +23263,7 @@ var WebhookResource = class extends BaseResource {
23067
23263
  })
23068
23264
  );
23069
23265
  }
23070
- /** Retry delivery of a specific webhook dispatch. */
23266
+ /** Retry delivery of a specific webhook dispatch to that entry's endpoint. */
23071
23267
  async retryDispatch(dispatchId, accountId) {
23072
23268
  const id = this.accountId(accountId);
23073
23269
  const did = this.requireId(dispatchId, "Dispatch ID");
@@ -23176,6 +23372,17 @@ function validateNotificationSender(value) {
23176
23372
 
23177
23373
  // src/api/support/webhook-verifier.ts
23178
23374
  var import_node_crypto2 = require("crypto");
23375
+ function readHeader(headers, name) {
23376
+ if (typeof headers.get === "function") {
23377
+ return headers.get(name) ?? void 0;
23378
+ }
23379
+ for (const [key, value] of Object.entries(headers)) {
23380
+ if (key.toLowerCase() !== name) continue;
23381
+ if (Array.isArray(value)) return value.length === 1 ? value[0] : void 0;
23382
+ return value;
23383
+ }
23384
+ return void 0;
23385
+ }
23179
23386
  var WebhookVerifier = class {
23180
23387
  constructor(webhookSecret, options = {}) {
23181
23388
  this.webhookSecret = webhookSecret;
@@ -23185,15 +23392,48 @@ var WebhookVerifier = class {
23185
23392
  webhookSecret;
23186
23393
  algorithm;
23187
23394
  encoding;
23188
- /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
23395
+ /**
23396
+ * Returns `true` when `headers` carry a Standard Webhooks signature that
23397
+ * matches the raw `payload` under this verifier's `whsec_` secret and the
23398
+ * `webhook-timestamp` is within the tolerance window. Pass the body exactly
23399
+ * as received; re-serialized JSON does not verify.
23400
+ */
23401
+ verifyDelivery(payload, headers, options = {}) {
23402
+ if (!this.webhookSecret || !headers) return false;
23403
+ const id = readHeader(headers, "webhook-id");
23404
+ const timestamp = readHeader(headers, "webhook-timestamp");
23405
+ const signatures = readHeader(headers, "webhook-signature");
23406
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
23407
+ const tolerance = options.toleranceSeconds ?? 300;
23408
+ const now = Math.floor((options.now ?? Date.now()) / 1e3);
23409
+ if (Math.abs(now - Number(timestamp)) > tolerance) return false;
23410
+ const secret = this.webhookSecret.startsWith("whsec_") ? this.webhookSecret.slice("whsec_".length) : this.webhookSecret;
23411
+ const key = Buffer.from(secret, "base64");
23412
+ if (key.length === 0) return false;
23413
+ const expected = Buffer.from(
23414
+ (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`).update(typeof payload === "string" ? Buffer.from(payload, "utf8") : payload).digest("base64")
23415
+ );
23416
+ return signatures.split(" ").some((entry) => {
23417
+ const [version, value] = entry.split(",", 2);
23418
+ if (version !== "v1" || !value) return false;
23419
+ const provided = Buffer.from(value);
23420
+ return provided.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(provided, expected);
23421
+ });
23422
+ }
23423
+ /**
23424
+ * Returns `true` if `signature` is an HMAC of `payload` keyed with the raw
23425
+ * secret string under the configured algorithm/encoding.
23426
+ *
23427
+ * @deprecated Assinafy signs deliveries with Standard Webhooks headers; use
23428
+ * {@link verifyDelivery}. Retained for existing callers.
23429
+ */
23189
23430
  verify(payload, signature) {
23190
23431
  if (!this.webhookSecret || !signature) return false;
23191
23432
  try {
23192
23433
  const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
23193
23434
  const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
23194
- const provided = signature.trim();
23195
23435
  const a2 = Buffer.from(expected, "utf8");
23196
- const b = Buffer.from(provided, "utf8");
23436
+ const b = Buffer.from(signature.trim(), "utf8");
23197
23437
  if (a2.length !== b.length) return false;
23198
23438
  return (0, import_node_crypto2.timingSafeEqual)(a2, b);
23199
23439
  } catch {
@@ -23461,7 +23701,8 @@ function normalizeError(err) {
23461
23701
  statusCode: err.statusCode,
23462
23702
  details: err.responseData ?? void 0,
23463
23703
  ...err.wwwAuthenticate ? { wwwAuthenticate: err.wwwAuthenticate } : {},
23464
- ...err.retryAfter ? { retryAfter: err.retryAfter } : {}
23704
+ ...err.retryAfter ? { retryAfter: err.retryAfter } : {},
23705
+ ...err.rateLimit ? { rateLimit: err.rateLimit } : {}
23465
23706
  };
23466
23707
  }
23467
23708
  if (err instanceof PartialWorkflowError) {
@@ -23474,6 +23715,7 @@ function normalizeError(err) {
23474
23715
  if (cause.statusCode !== void 0) normalized.statusCode = cause.statusCode;
23475
23716
  if (cause.wwwAuthenticate !== void 0) normalized.wwwAuthenticate = cause.wwwAuthenticate;
23476
23717
  if (cause.retryAfter !== void 0) normalized.retryAfter = cause.retryAfter;
23718
+ if (cause.rateLimit !== void 0) normalized.rateLimit = cause.rateLimit;
23477
23719
  return normalized;
23478
23720
  }
23479
23721
  if (err instanceof ValidationError) {
@@ -23670,6 +23912,14 @@ function printError(err, config) {
23670
23912
  if (normalized.statusCode) {
23671
23913
  writeErr(import_picocolors.default.dim(` (HTTP ${normalized.statusCode})`));
23672
23914
  }
23915
+ if (normalized.statusCode === 429) {
23916
+ const wait = normalized.retryAfter ?? normalized.rateLimit?.reset;
23917
+ writeErr(
23918
+ import_picocolors.default.dim(
23919
+ ` (rate limit reached${wait === void 0 ? "" : `; retry after ${sanitizeTerminalText(String(wait))} s`})`
23920
+ )
23921
+ );
23922
+ }
23673
23923
  const challenge = normalized.wwwAuthenticate ?? "";
23674
23924
  const scope = challenge.includes("insufficient_scope") && /\bscope="([^"]+)"/.exec(challenge)?.[1];
23675
23925
  if (scope) {
@@ -25131,30 +25381,157 @@ function unwrap(value) {
25131
25381
  function resetPasswordPayload(email, resetToken, newPassword) {
25132
25382
  return { email, token: resetToken, new_password: newPassword };
25133
25383
  }
25384
+ var mfaCodeOption = () => new Option(
25385
+ "--mfa-code <code>",
25386
+ "Authenticator or recovery code (prompted if required and omitted)"
25387
+ ).env("ASSINAFY_MFA_CODE");
25388
+ var printSession = (result, config) => {
25389
+ printSuccess(`Logged in as ${result.user.email}`, config);
25390
+ printData(
25391
+ result,
25392
+ config,
25393
+ (r2) => renderKeyValue({
25394
+ access_token: r2.access_token,
25395
+ user: r2.user.email,
25396
+ accounts: r2.accounts.map((a2) => a2.id)
25397
+ })
25398
+ );
25399
+ };
25134
25400
  var loginCommand = new Command("login").description(
25135
- "Exchange email + password for a JWT access token (no existing credentials required)"
25401
+ "Exchange email + password (and a two-factor code when enabled) for a JWT access token (no existing credentials required)"
25136
25402
  ).argument("<email>", "Account email").addOption(
25137
25403
  new Option("--password <password>", "Password (prompted if omitted)").env("ASSINAFY_PASSWORD")
25138
- ).action(async (email, opts, command) => {
25404
+ ).addOption(mfaCodeOption()).action(async (email, opts, command) => {
25139
25405
  await runWithPublicClient(command, async ({ client, config }) => {
25140
25406
  const password2 = opts.password ?? await promptSecret("Password");
25141
- const result = await withSpinner(
25407
+ let result = await withSpinner(
25142
25408
  "Logging in",
25143
25409
  config,
25144
25410
  () => client.auth.login(email, password2)
25145
25411
  );
25146
- printSuccess(`Logged in as ${result.user.email}`, config);
25412
+ if (!result.access_token && result.mfa_token) {
25413
+ const mfaToken = result.mfa_token;
25414
+ const code = opts.mfaCode ?? await promptSecret("Two-factor code");
25415
+ result = await withSpinner(
25416
+ "Verifying two-factor code",
25417
+ config,
25418
+ () => client.auth.verifyMfa({ mfa_token: mfaToken, code })
25419
+ );
25420
+ }
25421
+ printSession(result, config);
25422
+ });
25423
+ });
25424
+ var mfaVerifyCommand = new Command("verify").description(
25425
+ "Complete a two-factor login with the mfa_token from login (no existing credentials required)"
25426
+ ).addOption(
25427
+ new Option("--mfa-token <token>", "Challenge token returned by login").env("ASSINAFY_MFA_TOKEN").makeOptionMandatory()
25428
+ ).addOption(mfaCodeOption()).action(async (opts, command) => {
25429
+ await runWithPublicClient(command, async ({ client, config }) => {
25430
+ const code = opts.mfaCode ?? await promptSecret("Two-factor code");
25431
+ const result = await withSpinner(
25432
+ "Verifying two-factor code",
25433
+ config,
25434
+ () => client.auth.verifyMfa({ mfa_token: opts.mfaToken, code })
25435
+ );
25436
+ printSession(result, config);
25437
+ });
25438
+ });
25439
+ var mfaListCommand = new Command("list").alias("ls").description("List enrolled two-factor methods and remaining recovery codes").action(async (_opts, command) => {
25440
+ await runWithClient(command, async ({ client, config }) => {
25441
+ const result = await withSpinner(
25442
+ "Fetching two-factor methods",
25443
+ config,
25444
+ () => client.auth.listMfaMethods()
25445
+ );
25147
25446
  printData(
25148
25447
  result,
25149
25448
  config,
25150
- (r2) => renderKeyValue({
25151
- access_token: r2.access_token,
25152
- user: r2.user.email,
25153
- accounts: r2.accounts.map((a2) => a2.id)
25449
+ (r2) => [
25450
+ renderTable(r2.methods, [
25451
+ { header: "ID", value: (m) => m.id },
25452
+ { header: "TYPE", value: (m) => m.type },
25453
+ { header: "LABEL", value: (m) => m.label },
25454
+ { header: "CONFIRMED", value: (m) => m.confirmed_at },
25455
+ { header: "LAST USED", value: (m) => m.last_used_at }
25456
+ ]),
25457
+ `Recovery codes remaining: ${r2.recovery_codes_remaining}`
25458
+ ].join("\n")
25459
+ );
25460
+ });
25461
+ });
25462
+ var mfaEnrollCommand = new Command("enroll").description("Start authenticator enrollment; prints the one-time secret and provisioning URI").option("--label <label>", "Name for the authenticator").action(async (opts, command) => {
25463
+ await runWithClient(command, async ({ client, config }) => {
25464
+ const result = await withSpinner(
25465
+ "Starting enrollment",
25466
+ config,
25467
+ () => client.auth.startTotpEnrollment(opts.label)
25468
+ );
25469
+ printSuccess(
25470
+ `Enrollment started. Confirm with: assinafy auth mfa confirm ${result.id}`,
25471
+ config
25472
+ );
25473
+ printData(result, config, (r2) => renderKeyValue({ ...r2 }));
25474
+ });
25475
+ });
25476
+ var reauthPasswordOption = () => new Option("--password <password>", "Current password").env("ASSINAFY_PASSWORD");
25477
+ async function reauthPayload(opts) {
25478
+ if (opts.password) return { password: opts.password };
25479
+ return { code: opts.mfaCode ?? await promptSecret("Authenticator or recovery code") };
25480
+ }
25481
+ var mfaConfirmCommand = new Command("confirm").description("Activate an enrolled authenticator and print the one-time recovery codes").argument("<methodId>", "Method ID returned by enroll").addOption(new Option("--code <code>", "Live code from the new authenticator")).addOption(
25482
+ new Option(
25483
+ "--password <password>",
25484
+ "Current password (only when replacing a confirmed method)"
25485
+ ).env("ASSINAFY_PASSWORD")
25486
+ ).addOption(
25487
+ new Option(
25488
+ "--reauth-code <code>",
25489
+ "Code from the current authenticator or a recovery code (only when replacing)"
25490
+ ).conflicts("password")
25491
+ ).action(async (methodId, opts, command) => {
25492
+ await runWithClient(command, async ({ client, config }) => {
25493
+ const code = opts.code ?? await promptSecret("Code from the new authenticator");
25494
+ const result = await withSpinner(
25495
+ "Confirming enrollment",
25496
+ config,
25497
+ () => client.auth.confirmTotpEnrollment({
25498
+ id: methodId,
25499
+ code,
25500
+ ...opts.password ? { password: opts.password } : {},
25501
+ ...opts.reauthCode ? { reauth_code: opts.reauthCode } : {}
25154
25502
  })
25155
25503
  );
25504
+ printSuccess("Two-factor authentication enabled. Store the recovery codes now.", config);
25505
+ printData(result, config, (r2) => r2.recovery_codes.join("\n"));
25156
25506
  });
25157
25507
  });
25508
+ var mfaRecoveryCodesCommand = new Command("recovery-codes").description("Issue ten new recovery codes and invalidate the previous set").addOption(reauthPasswordOption()).addOption(mfaCodeOption().conflicts("password")).action(async (opts, command) => {
25509
+ await runWithClient(command, async ({ client, config }) => {
25510
+ const payload = await reauthPayload(opts);
25511
+ const result = await withSpinner(
25512
+ "Regenerating recovery codes",
25513
+ config,
25514
+ () => client.auth.regenerateRecoveryCodes(payload)
25515
+ );
25516
+ printSuccess("Recovery codes regenerated. Store them now.", config);
25517
+ printData(result, config, (r2) => r2.recovery_codes.join("\n"));
25518
+ });
25519
+ });
25520
+ var mfaRemoveCommand = new Command("remove").alias("rm").description("Remove a two-factor method (the last one also discards recovery codes)").argument("<methodId>", "Method ID").addOption(reauthPasswordOption()).addOption(mfaCodeOption().conflicts("password")).option("-y, --yes", "Skip the confirmation prompt").action(async (methodId, opts, command) => {
25521
+ await runWithClient(command, async ({ client, config }) => {
25522
+ if (!await confirmDestructive(`Remove two-factor method ${methodId}?`, Boolean(opts.yes)))
25523
+ return;
25524
+ const payload = await reauthPayload(opts);
25525
+ const result = await withSpinner(
25526
+ "Removing two-factor method",
25527
+ config,
25528
+ () => client.auth.removeMfaMethod(methodId, payload)
25529
+ );
25530
+ printSuccess("Two-factor method removed", config);
25531
+ printData(result, config);
25532
+ });
25533
+ });
25534
+ var mfaCommand = new Command("mfa").description("Two-factor authentication: login verification, enrollment, and recovery codes").addCommand(mfaVerifyCommand).addCommand(mfaListCommand).addCommand(mfaEnrollCommand).addCommand(mfaConfirmCommand).addCommand(mfaRecoveryCodesCommand).addCommand(mfaRemoveCommand);
25158
25535
  var socialLoginCommand = new Command("social-login").description("Exchange a provider token for an Assinafy JWT (no existing credentials required)").addOption(
25159
25536
  new Option("--provider <provider>", "OAuth provider").choices(["google"]).makeOptionMandatory()
25160
25537
  ).addOption(
@@ -25277,7 +25654,7 @@ var apiKeyDeleteCommand = new Command("delete").alias("rm").description("Revoke
25277
25654
  });
25278
25655
  });
25279
25656
  var apiKeysCommand = new Command("api-keys").description("Manage the current user personal API key").addCommand(apiKeyCreateCommand).addCommand(apiKeyGetCommand).addCommand(apiKeyDeleteCommand);
25280
- var authCommand = new Command("auth").description("Authentication, password management, and personal API keys").addCommand(loginCommand).addCommand(socialLoginCommand).addCommand(linkSocialLoginCommand).addCommand(changePasswordCommand).addCommand(requestResetCommand).addCommand(resetPasswordCommand).addCommand(apiKeysCommand);
25657
+ var authCommand = new Command("auth").description("Authentication, password management, and personal API keys").addCommand(loginCommand).addCommand(socialLoginCommand).addCommand(linkSocialLoginCommand).addCommand(changePasswordCommand).addCommand(requestResetCommand).addCommand(resetPasswordCommand).addCommand(apiKeysCommand).addCommand(mfaCommand);
25281
25658
 
25282
25659
  // src/commands/config/index.ts
25283
25660
  var import_picocolors5 = __toESM(require_picocolors(), 1);
@@ -25944,32 +26321,27 @@ var publicCommand = new Command("public").description("Public (unauthenticated)
25944
26321
  printData(info, config, (d) => renderKeyValue(d));
25945
26322
  });
25946
26323
  });
25947
- var sendTokenCommand = new Command("send-token").description("Send a 6-digit verification token to a signer").argument("<id>", "Document ID").addOption(
25948
- new Option(
25949
- "--email <email>",
25950
- "Email address (compatibility overload for older deployments)"
25951
- ).conflicts(["recipient", "channel"])
25952
- ).addOption(
25953
- new Option(
25954
- "--recipient <value>",
25955
- "Email address or phone number (production payload)"
25956
- ).conflicts("email")
25957
- ).addOption(
25958
- new Option("--channel <channel>", "email or whatsapp").default("email").conflicts("email")
26324
+ var sendTokenCommand = new Command("send-token").description("Email a one-time access token to a signer of a pending document").argument("<id>", "Document ID").addOption(
26325
+ new Option("--recipient <email>", "Email of a signer who has not signed yet").conflicts(
26326
+ "email"
26327
+ )
26328
+ ).addOption(new Option("--email <email>", "Alias of --recipient").conflicts("recipient")).addOption(
26329
+ new Option("--channel <channel>", "Delivery channel").choices(["email"]).default("email")
25959
26330
  ).action(async (id, opts, command) => {
25960
26331
  await runWithPublicClient(command, async ({ client, config }) => {
25961
- if (!opts.email && !opts.recipient) {
25962
- throw new CliError("Pass --email <email> or --recipient <value>.");
25963
- }
25964
- const recipient = opts.email ? { email: opts.email } : opts.recipient;
25965
- const channel = parseSendTokenChannel(opts.channel);
26332
+ const recipient = opts.recipient ?? opts.email;
26333
+ if (!recipient) throw new CliError("Pass --recipient <email>.");
25966
26334
  const result = await withSpinner(
25967
26335
  "Sending token",
25968
26336
  config,
25969
- () => client.documents.sendToken(id, recipient, channel)
26337
+ () => client.documents.sendToken(id, recipient)
26338
+ );
26339
+ printSuccess(`Token sent to ${recipient}`, config);
26340
+ printData(
26341
+ result,
26342
+ config,
26343
+ (r2) => renderKeyValue({ document: r2.document.id, channel: r2.channel, recipient: r2.recipient })
25970
26344
  );
25971
- printSuccess(`Token sent to ${opts.email ?? opts.recipient}`, config);
25972
- printData(result, config);
25973
26345
  });
25974
26346
  });
25975
26347
  var progressCommand = new Command("progress").description("Show signing progress for a document").argument("<id>", "Document ID").action(async (id, _opts, command) => {
@@ -26004,10 +26376,6 @@ var waitCommand = new Command("wait").description("Poll a document until it is r
26004
26376
  printData(doc, config, (d) => renderKeyValue({ id: d.id, status: d.status }));
26005
26377
  });
26006
26378
  });
26007
- function parseSendTokenChannel(value) {
26008
- if (value === "email" || value === "whatsapp") return value;
26009
- throw new CliError("--channel must be email or whatsapp");
26010
- }
26011
26379
  var documentsCommand = new Command("documents").description("Upload, list, download, and manage documents").addCommand(uploadCommand).addCommand(listCommand3).addCommand(searchCommand).addCommand(getCommand2).addCommand(renameCommand).addCommand(downloadCommand).addCommand(thumbnailCommand).addCommand(downloadPageCommand).addCommand(activitiesCommand).addCommand(deleteCommand).addCommand(tagsCommand).addCommand(tagsSetCommand).addCommand(tagsAddCommand).addCommand(tagsRemoveCommand).addCommand(createFromTemplateCommand).addCommand(estimateTemplateCostCommand).addCommand(verifyCommand).addCommand(statusesCommand).addCommand(publicCommand).addCommand(sendTokenCommand).addCommand(progressCommand).addCommand(waitCommand);
26012
26380
 
26013
26381
  // src/commands/fields.ts
@@ -26401,6 +26769,10 @@ var sendCommand = new Command("send").description("Upload a PDF, create signers,
26401
26769
 
26402
26770
  // src/commands/signer.ts
26403
26771
  var accessCodeOption = () => new Option("--access-code <code>", "Signer access code").env("ASSINAFY_SIGNER_ACCESS_CODE").makeOptionMandatory();
26772
+ var optionalAccessCodeOption = () => new Option("--access-code <code>", "Signer access code (omit to use your API key or token)").env(
26773
+ "ASSINAFY_SIGNER_ACCESS_CODE"
26774
+ );
26775
+ var runSignerOrOwner = (accessCode) => accessCode === void 0 ? runWithClient : runWithPublicClient;
26404
26776
  var documentCommand = new Command("document").description("Fetch the signer's current document").argument("<signerId>", "Signer ID").addOption(accessCodeOption()).action(async (signerId, opts, command) => {
26405
26777
  await runWithPublicClient(command, async ({ client, config }) => {
26406
26778
  const doc = await withSpinner(
@@ -26412,9 +26784,9 @@ var documentCommand = new Command("document").description("Fetch the signer's cu
26412
26784
  });
26413
26785
  });
26414
26786
  var documentsCommand2 = addListOptions(
26415
- new Command("documents").description("List the signer's documents").argument("<signerId>", "Signer ID").addOption(accessCodeOption())
26787
+ new Command("documents").description("List the signer's documents").argument("<signerId>", "Signer ID").addOption(optionalAccessCodeOption())
26416
26788
  ).action(async (signerId, opts, command) => {
26417
- await runWithPublicClient(command, async ({ client, config }) => {
26789
+ await runSignerOrOwner(opts.accessCode)(command, async ({ client, config }) => {
26418
26790
  const result = await withSpinner(
26419
26791
  "Fetching documents",
26420
26792
  config,
@@ -26431,8 +26803,8 @@ var documentsCommand2 = addListOptions(
26431
26803
  );
26432
26804
  });
26433
26805
  });
26434
- var searchCommand2 = new Command("search").description("Search the signer's documents").argument("<signerId>", "Signer ID").argument("<query>", "Search text").addOption(accessCodeOption()).action(async (signerId, query, opts, command) => {
26435
- await runWithPublicClient(command, async ({ client, config }) => {
26806
+ var searchCommand2 = new Command("search").description("Search the signer's documents").argument("<signerId>", "Signer ID").argument("<query>", "Search text").addOption(optionalAccessCodeOption()).action(async (signerId, query, opts, command) => {
26807
+ await runSignerOrOwner(opts.accessCode)(command, async ({ client, config }) => {
26436
26808
  const result = await withSpinner(
26437
26809
  "Searching documents",
26438
26810
  config,
@@ -26932,7 +27304,7 @@ var preferencesCommand = new Command("notification-preferences").alias("preferen
26932
27304
  var usersCommand = new Command("users").description("Show the authenticated user and personal preferences").addCommand(selfCommand2).addCommand(statsCommand).addCommand(preferencesCommand);
26933
27305
 
26934
27306
  // src/commands/webhooks.ts
26935
- var registerCommand = new Command("register").description("Register (or replace) the workspace webhook subscription").requiredOption("--url <url>", "Endpoint URL to receive events").requiredOption("--email <email>", "Contact email for delivery problems").option("--events <csv>", "Comma-separated event names (defaults to a sensible set)").option("--inactive", "Register the subscription as inactive").action(async (opts, command) => {
27307
+ var registerCommand = new Command("register").description("Register (or replace) the account's oldest webhook endpoint").requiredOption("--url <url>", "Endpoint URL to receive events").requiredOption("--email <email>", "Contact email for delivery problems").option("--events <csv>", "Comma-separated event names (defaults to a sensible set)").option("--inactive", "Register the subscription as inactive").action(async (opts, command) => {
26936
27308
  await runWithClient(command, async ({ client, config }) => {
26937
27309
  const accountId = requireAccountId(config);
26938
27310
  const events = splitList(opts.events);
@@ -26952,7 +27324,7 @@ var registerCommand = new Command("register").description("Register (or replace)
26952
27324
  );
26953
27325
  });
26954
27326
  });
26955
- var getCommand6 = new Command("get").description("Show the current webhook subscription").action(async (_opts, command) => {
27327
+ var getCommand6 = new Command("get").description("Show the account's oldest webhook endpoint").action(async (_opts, command) => {
26956
27328
  await runWithClient(command, async ({ client, config }) => {
26957
27329
  const accountId = requireAccountId(config);
26958
27330
  const sub = await withSpinner(
@@ -26971,7 +27343,7 @@ var getCommand6 = new Command("get").description("Show the current webhook subsc
26971
27343
  );
26972
27344
  });
26973
27345
  });
26974
- var inactivateCommand = new Command("inactivate").description("Inactivate the webhook subscription without deleting it").action(async (_opts, command) => {
27346
+ var inactivateCommand = new Command("inactivate").description("Inactivate the account's oldest webhook endpoint without deleting it").action(async (_opts, command) => {
26975
27347
  await runWithClient(command, async ({ client, config }) => {
26976
27348
  const accountId = requireAccountId(config);
26977
27349
  const sub = await withSpinner(
@@ -27001,12 +27373,13 @@ var eventTypesCommand = new Command("event-types").description("List supported w
27001
27373
  });
27002
27374
  });
27003
27375
  var dispatchesCommand = addSortableListOptions(
27004
- new Command("dispatches").description("List webhook delivery history").option("--event <event>", "Filter by event name").option("--delivered <bool>", "Filter by delivery status (true/false)").option("--from <unix>", "Start of time range (unix seconds)").option("--to <unix>", "End of time range (unix seconds)"),
27376
+ new Command("dispatches").description("List webhook delivery history").option("--endpoint <endpointId>", "Only deliveries to this webhook endpoint").option("--event <event>", "Filter by event name").option("--delivered <bool>", "Filter by delivery status (true/false)").option("--from <unix>", "Start of time range (unix seconds)").option("--to <unix>", "End of time range (unix seconds)"),
27005
27377
  "Sort by created_at (prefix with - for descending)"
27006
27378
  ).action(async (opts, command) => {
27007
27379
  await runWithClient(command, async ({ client, config }) => {
27008
27380
  const accountId = requireAccountId(config);
27009
27381
  const params = { ...listParams(opts) };
27382
+ if (opts.endpoint) params.endpoint_id = opts.endpoint;
27010
27383
  if (opts.event) params.event = opts.event;
27011
27384
  if (opts.delivered !== void 0) {
27012
27385
  const v = opts.delivered.toLowerCase();
@@ -27052,7 +27425,169 @@ var retryCommand = new Command("retry").description("Retry delivery of a specifi
27052
27425
  );
27053
27426
  });
27054
27427
  });
27055
- var webhooksCommand = new Command("webhooks").description("Manage webhook subscriptions and delivery history").addCommand(registerCommand).addCommand(getCommand6).addCommand(inactivateCommand).addCommand(eventTypesCommand).addCommand(dispatchesCommand).addCommand(retryCommand);
27428
+ var renderEndpoint = (e) => renderKeyValue({
27429
+ id: e.id,
27430
+ name: e.name,
27431
+ url: e.url,
27432
+ email: e.email,
27433
+ is_active: e.is_active,
27434
+ signing_enabled: e.signing_enabled,
27435
+ events: e.events
27436
+ });
27437
+ function endpointFieldOptions(command) {
27438
+ return command.option("--name <name>", "Label to tell endpoints apart").option("--events <csv>", "Comma-separated event names").addOption(new Option("--active", "Deliver events to this endpoint")).addOption(new Option("--inactive", "Stop delivering events").conflicts("active")).addOption(new Option("--signing", "Sign deliveries (Standard Webhooks)")).addOption(
27439
+ new Option("--no-signing", "Disable signing and discard the secret").default(void 0)
27440
+ );
27441
+ }
27442
+ function endpointPayload(opts) {
27443
+ const payload = {};
27444
+ if (opts.url !== void 0) payload.url = opts.url;
27445
+ if (opts.email !== void 0) payload.email = opts.email;
27446
+ if (opts.name !== void 0) payload.name = opts.name;
27447
+ const events = splitList(opts.events);
27448
+ if (events !== void 0) payload.events = events;
27449
+ if (opts.active || opts.inactive) payload.is_active = Boolean(opts.active);
27450
+ if (opts.signing !== void 0) payload.signing_enabled = opts.signing;
27451
+ return payload;
27452
+ }
27453
+ var endpointsListCommand = new Command("list").alias("ls").description("List webhook endpoints, oldest first").action(async (_opts, command) => {
27454
+ await runWithClient(command, async ({ client, config }) => {
27455
+ const accountId = requireAccountId(config);
27456
+ const rows = await withSpinner(
27457
+ "Fetching endpoints",
27458
+ config,
27459
+ () => client.webhooks.listEndpoints(accountId)
27460
+ );
27461
+ printData(
27462
+ rows,
27463
+ config,
27464
+ (list) => renderTable(list, [
27465
+ { header: "ID", value: (r2) => r2.id },
27466
+ { header: "NAME", value: (r2) => r2.name },
27467
+ { header: "URL", value: (r2) => r2.url },
27468
+ { header: "ACTIVE", value: (r2) => r2.is_active },
27469
+ { header: "SIGNED", value: (r2) => r2.signing_enabled }
27470
+ ])
27471
+ );
27472
+ });
27473
+ });
27474
+ var endpointsCreateCommand = endpointFieldOptions(
27475
+ new Command("create").description("Register a webhook endpoint (1 per account, up to 3 on paid plans)").requiredOption("--url <url>", "Endpoint URL to receive events").requiredOption("--email <email>", "Contact email for delivery problems")
27476
+ ).action(async (opts, command) => {
27477
+ await runWithClient(command, async ({ client, config }) => {
27478
+ const accountId = requireAccountId(config);
27479
+ const endpoint = await withSpinner(
27480
+ "Creating endpoint",
27481
+ config,
27482
+ () => client.webhooks.createEndpoint(
27483
+ { ...endpointPayload(opts), url: opts.url, email: opts.email },
27484
+ accountId
27485
+ )
27486
+ );
27487
+ printSuccess("Webhook endpoint created", config);
27488
+ printData(endpoint, config, renderEndpoint);
27489
+ });
27490
+ });
27491
+ var endpointsGetCommand = new Command("get").description("Show one webhook endpoint").argument("<endpointId>", "Endpoint ID").action(async (endpointId, _opts, command) => {
27492
+ await runWithClient(command, async ({ client, config }) => {
27493
+ const accountId = requireAccountId(config);
27494
+ const endpoint = await withSpinner(
27495
+ "Fetching endpoint",
27496
+ config,
27497
+ () => client.webhooks.getEndpoint(endpointId, accountId)
27498
+ );
27499
+ printData(endpoint, config, renderEndpoint);
27500
+ });
27501
+ });
27502
+ var endpointsUpdateCommand = endpointFieldOptions(
27503
+ new Command("update").description("Update the given fields of a webhook endpoint").argument("<endpointId>", "Endpoint ID").option("--url <url>", "Endpoint URL to receive events").option("--email <email>", "Contact email for delivery problems")
27504
+ ).action(async (endpointId, opts, command) => {
27505
+ await runWithClient(command, async ({ client, config }) => {
27506
+ const accountId = requireAccountId(config);
27507
+ const payload = endpointPayload(opts);
27508
+ if (Object.keys(payload).length === 0) {
27509
+ throw new CliError("Provide at least one field to update");
27510
+ }
27511
+ const endpoint = await withSpinner(
27512
+ "Updating endpoint",
27513
+ config,
27514
+ () => client.webhooks.updateEndpoint(endpointId, payload, accountId)
27515
+ );
27516
+ printSuccess("Webhook endpoint updated", config);
27517
+ printData(endpoint, config, renderEndpoint);
27518
+ });
27519
+ });
27520
+ var endpointsDeleteCommand = new Command("delete").alias("rm").description("Delete a webhook endpoint and free its slot").argument("<endpointId>", "Endpoint ID").option("-y, --yes", "Skip the confirmation prompt").action(async (endpointId, opts, command) => {
27521
+ await runWithClient(command, async ({ client, config }) => {
27522
+ const accountId = requireAccountId(config);
27523
+ if (!await confirmDestructive(`Delete webhook endpoint ${endpointId}?`, Boolean(opts.yes)))
27524
+ return;
27525
+ await withSpinner(
27526
+ "Deleting endpoint",
27527
+ config,
27528
+ () => client.webhooks.deleteEndpoint(endpointId, accountId)
27529
+ );
27530
+ printSuccess("Webhook endpoint deleted", config);
27531
+ printData({ id: endpointId, deleted: true }, config);
27532
+ });
27533
+ });
27534
+ var endpointsSecretCommand = new Command("secret").description(
27535
+ "Print the endpoint signing secret (signing must be enabled; not available via OAuth)"
27536
+ ).argument("<endpointId>", "Endpoint ID").action(async (endpointId, _opts, command) => {
27537
+ await runWithClient(command, async ({ client, config }) => {
27538
+ const accountId = requireAccountId(config);
27539
+ const result = await withSpinner(
27540
+ "Fetching secret",
27541
+ config,
27542
+ () => client.webhooks.getEndpointSecret(endpointId, accountId)
27543
+ );
27544
+ printData(result, config, (r2) => r2.secret);
27545
+ });
27546
+ });
27547
+ var endpointsRotateSecretCommand = new Command("rotate-secret").description("Replace the endpoint signing secret; the old one stops working immediately").argument("<endpointId>", "Endpoint ID").option("-y, --yes", "Skip the confirmation prompt").action(async (endpointId, opts, command) => {
27548
+ await runWithClient(command, async ({ client, config }) => {
27549
+ const accountId = requireAccountId(config);
27550
+ if (!await confirmDestructive(
27551
+ `Rotate the signing secret of ${endpointId}? The current secret stops working immediately.`,
27552
+ Boolean(opts.yes)
27553
+ ))
27554
+ return;
27555
+ const result = await withSpinner(
27556
+ "Rotating secret",
27557
+ config,
27558
+ () => client.webhooks.rotateEndpointSecret(endpointId, accountId)
27559
+ );
27560
+ printSuccess("Signing secret rotated", config);
27561
+ printData(result, config, (r2) => r2.secret);
27562
+ });
27563
+ });
27564
+ var verifyCommand2 = new Command("verify").description(
27565
+ "Verify a signed delivery (Standard Webhooks) against ASSINAFY_WEBHOOK_SECRET or the profile secret"
27566
+ ).argument("<bodyFile>", "Raw request body exactly as received").requiredOption("--id <value>", "webhook-id header").requiredOption("--timestamp <seconds>", "webhook-timestamp header").requiredOption("--signature <value>", "webhook-signature header").option("--tolerance <seconds>", "Accepted clock difference in seconds", "300").action(async (bodyFile, opts, command) => {
27567
+ await runAction(command, async ({ config }) => {
27568
+ if (!config.webhookSecret) {
27569
+ throw new CliError(
27570
+ "No webhook secret found. Set ASSINAFY_WEBHOOK_SECRET or `assinafy config set --webhook-secret`."
27571
+ );
27572
+ }
27573
+ const valid = new WebhookVerifier(config.webhookSecret).verifyDelivery(
27574
+ readBinary(bodyFile),
27575
+ {
27576
+ "webhook-id": opts.id,
27577
+ "webhook-timestamp": opts.timestamp,
27578
+ "webhook-signature": opts.signature
27579
+ },
27580
+ { toleranceSeconds: parseInteger(opts.tolerance, "--tolerance", { min: 0 }) }
27581
+ );
27582
+ if (!valid) {
27583
+ throw new CliError("Invalid webhook signature or timestamp outside the tolerance window.");
27584
+ }
27585
+ printSuccess("Webhook signature is valid", config);
27586
+ printData({ valid, id: opts.id }, config, () => "valid");
27587
+ });
27588
+ });
27589
+ var endpointsCommand = new Command("endpoints").description("Manage webhook endpoints and their signing secrets").addCommand(endpointsListCommand).addCommand(endpointsCreateCommand).addCommand(endpointsGetCommand).addCommand(endpointsUpdateCommand).addCommand(endpointsDeleteCommand).addCommand(endpointsSecretCommand).addCommand(endpointsRotateSecretCommand);
27590
+ var webhooksCommand = new Command("webhooks").description("Manage webhook endpoints, the primary subscription, and delivery history").addCommand(endpointsCommand).addCommand(registerCommand).addCommand(getCommand6).addCommand(inactivateCommand).addCommand(eventTypesCommand).addCommand(dispatchesCommand).addCommand(retryCommand).addCommand(verifyCommand2);
27056
27591
 
27057
27592
  // src/commands/whoami.ts
27058
27593
  var whoamiCommand = new Command("whoami").description("Verify credentials and list the workspaces they can access").action(async (_opts, command) => {
@@ -27275,7 +27810,7 @@ function handleStreamError(err, fallback, exit = process.exit) {
27275
27810
  // package.json
27276
27811
  var package_default = {
27277
27812
  name: "@assinafy/cli",
27278
- version: "2.4.2",
27813
+ version: "2.5.1",
27279
27814
  description: "The official command-line interface for the Assinafy digital-signature API",
27280
27815
  license: "MIT",
27281
27816
  type: "module",
@@ -27329,7 +27864,7 @@ var package_default = {
27329
27864
  bugs: {
27330
27865
  url: "https://github.com/assinafy/assinafy-cli/issues"
27331
27866
  },
27332
- homepage: "https://github.com/assinafy/assinafy-cli#readme",
27867
+ homepage: "https://www.assinafy.com.br",
27333
27868
  scripts: {
27334
27869
  dev: "tsx src/cli.ts",
27335
27870
  "dev:watch": "tsx --watch src/cli.ts",