@assinafy/cli 2.4.2 → 2.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/api.js CHANGED
@@ -530,6 +530,12 @@ var AssignmentResource = class extends BaseResource {
530
530
  };
531
531
 
532
532
  // src/api/resources/authentication.ts
533
+ function requireReauth(payload) {
534
+ if (!payload?.password && !payload?.code) {
535
+ throw new ValidationError("password or code is required");
536
+ }
537
+ return payload;
538
+ }
533
539
  var AuthenticationResource = class extends BaseResource {
534
540
  /** `POST /login` — exchange email + password for a JWT access token. */
535
541
  async login(email, password) {
@@ -540,6 +546,70 @@ var AuthenticationResource = class extends BaseResource {
540
546
  () => this.http.post("/login", { email, password }, publicRequestConfig())
541
547
  );
542
548
  }
549
+ /**
550
+ * `POST /authentication/mfa/verify` — exchange the login `mfa_token` and an
551
+ * authenticator or recovery code for an access token. The challenge is
552
+ * single-use and expires 5 minutes after login.
553
+ */
554
+ async verifyMfa(payload) {
555
+ if (!payload?.mfa_token) throw new ValidationError("mfa_token is required");
556
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
557
+ return this.call(
558
+ "Two-factor verification failed",
559
+ () => this.http.post(
560
+ "/authentication/mfa/verify",
561
+ { mfa_token: payload.mfa_token, code: payload.code.trim() },
562
+ publicRequestConfig()
563
+ )
564
+ );
565
+ }
566
+ /** `GET /users/self/mfa` — enrolled two-factor methods and remaining recovery codes. */
567
+ async listMfaMethods() {
568
+ return this.call("Failed to list two-factor methods", () => this.http.get("/users/self/mfa"));
569
+ }
570
+ /**
571
+ * `POST /users/self/mfa/totp` — start authenticator enrollment. The secret
572
+ * and provisioning URI are returned only once; two-factor stays inactive
573
+ * until {@link confirmTotpEnrollment}.
574
+ */
575
+ async startTotpEnrollment(label) {
576
+ return this.call(
577
+ "Failed to start authenticator enrollment",
578
+ () => this.http.post("/users/self/mfa/totp", label ? { label } : {})
579
+ );
580
+ }
581
+ /**
582
+ * `PUT /users/self/mfa/totp/confirm` — activate the method with a live code
583
+ * and receive one-time recovery codes. Replacing a confirmed method also
584
+ * requires `password` or `reauth_code`.
585
+ */
586
+ async confirmTotpEnrollment(payload) {
587
+ if (!payload?.id) throw new ValidationError("id is required");
588
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
589
+ return this.call(
590
+ "Failed to confirm authenticator enrollment",
591
+ () => this.http.put("/users/self/mfa/totp/confirm", payload)
592
+ );
593
+ }
594
+ /** `POST /users/self/mfa/recovery-codes` — issue ten new recovery codes, invalidating the old set. */
595
+ async regenerateRecoveryCodes(payload) {
596
+ return this.call(
597
+ "Failed to regenerate recovery codes",
598
+ () => this.http.post("/users/self/mfa/recovery-codes", requireReauth(payload))
599
+ );
600
+ }
601
+ /**
602
+ * `DELETE /users/self/mfa/{methodId}` — remove a method. Removing the last
603
+ * one also discards the recovery codes.
604
+ */
605
+ async removeMfaMethod(methodId, payload) {
606
+ const id = this.requireId(methodId, "Method ID");
607
+ const data = requireReauth(payload);
608
+ return this.call(
609
+ "Failed to remove two-factor method",
610
+ () => this.http.delete(`/users/self/mfa/${id}`, { data })
611
+ );
612
+ }
543
613
  /** `POST /authentication/social-login` — exchange a provider token for an Assinafy JWT. */
544
614
  async socialLogin(payload) {
545
615
  if (payload.provider !== "google") throw new ValidationError("provider must be google");
@@ -1921,10 +1991,8 @@ var DEFAULT_EVENTS = [
1921
1991
  "signer_rejected_document",
1922
1992
  "document_processing_failed"
1923
1993
  ];
1924
- var WebhookResource = class extends BaseResource {
1925
- /** Register (or replace) the webhook subscription for the workspace. */
1926
- async register(payload, accountId) {
1927
- if (!payload.url) throw new ValidationError("Webhook URL is required");
1994
+ function validateWebhookFields(payload) {
1995
+ if (payload.url !== void 0) {
1928
1996
  let webhookUrl;
1929
1997
  try {
1930
1998
  webhookUrl = new URL(payload.url);
@@ -1934,13 +2002,29 @@ var WebhookResource = class extends BaseResource {
1934
2002
  if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
1935
2003
  throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1936
2004
  }
1937
- requireEmail(payload.email);
1938
- if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
1939
- throw new ValidationError("Webhook events must contain non-empty strings");
1940
- }
1941
- if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
1942
- throw new ValidationError("Webhook is_active must be a boolean");
2005
+ }
2006
+ if (payload.email !== void 0) requireEmail(payload.email);
2007
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
2008
+ throw new ValidationError("Webhook events must contain non-empty strings");
2009
+ }
2010
+ if (payload.name !== void 0 && typeof payload.name !== "string") {
2011
+ throw new ValidationError("Webhook name must be a string");
2012
+ }
2013
+ for (const key of ["is_active", "signing_enabled"]) {
2014
+ if (payload[key] !== void 0 && typeof payload[key] !== "boolean") {
2015
+ throw new ValidationError(`Webhook ${key} must be a boolean`);
1943
2016
  }
2017
+ }
2018
+ }
2019
+ var WebhookResource = class extends BaseResource {
2020
+ /**
2021
+ * `PUT /accounts/{accountId}/webhooks/subscriptions` — create or replace the
2022
+ * account's oldest webhook endpoint. Use the endpoint methods for accounts
2023
+ * with several endpoints or for signed deliveries.
2024
+ */
2025
+ async register(payload, accountId) {
2026
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
2027
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
1944
2028
  const id = this.accountId(accountId);
1945
2029
  const body = {
1946
2030
  url: payload.url,
@@ -1956,7 +2040,7 @@ var WebhookResource = class extends BaseResource {
1956
2040
  () => this.http.put(`/accounts/${id}/webhooks/subscriptions`, body)
1957
2041
  );
1958
2042
  }
1959
- /** Fetch the current webhook subscription. Returns `null` if none exists. */
2043
+ /** Fetch the account's oldest webhook endpoint. Returns `null` if none exists. */
1960
2044
  async get(accountId) {
1961
2045
  const id = this.accountId(accountId);
1962
2046
  return this.callOptional(
@@ -1964,7 +2048,7 @@ var WebhookResource = class extends BaseResource {
1964
2048
  () => this.http.get(`/accounts/${id}/webhooks/subscriptions`)
1965
2049
  );
1966
2050
  }
1967
- /** Inactivate the current webhook subscription without deleting it. */
2051
+ /** Inactivate the account's oldest webhook endpoint without deleting it. */
1968
2052
  async inactivate(accountId) {
1969
2053
  const id = this.accountId(accountId);
1970
2054
  this.logger.info("Inactivating webhook subscription");
@@ -1973,6 +2057,91 @@ var WebhookResource = class extends BaseResource {
1973
2057
  () => this.http.put(`/accounts/${id}/webhooks/inactivate`)
1974
2058
  );
1975
2059
  }
2060
+ /** `GET /accounts/{accountId}/webhooks/endpoints` — list webhook endpoints, oldest first. */
2061
+ async listEndpoints(accountId) {
2062
+ const id = this.accountId(accountId);
2063
+ return this.call(
2064
+ "Failed to list webhook endpoints",
2065
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints`)
2066
+ );
2067
+ }
2068
+ /**
2069
+ * `POST /accounts/{accountId}/webhooks/endpoints` — register another
2070
+ * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past
2071
+ * the limit); URLs must be unique per workspace. Omitted `events` uses the
2072
+ * same default set as {@link register}.
2073
+ */
2074
+ async createEndpoint(payload, accountId) {
2075
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
2076
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
2077
+ const id = this.accountId(accountId);
2078
+ const body = { ...payload, events: payload.events ?? DEFAULT_EVENTS };
2079
+ this.logger.info("Creating webhook endpoint", { eventCount: body.events.length });
2080
+ return this.call(
2081
+ "Failed to create webhook endpoint",
2082
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints`, body)
2083
+ );
2084
+ }
2085
+ /** `GET /accounts/{accountId}/webhooks/endpoints/{endpointId}` — fetch one endpoint. */
2086
+ async getEndpoint(endpointId, accountId) {
2087
+ const id = this.accountId(accountId);
2088
+ const eid = this.requireId(endpointId, "Endpoint ID");
2089
+ return this.call(
2090
+ "Failed to fetch webhook endpoint",
2091
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}`)
2092
+ );
2093
+ }
2094
+ /**
2095
+ * `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` — update only
2096
+ * the fields sent. Enabling signing creates a secret when none exists;
2097
+ * disabling it discards the secret.
2098
+ */
2099
+ async updateEndpoint(endpointId, payload, accountId) {
2100
+ const id = this.accountId(accountId);
2101
+ const eid = this.requireId(endpointId, "Endpoint ID");
2102
+ if (!payload || typeof payload !== "object" || Object.keys(payload).length === 0) {
2103
+ throw new ValidationError("At least one webhook endpoint field is required");
2104
+ }
2105
+ validateWebhookFields(payload);
2106
+ return this.call(
2107
+ "Failed to update webhook endpoint",
2108
+ () => this.http.put(`/accounts/${id}/webhooks/endpoints/${eid}`, payload)
2109
+ );
2110
+ }
2111
+ /** `DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}` — delete an endpoint and free its slot. */
2112
+ async deleteEndpoint(endpointId, accountId) {
2113
+ const id = this.accountId(accountId);
2114
+ const eid = this.requireId(endpointId, "Endpoint ID");
2115
+ return this.call(
2116
+ "Failed to delete webhook endpoint",
2117
+ () => this.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`)
2118
+ );
2119
+ }
2120
+ /**
2121
+ * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.
2122
+ * Returns `400` when signing is disabled. Not available to OAuth applications.
2123
+ */
2124
+ async getEndpointSecret(endpointId, accountId) {
2125
+ const id = this.accountId(accountId);
2126
+ const eid = this.requireId(endpointId, "Endpoint ID");
2127
+ return this.call(
2128
+ "Failed to fetch webhook endpoint secret",
2129
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}/secret`)
2130
+ );
2131
+ }
2132
+ /**
2133
+ * `POST …/endpoints/{endpointId}/secret/rotate` — replace the signing secret.
2134
+ * The old secret stops working immediately. Not available to OAuth applications.
2135
+ */
2136
+ async rotateEndpointSecret(endpointId, accountId) {
2137
+ const id = this.accountId(accountId);
2138
+ const eid = this.requireId(endpointId, "Endpoint ID");
2139
+ this.logger.info("Rotating webhook endpoint secret");
2140
+ return this.call(
2141
+ "Failed to rotate webhook endpoint secret",
2142
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints/${eid}/secret/rotate`)
2143
+ );
2144
+ }
1976
2145
  /** List currently supported webhook event types. */
