@assinafy/cli 2.0.1 → 2.0.3

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
@@ -51,6 +51,13 @@ var DOCUMENT_ARTIFACT_NAMES = [
51
51
  "pades",
52
52
  "bundle"
53
53
  ];
54
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
55
+ var VERIFICATION_METHODS = [
56
+ "Email",
57
+ "Whatsapp",
58
+ "DigitalCertificate"
59
+ ];
60
+ var NOTIFICATION_METHODS = ["Email", "Whatsapp"];
54
61
  function handleAssinafyResponse(response) {
55
62
  const resp = response;
56
63
  if (resp && typeof resp === "object" && resp.status !== void 0 && "data" in resp) {
@@ -128,6 +135,51 @@ function requireIso8601(value, name = "timestamp") {
128
135
  }
129
136
  return value;
130
137
  }
138
+ function requireEmail(value) {
139
+ if (!value || !EMAIL_RE.test(value)) {
140
+ throw new ValidationError("Invalid email address", { email: value });
141
+ }
142
+ return value;
143
+ }
144
+ function validateSignerOptions(input) {
145
+ if (input.verification_method !== void 0 && !VERIFICATION_METHODS.includes(input.verification_method)) {
146
+ throw new ValidationError(
147
+ `verification_method must be one of: ${VERIFICATION_METHODS.join(", ")}`
148
+ );
149
+ }
150
+ if (input.notification_methods !== void 0 && (!Array.isArray(input.notification_methods) || input.notification_methods.some(
151
+ (method) => !NOTIFICATION_METHODS.includes(method)
152
+ ))) {
153
+ throw new ValidationError(
154
+ `notification_methods must contain only: ${NOTIFICATION_METHODS.join(", ")}`
155
+ );
156
+ }
157
+ if (input.step !== void 0 && !Number.isInteger(input.step)) {
158
+ throw new ValidationError("step must be an integer");
159
+ }
160
+ }
161
+ function validateSigningSteps(signers) {
162
+ const withSteps = signers.filter((signer) => signer.step !== void 0);
163
+ if (withSteps.length > 0) {
164
+ if (withSteps.length !== signers.length) {
165
+ throw new ValidationError("step must be supplied for every signer when used");
166
+ }
167
+ const steps = [...new Set(withSteps.map((signer) => signer.step))].sort(
168
+ (a, b) => a - b
169
+ );
170
+ if (steps.some((step, index) => step !== index + 1)) {
171
+ throw new ValidationError("steps must form a contiguous sequence starting at 1");
172
+ }
173
+ }
174
+ validateDigitalCertificateSteps(signers);
175
+ }
176
+ function validateDigitalCertificateSteps(signers) {
177
+ for (const signer of signers) {
178
+ if (signer.verification_method === "DigitalCertificate" && signers.some((other) => other !== signer && (other.step ?? 1) === (signer.step ?? 1))) {
179
+ throw new ValidationError("a DigitalCertificate signer must be alone in its signing step");
180
+ }
181
+ }
182
+ }
131
183
  function documentStatsParams(params = {}) {
132
184
  if (params.granularity !== void 0 && !["monthly", "daily"].includes(params.granularity)) {
133
185
  throw new ValidationError("granularity must be monthly or daily");
@@ -273,15 +325,25 @@ function toInt(value) {
273
325
 
274
326
  // src/api/resources/assignments.ts
275
327
  function buildAssignmentPayload(payload, options = {}) {
328
+ if (payload.method !== void 0 && payload.method !== "virtual" && payload.method !== "collect") {
329
+ throw new ValidationError("method must be virtual or collect");
330
+ }
276
331
  const signers = extractSignerRefs(payload);
277
- if (signers.length === 0 && !options.allowEmptySigners) {
332
+ if (signers.length === 0 && (!options.allowEmptySigners || (payload.method ?? "virtual") !== "collect")) {
278
333
  throw new ValidationError("At least one signer is required", {
279
334
  signers: payload.signers ?? payload.signer_ids ?? payload.signerIds
280
335
  });
281
336
  }
337
+ if (payload.method === "collect" && !Array.isArray(payload.entries)) {
338
+ throw new ValidationError("entries are required for collect assignments");
339
+ }
340
+ const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
341
+ if (!options.skipDigitalCertificateStepValidation) {
342
+ validateDigitalCertificateSteps(normalisedSigners);
343
+ }
282
344
  return cleanParams({
283
345
  method: payload.method ?? "virtual",
284
- signers: signers.map((ref) => normaliseSignerRef(ref, options)),
346
+ signers: normalisedSigners,
285
347
  message: payload.message,
286
348
  expires_at: payload.expires_at === void 0 ? void 0 : requireIso8601(payload.expires_at, "expires_at"),
287
349
  copy_receivers: payload.copy_receivers,
@@ -309,6 +371,7 @@ function normaliseSignerRef(ref, options) {
309
371
  if (ref && typeof ref === "object") {
310
372
  const input = ref;
311
373
  const id = input.id ?? input.signer_id;
374
+ validateSignerOptions(input);
312
375
  const normalised = cleanParams({
313
376
  id,
314
377
  verification_method: input.verification_method,
@@ -366,14 +429,16 @@ var AssignmentResource = class extends BaseResource {
366
429
  `/documents/${docId}/assignments/estimate-cost`,
367
430
  buildAssignmentPayload(payload, {
368
431
  allowSignersWithoutId: true,
369
- allowEmptySigners: true
432
+ allowEmptySigners: true,
433
+ skipDigitalCertificateStepValidation: true
370
434
  })
371
435
  )
372
436
  );
373
437
  }
374
438
  /**
375
439
  * Update the expiration date of an existing assignment.
376
- * Pass `null` to remove the expiration entirely.
440
+ * The published API accepts an ISO 8601 timestamp. Deployments that support
441
+ * clearing an expiration also accept `null`.
377
442
  */
378
443
  async resetExpiration(documentId, assignmentId, expiresAt) {
379
444
  const docId = this.requireId(documentId, "Document ID");
@@ -708,24 +773,24 @@ var DocumentResource = class extends BaseResource {
708
773
  );
709
774
  }
710
775
  /**
711
- * Replace the document's tag set with `tags` (an array of tag names).
712
- * Unknown names are auto-created; an empty array detaches all tags.
776
+ * Replace the document's tag set with tag IDs. An empty array detaches all tags.
777
+ * Values are forwarded unchanged for compatibility with deployments that also accept names.
713
778
  */
714
779
  async replaceTags(documentId, tags, accountId) {
715
780
  const accId = this.accountId(accountId);
716
781
  const docId = this.requireId(documentId, "Document ID");
717
- if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag names");
782
+ if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag IDs");
718
783
  return this.call(
719
784
  "Failed to replace document tags",
720
785
  () => this.http.put(`/accounts/${accId}/documents/${docId}/tags`, { tags })
721
786
  );
722
787
  }
723
- /** Attach additional tags (by name) without removing existing ones. Idempotent. */
788
+ /** Attach additional tag IDs without removing existing ones. */
724
789
  async addTags(documentId, tags, accountId) {
725
790
  const accId = this.accountId(accountId);
726
791
  const docId = this.requireId(documentId, "Document ID");
727
792
  if (!Array.isArray(tags) || tags.length === 0) {
728
- throw new ValidationError("tags must be a non-empty array of tag names");
793
+ throw new ValidationError("tags must be a non-empty array of tag IDs");
729
794
  }
730
795
  return this.call(
731
796
  "Failed to add document tags",
@@ -755,7 +820,14 @@ var DocumentResource = class extends BaseResource {
755
820
  async createFromTemplate(templateId, signers, options = {}, accountId) {
756
821
  const tmplId = this.requireId(templateId, "Template ID");
757
822
  const accId = this.accountId(accountId);
823
+ validateTemplateSigners(signers, { requireId: true, singleNotification: true });
758
824
  if (options.expires_at !== void 0) requireIso8601(options.expires_at, "expires_at");
825
+ if (options.editor_fields !== void 0 && (!Array.isArray(options.editor_fields) || options.editor_fields.some((field) => !field?.field_id || typeof field.value !== "string"))) {
826
+ throw new ValidationError("editor_fields must contain field_id and value");
827
+ }
828
+ if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !tag))) {
829
+ throw new ValidationError("tags must contain non-empty tag names");
830
+ }
759
831
  const body = { ...options, signers };
760
832
  this.logger.info("Creating document from template", { templateId: tmplId, accountId: accId });
761
833
  return this.call(
@@ -767,6 +839,7 @@ var DocumentResource = class extends BaseResource {
767
839
  async estimateCostFromTemplate(templateId, signers, accountId) {
768
840
  const tmplId = this.requireId(templateId, "Template ID");
769
841
  const accId = this.accountId(accountId);
842
+ validateTemplateSigners(signers, { requireId: false, singleNotification: false });
770
843
  return this.call(
771
844
  "Failed to estimate cost from template",
772
845
  () => this.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers })
@@ -813,7 +886,7 @@ var DocumentResource = class extends BaseResource {
813
886
  async sendToken(documentId, recipient, channel = "email") {
814
887
  const id = this.requireId(documentId, "Document ID");
815
888
  if (typeof recipient === "object") {
816
- if (!recipient?.email) throw new ValidationError("email is required");
889
+ requireEmail(recipient?.email);
817
890
  return this.call(
818
891
  "Failed to send signing token",
819
892
  () => this.http.put(
@@ -824,6 +897,10 @@ var DocumentResource = class extends BaseResource {
824
897
  );
825
898
  }
826
899
  if (!recipient) throw new ValidationError("recipient is required");
900
+ if (channel !== "email" && channel !== "whatsapp") {
901
+ throw new ValidationError("channel must be email or whatsapp");
902
+ }
903
+ if (channel === "email") requireEmail(recipient);
827
904
  return this.call(
828
905
  "Failed to send signing token",
829
906
  () => this.http.put(
@@ -854,6 +931,31 @@ var DocumentResource = class extends BaseResource {
854
931
  return { signed, total, pending, percentage };
855
932
  }
856
933
  };
934
+ function validateTemplateSigners(signers, options) {
935
+ if (!Array.isArray(signers)) throw new ValidationError("signers must be an array");
936
+ for (const value of signers) {
937
+ if (!value || typeof value !== "object") {
938
+ throw new ValidationError("each template signer must be an object");
939
+ }
940
+ const signer = value;
941
+ if (typeof signer.role_id !== "string" || !signer.role_id) {
942
+ throw new ValidationError("each template signer requires role_id");
943
+ }
944
+ if ((options.requireId || signer.id !== void 0) && (typeof signer.id !== "string" || !signer.id)) {
945
+ throw new ValidationError("each template signer requires a valid id");
946
+ }
947
+ validateSignerOptions(signer);
948
+ if (options.requireId && signer.step !== void 0 && Number(signer.step) < 1) {
949
+ throw new ValidationError("template signer step must be a positive integer");
950
+ }
951
+ if (options.singleNotification && Array.isArray(signer.notification_methods) && signer.notification_methods.length > 1) {
952
+ throw new ValidationError("template signers accept at most one notification method");
953
+ }
954
+ }
955
+ if (options.requireId) {
956
+ validateSigningSteps(signers);
957
+ }
958
+ }
857
959
  async function loadSource(source) {
858
960
  if ("buffer" in source) {
859
961
  if (!source.fileName) {
@@ -965,6 +1067,7 @@ var FieldsResource = class extends BaseResource {
965
1067
  async validate(fieldId, value, options = {}) {
966
1068
  const id = this.accountId(options.accountId);
967
1069
  const fid = this.requireId(fieldId, "Field ID");
1070
+ if (value === void 0) throw new ValidationError("value is required");
968
1071
  return this.call(
969
1072
  "Failed to validate field value",
970
1073
  () => this.http.post(
@@ -979,6 +1082,11 @@ var FieldsResource = class extends BaseResource {
979
1082
  if (!Array.isArray(entries) || entries.length === 0) {
980
1083
  throw new ValidationError("entries must be a non-empty array");
981
1084
  }
1085
+ if (entries.some(
1086
+ (entry) => !entry || typeof entry !== "object" || typeof entry.field_id !== "string" || !entry.field_id || entry.value === void 0
1087
+ )) {
1088
+ throw new ValidationError("each entry must contain field_id and value");
1089
+ }
982
1090
  const id = this.accountId(options.accountId);
983
1091
  return this.call(
984
1092
  "Failed to validate field values",
@@ -1030,20 +1138,28 @@ var SignerDocumentsResource = class extends BaseResource {
1030
1138
  () => this.http.get(`/signers/${sid}/documents/search`, signerAccessConfig(code, { search }))
1031
1139
  );
1032
1140
  }
1033
- /** `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}?signer-access-code=…` */
1141
+ /**
1142
+ * Public `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`.
1143
+ * When an access code is supplied, the SDK first verifies that it belongs to
1144
+ * the requested signer for callers that want that additional check.
1145
+ */
1034
1146
  async download(signerId, documentId, artifactName, signerAccessCode) {
1035
1147
  const sid = this.requireId(signerId, "Signer ID");
1036
1148
  const did = this.requireId(documentId, "Document ID");
1037
1149
  const artifact = requireDocumentArtifactName(artifactName);
1038
- const code = this.requireId(signerAccessCode, "signer-access-code");
1039
- const signer = await this.self(code);
1040
- if (signer.id !== sid) {
1041
- throw new ValidationError("Signer access code does not match the signer ID");
1150
+ let config = publicRequestConfig();
1151
+ if (signerAccessCode !== void 0) {
1152
+ const code = this.requireId(signerAccessCode, "signer-access-code");
1153
+ const signer = await this.self(code);
1154
+ if (signer.id !== sid) {
1155
+ throw new ValidationError("Signer access code does not match the signer ID");
1156
+ }
1157
+ config = signerAccessConfig(code);
1042
1158
  }
1043
1159
  return this.callBinary(
1044
1160
  "Failed to download signer document",
1045
1161
  () => this.http.get(`/signers/${sid}/documents/${did}/download/${artifact}`, {
1046
- ...signerAccessConfig(code),
1162
+ ...config,
1047
1163
  responseType: "arraybuffer"
1048
1164
  })
1049
1165
  );
@@ -1211,15 +1327,9 @@ var SignerDocumentsResource = class extends BaseResource {
1211
1327
  };
1212
1328
 
1213
1329
  // src/api/resources/signers.ts
1214
- var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1215
1330
  function validateCreateSignerPayload(payload) {
1216
1331
  if (!payload.full_name?.trim()) throw new ValidationError("Signer full name is required");
1217
- if (payload.email) assertEmail(payload.email);
1218
- }
1219
- function assertEmail(email) {
1220
- if (!email || !EMAIL_RE.test(email)) {
1221
- throw new ValidationError("Invalid email address", { email });
1222
- }
1332
+ if (payload.email !== void 0) requireEmail(payload.email);
1223
1333
  }
1224
1334
  var SignerResource = class extends BaseResource {
1225
1335
  /**
@@ -1282,6 +1392,10 @@ var SignerResource = class extends BaseResource {
1282
1392
  async update(signerId, payload, accountId) {
1283
1393
  const id = this.accountId(accountId);
1284
1394
  const sid = this.requireId(signerId, "Signer ID");
1395
+ if (payload.full_name !== void 0 && !payload.full_name.trim()) {
1396
+ throw new ValidationError("Signer full name cannot be blank");
1397
+ }
1398
+ if (payload.email !== void 0) requireEmail(payload.email);
1285
1399
  return this.call(
1286
1400
  "Failed to update signer",
1287
1401
  () => this.http.put(`/accounts/${id}/signers/${sid}`, normaliseSignerPayload(payload, true))
@@ -1298,7 +1412,7 @@ var SignerResource = class extends BaseResource {
1298
1412
  }
1299
1413
  /** Find a signer by email via the API's `search` parameter. Returns `null` if none match. */
1300
1414
  async findByEmail(email, accountId) {
1301
- assertEmail(email);
1415
+ requireEmail(email);
1302
1416
  try {
1303
1417
  const { data } = await this.list({ search: email, per_page: 100 }, accountId);
1304
1418
  const lower = email.toLowerCase();
@@ -1496,7 +1610,22 @@ var WebhookResource = class extends BaseResource {
1496
1610
  /** Register (or replace) the webhook subscription for the workspace. */
1497
1611
  async register(payload, accountId) {
1498
1612
  if (!payload.url) throw new ValidationError("Webhook URL is required");
1499
- if (!payload.email) throw new ValidationError("Webhook email is required");
1613
+ let webhookUrl;
1614
+ try {
1615
+ webhookUrl = new URL(payload.url);
1616
+ } catch {
1617
+ throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1618
+ }
1619
+ if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
1620
+ throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1621
+ }
1622
+ requireEmail(payload.email);
1623
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
1624
+ throw new ValidationError("Webhook events must contain non-empty strings");
1625
+ }
1626
+ if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
1627
+ throw new ValidationError("Webhook is_active must be a boolean");
1628
+ }
1500
1629
  const id = this.accountId(accountId);
1501
1630
  const body = {
1502
1631
  url: payload.url,
@@ -1670,13 +1799,13 @@ var WebhookVerifier = class {
1670
1799
  /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
1671
1800
  verify(payload, signature) {
1672
1801
  if (!this.webhookSecret || !signature) return false;
1673
- const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
1674
- const expected = createHmac(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
1675
- const provided = signature.trim();
1676
- const a = Buffer.from(expected, "utf8");
1677
- const b = Buffer.from(provided, "utf8");
1678
- if (a.length !== b.length) return false;
1679
1802
  try {
1803
+ const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
1804
+ const expected = createHmac(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
1805
+ const provided = signature.trim();
1806
+ const a = Buffer.from(expected, "utf8");
1807
+ const b = Buffer.from(provided, "utf8");
1808
+ if (a.length !== b.length) return false;
1680
1809
  return timingSafeEqual(a, b);
1681
1810
  } catch {
1682
1811
  return false;
@@ -1696,7 +1825,8 @@ var WebhookVerifier = class {
1696
1825
  getEventType(event) {
1697
1826
  if (!event || typeof event !== "object") return null;
1698
1827
  const e = event;
1699
- return e.event ?? e.type ?? null;
1828
+ if (typeof e.event === "string") return e.event;
1829
+ return typeof e.type === "string" ? e.type : null;
1700
1830
  }
1701
1831
  /**
1702
1832
  * Extract the event data from an event envelope.
@@ -1741,6 +1871,9 @@ var AssinafyClient = class _AssinafyClient {
1741
1871
  "An API key (options.apiKey) or legacy access token (options.token) is required."
1742
1872
  );
1743
1873
  }
1874
+ if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
1875
+ throw new ValidationError("timeout must be a finite positive number");
1876
+ }
1744
1877
  this.defaultAccountId = options.accountId;
1745
1878
  this.logger = options.logger ?? createNoopLogger();
1746
1879
  this.webhookSecret = options.webhookSecret;