@assinafy/cli 2.4.1 → 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.cjs CHANGED
@@ -589,6 +589,12 @@ var AssignmentResource = class extends BaseResource {
589
589
  };
590
590
 
591
591
  // src/api/resources/authentication.ts
592
+ function requireReauth(payload) {
593
+ if (!payload?.password && !payload?.code) {
594
+ throw new ValidationError("password or code is required");
595
+ }
596
+ return payload;
597
+ }
592
598
  var AuthenticationResource = class extends BaseResource {
593
599
  /** `POST /login` — exchange email + password for a JWT access token. */
594
600
  async login(email, password) {
@@ -599,6 +605,70 @@ var AuthenticationResource = class extends BaseResource {
599
605
  () => this.http.post("/login", { email, password }, publicRequestConfig())
600
606
  );
601
607
  }
608
+ /**
609
+ * `POST /authentication/mfa/verify` — exchange the login `mfa_token` and an
610
+ * authenticator or recovery code for an access token. The challenge is
611
+ * single-use and expires 5 minutes after login.
612
+ */
613
+ async verifyMfa(payload) {
614
+ if (!payload?.mfa_token) throw new ValidationError("mfa_token is required");
615
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
616
+ return this.call(
617
+ "Two-factor verification failed",
618
+ () => this.http.post(
619
+ "/authentication/mfa/verify",
620
+ { mfa_token: payload.mfa_token, code: payload.code.trim() },
621
+ publicRequestConfig()
622
+ )
623
+ );
624
+ }
625
+ /** `GET /users/self/mfa` — enrolled two-factor methods and remaining recovery codes. */
626
+ async listMfaMethods() {
627
+ return this.call("Failed to list two-factor methods", () => this.http.get("/users/self/mfa"));
628
+ }
629
+ /**
630
+ * `POST /users/self/mfa/totp` — start authenticator enrollment. The secret
631
+ * and provisioning URI are returned only once; two-factor stays inactive
632
+ * until {@link confirmTotpEnrollment}.
633
+ */
634
+ async startTotpEnrollment(label) {
635
+ return this.call(
636
+ "Failed to start authenticator enrollment",
637
+ () => this.http.post("/users/self/mfa/totp", label ? { label } : {})
638
+ );
639
+ }
640
+ /**
641
+ * `PUT /users/self/mfa/totp/confirm` — activate the method with a live code
642
+ * and receive one-time recovery codes. Replacing a confirmed method also
643
+ * requires `password` or `reauth_code`.
644
+ */
645
+ async confirmTotpEnrollment(payload) {
646
+ if (!payload?.id) throw new ValidationError("id is required");
647
+ if (!payload.code?.trim()) throw new ValidationError("code is required");
648
+ return this.call(
649
+ "Failed to confirm authenticator enrollment",
650
+ () => this.http.put("/users/self/mfa/totp/confirm", payload)
651
+ );
652
+ }
653
+ /** `POST /users/self/mfa/recovery-codes` — issue ten new recovery codes, invalidating the old set. */
654
+ async regenerateRecoveryCodes(payload) {
655
+ return this.call(
656
+ "Failed to regenerate recovery codes",
657
+ () => this.http.post("/users/self/mfa/recovery-codes", requireReauth(payload))
658
+ );
659
+ }
660
+ /**
661
+ * `DELETE /users/self/mfa/{methodId}` — remove a method. Removing the last
662
+ * one also discards the recovery codes.
663
+ */
664
+ async removeMfaMethod(methodId, payload) {
665
+ const id = this.requireId(methodId, "Method ID");
666
+ const data = requireReauth(payload);
667
+ return this.call(
668
+ "Failed to remove two-factor method",
669
+ () => this.http.delete(`/users/self/mfa/${id}`, { data })
670
+ );
671
+ }
602
672
  /** `POST /authentication/social-login` — exchange a provider token for an Assinafy JWT. */
603
673
  async socialLogin(payload) {
604
674
  if (payload.provider !== "google") throw new ValidationError("provider must be google");
@@ -1204,7 +1274,11 @@ var FieldsResource = class extends BaseResource {
1204
1274
  }
1205
1275
  };
1206
1276
  function validationConfig(signerAccessCode) {
1207
- return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
1277
+ if (signerAccessCode === void 0) return void 0;
1278
+ if (typeof signerAccessCode !== "string" || !signerAccessCode.trim()) {
1279
+ throw new ValidationError("signerAccessCode is required when supplied");
1280
+ }
1281
+ return signerAccessConfig(signerAccessCode);
1208
1282
  }
1209
1283
 
1210
1284
  // src/api/resources/oauth.ts
@@ -1312,6 +1386,9 @@ var OAuthResource = class extends BaseResource {
1312
1386
  if (callback.searchParams.get("iss") !== request.issuer) {
1313
1387
  throw new ValidationError("OAuth issuer mismatch");
1314
1388
  }
1389
+ if (callback.searchParams.has("code") === callback.searchParams.has("error")) {
1390
+ throw new ValidationError("OAuth callback must contain exactly one of code or error");
1391
+ }
1315
1392
  if (callback.searchParams.has("error")) {
1316
1393
  const error = callback.searchParams.get("error");
1317
1394
  const oauthError = error.length > 0 && error.length <= 64 && !/[^a-z_]/.test(error) ? error : "unknown_error";
@@ -1973,10 +2050,8 @@ var DEFAULT_EVENTS = [
1973
2050
  "signer_rejected_document",
1974
2051
  "document_processing_failed"
1975
2052
  ];
1976
- var WebhookResource = class extends BaseResource {
1977
- /** Register (or replace) the webhook subscription for the workspace. */
1978
- async register(payload, accountId) {
1979
- if (!payload.url) throw new ValidationError("Webhook URL is required");
2053
+ function validateWebhookFields(payload) {
2054
+ if (payload.url !== void 0) {
1980
2055
  let webhookUrl;
1981
2056
  try {
1982
2057
  webhookUrl = new URL(payload.url);
@@ -1986,13 +2061,29 @@ var WebhookResource = class extends BaseResource {
1986
2061
  if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
1987
2062
  throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1988
2063
  }
1989
- requireEmail(payload.email);
1990
- if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
1991
- throw new ValidationError("Webhook events must contain non-empty strings");
1992
- }
1993
- if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
1994
- throw new ValidationError("Webhook is_active must be a boolean");
2064
+ }
2065
+ if (payload.email !== void 0) requireEmail(payload.email);
2066
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
2067
+ throw new ValidationError("Webhook events must contain non-empty strings");
2068
+ }
2069
+ if (payload.name !== void 0 && typeof payload.name !== "string") {
2070
+ throw new ValidationError("Webhook name must be a string");
2071
+ }
2072
+ for (const key of ["is_active", "signing_enabled"]) {
2073
+ if (payload[key] !== void 0 && typeof payload[key] !== "boolean") {
2074
+ throw new ValidationError(`Webhook ${key} must be a boolean`);
1995
2075
  }
2076
+ }
2077
+ }
2078
+ var WebhookResource = class extends BaseResource {
2079
+ /**
2080
+ * `PUT /accounts/{accountId}/webhooks/subscriptions` — create or replace the
2081
+ * account's oldest webhook endpoint. Use the endpoint methods for accounts
2082
+ * with several endpoints or for signed deliveries.
2083
+ */
2084
+ async register(payload, accountId) {
2085
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
2086
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
1996
2087
  const id = this.accountId(accountId);
1997
2088
  const body = {
1998
2089
  url: payload.url,
@@ -2008,7 +2099,7 @@ var WebhookResource = class extends BaseResource {
2008
2099
  () => this.http.put(`/accounts/${id}/webhooks/subscriptions`, body)
2009
2100
  );
2010
2101
  }
2011
- /** Fetch the current webhook subscription. Returns `null` if none exists. */
2102
+ /** Fetch the account's oldest webhook endpoint. Returns `null` if none exists. */
2012
2103
  async get(accountId) {
2013
2104
  const id = this.accountId(accountId);
2014
2105
  return this.callOptional(
@@ -2016,7 +2107,7 @@ var WebhookResource = class extends BaseResource {
2016
2107
  () => this.http.get(`/accounts/${id}/webhooks/subscriptions`)
2017
2108
  );
2018
2109
  }
2019
- /** Inactivate the current webhook subscription without deleting it. */
2110
+ /** Inactivate the account's oldest webhook endpoint without deleting it. */
2020
2111
  async inactivate(accountId) {
2021
2112
  const id = this.accountId(accountId);
2022
2113
  this.logger.info("Inactivating webhook subscription");
@@ -2025,6 +2116,91 @@ var WebhookResource = class extends BaseResource {
2025
2116
  () => this.http.put(`/accounts/${id}/webhooks/inactivate`)
2026
2117
  );
2027
2118
  }
2119
+ /** `GET /accounts/{accountId}/webhooks/endpoints` — list webhook endpoints, oldest first. */
2120
+ async listEndpoints(accountId) {
2121
+ const id = this.accountId(accountId);
2122
+ return this.call(
2123
+ "Failed to list webhook endpoints",
2124
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints`)
2125
+ );
2126
+ }
2127
+ /**
2128
+ * `POST /accounts/{accountId}/webhooks/endpoints` — register another
2129
+ * endpoint. Accounts allow 1 endpoint, or up to 3 on paid plans (`403` past
2130
+ * the limit); URLs must be unique per workspace. Omitted `events` uses the
2131
+ * same default set as {@link register}.
2132
+ */
2133
+ async createEndpoint(payload, accountId) {
2134
+ if (!payload.url) throw new ValidationError("Webhook URL is required");
2135
+ validateWebhookFields({ ...payload, email: payload.email ?? "" });
2136
+ const id = this.accountId(accountId);
2137
+ const body = { ...payload, events: payload.events ?? DEFAULT_EVENTS };
2138
+ this.logger.info("Creating webhook endpoint", { eventCount: body.events.length });
2139
+ return this.call(
2140
+ "Failed to create webhook endpoint",
2141
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints`, body)
2142
+ );
2143
+ }
2144
+ /** `GET /accounts/{accountId}/webhooks/endpoints/{endpointId}` — fetch one endpoint. */
2145
+ async getEndpoint(endpointId, accountId) {
2146
+ const id = this.accountId(accountId);
2147
+ const eid = this.requireId(endpointId, "Endpoint ID");
2148
+ return this.call(
2149
+ "Failed to fetch webhook endpoint",
2150
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}`)
2151
+ );
2152
+ }
2153
+ /**
2154
+ * `PUT /accounts/{accountId}/webhooks/endpoints/{endpointId}` — update only
2155
+ * the fields sent. Enabling signing creates a secret when none exists;
2156
+ * disabling it discards the secret.
2157
+ */
2158
+ async updateEndpoint(endpointId, payload, accountId) {
2159
+ const id = this.accountId(accountId);
2160
+ const eid = this.requireId(endpointId, "Endpoint ID");
2161
+ if (!payload || typeof payload !== "object" || Object.keys(payload).length === 0) {
2162
+ throw new ValidationError("At least one webhook endpoint field is required");
2163
+ }
2164
+ validateWebhookFields(payload);
2165
+ return this.call(
2166
+ "Failed to update webhook endpoint",
2167
+ () => this.http.put(`/accounts/${id}/webhooks/endpoints/${eid}`, payload)
2168
+ );
2169
+ }
2170
+ /** `DELETE /accounts/{accountId}/webhooks/endpoints/{endpointId}` — delete an endpoint and free its slot. */
2171
+ async deleteEndpoint(endpointId, accountId) {
2172
+ const id = this.accountId(accountId);
2173
+ const eid = this.requireId(endpointId, "Endpoint ID");
2174
+ return this.call(
2175
+ "Failed to delete webhook endpoint",
2176
+ () => this.http.delete(`/accounts/${id}/webhooks/endpoints/${eid}`)
2177
+ );
2178
+ }
2179
+ /**
2180
+ * `GET …/endpoints/{endpointId}/secret` — the `whsec_` signing secret.
2181
+ * Returns `400` when signing is disabled. Not available to OAuth applications.
2182
+ */
2183
+ async getEndpointSecret(endpointId, accountId) {
2184
+ const id = this.accountId(accountId);
2185
+ const eid = this.requireId(endpointId, "Endpoint ID");
2186
+ return this.call(
2187
+ "Failed to fetch webhook endpoint secret",
2188
+ () => this.http.get(`/accounts/${id}/webhooks/endpoints/${eid}/secret`)
2189
+ );
2190
+ }
2191
+ /**
2192
+ * `POST …/endpoints/{endpointId}/secret/rotate` — replace the signing secret.
2193
+ * The old secret stops working immediately. Not available to OAuth applications.
2194
+ */
2195
+ async rotateEndpointSecret(endpointId, accountId) {
2196
+ const id = this.accountId(accountId);
2197
+ const eid = this.requireId(endpointId, "Endpoint ID");
2198
+ this.logger.info("Rotating webhook endpoint secret");
2199
+ return this.call(
2200
+ "Failed to rotate webhook endpoint secret",
2201
+ () => this.http.post(`/accounts/${id}/webhooks/endpoints/${eid}/secret/rotate`)
2202
+ );
2203
+ }
2028
2204
  /** List currently supported webhook event types. */
2029
2205
  async listEventTypes() {
2030
2206
  return this.call(
@@ -2032,7 +2208,7 @@ var WebhookResource = class extends BaseResource {
2032
2208
  () => this.http.get("/webhooks/event-types")
2033
2209
  );
2034
2210
  }
2035
- /** List webhook delivery history for the workspace. */
2211
+ /** List webhook delivery history for the workspace, optionally for one endpoint. */
2036
2212
  async listDispatches(params = {}, accountId) {
2037
2213
  const id = this.accountId(accountId);
2038
2214
  if ("search" in params) throw new ValidationError("webhook dispatch search is not supported");
@@ -2044,7 +2220,7 @@ var WebhookResource = class extends BaseResource {
2044
2220
  })
2045
2221
  );
2046
2222
  }
2047
- /** Retry delivery of a specific webhook dispatch. */
2223
+ /** Retry delivery of a specific webhook dispatch to that entry's endpoint. */
2048
2224
  async retryDispatch(dispatchId, accountId) {
2049
2225
  const id = this.accountId(accountId);
2050
2226
  const did = this.requireId(dispatchId, "Dispatch ID");
@@ -2153,6 +2329,17 @@ function validateNotificationSender(value) {
2153
2329
 
2154
2330
  // src/api/support/webhook-verifier.ts
2155
2331
  var import_node_crypto2 = require("crypto");
2332
+ function readHeader(headers, name) {
2333
+ if (typeof headers.get === "function") {
2334
+ return headers.get(name) ?? void 0;
2335
+ }
2336
+ for (const [key, value] of Object.entries(headers)) {
2337
+ if (key.toLowerCase() !== name) continue;
2338
+ if (Array.isArray(value)) return value.length === 1 ? value[0] : void 0;
2339
+ return value;
2340
+ }
2341
+ return void 0;
2342
+ }
2156
2343
  var WebhookVerifier = class {
2157
2344
  constructor(webhookSecret, options = {}) {
2158
2345
  this.webhookSecret = webhookSecret;
@@ -2162,15 +2349,48 @@ var WebhookVerifier = class {
2162
2349
  webhookSecret;
2163
2350
  algorithm;
2164
2351
  encoding;
2165
- /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
2352
+ /**
2353
+ * Returns `true` when `headers` carry a Standard Webhooks signature that
2354
+ * matches the raw `payload` under this verifier's `whsec_` secret and the
2355
+ * `webhook-timestamp` is within the tolerance window. Pass the body exactly
2356
+ * as received; re-serialized JSON does not verify.
2357
+ */
2358
+ verifyDelivery(payload, headers, options = {}) {
2359
+ if (!this.webhookSecret || !headers) return false;
2360
+ const id = readHeader(headers, "webhook-id");
2361
+ const timestamp = readHeader(headers, "webhook-timestamp");
2362
+ const signatures = readHeader(headers, "webhook-signature");
2363
+ if (!id || !timestamp || !signatures || !/^\d+$/.test(timestamp)) return false;
2364
+ const tolerance = options.toleranceSeconds ?? 300;
2365
+ const now = Math.floor((options.now ?? Date.now()) / 1e3);
2366
+ if (Math.abs(now - Number(timestamp)) > tolerance) return false;
2367
+ const secret = this.webhookSecret.startsWith("whsec_") ? this.webhookSecret.slice("whsec_".length) : this.webhookSecret;
2368
+ const key = Buffer.from(secret, "base64");
2369
+ if (key.length === 0) return false;
2370
+ const expected = Buffer.from(
2371
+ (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`).update(typeof payload === "string" ? Buffer.from(payload, "utf8") : payload).digest("base64")
2372
+ );
2373
+ return signatures.split(" ").some((entry) => {
2374
+ const [version, value] = entry.split(",", 2);
2375
+ if (version !== "v1" || !value) return false;
2376
+ const provided = Buffer.from(value);
2377
+ return provided.length === expected.length && (0, import_node_crypto2.timingSafeEqual)(provided, expected);
2378
+ });
2379
+ }
2380
+ /**
2381
+ * Returns `true` if `signature` is an HMAC of `payload` keyed with the raw
2382
+ * secret string under the configured algorithm/encoding.
2383
+ *
2384
+ * @deprecated Assinafy signs deliveries with Standard Webhooks headers; use
2385
+ * {@link verifyDelivery}. Retained for existing callers.
2386
+ */
2166
2387
  verify(payload, signature) {
2167
2388
  if (!this.webhookSecret || !signature) return false;
2168
2389
  try {
2169
2390
  const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
2170
2391
  const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
2171
- const provided = signature.trim();
2172
2392
  const a = Buffer.from(expected, "utf8");
2173
- const b = Buffer.from(provided, "utf8");
2393
+ const b = Buffer.from(signature.trim(), "utf8");
2174
2394
  if (a.length !== b.length) return false;
2175
2395
  return (0, import_node_crypto2.timingSafeEqual)(a, b);
2176
2396
  } catch {