@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/api.cjs CHANGED
@@ -76,6 +76,8 @@ var ApiError = class _ApiError extends AssinafyError {
76
76
  wwwAuthenticate;
77
77
  /** Server retry delay (seconds or HTTP date), when provided. */
78
78
  retryAfter;
79
+ /** Rate-limit window reported by the API, when the headers are present. */
80
+ rateLimit;
79
81
  constructor(message, statusCode, responseData = null, options) {
80
82
  super(message, { statusCode, responseData }, options);
81
83
  this.name = "ApiError";
@@ -83,6 +85,7 @@ var ApiError = class _ApiError extends AssinafyError {
83
85
  this.responseData = responseData;
84
86
  this.wwwAuthenticate = options?.wwwAuthenticate;
85
87
  this.retryAfter = options?.retryAfter;
88
+ this.rateLimit = options?.rateLimit;
86
89
  }
87
90
  static fromResponse(statusCode, responseData, headers = {}) {
88
91
  if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
@@ -96,13 +99,23 @@ var ApiError = class _ApiError extends AssinafyError {
96
99
  const data = responseData ?? {};
97
100
  const rawMessage = data.message;
98
101
  const rawError = data.error;
99
- const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
102
+ const description = data.error_description;
103
+ const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? typeof description === "string" && description.length > 0 ? `${rawError}: ${description}` : rawError : "API request failed";
100
104
  return new _ApiError(message, statusCode, responseData, {
101
105
  wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
102
- retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
106
+ retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0,
107
+ rateLimit: parseRateLimit(headers)
103
108
  });
104
109
  }
105
110
  };
111
+ function parseRateLimit(headers) {
112
+ const info = {};
113
+ for (const key of ["limit", "remaining", "reset"]) {
114
+ const value = Number.parseInt(String(headers[`x-rate-limit-${key}`]), 10);
115
+ if (Number.isFinite(value)) info[key] = value;
116
+ }
117
+ return Object.keys(info).length > 0 ? info : void 0;
118
+ }
106
119
  var ValidationError = class extends AssinafyError {
107
120
  errors;
108
121
  constructor(message = "Validation failed", errors = {}) {
@@ -256,6 +269,16 @@ function validateSignerOptions(input) {
256
269
  `notification_methods must contain only: ${NOTIFICATION_METHODS.join(", ")}`
257
270
  );
258
271
  }
272
+ const notifications = input.notification_methods ?? [];
273
+ if (notifications.length > 1) {
274
+ throw new ValidationError("notification_methods accepts exactly one method per signer");
275
+ }
276
+ const [notification] = notifications;
277
+ if (notification !== void 0 && (input.verification_method === "Email" || input.verification_method === "Whatsapp") && notification !== input.verification_method) {
278
+ throw new ValidationError(
279
+ `${input.verification_method} verification requires the ${input.verification_method} notification method`
280
+ );
281
+ }
259
282
  if (input.step !== void 0 && !Number.isInteger(input.step)) {
260
283
  throw new ValidationError("step must be an integer");
261
284
  }
@@ -589,6 +612,12 @@ var AssignmentResource = class extends BaseResource {
589
612
  };
590
613
 
591
614
  // src/api/resources/authentication.ts
615
+ function requireReauth(payload) {
616
+ if (!payload?.password && !payload?.code) {
617
+ throw new ValidationError("password or code is required");
618
+ }
619
+ return payload;
620
+ }
592
621
  var AuthenticationResource = class extends BaseResource {
593
622
  /** `POST /login` — exchange email + password for a JWT access token. */
594
623
  async login(email, password) {
@@ -599,6 +628,70 @@ var AuthenticationResource = class extends BaseResource {
599
628
  () => this.http.post("/login", { email, password }, publicRequestConfig())
600
629
  );
601
630
  }
631
+ /**
632
+ * `POST /authentication/mfa/verify` — exchange the login `mfa_token` and an
633
+ * authenticator or recovery code for an access token. The challenge is
634
+ * single-use and expires 5 minutes after login.
635
+ */
636
+ async verifyMfa(payload) {
637
+ if (!payload?.mfa_token) throw new ValidationError("mfa_token is required");
638
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
639
+ return this.call(
640
+ "Two-factor verification failed",
641
+ () => this.http.post(
642
+ "/authentication/mfa/verify",
643
+ { mfa_token: payload.mfa_token, code: payload.code.trim() },
644
+ publicRequestConfig()
645
+ )
646
+ );
647
+ }
648
+ /** `GET /users/self/mfa` — enrolled two-factor methods and remaining recovery codes. */
649
+ async listMfaMethods() {
650
+ return this.call("Failed to list two-factor methods", () => this.http.get("/users/self/mfa"));
651
+ }
652
+ /**
653
+ * `POST /users/self/mfa/totp` — start authenticator enrollment. The secret
654
+ * and provisioning URI are returned only once; two-factor stays inactive
655
+ * until {@link confirmTotpEnrollment}.
656
+ */
657
+ async startTotpEnrollment(label) {
658
+ return this.call(
659
+ "Failed to start authenticator enrollment",
660
+ () => this.http.post("/users/self/mfa/totp", label ? { label } : {})
661
+ );
662
+ }
663
+ /**
664
+ * `PUT /users/self/mfa/totp/confirm` — activate the method with a live code
665
+ * and receive one-time recovery codes. Replacing a confirmed method also
666
+ * requires `password` or `reauth_code`.
667
+ */
668
+ async confirmTotpEnrollment(payload) {
669
+ if (!payload?.id) throw new ValidationError("id is required");
670
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
671
+ return this.call(
672
+ "Failed to confirm authenticator enrollment",
673
+ () => this.http.put("/users/self/mfa/totp/confirm", payload)
674
+ );
675
+ }
676
+ /** `POST /users/self/mfa/recovery-codes` — issue ten new recovery codes, invalidating the old set. */
677
+ async regenerateRecoveryCodes(payload) {
678
+ return this.call(
679
+ "Failed to regenerate recovery codes",
680
+ () => this.http.post("/users/self/mfa/recovery-codes", requireReauth(payload))
681
+ );
682
+ }
683
+ /**
684
+ * `DELETE /users/self/mfa/{methodId}` — remove a method. Removing the last
685
+ * one also discards the recovery codes.
686
+ */
687
+ async removeMfaMethod(methodId, payload) {
688
+ const id = this.requireId(methodId, "Method ID");
689
+ const data = requireReauth(payload);
690
+ return this.call(
691
+ "Failed to remove two-factor method",
692
+ () => this.http.delete(`/users/self/mfa/${id}`, { data })
693
+ );
694
+ }
602
695
  /** `POST /authentication/social-login` — exchange a provider token for an Assinafy JWT. */
603
696
  async socialLogin(payload) {
604
697
  if (payload.provider !== "google") throw new ValidationError("provider must be google");
@@ -922,7 +1015,7 @@ var DocumentResource = class extends BaseResource {
922
1015
  async createFromTemplate(templateId, signers, options = {}, accountId) {
923
1016
  const tmplId = this.requireId(templateId, "Template ID");
924
1017
  const accId = this.accountId(accountId);
925
- validateTemplateSigners(signers, { requireId: true, singleNotification: true });
1018
+ validateTemplateSigners(signers, { requireId: true });
926
1019
  if (options.expires_at !== void 0) requireIso8601(options.expires_at, "expires_at");
927
1020
  if (options.editor_fields !== void 0 && (!Array.isArray(options.editor_fields) || options.editor_fields.some((field) => !field?.field_id || typeof field.value !== "string"))) {
928
1021
  throw new ValidationError("editor_fields must contain field_id and value");
@@ -941,7 +1034,7 @@ var DocumentResource = class extends BaseResource {
941
1034
  async estimateCostFromTemplate(templateId, signers, accountId) {
942
1035
  const tmplId = this.requireId(templateId, "Template ID");
943
1036
  const accId = this.accountId(accountId);
944
- validateTemplateSigners(signers, { requireId: false, singleNotification: false });
1037
+ validateTemplateSigners(signers, { requireId: false });
945
1038
  return this.call(
946
1039
  "Failed to estimate cost from template",
947
1040
  () => this.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers })
@@ -981,33 +1074,21 @@ var DocumentResource = class extends BaseResource {
981
1074
  );
982
1075
  }
983
1076
  /**
984
- * `PUT /public/documents/{document_id}/send-token` — send the 6-digit
985
- * verification token to the signer's email / WhatsApp. Pass `{ email }` for
986
- * the published OpenAPI body or a string plus channel for the live legacy body.
1077
+ * `PUT /public/documents/{document_id}/send-token` — email a one-time access
1078
+ * token to a signer who has not signed a pending document yet. The API sends
1079
+ * `{ channel: 'email', recipient }`; only the `email` channel is accepted.
1080
+ * The `{ email }` form is kept for existing callers and sends the same body.
987
1081
  */
988
1082
  async sendToken(documentId, recipient, channel = "email") {
989
1083
  const id = this.requireId(documentId, "Document ID");
990
- if (typeof recipient === "object") {
991
- requireEmail(recipient?.email);
992
- return this.call(
993
- "Failed to send signing token",
994
- () => this.http.put(
995
- `/public/documents/${id}/send-token`,
996
- { email: recipient.email },
997
- publicRequestConfig()
998
- )
999
- );
1000
- }
1001
- if (!recipient) throw new ValidationError("recipient is required");
1002
- if (channel !== "email" && channel !== "whatsapp") {
1003
- throw new ValidationError("channel must be email or whatsapp");
1004
- }
1005
- if (channel === "email") requireEmail(recipient);
1084
+ const email = typeof recipient === "object" ? recipient?.email : recipient;
1085
+ if (channel !== "email") throw new ValidationError("channel must be email");
1086
+ requireEmail(email);
1006
1087
  return this.call(
1007
1088
  "Failed to send signing token",
1008
1089
  () => this.http.put(
1009
1090
  `/public/documents/${id}/send-token`,
1010
- { recipient, channel },
1091
+ { channel, recipient: email },
1011
1092
  publicRequestConfig()
1012
1093
  )
1013
1094
  );
@@ -1050,9 +1131,6 @@ function validateTemplateSigners(signers, options) {
1050
1131
  if (options.requireId && signer.step !== void 0 && Number(signer.step) < 1) {
1051
1132
  throw new ValidationError("template signer step must be a positive integer");
1052
1133
  }
1053
- if (options.singleNotification && Array.isArray(signer.notification_methods) && signer.notification_methods.length > 1) {
1054
- throw new ValidationError("template signers accept at most one notification method");
1055
- }
1056
1134
  }
1057
1135
  if (options.requireId) {
1058
1136
  validateSigningSteps(signers);
@@ -1337,7 +1415,7 @@ var OAuthResource = class extends BaseResource {
1337
1415
  });
1338
1416
  }
1339
1417
  /**
1340
- * `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body.
1418
+ * `POST /oauth/token` — code exchange, refresh, or RFC 8693 token exchange; returns the flat OAuth JSON body.
1341
1419
  * A refresh must return a new `refresh_token`; otherwise this throws `ValidationError`.
1342
1420
  */
1343
1421
  async token(payload) {
@@ -1354,8 +1432,20 @@ var OAuthResource = class extends BaseResource {
1354
1432
  }
1355
1433
  } else if (payload.grant_type === "refresh_token") {
1356
1434
  required(payload.refresh_token, "refresh_token");
1435
+ } else if (payload.grant_type === TOKEN_EXCHANGE) {
1436
+ required(payload.client_secret, "client_secret");
1437
+ httpsUrl(required(payload.resource, "resource"), "resource");
1438
+ required(payload.subject_token, "subject_token");
1439
+ for (const field of ["subject_token_type", "requested_token_type"]) {
1440
+ const value = payload[field];
1441
+ if ((value !== void 0 || field === "subject_token_type") && value !== ACCESS_TOKEN_TYPE) {
1442
+ throw new ValidationError(`${field} must be ${ACCESS_TOKEN_TYPE}`);
1443
+ }
1444
+ }
1357
1445
  } else {
1358
- throw new ValidationError("grant_type must be authorization_code or refresh_token");
1446
+ throw new ValidationError(
1447
+ `grant_type must be authorization_code, refresh_token or ${TOKEN_EXCHANGE}`
1448
+ );
1359
1449
  }
1360
1450
  const tokens = await this.call(
1361
1451
  "OAuth token request failed",
@@ -1388,6 +1478,8 @@ var OAuthResource = class extends BaseResource {
1388
1478
  return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
1389
1479
  }
1390
1480
  };
1481
+ var TOKEN_EXCHANGE = "urn:ietf:params:oauth:grant-type:token-exchange";
1482
+ var ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";
1391
1483
  function required(value, name) {
1392
1484
  if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
1393
1485
  return value;
@@ -1416,27 +1508,32 @@ var SignerDocumentsResource = class extends BaseResource {
1416
1508
  () => this.http.get(`/signers/${sid}/document`, signerAccessConfig(code))
1417
1509
  );
1418
1510
  }
1419
- /** `GET /signers/{signer_id}/documents?signer-access-code=…` */
1511
+ /**
1512
+ * `GET /signers/{signer_id}/documents` — with a signer access code, or with
1513
+ * the client's owner credentials when the code is omitted (the signer must
1514
+ * belong to that workspace).
1515
+ */
1420
1516
  async list(signerId, signerAccessCode, params = {}) {
1421
1517
  const sid = this.requireId(signerId, "Signer ID");
1422
- const code = this.requireId(signerAccessCode, "signer-access-code");
1518
+ const config = this.signerOrOwnerConfig(signerAccessCode, { ...params });
1423
1519
  return this.callList(
1424
1520
  "Failed to list signer documents",
1425
- () => this.http.get(
1426
- `/signers/${sid}/documents`,
1427
- signerAccessConfig(code, params)
1428
- )
1521
+ () => this.http.get(`/signers/${sid}/documents`, config)
1429
1522
  );
1430
1523
  }
1431
- /** `GET /signers/{signer_id}/documents/search?signer-access-code=…&search=…` */
1524
+ /** `GET /signers/{signer_id}/documents/search?search=…` — access code or owner credentials. */
1432
1525
  async search(signerId, search, signerAccessCode) {
1433
1526
  const sid = this.requireId(signerId, "Signer ID");
1434
- const code = this.requireId(signerAccessCode, "signer-access-code");
1527
+ const config = this.signerOrOwnerConfig(signerAccessCode, { search });
1435
1528
  return this.callList(
1436
1529
  "Failed to search signer documents",
1437
- () => this.http.get(`/signers/${sid}/documents/search`, signerAccessConfig(code, { search }))
1530
+ () => this.http.get(`/signers/${sid}/documents/search`, config)
1438
1531
  );
1439
1532
  }
1533
+ signerOrOwnerConfig(signerAccessCode, params) {
1534
+ if (signerAccessCode === void 0) return { params: cleanParams(params) };
1535
+ return signerAccessConfig(this.requireId(signerAccessCode, "signer-access-code"), params);
1536
+ }
1440
1537
  /**
1441
1538
  * Public `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`.
1442
1539
  * When an access code is supplied, the SDK first verifies that it belongs to
@@ -1980,10 +2077,8 @@ var DEFAULT_EVENTS = [
1980
2077
  "signer_rejected_document",
1981
2078
  "document_processing_failed"
1982
2079
  ];
1983
- var WebhookResource = class extends BaseResource {
1984
- /** Register (or replace) the webhook subscription for the workspace. */
1985
- async register(payload, accountId) {
1986
- if (!payload.url) throw new ValidationError("Webhook URL is required");
2080
+ function validateWebhookFields(payload) {
2081
+ if (payload.url !== void 0) {
1987
2082
  let webhookUrl;
1988
2083
  try {
1989
2084
  webhookUrl = new URL(payload.url);
@@ -1993,13 +2088,29 @@ var WebhookResource = class extends BaseResource {
1993
2088
  if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
1994
2089
  throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1995
2090
  }
1996
- requireEmail(payload.email);
1997
- if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
1998
- throw new ValidationError("Webhook events must contain non-empty strings");
1999
- }
2000
- if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
2001
- throw new ValidationError("Webhook is_active must be a boolean");
2091
+ }
2092
+ if (payload.email !== void 0) requireEmail(payload.email);
2093
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
2094
+ throw new ValidationError("Webhook events must contain non-empty strings");
2095
+ }
2096
+ if (payload.name !== void 0 && typeof payload.name !== "string") {
2097
+ throw new ValidationError("Webhook name must be a string");
2098
+ }
2099
+ for (const key of ["is_active", "signing_enabled"]) {
2100
+ if (payload[key] !== void 0 && typeof payload[key] !== "boolean") {
2101
+ throw new ValidationError(`Webhook ${key} must be a boolean`);
2002
2102
  }
2103
+ }
2104
+ }
2105
+ var WebhookResource = class extends BaseResource {
2106
+ /**
2107
+ * `PUT /accounts/{accountId}/webhooks/subscriptions` — create or replace the
2108
+ * account's oldest webhook endpoint. Use the endpoint methods for accounts
2109
+ * with several endpoints or for signed deliveries.
2110
+ */
2111
+ async register(payload, accountId) {
2112
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
2113
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
2003
2114
  const id = this.accountId(accountId);
2004
2115
  const body = {
2005
2116
  url: payload.url,
@@ -2015,7 +2126,7 @@ var WebhookResource = class extends BaseResource {
2015
2126
  () => this.http.put(`/accounts/${id}/webhooks/subscriptions`, body)
2016
2127
  );
2017
2128
  }
2018
- /** Fetch the current webhook subscription. Returns `null` if none exists. */
2129
+ /** Fetch the account's oldest webhook endpoint. Returns `null` if none exists. */
2019
2130
  async get(accountId) {
2020
2131
  const id = this.accountId(accountId);
2021
2132
  return this.callOptional(
@@ -2023,7 +2134,7 @@ var WebhookResource = class extends BaseResource {
2023
2134
  () => this.http.get(`/accounts/${id}/webhooks/subscriptions`)
2024
2135
  );
2025
2136
  }
2026
- /** Inactivate the current webhook subscription without deleting it. */
2137
+ /** Inactivate the account's oldest webhook endpoint without deleting it. */
2027
2138
  async inactivate(accountId) {
2028
2139
  const id = this.accountId(accountId);
2029
2140
  this.logger.info("Inactivating webhook subscription");
@@ -2032,6 +2143,91 @@ var WebhookResource = class extends BaseResource {
2032
2143
  () => this.http.put(`/accounts/${id}/webhooks/inactivate`)
2033
2144
  );
2034
2145
  }
2146
+ /** `GET /accounts/{accountId}/webhooks/endpoints` — list webhook endpoints, oldest first. */
2147
+ async listEndpoints(accountId) {
2148
+ const id = this.accountId(accountId);
2149
+ return this.call(
2150
+ "Failed to list webhook endpoints",
2151
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints`)
2152
+ );
2153
+ }
2154
+ /**
2155
+ * `POST /accounts/{accountId}/webhooks/endpoints` — register another
2156
+ * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past
2157
+ * the limit); URLs must be unique per workspace. Omitted `events` uses the
2158
+ * same default set as {@link register}.
2159
+ */
2160
+ async createEndpoint(payload, accountId) {
2161
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
2162
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
2163
+ const id = this.accountId(accountId);
2164
+ const body = { ...payload, events: payload.events ?? DEFAULT_EVENTS };
2165
+ this.logger.info("Creating webhook endpoint", { eventCount: body.events.length });
2166
+ return this.call(
2167
+ "Failed to create webhook endpoint",
2168
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints`, body)
2169
+ );
2170
+ }
2171
+ /** `GET /accounts/{accountId}/webhooks/endpoints/{endpointId}` — fetch one endpoint. */
2172
+ async getEndpoint(endpointId, accountId) {
2173
+ const id = this.accountId(accountId);
2174
+ const eid = this.requireId(endpointId, "Endpoint ID");
2175
+ return this.call(
2176
+ "Failed to fetch webhook endpoint",
2177
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}`)
2178
+ );
2179
+ }
2180
+ /**
2181
+ * `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` — update only
2182
+ * the fields sent. Enabling signing creates a secret when none exists;
2183
+ * disabling it discards the secret.
2184
+ */
2185
+ async updateEndpoint(endpointId, payload, accountId) {
2186
+ const id = this.accountId(accountId);
2187
+ const eid = this.requireId(endpointId, "Endpoint ID");
2188
+ if (!payload || typeof payload !== "object" || Object.keys(payload).length === 0) {
2189
+ throw new ValidationError("At least one webhook endpoint field is required");
2190
+ }
2191
+ validateWebhookFields(payload);
2192
+ return this.call(
2193
+ "Failed to update webhook endpoint",
2194
+ () => this.http.put(`/accounts/${id}/webhooks/endpoints/${eid}`, payload)
2195
+ );
2196
+ }
2197
+ /** `DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}` — delete an endpoint and free its slot. */
2198
+ async deleteEndpoint(endpointId, accountId) {
2199
+ const id = this.accountId(accountId);
2200
+ const eid = this.requireId(endpointId, "Endpoint ID");
2201
+ return this.call(
2202
+ "Failed to delete webhook endpoint",
2203
+ () => this.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`)
2204
+ );
2205
+ }
2206
+ /**
2207
+ * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.
2208
+ * Returns `400` when signing is disabled. Not available to OAuth applications.
2209
+ */
2210
+ async getEndpointSecret(endpointId, accountId) {
2211
+ const id = this.accountId(accountId);
2212
+ const eid = this.requireId(endpointId, "Endpoint ID");
2213
+ return this.call(
2214
+ "Failed to fetch webhook endpoint secret",
2215
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}/secret`)
2216
+ );
2217
+ }
2218
+ /**
2219
+ * `POST …/endpoints/{endpointId}/secret/rotate` — replace the signing secret.
2220
+ * The old secret stops working immediately. Not available to OAuth applications.
2221
+ */
2222
+ async rotateEndpointSecret(endpointId, accountId) {
2223
+ const id = this.accountId(accountId);
2224
+ const eid = this.requireId(endpointId, "Endpoint ID");
2225
+ this.logger.info("Rotating webhook endpoint secret");
2226
+ return this.call(
2227
+ "Failed to rotate webhook endpoint secret",
2228
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints/${eid}/secret/rotate`)
2229
+ );
2230
+ }
2035
2231
  /** List currently supported webhook event types. */
2036
2232
  async listEventTypes() {
2037
2233
  return this.call(
@@ -2039,7 +2235,7 @@ var WebhookResource = class extends BaseResource {
2039
2235
  () => this.http.get("/webhooks/event-types")
2040
2236
  );
2041
2237
  }
2042
- /** List webhook delivery history for the workspace. */
2238
+ /** List webhook delivery history for the workspace, optionally for one endpoint. */
2043
2239
  async listDispatches(params = {}, accountId) {
2044
2240
  const id = this.accountId(accountId);
2045
2241
  if ("search" in params) throw new ValidationError("webhook dispatch search is not supported");
@@ -2051,7 +2247,7 @@ var WebhookResource = class extends BaseResource {
2051
2247
  })
2052
2248
  );
2053
2249
  }
2054
- /** Retry delivery of a specific webhook dispatch. */
2250
+ /** Retry delivery of a specific webhook dispatch to that entry's endpoint. */
2055
2251
  async retryDispatch(dispatchId, accountId) {
2056
2252
  const id = this.accountId(accountId);
2057
2253
  const did = this.requireId(dispatchId, "Dispatch ID");
@@ -2160,6 +2356,17 @@ function validateNotificationSender(value) {
2160
2356
 
2161
2357
  // src/api/support/webhook-verifier.ts
2162
2358
  var import_node_crypto2 = require("crypto");
2359
+ function readHeader(headers, name) {
2360
+ if (typeof headers.get === "function") {
2361
+ return headers.get(name) ?? void 0;
2362
+ }
2363
+ for (const [key, value] of Object.entries(headers)) {
2364
+ if (key.toLowerCase() !== name) continue;
2365
+ if (Array.isArray(value)) return value.length === 1 ? value[0] : void 0;
2366
+ return value;
2367
+ }
2368
+ return void 0;
2369
+ }
2163
2370
  var WebhookVerifier = class {
2164
2371
  constructor(webhookSecret, options = {}) {
2165
2372
  this.webhookSecret = webhookSecret;
@@ -2169,15 +2376,48 @@ var WebhookVerifier = class {
2169
2376
  webhookSecret;
2170
2377
  algorithm;
2171
2378
  encoding;
2172
- /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
2379
+ /**
2380
+ * Returns `true` when `headers` carry a Standard Webhooks signature that
2381
+ * matches the raw `payload` under this verifier's `whsec_` secret and the
2382
+ * `webhook-timestamp` is within the tolerance window. Pass the body exactly
2383
+ * as received; re-serialized JSON does not verify.
2384
+ */
2385
+ verifyDelivery(payload, headers, options = {}) {
2386
+ if (!this.webhookSecret || !headers) return false;
2387
+ const id = readHeader(headers, "webhook-id");
2388
+ const timestamp = readHeader(headers, "webhook-timestamp");
2389
+ const signatures = readHeader(headers, "webhook-signature");
2390
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
2391
+ const tolerance = options.toleranceSeconds ?? 300;
2392
+ const now = Math.floor((options.now ?? Date.now()) / 1e3);
2393
+ if (Math.abs(now - Number(timestamp)) > tolerance) return false;
2394
+ const secret = this.webhookSecret.startsWith("whsec_") ? this.webhookSecret.slice("whsec_".length) : this.webhookSecret;
2395
+ const key = Buffer.from(secret, "base64");
2396
+ if (key.length === 0) return false;
2397
+ const expected = Buffer.from(
2398
+ (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`).update(typeof payload === "string" ? Buffer.from(payload, "utf8") : payload).digest("base64")
2399
+ );
2400
+ return signatures.split(" ").some((entry) => {
2401
+ const [version, value] = entry.split(",", 2);
2402
+ if (version !== "v1" || !value) return false;
2403
+ const provided = Buffer.from(value);
2404
+ return provided.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(provided, expected);
2405
+ });
2406
+ }
2407
+ /**
2408
+ * Returns `true` if `signature` is an HMAC of `payload` keyed with the raw
2409
+ * secret string under the configured algorithm/encoding.
2410
+ *
2411
+ * @deprecated Assinafy signs deliveries with Standard Webhooks headers; use
2412
+ * {@link verifyDelivery}. Retained for existing callers.
2413
+ */
2173
2414
  verify(payload, signature) {
2174
2415
  if (!this.webhookSecret || !signature) return false;
2175
2416
  try {
2176
2417
  const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
2177
2418
  const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
2178
- const provided = signature.trim();
2179
2419
  const a = Buffer.from(expected, "utf8");
2180
- const b = Buffer.from(provided, "utf8");
2420
+ const b = Buffer.from(signature.trim(), "utf8");
2181
2421
  if (a.length !== b.length) return false;
2182
2422
  return (0, import_node_crypto2.timingSafeEqual)(a, b);
2183
2423
  } catch {