@assinafy/cli 2.0.2 → 2.1.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 (48) hide show
  1. package/.env.example +54 -0
  2. package/CONTRIBUTING.md +29 -0
  3. package/README.en.md +559 -0
  4. package/README.md +314 -180
  5. package/SECURITY.md +10 -0
  6. package/THIRD_PARTY_NOTICES.md +3 -3
  7. package/dist/api.cjs +453 -74
  8. package/dist/api.cjs.map +1 -1
  9. package/dist/api.js +451 -74
  10. package/dist/api.js.map +1 -1
  11. package/dist/cli.cjs +1278 -228
  12. package/dist/types/api/client.d.ts +7 -0
  13. package/dist/types/api/client.d.ts.map +1 -1
  14. package/dist/types/api/errors.d.ts +42 -1
  15. package/dist/types/api/errors.d.ts.map +1 -1
  16. package/dist/types/api/index.d.ts +1 -0
  17. package/dist/types/api/index.d.ts.map +1 -1
  18. package/dist/types/api/resources/assignments.d.ts +3 -1
  19. package/dist/types/api/resources/assignments.d.ts.map +1 -1
  20. package/dist/types/api/resources/documents.d.ts +3 -3
  21. package/dist/types/api/resources/documents.d.ts.map +1 -1
  22. package/dist/types/api/resources/fields.d.ts.map +1 -1
  23. package/dist/types/api/resources/oauth.d.ts +20 -0
  24. package/dist/types/api/resources/oauth.d.ts.map +1 -0
  25. package/dist/types/api/resources/signer-documents.d.ts +9 -5
  26. package/dist/types/api/resources/signer-documents.d.ts.map +1 -1
  27. package/dist/types/api/resources/signers.d.ts.map +1 -1
  28. package/dist/types/api/resources/webhooks.d.ts.map +1 -1
  29. package/dist/types/api/support/webhook-verifier.d.ts.map +1 -1
  30. package/dist/types/api/types.d.ts +146 -56
  31. package/dist/types/api/types.d.ts.map +1 -1
  32. package/dist/types/api/utils.d.ts +18 -0
  33. package/dist/types/api/utils.d.ts.map +1 -1
  34. package/docs/README.md +4 -2
  35. package/docs/api-operations.json +33 -1
  36. package/docs/api-reference.md +323 -79
  37. package/docs/assignments.md +3 -3
  38. package/docs/documents.md +8 -8
  39. package/docs/fields.md +4 -4
  40. package/docs/migration-v2.md +6 -2
  41. package/docs/oauth-guide.md +343 -0
  42. package/docs/oauth.md +162 -0
  43. package/docs/releasing.md +16 -6
  44. package/docs/sdk-reference.md +121 -24
  45. package/docs/signer.md +3 -2
  46. package/install.ps1 +9 -2
  47. package/install.sh +5 -5
  48. package/package.json +8 -5
package/dist/api.js CHANGED
@@ -13,18 +13,35 @@ var AssinafyError = class extends Error {
13
13
  var ApiError = class _ApiError extends AssinafyError {
14
14
  statusCode;
15
15
  responseData;
16
+ /** Bearer challenge, including insufficient_scope and resource_metadata when provided. */
17
+ wwwAuthenticate;
18
+ /** Server retry delay (seconds or HTTP date), when provided. */
19
+ retryAfter;
16
20
  constructor(message, statusCode, responseData = null, options) {
17
21
  super(message, { statusCode, responseData }, options);
18
22
  this.name = "ApiError";
19
23
  this.statusCode = statusCode;
20
24
  this.responseData = responseData;
25
+ this.wwwAuthenticate = options?.wwwAuthenticate;
26
+ this.retryAfter = options?.retryAfter;
21
27
  }
22
- static fromResponse(statusCode, responseData) {
28
+ static fromResponse(statusCode, responseData, headers = {}) {
29
+ if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
30
+ const text = (Buffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)).toString("utf8");
31
+ try {
32
+ responseData = JSON.parse(text);
33
+ } catch {
34
+ responseData = text;
35
+ }
36
+ }
23
37
  const data = responseData ?? {};
24
38
  const rawMessage = data.message;
25
39
  const rawError = data.error;
26
40
  const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
27
- return new _ApiError(message, statusCode, responseData);
41
+ return new _ApiError(message, statusCode, responseData, {
42
+ wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
43
+ retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
44
+ });
28
45
  }
29
46
  };
30
47
  var ValidationError = class extends AssinafyError {
@@ -41,6 +58,19 @@ var NetworkError = class extends AssinafyError {
41
58
  this.name = "NetworkError";
42
59
  }
43
60
  };
61
+ var PartialWorkflowError = class extends AssinafyError {
62
+ /** The document that was uploaded before the failure, if any. */
63
+ documentId;
64
+ /** IDs of every signer created (or reused) before the failure. */
65
+ signerIds;
66
+ constructor(message, created, options) {
67
+ const signerIds = created.signerIds ?? [];
68
+ super(message, { documentId: created.documentId, signerIds }, options);
69
+ this.name = "PartialWorkflowError";
70
+ this.documentId = created.documentId;
71
+ this.signerIds = signerIds;
72
+ }
73
+ };
44
74
 
45
75
  // src/api/utils.ts