1977
2146
  async listEventTypes() {
1978
2147
  return this.call(
@@ -1980,7 +2149,7 @@ var WebhookResource = class extends BaseResource {
1980
2149
  () => this.http.get("/webhooks/event-types")
1981
2150
  );
1982
2151
  }
1983
- /** List webhook delivery history for the workspace. */
2152
+ /** List webhook delivery history for the workspace, optionally for one endpoint. */
1984
2153
  async listDispatches(params = {}, accountId) {
1985
2154
  const id = this.accountId(accountId);
1986
2155
  if ("search" in params) throw new ValidationError("webhook dispatch search is not supported");
@@ -1992,7 +2161,7 @@ var WebhookResource = class extends BaseResource {
1992
2161
  })
1993
2162
  );
1994
2163
  }
1995
- /** Retry delivery of a specific webhook dispatch. */
2164
+ /** Retry delivery of a specific webhook dispatch to that entry's endpoint. */
1996
2165
  async retryDispatch(dispatchId, accountId) {
1997
2166
  const id = this.accountId(accountId);
1998
2167
  const did = this.requireId(dispatchId, "Dispatch ID");
@@ -2101,6 +2270,17 @@ function validateNotificationSender(value) {
2101
2270
 
2102
2271
  // src/api/support/webhook-verifier.ts
2103
2272
  import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
2273
+ function readHeader(headers, name) {
2274
+ if (typeof headers.get === "function") {
2275
+ return headers.get(name) ?? void 0;
2276
+ }
2277
+ for (const [key, value] of Object.entries(headers)) {
2278
+ if (key.toLowerCase() !== name) continue;
2279
+ if (Array.isArray(value)) return value.length === 1 ? value[0] : void 0;
2280
+ return value;
2281
+ }
2282
+ return void 0;
2283
+ }
2104
2284
  var WebhookVerifier = class {
2105
2285
  constructor(webhookSecret, options = {}) {
2106
2286
  this.webhookSecret = webhookSecret;
@@ -2110,15 +2290,48 @@ var WebhookVerifier = class {
2110
2290
  webhookSecret;
2111
2291
  algorithm;
2112
2292
  encoding;
2113
- /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
2293
+ /**
2294
+ * Returns `true` when `headers` carry a Standard Webhooks signature that
2295
+ * matches the raw `payload` under this verifier's `whsec_` secret and the
2296
+ * `webhook-timestamp` is within the tolerance window. Pass the body exactly
2297
+ * as received; re-serialized JSON does not verify.
2298
+ */
2299
+ verifyDelivery(payload, headers, options = {}) {
2300
+ if (!this.webhookSecret || !headers) return false;
2301
+ const id = readHeader(headers, "webhook-id");
2302
+ const timestamp = readHeader(headers, "webhook-timestamp");
2303
+ const signatures = readHeader(headers, "webhook-signature");
2304
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
2305
+ const tolerance = options.toleranceSeconds ?? 300;
2306
+ const now = Math.floor((options.now ?? Date.now()) / 1e3);
2307
+ if (Math.abs(now - Number(timestamp)) > tolerance) return false;
2308
+ const secret = this.webhookSecret.startsWith("whsec_") ? this.webhookSecret.slice("whsec_".length) : this.webhookSecret;
2309
+ const key = Buffer.from(secret, "base64");
2310
+ if (key.length === 0) return false;
2311
+ const expected = Buffer.from(
2312
+ createHmac("sha256", key).update(`${id}.${timestamp}.`).update(typeof payload === "string" ? Buffer.from(payload, "utf8") : payload).digest("base64")
2313
+ );
2314
+ return signatures.split(" ").some((entry) => {
2315
+ const [version, value] = entry.split(",", 2);
2316
+ if (version !== "v1" || !value) return false;
2317
+ const provided = Buffer.from(value);
2318
+ return provided.length === expected.length && timingSafeEqual2(provided, expected);
2319
+ });
2320
+ }
2321
+ /**
2322
+ * Returns `true` if `signature` is an HMAC of `payload` keyed with the raw
2323
+ * secret string under the configured algorithm/encoding.
2324
+ *
2325
+ * @deprecated Assinafy signs deliveries with Standard Webhooks headers; use
2326
+ * {@link verifyDelivery}. Retained for existing callers.
2327
+ */
2114
2328
  verify(payload, signature) {
2115
2329
  if (!this.webhookSecret || !signature) return false;
2116
2330
  try {
2117
2331
  const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
2118
2332
  const expected = createHmac(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
2119
- const provided = signature.trim();
2120
2333
  const a = Buffer.from(expected, "utf8");
2121
- const b = Buffer.from(provided, "utf8");
2334
+ const b = Buffer.from(signature.trim(), "utf8");
2122
2335
  if (a.length !== b.length) return false;
2123
2336
  return timingSafeEqual2(a, b);
2124
2337
  } catch {