46
76
  import axios from "axios";
@@ -51,6 +81,13 @@ var DOCUMENT_ARTIFACT_NAMES = [
51
81
  "pades",
52
82
  "bundle"
53
83
  ];
84
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
85
+ var VERIFICATION_METHODS = [
86
+ "Email",
87
+ "Whatsapp",
88
+ "DigitalCertificate"
89
+ ];
90
+ var NOTIFICATION_METHODS = ["Email", "Whatsapp"];
54
91
  function handleAssinafyResponse(response) {
55
92
  const resp = response;
56
93
  if (resp && typeof resp === "object" && resp.status !== void 0 && "data" in resp) {
@@ -68,7 +105,7 @@ function toSdkError(error, fallbackMessage) {
68
105
  if (axios.isAxiosError(error)) {
69
106
  const status = error.response?.status;
70
107
  if (status) {
71
- return ApiError.fromResponse(status, error.response?.data ?? null);
108
+ return ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);
72
109
  }
73
110
  return new NetworkError(`${fallbackMessage}: ${error.message}`);
74
111
  }
@@ -128,6 +165,51 @@ function requireIso8601(value, name = "timestamp") {
128
165
  }
129
166
  return value;
130
167
  }
168
+ function requireEmail(value) {
169
+ if (!value || !EMAIL_RE.test(value)) {
170
+ throw new ValidationError("Invalid email address", { email: value });
171
+ }
172
+ return value;
173
+ }
174
+ function validateSignerOptions(input) {
175
+ if (input.verification_method !== void 0 && !VERIFICATION_METHODS.includes(input.verification_method)) {
176
+ throw new ValidationError(
177
+ `verification_method must be one of: ${VERIFICATION_METHODS.join(", ")}`
178
+ );
179
+ }
180
+ if (input.notification_methods !== void 0 && (!Array.isArray(input.notification_methods) || input.notification_methods.some(
181
+ (method) => !NOTIFICATION_METHODS.includes(method)
182
+ ))) {
183
+ throw new ValidationError(
184
+ `notification_methods must contain only: ${NOTIFICATION_METHODS.join(", ")}`
185
+ );
186
+ }
187
+ if (input.step !== void 0 && !Number.isInteger(input.step)) {
188
+ throw new ValidationError("step must be an integer");
189
+ }
190
+ }
191
+ function validateSigningSteps(signers) {
192
+ const withSteps = signers.filter((signer) => signer.step !== void 0);
193
+ if (withSteps.length > 0) {
194
+ if (withSteps.length !== signers.length) {
195
+ throw new ValidationError("step must be supplied for every signer when used");
196
+ }
197
+ const steps = [...new Set(withSteps.map((signer) => signer.step))].sort(
198
+ (a, b) => a - b
199
+ );
200
+ if (steps.some((step, index) => step !== index + 1)) {
201
+ throw new ValidationError("steps must form a contiguous sequence starting at 1");
202
+ }
203
+ }
204
+ validateDigitalCertificateSteps(signers);
205
+ }
206
+ function validateDigitalCertificateSteps(signers) {
207
+ for (const signer of signers) {
208
+ if (signer.verification_method === "DigitalCertificate" && signers.some((other) => other !== signer && (other.step ?? 1) === (signer.step ?? 1))) {
209
+ throw new ValidationError("a DigitalCertificate signer must be alone in its signing step");
210
+ }
211
+ }
212
+ }
131
213
  function documentStatsParams(params = {}) {
132
214
  if (params.granularity !== void 0 && !["monthly", "daily"].includes(params.granularity)) {
133
215
  throw new ValidationError("granularity must be monthly or daily");
@@ -273,15 +355,25 @@ function toInt(value) {
273
355
 
274
356
  // src/api/resources/assignments.ts
275
357
  function buildAssignmentPayload(payload, options = {}) {
358
+ if (payload.method !== void 0 && payload.method !== "virtual" && payload.method !== "collect") {
359
+ throw new ValidationError("method must be virtual or collect");
360
+ }
276
361
  const signers = extractSignerRefs(payload);
277
- if (signers.length === 0 && !options.allowEmptySigners) {
362
+ if (signers.length === 0 && (!options.allowEmptySigners || (payload.method ?? "virtual") !== "collect")) {
278
363
  throw new ValidationError("At least one signer is required", {
279
364
  signers: payload.signers ?? payload.signer_ids ?? payload.signerIds
280
365
  });
281
366
  }
367
+ if (payload.method === "collect" && !Array.isArray(payload.entries)) {
368
+ throw new ValidationError("entries are required for collect assignments");
369
+ }
370
+ const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
371
+ if (!options.skipDigitalCertificateStepValidation) {
372
+ validateSigningSteps(normalisedSigners);
373
+ }
282
374
  return cleanParams({
283
375
  method: payload.method ?? "virtual",
284
- signers: signers.map((ref) => normaliseSignerRef(ref, options)),
376
+ signers: normalisedSigners,
285
377
  message: payload.message,
286
378
  expires_at: payload.expires_at === void 0 ? void 0 : requireIso8601(payload.expires_at, "expires_at"),
287
379
  copy_receivers: payload.copy_receivers,
@@ -309,6 +401,7 @@ function normaliseSignerRef(ref, options) {
309
401
  if (ref && typeof ref === "object") {
310
402
  const input = ref;
311
403
  const id = input.id ?? input.signer_id;
404
+ validateSignerOptions(input);
312
405
  const normalised = cleanParams({
313
406
  id,
314
407
  verification_method: input.verification_method,
@@ -366,14 +459,16 @@ var AssignmentResource = class extends BaseResource {
366
459
  `/documents/${docId}/assignments/estimate-cost`,
367
460
  buildAssignmentPayload(payload, {
368
461
  allowSignersWithoutId: true,
369
- allowEmptySigners: true
462
+ allowEmptySigners: true,
463
+ skipDigitalCertificateStepValidation: true
370
464
  })
371
465
  )
372
466
  );
373
467
  }
374
468
  /**
375
469
  * Update the expiration date of an existing assignment.
376
- * Pass `null` to remove the expiration entirely.
470
+ * The published API accepts an ISO 8601 timestamp. Deployments that support
471
+ * clearing an expiration also accept `null`.
377
472
  */
378
473
  async resetExpiration(documentId, assignmentId, expiresAt) {
379
474
  const docId = this.requireId(documentId, "Document ID");
@@ -708,24 +803,24 @@ var DocumentResource = class extends BaseResource {
708
803
  );
709
804
  }
710
805
  /**
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.
806
+ * Replace the document's tag set with tag IDs. An empty array detaches all tags.
807
+ * Values are forwarded unchanged for compatibility with deployments that also accept names.
713
808
  */
714
809
  async replaceTags(documentId, tags, accountId) {
715
810
  const accId = this.accountId(accountId);
716
811
  const docId = this.requireId(documentId, "Document ID");
717
- if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag names");
812
+ if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag IDs");
718
813
  return this.call(
719
814
  "Failed to replace document tags",
720
815
  () => this.http.put(`/accounts/${accId}/documents/${docId}/tags`, { tags })
721
816
  );
722
817
  }
723
- /** Attach additional tags (by name) without removing existing ones. Idempotent. */
818
+ /** Attach additional tag IDs without removing existing ones. */
724
819
  async addTags(documentId, tags, accountId) {
725
820
  const accId = this.accountId(accountId);
726
821
  const docId = this.requireId(documentId, "Document ID");
727
822
  if (!Array.isArray(tags) || tags.length === 0) {
728
- throw new ValidationError("tags must be a non-empty array of tag names");
823
+ throw new ValidationError("tags must be a non-empty array of tag IDs");
729
824
  }
730
825
  return this.call(
731
826
  "Failed to add document tags",
@@ -755,7 +850,14 @@ var DocumentResource = class extends BaseResource {
755
850
  async createFromTemplate(templateId, signers, options = {}, accountId) {
756
851
  const tmplId = this.requireId(templateId, "Template ID");
757
852
  const accId = this.accountId(accountId);
853
+ validateTemplateSigners(signers, { requireId: true, singleNotification: true });
758
854
  if (options.expires_at !== void 0) requireIso8601(options.expires_at, "expires_at");
855
+ if (options.editor_fields !== void 0 && (!Array.isArray(options.editor_fields) || options.editor_fields.some((field) => !field?.field_id || typeof field.value !== "string"))) {
856
+ throw new ValidationError("editor_fields must contain field_id and value");
857
+ }
858
+ if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !tag))) {
859
+ throw new ValidationError("tags must contain non-empty tag names");
860
+ }
759
861
  const body = { ...options, signers };
760
862
  this.logger.info("Creating document from template", { templateId: tmplId, accountId: accId });
761
863
  return this.call(
@@ -767,6 +869,7 @@ var DocumentResource = class extends BaseResource {
767
869
  async estimateCostFromTemplate(templateId, signers, accountId) {
768
870
  const tmplId = this.requireId(templateId, "Template ID");
769
871
  const accId = this.accountId(accountId);
872
+ validateTemplateSigners(signers, { requireId: false, singleNotification: false });
770
873
  return this.call(
771
874
  "Failed to estimate cost from template",
772
875
  () => this.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers })
@@ -813,7 +916,7 @@ var DocumentResource = class extends BaseResource {
813
916
  async sendToken(documentId, recipient, channel = "email") {
814
917
  const id = this.requireId(documentId, "Document ID");
815
918
  if (typeof recipient === "object") {
816
- if (!recipient?.email) throw new ValidationError("email is required");
919
+ requireEmail(recipient?.email);
817
920
  return this.call(
818
921
  "Failed to send signing token",
819
922
  () => this.http.put(
@@ -824,6 +927,10 @@ var DocumentResource = class extends BaseResource {
824
927
  );
825
928
  }
826
929
  if (!recipient) throw new ValidationError("recipient is required");
930
+ if (channel !== "email" && channel !== "whatsapp") {
931
+ throw new ValidationError("channel must be email or whatsapp");
932
+ }
933
+ if (channel === "email") requireEmail(recipient);
827
934
  return this.call(
828
935
  "Failed to send signing token",
829
936
  () => this.http.put(
@@ -854,6 +961,31 @@ var DocumentResource = class extends BaseResource {
854
961
  return { signed, total, pending, percentage };
855
962
  }
856
963
  };
964
+ function validateTemplateSigners(signers, options) {
965
+ if (!Array.isArray(signers)) throw new ValidationError("signers must be an array");
966
+ for (const value of signers) {
967
+ if (!value || typeof value !== "object") {
968
+ throw new ValidationError("each template signer must be an object");
969
+ }
970
+ const signer = value;
971
+ if (typeof signer.role_id !== "string" || !signer.role_id) {
972
+ throw new ValidationError("each template signer requires role_id");
973
+ }
974
+ if ((options.requireId || signer.id !== void 0) && (typeof signer.id !== "string" || !signer.id)) {
975
+ throw new ValidationError("each template signer requires a valid id");
976
+ }
977
+ validateSignerOptions(signer);
978
+ if (options.requireId && signer.step !== void 0 && Number(signer.step) < 1) {
979
+ throw new ValidationError("template signer step must be a positive integer");
980
+ }
981
+ if (options.singleNotification && Array.isArray(signer.notification_methods) && signer.notification_methods.length > 1) {
982
+ throw new ValidationError("template signers accept at most one notification method");
983
+ }
984
+ }
985
+ if (options.requireId) {
986
+ validateSigningSteps(signers);
987
+ }
988
+ }
857
989
  async function loadSource(source) {
858
990
  if ("buffer" in source) {
859
991
  if (!source.fileName) {
@@ -965,6 +1097,7 @@ var FieldsResource = class extends BaseResource {
965
1097
  async validate(fieldId, value, options = {}) {
966
1098
  const id = this.accountId(options.accountId);
967
1099
  const fid = this.requireId(fieldId, "Field ID");
1100
+ if (value === void 0) throw new ValidationError("value is required");
968
1101
  return this.call(
969
1102
  "Failed to validate field value",
970
1103
  () => this.http.post(
@@ -979,6 +1112,11 @@ var FieldsResource = class extends BaseResource {
979
1112
  if (!Array.isArray(entries) || entries.length === 0) {
980
1113
  throw new ValidationError("entries must be a non-empty array");
981
1114
  }
1115
+ if (entries.some(
1116
+ (entry) => !entry || typeof entry !== "object" || typeof entry.field_id !== "string" || !entry.field_id || entry.value === void 0
1117
+ )) {
1118
+ throw new ValidationError("each entry must contain field_id and value");
1119
+ }
982
1120
  const id = this.accountId(options.accountId);
983
1121
  return this.call(
984
1122
  "Failed to validate field values",
@@ -998,6 +1136,174 @@ function validationConfig(signerAccessCode) {
998
1136
  return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
999
1137
  }
1000
1138
 
1139
+ // src/api/resources/oauth.ts
1140
+ import { createHash, randomBytes, timingSafeEqual } from "crypto";
1141
+ var OAuthResource = class extends BaseResource {
1142
+ /** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
1143
+ async metadata() {
1144
+ return this.call(
1145
+ "Failed to discover OAuth resource",
1146
+ () => this.http.get(
1147
+ "/.well-known/oauth-protected-resource",
1148
+ publicRequestConfig({
1149
+ baseURL: new URL(this.http.defaults.baseURL).origin
1150
+ })
1151
+ )
1152
+ );
1153
+ }
1154
+ /** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
1155
+ async discovery(issuer) {
1156
+ const url = httpsUrl(issuer, "issuer");
1157
+ if (url.search || url.pathname !== "/") {
1158
+ throw new ValidationError("issuer must be an HTTPS origin");
1159
+ }
1160
+ const metadata = await this.call(
1161
+ "Failed to discover OAuth authorization server",
1162
+ () => this.http.get(
1163
+ `${url.origin}/.well-known/oauth-authorization-server`,
1164
+ publicRequestConfig()
1165
+ )
1166
+ );
1167
+ if (metadata.issuer !== issuer) throw new ValidationError("OAuth issuer mismatch");
1168
+ httpsUrl(metadata.authorization_endpoint, "authorization_endpoint");
1169
+ return metadata;
1170
+ }
1171
+ /** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */
1172
+ async authorize(options) {
1173
+ required(options.clientId, "clientId");
1174
+ httpsUrl(options.redirectUri, "redirectUri");
1175
+ if (!Array.isArray(options.scopes) || options.scopes.length === 0 || options.scopes.some(
1176
+ (scope) => typeof scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)
1177
+ )) {
1178
+ throw new ValidationError("scopes must contain non-empty OAuth scope names");
1179
+ }
1180
+ const resource = await this.metadata();
1181
+ const issuer = resource.authorization_servers?.[0];
1182
+ if (!issuer) throw new ValidationError("OAuth metadata has no authorization server");
1183
+ httpsUrl(resource.resource, "resource");
1184
+ const server = await this.discovery(issuer);
1185
+ const codeVerifier = randomBytes(32).toString("base64url");
1186
+ const state = randomBytes(32).toString("base64url");
1187
+ const nonce = options.scopes.includes("openid") ? randomBytes(32).toString("base64url") : void 0;
1188
+ const url = new URL(server.authorization_endpoint);
1189
+ const params = {
1190
+ response_type: "code",
1191
+ client_id: options.clientId,
1192
+ redirect_uri: options.redirectUri,
1193
+ scope: options.scopes.join(" "),
1194
+ state,
1195
+ code_challenge: createHash("sha256").update(codeVerifier).digest("base64url"),
1196
+ code_challenge_method: "S256",
1197
+ resource: resource.resource
1198
+ };
1199
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
1200
+ if (nonce) url.searchParams.set("nonce", nonce);
1201
+ return {
1202
+ authorization_url: url.toString(),
1203
+ code_verifier: codeVerifier,
1204
+ state,
1205
+ issuer,
1206
+ client_id: options.clientId,
1207
+ redirect_uri: options.redirectUri,
1208
+ resource: resource.resource,
1209
+ ...nonce ? { nonce } : {}
1210
+ };
1211
+ }
1212
+ /** Validate callback URI, state, and issuer before exchanging its one-time code. */
1213
+ async exchangeCode(callbackUrl, request, clientSecret) {
1214
+ const callback = httpsUrl(callbackUrl, "callbackUrl");
1215
+ const redirect = httpsUrl(request.redirect_uri, "redirect_uri");
1216
+ if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname || [...new Set(redirect.searchParams.keys())].some((key) => {
1217
+ const expected2 = redirect.searchParams.getAll(key);
1218
+ const actual2 = callback.searchParams.getAll(key);
1219
+ return expected2.length !== actual2.length || expected2.some((value, i) => value !== actual2[i]);
1220
+ })) {
1221
+ throw new ValidationError("OAuth callback does not match the registered redirect URI");
1222
+ }
1223
+ for (const key of ["state", "iss", "code", "error"]) {
1224
+ if (callback.searchParams.getAll(key).length > 1) {
1225
+ throw new ValidationError(`Duplicate OAuth callback parameter: ${key}`);
1226
+ }
1227
+ }
1228
+ const actual = Buffer.from(callback.searchParams.get("state") ?? "");
1229
+ const expected = Buffer.from(required(request.state, "state"));
1230
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
1231
+ throw new ValidationError("OAuth state mismatch");
1232
+ }
1233
+ if (callback.searchParams.get("iss") !== request.issuer) {
1234
+ throw new ValidationError("OAuth issuer mismatch");
1235
+ }
1236
+ if (callback.searchParams.has("error")) {
1237
+ throw new ValidationError("OAuth authorization was declined or failed");
1238
+ }
1239
+ return this.token({
1240
+ grant_type: "authorization_code",
1241
+ code: required(callback.searchParams.get("code"), "code"),
1242
+ client_id: request.client_id,
1243
+ client_secret: clientSecret,
1244
+ redirect_uri: request.redirect_uri,
1245
+ code_verifier: request.code_verifier,
1246
+ resource: request.resource
1247
+ });
1248
+ }
1249
+ /** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
1250
+ async token(payload) {
1251
+ required(payload.client_id, "client_id");
1252
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1253
+ if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
1254
+ if (payload.grant_type === "authorization_code") {
1255
+ required(payload.code, "code");
1256
+ httpsUrl(payload.redirect_uri, "redirect_uri");
1257
+ if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
1258
+ throw new ValidationError(
1259
+ "code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
1260
+ );
1261
+ }
1262
+ } else if (payload.grant_type === "refresh_token") {
1263
+ required(payload.refresh_token, "refresh_token");
1264
+ } else {
1265
+ throw new ValidationError("grant_type must be authorization_code or refresh_token");
1266
+ }
1267
+ return this.call(
1268
+ "OAuth token request failed",
1269
+ () => this.http.post("/oauth/token", payload, publicRequestConfig())
1270
+ );
1271
+ }
1272
+ /** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
1273
+ async revoke(payload) {
1274
+ required(payload.client_id, "client_id");
1275
+ required(payload.token, "token");
1276
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1277
+ if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
1278
+ throw new ValidationError("token_type_hint must be access_token or refresh_token");
1279
+ }
1280
+ await this.call(
1281
+ "OAuth revocation failed",
1282
+ () => this.http.post("/oauth/revoke", payload, publicRequestConfig())
1283
+ );
1284
+ }
1285
+ /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
1286
+ async userinfo() {
1287
+ return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
1288
+ }
1289
+ };
1290
+ function required(value, name) {
1291
+ if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
1292
+ return value;
1293
+ }
1294
+ function httpsUrl(value, name) {
1295
+ let url;
1296
+ try {
1297
+ url = new URL(value);
1298
+ } catch {
1299
+ throw new ValidationError(`${name} must be an absolute HTTPS URL`);
1300
+ }
1301
+ if (url.protocol !== "https:" || url.username || url.password || url.hash) {
1302
+ throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
1303
+ }
1304
+ return url;
1305
+ }
1306
+
1001
1307
  // src/api/resources/signer-documents.ts
1002
1308
  var SignerDocumentsResource = class extends BaseResource {
1003
1309
  /** `GET /signers/{signer_id}/document?signer-access-code=…` */
@@ -1030,20 +1336,28 @@ var SignerDocumentsResource = class extends BaseResource {
1030
1336
  () => this.http.get(`/signers/${sid}/documents/search`, signerAccessConfig(code, { search }))
1031
1337
  );
1032
1338
  }
1033
- /** `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}?signer-access-code=…` */
1339
+ /**
1340
+ * Public `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`.
1341
+ * When an access code is supplied, the SDK first verifies that it belongs to
1342
+ * the requested signer for callers that want that additional check.
1343
+ */
1034
1344
  async download(signerId, documentId, artifactName, signerAccessCode) {
1035
1345
  const sid = this.requireId(signerId, "Signer ID");
1036
1346
  const did = this.requireId(documentId, "Document ID");
1037
1347
  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");
1348
+ let config = publicRequestConfig();
1349
+ if (signerAccessCode !== void 0) {
1350
+ const code = this.requireId(signerAccessCode, "signer-access-code");
1351
+ const signer = await this.self(code);
1352
+ if (signer.id !== sid) {
1353
+ throw new ValidationError("Signer access code does not match the signer ID");
1354
+ }
1355
+ config = signerAccessConfig(code);
1042
1356
  }
1043
1357
  return this.callBinary(
1044
1358
  "Failed to download signer document",
1045
1359
  () => this.http.get(`/signers/${sid}/documents/${did}/download/${artifact}`, {
1046
- ...signerAccessConfig(code),
1360
+ ...config,
1047
1361
  responseType: "arraybuffer"
1048
1362
  })
1049
1363
  );
@@ -1068,7 +1382,7 @@ var SignerDocumentsResource = class extends BaseResource {
1068
1382
  if (!Array.isArray(documentIds) || documentIds.length === 0) {
1069
1383
  throw new ValidationError("documentIds must be a non-empty array");
1070
1384
  }
1071
- if (!declineReason) throw new ValidationError("declineReason is required");
1385
+ validateDeclineReason(declineReason);
1072
1386
  const code = this.requireId(signerAccessCode, "signer-access-code");
1073
1387
  return this.call(
1074
1388
  "Failed to decline multiple documents",
@@ -1198,7 +1512,7 @@ var SignerDocumentsResource = class extends BaseResource {
1198
1512
  const did = this.requireId(documentId, "Document ID");
1199
1513
  const aid = this.requireId(assignmentId, "Assignment ID");
1200
1514
  const code = this.requireId(signerAccessCode, "signer-access-code");
1201
- if (!declineReason) throw new ValidationError("declineReason is required");
1515
+ validateDeclineReason(declineReason);
1202
1516
  return this.call(
1203
1517
  "Failed to decline assignment",
1204
1518
  () => this.http.put(
@@ -1209,17 +1523,19 @@ var SignerDocumentsResource = class extends BaseResource {
1209
1523
  );
1210
1524
  }
1211
1525
  };
1526
+ function validateDeclineReason(value) {
1527
+ if (typeof value !== "string" || !value.trim()) {
1528
+ throw new ValidationError("declineReason is required");
1529
+ }
1530
+ if ([...value].length > 2e3) {
1531
+ throw new ValidationError("declineReason must contain at most 2000 characters");
1532
+ }
1533
+ }
1212
1534
 
1213
1535
  // src/api/resources/signers.ts
1214
- var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1215
1536
  function validateCreateSignerPayload(payload) {
1216
1537
  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
- }
1538
+ if (payload.email !== void 0) requireEmail(payload.email);
1223
1539
  }
1224
1540
  var SignerResource = class extends BaseResource {
1225
1541
  /**
@@ -1282,6 +1598,10 @@ var SignerResource = class extends BaseResource {
1282
1598
  async update(signerId, payload, accountId) {
1283
1599
  const id = this.accountId(accountId);
1284
1600
  const sid = this.requireId(signerId, "Signer ID");
1601
+ if (payload.full_name !== void 0 && !payload.full_name.trim()) {
1602
+ throw new ValidationError("Signer full name cannot be blank");
1603
+ }
1604
+ if (payload.email !== void 0) requireEmail(payload.email);
1285
1605
  return this.call(
1286
1606
  "Failed to update signer",
1287
1607
  () => this.http.put(`/accounts/${id}/signers/${sid}`, normaliseSignerPayload(payload, true))
@@ -1298,11 +1618,15 @@ var SignerResource = class extends BaseResource {
1298
1618
  }
1299
1619
  /** Find a signer by email via the API's `search` parameter. Returns `null` if none match. */
1300
1620
  async findByEmail(email, accountId) {
1301
- assertEmail(email);
1621
+ requireEmail(email);
1302
1622
  try {
1303
- const { data } = await this.list({ search: email, per_page: 100 }, accountId);
1304
1623
  const lower = email.toLowerCase();
1305
- return data.find((s) => (s.email ?? "").toLowerCase() === lower) ?? null;
1624
+ for (let page = 1; ; page++) {
1625
+ const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
1626
+ const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
1627
+ if (match) return match;
1628
+ if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
1629
+ }
1306
1630
  } catch (err) {
1307
1631
  if (err instanceof ApiError && err.statusCode === 404) {
1308
1632
  return null;
@@ -1496,7 +1820,22 @@ var WebhookResource = class extends BaseResource {
1496
1820
  /** Register (or replace) the webhook subscription for the workspace. */
1497
1821
  async register(payload, accountId) {
1498
1822
  if (!payload.url) throw new ValidationError("Webhook URL is required");
1499
- if (!payload.email) throw new ValidationError("Webhook email is required");
1823
+ let webhookUrl;
1824
+ try {
1825
+ webhookUrl = new URL(payload.url);
1826
+ } catch {
1827
+ throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1828
+ }
1829
+ if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
1830
+ throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1831
+ }
1832
+ requireEmail(payload.email);
1833
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
1834
+ throw new ValidationError("Webhook events must contain non-empty strings");
1835
+ }
1836
+ if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
1837
+ throw new ValidationError("Webhook is_active must be a boolean");
1838
+ }
1500
1839
  const id = this.accountId(accountId);
1501
1840
  const body = {
1502
1841
  url: payload.url,
@@ -1657,7 +1996,7 @@ function validateNotificationSender(value) {
1657
1996
  }
1658
1997
 
1659
1998
  // src/api/support/webhook-verifier.ts
1660
- import { createHmac, timingSafeEqual } from "crypto";
1999
+ import { createHmac, timingSafeEqual as timingSafeEqual2 } from "crypto";
1661
2000
  var WebhookVerifier = class {
1662
2001
  constructor(webhookSecret, options = {}) {
1663
2002
  this.webhookSecret = webhookSecret;
@@ -1670,14 +2009,14 @@ var WebhookVerifier = class {
1670
2009
  /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
1671
2010
  verify(payload, signature) {
1672
2011
  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
2012
  try {
1680
- return timingSafeEqual(a, b);
2013
+ const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
2014
+ const expected = createHmac(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
2015
+ const provided = signature.trim();
2016
+ const a = Buffer.from(expected, "utf8");
2017
+ const b = Buffer.from(provided, "utf8");
2018
+ if (a.length !== b.length) return false;
2019
+ return timingSafeEqual2(a, b);
1681
2020
  } catch {
1682
2021
  return false;
1683
2022
  }
@@ -1696,7 +2035,8 @@ var WebhookVerifier = class {
1696
2035
  getEventType(event) {
1697
2036
  if (!event || typeof event !== "object") return null;
1698
2037
  const e = event;
1699
- return e.event ?? e.type ?? null;
2038
+ if (typeof e.event === "string") return e.event;
2039
+ return typeof e.type === "string" ? e.type : null;
1700
2040
  }
1701
2041
  /**
1702
2042
  * Extract the event data from an event envelope.
@@ -1718,6 +2058,9 @@ var WebhookVerifier = class {
1718
2058
 
1719
2059
  // src/api/client.ts
1720
2060
  var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
2061
+ function isLoopbackHost(hostname) {
2062
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
2063
+ }
1721
2064
  var AssinafyClient = class _AssinafyClient {
1722
2065
  axiosInstance;
1723
2066
  defaultAccountId;
@@ -1731,6 +2074,7 @@ var AssinafyClient = class _AssinafyClient {
1731
2074
  templates;
1732
2075
  tags;
1733
2076
  auth;
2077
+ oauth;
1734
2078
  fields;
1735
2079
  users;
1736
2080
  signerDocuments;
@@ -1738,9 +2082,12 @@ var AssinafyClient = class _AssinafyClient {
1738
2082
  constructor(options) {
1739
2083
  if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
1740
2084
  throw new ValidationError(
1741
- "An API key (options.apiKey) or legacy access token (options.token) is required."
2085
+ "An API key (options.apiKey) or access token (options.token) is required."
1742
2086
  );
1743
2087
  }
2088
+ if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
2089
+ throw new ValidationError("timeout must be a finite positive number");
2090
+ }
1744
2091
  this.defaultAccountId = options.accountId;
1745
2092
  this.logger = options.logger ?? createNoopLogger();
1746
2093
  this.webhookSecret = options.webhookSecret;
@@ -1751,13 +2098,17 @@ var AssinafyClient = class _AssinafyClient {
1751
2098
  } catch {
1752
2099
  throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
1753
2100
  }
1754
- if (!["https:", "http:"].includes(parsedBaseUrl.protocol)) {
1755
- throw new ValidationError("baseUrl must use HTTPS");
1756
- }
1757
- if (parsedBaseUrl.protocol !== "https:" && !options.allowInsecureHttp) {
1758
- throw new ValidationError(
1759
- "baseUrl must use HTTPS; set allowInsecureHttp only for isolated local development"
1760
- );
2101
+ if (parsedBaseUrl.protocol !== "https:") {
2102
+ if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
2103
+ throw new ValidationError(
2104
+ "baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
2105
+ );
2106
+ }
2107
+ if (!isLoopbackHost(parsedBaseUrl.hostname)) {
2108
+ throw new ValidationError(
2109
+ "allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
2110
+ );
2111
+ }
1761
2112
  }
1762
2113
  if (parsedBaseUrl.username || parsedBaseUrl.password) {
1763
2114
  throw new ValidationError("baseUrl must not contain embedded credentials");
@@ -1793,6 +2144,7 @@ var AssinafyClient = class _AssinafyClient {
1793
2144
  this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
1794
2145
  this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
1795
2146
  this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
2147
+ this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
1796
2148
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
1797
2149
  this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
1798
2150
  this.signerDocuments = new SignerDocumentsResource(
@@ -1828,13 +2180,22 @@ var AssinafyClient = class _AssinafyClient {
1828
2180
  /**
1829
2181
  * High-level helper that uploads a PDF, ensures it's processed, creates any
1830
2182
  * missing signers, and kicks off a virtual signature assignment.
2183
+ *
2184
+ * Once the upload succeeds the workflow owns real workspace resources, so any
2185
+ * later failure is rethrown as a {@link PartialWorkflowError} carrying the
2186
+ * document and signer IDs that already exist. Catch it to resume or clean up;
2187
+ * nothing is deleted automatically.
1831
2188
  */
1832
2189
  async uploadAndRequestSignatures(options) {
1833
- if (!options.signers || options.signers.length === 0) {
2190
+ if (!Array.isArray(options.signers) || options.signers.length === 0) {
1834
2191
  throw new ValidationError("At least one signer is required");
1835
2192
  }
1836
2193
  if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
1837
2194
  const preparedSigners = options.signers.map((signer) => {
2195
+ if (!signer || typeof signer !== "object") {
2196
+ throw new ValidationError("Each signer must be an object");
2197
+ }
2198
+ validateSignerOptions(signer);
1838
2199
  const payload = { full_name: signer.name };
1839
2200
  if (signer.email !== void 0) payload.email = signer.email;
1840
2201
  const phone = signer.whatsapp_phone_number ?? signer.phone;
@@ -1844,6 +2205,7 @@ var AssinafyClient = class _AssinafyClient {
1844
2205
  validateCreateSignerPayload(payload);
1845
2206
  return { signer, payload, phone };
1846
2207
  });
2208
+ validateSigningSteps(options.signers);
1847
2209
  this.logger.info("Starting upload + signature workflow", {
1848
2210
  signerCount: options.signers.length
1849
2211
  });
@@ -1851,33 +2213,46 @@ var AssinafyClient = class _AssinafyClient {
1851
2213
  if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
1852
2214
  if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
1853
2215
  const document = await this.documents.upload(options.source, uploadOpts);
1854
- if (options.waitForReady !== false) {
1855
- await this.documents.waitUntilReady(document.id);
1856
- }
1857
2216
  const signerIds = [];
1858
- const assignmentSigners = [];
1859
- for (const { signer, payload, phone } of preparedSigners) {
1860
- const created = await this.signers.create(payload, options.accountId);
1861
- signerIds.push(created.id);
1862
- const useWhatsapp = phone !== void 0 && signer.email === void 0;
1863
- assignmentSigners.push({
1864
- id: created.id,
1865
- verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
1866
- notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
1867
- step: signer.step
2217
+ try {
2218
+ if (options.waitForReady !== false) {
2219
+ await this.documents.waitUntilReady(document.id);
2220
+ }
2221
+ const assignmentSigners = [];
2222
+ for (const { signer, payload, phone } of preparedSigners) {
2223
+ const created = await this.signers.create(payload, options.accountId);
2224
+ signerIds.push(created.id);
2225
+ const useWhatsapp = phone !== void 0 && signer.email === void 0;
2226
+ assignmentSigners.push({
2227
+ id: created.id,
2228
+ verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
2229
+ notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
2230
+ step: signer.step
2231
+ });
2232
+ }
2233
+ const assignmentPayload = {
2234
+ method: "virtual",
2235
+ signers: assignmentSigners
2236
+ };
2237
+ if (options.message !== void 0) assignmentPayload.message = options.message;
2238
+ if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
2239
+ if (options.copyReceivers !== void 0)
2240
+ assignmentPayload.copy_receivers = options.copyReceivers;
2241
+ const assignment = await this.assignments.create(document.id, assignmentPayload);
2242
+ this.logger.info("Upload + signature workflow completed", { documentId: document.id });
2243
+ return { document, assignment, signer_ids: signerIds };
2244
+ } catch (err) {
2245
+ this.logger.error("Upload + signature workflow failed after creating resources", {
2246
+ documentId: document.id,
2247
+ signerIds
1868
2248
  });
2249
+ const reason = err instanceof Error ? err.message : String(err);
2250
+ throw new PartialWorkflowError(
2251
+ `${reason} (document ${document.id} exists; ${signerIds.length} signer(s) created or reused)`,
2252
+ { documentId: document.id, signerIds },
2253
+ { cause: err }
2254
+ );
1869
2255
  }
1870
- const assignmentPayload = {
1871
- method: "virtual",
1872
- signers: assignmentSigners
1873
- };
1874
- if (options.message !== void 0) assignmentPayload.message = options.message;
1875
- if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
1876
- if (options.copyReceivers !== void 0)
1877
- assignmentPayload.copy_receivers = options.copyReceivers;
1878
- const assignment = await this.assignments.create(document.id, assignmentPayload);
1879
- this.logger.info("Upload + signature workflow completed", { documentId: document.id });
1880
- return { document, assignment, signer_ids: signerIds };
1881
2256
  }
1882
2257
  /** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
1883
2258
  getAxiosInstance() {
@@ -1894,6 +2269,8 @@ export {
1894
2269
  FieldsResource,
1895
2270
  NOTIFICATION_PREFERENCE_CODES,
1896
2271
  NetworkError,
2272
+ OAuthResource,
2273
+ PartialWorkflowError,
1897
2274
  SignerDocumentsResource,
1898
2275
  SignerResource,
1899
2276
  TagResource,