@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.cjs CHANGED
@@ -39,6 +39,8 @@ __export(api_exports, {
39
39
  FieldsResource: () => FieldsResource,
40
40
  NOTIFICATION_PREFERENCE_CODES: () => NOTIFICATION_PREFERENCE_CODES,
41
41
  NetworkError: () => NetworkError,
42
+ OAuthResource: () => OAuthResource,
43
+ PartialWorkflowError: () => PartialWorkflowError,
42
44
  SignerDocumentsResource: () => SignerDocumentsResource,
43
45
  SignerResource: () => SignerResource,
44
46
  TagResource: () => TagResource,
@@ -68,18 +70,35 @@ var AssinafyError = class extends Error {
68
70
  var ApiError = class _ApiError extends AssinafyError {
69
71
  statusCode;
70
72
  responseData;
73
+ /** Bearer challenge, including insufficient_scope and resource_metadata when provided. */
74
+ wwwAuthenticate;
75
+ /** Server retry delay (seconds or HTTP date), when provided. */
76
+ retryAfter;
71
77
  constructor(message, statusCode, responseData = null, options) {
72
78
  super(message, { statusCode, responseData }, options);
73
79
  this.name = "ApiError";
74
80
  this.statusCode = statusCode;
75
81
  this.responseData = responseData;
82
+ this.wwwAuthenticate = options?.wwwAuthenticate;
83
+ this.retryAfter = options?.retryAfter;
76
84
  }
77
- static fromResponse(statusCode, responseData) {
85
+ static fromResponse(statusCode, responseData, headers = {}) {
86
+ if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
87
+ const text = (Buffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)).toString("utf8");
88
+ try {
89
+ responseData = JSON.parse(text);
90
+ } catch {
91
+ responseData = text;
92
+ }
93
+ }
78
94
  const data = responseData ?? {};
79
95
  const rawMessage = data.message;
80
96
  const rawError = data.error;
81
97
  const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
82
- return new _ApiError(message, statusCode, responseData);
98
+ return new _ApiError(message, statusCode, responseData, {
99
+ wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
100
+ retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
101
+ });
83
102
  }
84
103
  };
85
104
  var ValidationError = class extends AssinafyError {
@@ -96,6 +115,19 @@ var NetworkError = class extends AssinafyError {
96
115
  this.name = "NetworkError";
97
116
  }
98
117
  };
118
+ var PartialWorkflowError = class extends AssinafyError {
119
+ /** The document that was uploaded before the failure, if any. */
120
+ documentId;
121
+ /** IDs of every signer created (or reused) before the failure. */
122
+ signerIds;
123
+ constructor(message, created, options) {
124
+ const signerIds = created.signerIds ?? [];
125
+ super(message, { documentId: created.documentId, signerIds }, options);
126
+ this.name = "PartialWorkflowError";
127
+ this.documentId = created.documentId;
128
+ this.signerIds = signerIds;
129
+ }
130
+ };
99
131
 
100
132
  // src/api/utils.ts
101
133
  var import_axios = __toESM(require("axios"), 1);
@@ -106,6 +138,13 @@ var DOCUMENT_ARTIFACT_NAMES = [
106
138
  "pades",
107
139
  "bundle"
108
140
  ];
141
+ var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
142
+ var VERIFICATION_METHODS = [
143
+ "Email",
144
+ "Whatsapp",
145
+ "DigitalCertificate"
146
+ ];
147
+ var NOTIFICATION_METHODS = ["Email", "Whatsapp"];
109
148
  function handleAssinafyResponse(response) {
110
149
  const resp = response;
111
150
  if (resp && typeof resp === "object" && resp.status !== void 0 && "data" in resp) {
@@ -123,7 +162,7 @@ function toSdkError(error, fallbackMessage) {
123
162
  if (import_axios.default.isAxiosError(error)) {
124
163
  const status = error.response?.status;
125
164
  if (status) {
126
- return ApiError.fromResponse(status, error.response?.data ?? null);
165
+ return ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);
127
166
  }
128
167
  return new NetworkError(`${fallbackMessage}: ${error.message}`);
129
168
  }
@@ -183,6 +222,51 @@ function requireIso8601(value, name = "timestamp") {
183
222
  }
184
223
  return value;
185
224
  }
225
+ function requireEmail(value) {
226
+ if (!value || !EMAIL_RE.test(value)) {
227
+ throw new ValidationError("Invalid email address", { email: value });
228
+ }
229
+ return value;
230
+ }
231
+ function validateSignerOptions(input) {
232
+ if (input.verification_method !== void 0 && !VERIFICATION_METHODS.includes(input.verification_method)) {
233
+ throw new ValidationError(
234
+ `verification_method must be one of: ${VERIFICATION_METHODS.join(", ")}`
235
+ );
236
+ }
237
+ if (input.notification_methods !== void 0 && (!Array.isArray(input.notification_methods) || input.notification_methods.some(
238
+ (method) => !NOTIFICATION_METHODS.includes(method)
239
+ ))) {
240
+ throw new ValidationError(
241
+ `notification_methods must contain only: ${NOTIFICATION_METHODS.join(", ")}`
242
+ );
243
+ }
244
+ if (input.step !== void 0 && !Number.isInteger(input.step)) {
245
+ throw new ValidationError("step must be an integer");
246
+ }
247
+ }
248
+ function validateSigningSteps(signers) {
249
+ const withSteps = signers.filter((signer) => signer.step !== void 0);
250
+ if (withSteps.length > 0) {
251
+ if (withSteps.length !== signers.length) {
252
+ throw new ValidationError("step must be supplied for every signer when used");
253
+ }
254
+ const steps = [...new Set(withSteps.map((signer) => signer.step))].sort(
255
+ (a, b) => a - b
256
+ );
257
+ if (steps.some((step, index) => step !== index + 1)) {
258
+ throw new ValidationError("steps must form a contiguous sequence starting at 1");
259
+ }
260
+ }
261
+ validateDigitalCertificateSteps(signers);
262
+ }
263
+ function validateDigitalCertificateSteps(signers) {
264
+ for (const signer of signers) {
265
+ if (signer.verification_method === "DigitalCertificate" && signers.some((other) => other !== signer && (other.step ?? 1) === (signer.step ?? 1))) {
266
+ throw new ValidationError("a DigitalCertificate signer must be alone in its signing step");
267
+ }
268
+ }
269
+ }
186
270
  function documentStatsParams(params = {}) {
187
271
  if (params.granularity !== void 0 && !["monthly", "daily"].includes(params.granularity)) {
188
272
  throw new ValidationError("granularity must be monthly or daily");
@@ -328,15 +412,25 @@ function toInt(value) {
328
412
 
329
413
  // src/api/resources/assignments.ts
330
414
  function buildAssignmentPayload(payload, options = {}) {
415
+ if (payload.method !== void 0 && payload.method !== "virtual" && payload.method !== "collect") {
416
+ throw new ValidationError("method must be virtual or collect");
417
+ }
331
418
  const signers = extractSignerRefs(payload);
332
- if (signers.length === 0 && !options.allowEmptySigners) {
419
+ if (signers.length === 0 && (!options.allowEmptySigners || (payload.method ?? "virtual") !== "collect")) {
333
420
  throw new ValidationError("At least one signer is required", {
334
421
  signers: payload.signers ?? payload.signer_ids ?? payload.signerIds
335
422
  });
336
423
  }
424
+ if (payload.method === "collect" && !Array.isArray(payload.entries)) {
425
+ throw new ValidationError("entries are required for collect assignments");
426
+ }
427
+ const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
428
+ if (!options.skipDigitalCertificateStepValidation) {
429
+ validateSigningSteps(normalisedSigners);
430
+ }
337
431
  return cleanParams({
338
432
  method: payload.method ?? "virtual",
339
- signers: signers.map((ref) => normaliseSignerRef(ref, options)),
433
+ signers: normalisedSigners,
340
434
  message: payload.message,
341
435
  expires_at: payload.expires_at === void 0 ? void 0 : requireIso8601(payload.expires_at, "expires_at"),
342
436
  copy_receivers: payload.copy_receivers,
@@ -364,6 +458,7 @@ function normaliseSignerRef(ref, options) {
364
458
  if (ref && typeof ref === "object") {
365
459
  const input = ref;
366
460
  const id = input.id ?? input.signer_id;
461
+ validateSignerOptions(input);
367
462
  const normalised = cleanParams({
368
463
  id,
369
464
  verification_method: input.verification_method,
@@ -421,14 +516,16 @@ var AssignmentResource = class extends BaseResource {
421
516
  `/documents/${docId}/assignments/estimate-cost`,
422
517
  buildAssignmentPayload(payload, {
423
518
  allowSignersWithoutId: true,
424
- allowEmptySigners: true
519
+ allowEmptySigners: true,
520
+ skipDigitalCertificateStepValidation: true
425
521
  })
426
522
  )
427
523
  );
428
524
  }
429
525
  /**
430
526
  * Update the expiration date of an existing assignment.
431
- * Pass `null` to remove the expiration entirely.
527
+ * The published API accepts an ISO 8601 timestamp. Deployments that support
528
+ * clearing an expiration also accept `null`.
432
529
  */
433
530
  async resetExpiration(documentId, assignmentId, expiresAt) {
434
531
  const docId = this.requireId(documentId, "Document ID");
@@ -763,24 +860,24 @@ var DocumentResource = class extends BaseResource {
763
860
  );
764
861
  }
765
862
  /**
766
- * Replace the document's tag set with `tags` (an array of tag names).
767
- * Unknown names are auto-created; an empty array detaches all tags.
863
+ * Replace the document's tag set with tag IDs. An empty array detaches all tags.
864
+ * Values are forwarded unchanged for compatibility with deployments that also accept names.
768
865
  */
769
866
  async replaceTags(documentId, tags, accountId) {
770
867
  const accId = this.accountId(accountId);
771
868
  const docId = this.requireId(documentId, "Document ID");
772
- if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag names");
869
+ if (!Array.isArray(tags)) throw new ValidationError("tags must be an array of tag IDs");
773
870
  return this.call(
774
871
  "Failed to replace document tags",
775
872
  () => this.http.put(`/accounts/${accId}/documents/${docId}/tags`, { tags })
776
873
  );
777
874
  }
778
- /** Attach additional tags (by name) without removing existing ones. Idempotent. */
875
+ /** Attach additional tag IDs without removing existing ones. */
779
876
  async addTags(documentId, tags, accountId) {
780
877
  const accId = this.accountId(accountId);
781
878
  const docId = this.requireId(documentId, "Document ID");
782
879
  if (!Array.isArray(tags) || tags.length === 0) {
783
- throw new ValidationError("tags must be a non-empty array of tag names");
880
+ throw new ValidationError("tags must be a non-empty array of tag IDs");
784
881
  }
785
882
  return this.call(
786
883
  "Failed to add document tags",
@@ -810,7 +907,14 @@ var DocumentResource = class extends BaseResource {
810
907
  async createFromTemplate(templateId, signers, options = {}, accountId) {
811
908
  const tmplId = this.requireId(templateId, "Template ID");
812
909
  const accId = this.accountId(accountId);
910
+ validateTemplateSigners(signers, { requireId: true, singleNotification: true });
813
911
  if (options.expires_at !== void 0) requireIso8601(options.expires_at, "expires_at");
912
+ if (options.editor_fields !== void 0 && (!Array.isArray(options.editor_fields) || options.editor_fields.some((field) => !field?.field_id || typeof field.value !== "string"))) {
913
+ throw new ValidationError("editor_fields must contain field_id and value");
914
+ }
915
+ if (options.tags !== void 0 && (!Array.isArray(options.tags) || options.tags.some((tag) => typeof tag !== "string" || !tag))) {
916
+ throw new ValidationError("tags must contain non-empty tag names");
917
+ }
814
918
  const body = { ...options, signers };
815
919
  this.logger.info("Creating document from template", { templateId: tmplId, accountId: accId });
816
920
  return this.call(
@@ -822,6 +926,7 @@ var DocumentResource = class extends BaseResource {
822
926
  async estimateCostFromTemplate(templateId, signers, accountId) {
823
927
  const tmplId = this.requireId(templateId, "Template ID");
824
928
  const accId = this.accountId(accountId);
929
+ validateTemplateSigners(signers, { requireId: false, singleNotification: false });
825
930
  return this.call(
826
931
  "Failed to estimate cost from template",
827
932
  () => this.http.post(`/accounts/${accId}/templates/${tmplId}/documents/estimate-cost`, { signers })
@@ -868,7 +973,7 @@ var DocumentResource = class extends BaseResource {
868
973
  async sendToken(documentId, recipient, channel = "email") {
869
974
  const id = this.requireId(documentId, "Document ID");
870
975
  if (typeof recipient === "object") {
871
- if (!recipient?.email) throw new ValidationError("email is required");
976
+ requireEmail(recipient?.email);
872
977
  return this.call(
873
978
  "Failed to send signing token",
874
979
  () => this.http.put(
@@ -879,6 +984,10 @@ var DocumentResource = class extends BaseResource {
879
984
  );
880
985
  }
881
986
  if (!recipient) throw new ValidationError("recipient is required");
987
+ if (channel !== "email" && channel !== "whatsapp") {
988
+ throw new ValidationError("channel must be email or whatsapp");
989
+ }
990
+ if (channel === "email") requireEmail(recipient);
882
991
  return this.call(
883
992
  "Failed to send signing token",
884
993
  () => this.http.put(
@@ -909,6 +1018,31 @@ var DocumentResource = class extends BaseResource {
909
1018
  return { signed, total, pending, percentage };
910
1019
  }
911
1020
  };
1021
+ function validateTemplateSigners(signers, options) {
1022
+ if (!Array.isArray(signers)) throw new ValidationError("signers must be an array");
1023
+ for (const value of signers) {
1024
+ if (!value || typeof value !== "object") {
1025
+ throw new ValidationError("each template signer must be an object");
1026
+ }
1027
+ const signer = value;
1028
+ if (typeof signer.role_id !== "string" || !signer.role_id) {
1029
+ throw new ValidationError("each template signer requires role_id");
1030
+ }
1031
+ if ((options.requireId || signer.id !== void 0) && (typeof signer.id !== "string" || !signer.id)) {
1032
+ throw new ValidationError("each template signer requires a valid id");
1033
+ }
1034
+ validateSignerOptions(signer);
1035
+ if (options.requireId && signer.step !== void 0 && Number(signer.step) < 1) {
1036
+ throw new ValidationError("template signer step must be a positive integer");
1037
+ }
1038
+ if (options.singleNotification && Array.isArray(signer.notification_methods) && signer.notification_methods.length > 1) {
1039
+ throw new ValidationError("template signers accept at most one notification method");
1040
+ }
1041
+ }
1042
+ if (options.requireId) {
1043
+ validateSigningSteps(signers);
1044
+ }
1045
+ }
912
1046
  async function loadSource(source) {
913
1047
  if ("buffer" in source) {
914
1048
  if (!source.fileName) {
@@ -1020,6 +1154,7 @@ var FieldsResource = class extends BaseResource {
1020
1154
  async validate(fieldId, value, options = {}) {
1021
1155
  const id = this.accountId(options.accountId);
1022
1156
  const fid = this.requireId(fieldId, "Field ID");
1157
+ if (value === void 0) throw new ValidationError("value is required");
1023
1158
  return this.call(
1024
1159
  "Failed to validate field value",
1025
1160
  () => this.http.post(
@@ -1034,6 +1169,11 @@ var FieldsResource = class extends BaseResource {
1034
1169
  if (!Array.isArray(entries) || entries.length === 0) {
1035
1170
  throw new ValidationError("entries must be a non-empty array");
1036
1171
  }
1172
+ if (entries.some(
1173
+ (entry) => !entry || typeof entry !== "object" || typeof entry.field_id !== "string" || !entry.field_id || entry.value === void 0
1174
+ )) {
1175
+ throw new ValidationError("each entry must contain field_id and value");
1176
+ }
1037
1177
  const id = this.accountId(options.accountId);
1038
1178
  return this.call(
1039
1179
  "Failed to validate field values",
@@ -1053,6 +1193,174 @@ function validationConfig(signerAccessCode) {
1053
1193
  return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
1054
1194
  }
1055
1195
 
1196
+ // src/api/resources/oauth.ts
1197
+ var import_node_crypto = require("crypto");
1198
+ var OAuthResource = class extends BaseResource {
1199
+ /** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
1200
+ async metadata() {
1201
+ return this.call(
1202
+ "Failed to discover OAuth resource",
1203
+ () => this.http.get(
1204
+ "/.well-known/oauth-protected-resource",
1205
+ publicRequestConfig({
1206
+ baseURL: new URL(this.http.defaults.baseURL).origin
1207
+ })
1208
+ )
1209
+ );
1210
+ }
1211
+ /** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
1212
+ async discovery(issuer) {
1213
+ const url = httpsUrl(issuer, "issuer");
1214
+ if (url.search || url.pathname !== "/") {
1215
+ throw new ValidationError("issuer must be an HTTPS origin");
1216
+ }
1217
+ const metadata = await this.call(
1218
+ "Failed to discover OAuth authorization server",
1219
+ () => this.http.get(
1220
+ `${url.origin}/.well-known/oauth-authorization-server`,
1221
+ publicRequestConfig()
1222
+ )
1223
+ );
1224
+ if (metadata.issuer !== issuer) throw new ValidationError("OAuth issuer mismatch");
1225
+ httpsUrl(metadata.authorization_endpoint, "authorization_endpoint");
1226
+ return metadata;
1227
+ }
1228
+ /** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */
1229
+ async authorize(options) {
1230
+ required(options.clientId, "clientId");
1231
+ httpsUrl(options.redirectUri, "redirectUri");
1232
+ if (!Array.isArray(options.scopes) || options.scopes.length === 0 || options.scopes.some(
1233
+ (scope) => typeof scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)
1234
+ )) {
1235
+ throw new ValidationError("scopes must contain non-empty OAuth scope names");
1236
+ }
1237
+ const resource = await this.metadata();
1238
+ const issuer = resource.authorization_servers?.[0];
1239
+ if (!issuer) throw new ValidationError("OAuth metadata has no authorization server");
1240
+ httpsUrl(resource.resource, "resource");
1241
+ const server = await this.discovery(issuer);
1242
+ const codeVerifier = (0, import_node_crypto.randomBytes)(32).toString("base64url");
1243
+ const state = (0, import_node_crypto.randomBytes)(32).toString("base64url");
1244
+ const nonce = options.scopes.includes("openid") ? (0, import_node_crypto.randomBytes)(32).toString("base64url") : void 0;
1245
+ const url = new URL(server.authorization_endpoint);
1246
+ const params = {
1247
+ response_type: "code",
1248
+ client_id: options.clientId,
1249
+ redirect_uri: options.redirectUri,
1250
+ scope: options.scopes.join(" "),
1251
+ state,
1252
+ code_challenge: (0, import_node_crypto.createHash)("sha256").update(codeVerifier).digest("base64url"),
1253
+ code_challenge_method: "S256",
1254
+ resource: resource.resource
1255
+ };
1256
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
1257
+ if (nonce) url.searchParams.set("nonce", nonce);
1258
+ return {
1259
+ authorization_url: url.toString(),
1260
+ code_verifier: codeVerifier,
1261
+ state,
1262
+ issuer,
1263
+ client_id: options.clientId,
1264
+ redirect_uri: options.redirectUri,
1265
+ resource: resource.resource,
1266
+ ...nonce ? { nonce } : {}
1267
+ };
1268
+ }
1269
+ /** Validate callback URI, state, and issuer before exchanging its one-time code. */
1270
+ async exchangeCode(callbackUrl, request, clientSecret) {
1271
+ const callback = httpsUrl(callbackUrl, "callbackUrl");
1272
+ const redirect = httpsUrl(request.redirect_uri, "redirect_uri");
1273
+ if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname || [...new Set(redirect.searchParams.keys())].some((key) => {
1274
+ const expected2 = redirect.searchParams.getAll(key);
1275
+ const actual2 = callback.searchParams.getAll(key);
1276
+ return expected2.length !== actual2.length || expected2.some((value, i) => value !== actual2[i]);
1277
+ })) {
1278
+ throw new ValidationError("OAuth callback does not match the registered redirect URI");
1279
+ }
1280
+ for (const key of ["state", "iss", "code", "error"]) {
1281
+ if (callback.searchParams.getAll(key).length > 1) {
1282
+ throw new ValidationError(`Duplicate OAuth callback parameter: ${key}`);
1283
+ }
1284
+ }
1285
+ const actual = Buffer.from(callback.searchParams.get("state") ?? "");
1286
+ const expected = Buffer.from(required(request.state, "state"));
1287
+ if (actual.length !== expected.length || !(0, import_node_crypto.timingSafeEqual)(actual, expected)) {
1288
+ throw new ValidationError("OAuth state mismatch");
1289
+ }
1290
+ if (callback.searchParams.get("iss") !== request.issuer) {
1291
+ throw new ValidationError("OAuth issuer mismatch");
1292
+ }
1293
+ if (callback.searchParams.has("error")) {
1294
+ throw new ValidationError("OAuth authorization was declined or failed");
1295
+ }
1296
+ return this.token({
1297
+ grant_type: "authorization_code",
1298
+ code: required(callback.searchParams.get("code"), "code"),
1299
+ client_id: request.client_id,
1300
+ client_secret: clientSecret,
1301
+ redirect_uri: request.redirect_uri,
1302
+ code_verifier: request.code_verifier,
1303
+ resource: request.resource
1304
+ });
1305
+ }
1306
+ /** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
1307
+ async token(payload) {
1308
+ required(payload.client_id, "client_id");
1309
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1310
+ if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
1311
+ if (payload.grant_type === "authorization_code") {
1312
+ required(payload.code, "code");
1313
+ httpsUrl(payload.redirect_uri, "redirect_uri");
1314
+ if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
1315
+ throw new ValidationError(
1316
+ "code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
1317
+ );
1318
+ }
1319
+ } else if (payload.grant_type === "refresh_token") {
1320
+ required(payload.refresh_token, "refresh_token");
1321
+ } else {
1322
+ throw new ValidationError("grant_type must be authorization_code or refresh_token");
1323
+ }
1324
+ return this.call(
1325
+ "OAuth token request failed",
1326
+ () => this.http.post("/oauth/token", payload, publicRequestConfig())
1327
+ );
1328
+ }
1329
+ /** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
1330
+ async revoke(payload) {
1331
+ required(payload.client_id, "client_id");
1332
+ required(payload.token, "token");
1333
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
1334
+ if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
1335
+ throw new ValidationError("token_type_hint must be access_token or refresh_token");
1336
+ }
1337
+ await this.call(
1338
+ "OAuth revocation failed",
1339
+ () => this.http.post("/oauth/revoke", payload, publicRequestConfig())
1340
+ );
1341
+ }
1342
+ /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
1343
+ async userinfo() {
1344
+ return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
1345
+ }
1346
+ };
1347
+ function required(value, name) {
1348
+ if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
1349
+ return value;
1350
+ }
1351
+ function httpsUrl(value, name) {
1352
+ let url;
1353
+ try {
1354
+ url = new URL(value);
1355
+ } catch {
1356
+ throw new ValidationError(`${name} must be an absolute HTTPS URL`);
1357
+ }
1358
+ if (url.protocol !== "https:" || url.username || url.password || url.hash) {
1359
+ throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
1360
+ }
1361
+ return url;
1362
+ }
1363
+
1056
1364
  // src/api/resources/signer-documents.ts
1057
1365
  var SignerDocumentsResource = class extends BaseResource {
1058
1366
  /** `GET /signers/{signer_id}/document?signer-access-code=…` */
@@ -1085,20 +1393,28 @@ var SignerDocumentsResource = class extends BaseResource {
1085
1393
  () => this.http.get(`/signers/${sid}/documents/search`, signerAccessConfig(code, { search }))
1086
1394
  );
1087
1395
  }
1088
- /** `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}?signer-access-code=…` */
1396
+ /**
1397
+ * Public `GET /signers/{signer_id}/documents/{document_id}/download/{artifact}`.
1398
+ * When an access code is supplied, the SDK first verifies that it belongs to
1399
+ * the requested signer for callers that want that additional check.
1400
+ */
1089
1401
  async download(signerId, documentId, artifactName, signerAccessCode) {
1090
1402
  const sid = this.requireId(signerId, "Signer ID");
1091
1403
  const did = this.requireId(documentId, "Document ID");
1092
1404
  const artifact = requireDocumentArtifactName(artifactName);
1093
- const code = this.requireId(signerAccessCode, "signer-access-code");
1094
- const signer = await this.self(code);
1095
- if (signer.id !== sid) {
1096
- throw new ValidationError("Signer access code does not match the signer ID");
1405
+ let config = publicRequestConfig();
1406
+ if (signerAccessCode !== void 0) {
1407
+ const code = this.requireId(signerAccessCode, "signer-access-code");
1408
+ const signer = await this.self(code);
1409
+ if (signer.id !== sid) {
1410
+ throw new ValidationError("Signer access code does not match the signer ID");
1411
+ }
1412
+ config = signerAccessConfig(code);
1097
1413
  }
1098
1414
  return this.callBinary(
1099
1415
  "Failed to download signer document",
1100
1416
  () => this.http.get(`/signers/${sid}/documents/${did}/download/${artifact}`, {
1101
- ...signerAccessConfig(code),
1417
+ ...config,
1102
1418
  responseType: "arraybuffer"
1103
1419
  })
1104
1420
  );
@@ -1123,7 +1439,7 @@ var SignerDocumentsResource = class extends BaseResource {
1123
1439
  if (!Array.isArray(documentIds) || documentIds.length === 0) {
1124
1440
  throw new ValidationError("documentIds must be a non-empty array");
1125
1441
  }
1126
- if (!declineReason) throw new ValidationError("declineReason is required");
1442
+ validateDeclineReason(declineReason);
1127
1443
  const code = this.requireId(signerAccessCode, "signer-access-code");
1128
1444
  return this.call(
1129
1445
  "Failed to decline multiple documents",
@@ -1253,7 +1569,7 @@ var SignerDocumentsResource = class extends BaseResource {
1253
1569
  const did = this.requireId(documentId, "Document ID");
1254
1570
  const aid = this.requireId(assignmentId, "Assignment ID");
1255
1571
  const code = this.requireId(signerAccessCode, "signer-access-code");
1256
- if (!declineReason) throw new ValidationError("declineReason is required");
1572
+ validateDeclineReason(declineReason);
1257
1573
  return this.call(
1258
1574
  "Failed to decline assignment",
1259
1575
  () => this.http.put(
@@ -1264,17 +1580,19 @@ var SignerDocumentsResource = class extends BaseResource {
1264
1580
  );
1265
1581
  }
1266
1582
  };
1583
+ function validateDeclineReason(value) {
1584
+ if (typeof value !== "string" || !value.trim()) {
1585
+ throw new ValidationError("declineReason is required");
1586
+ }
1587
+ if ([...value].length > 2e3) {
1588
+ throw new ValidationError("declineReason must contain at most 2000 characters");
1589
+ }
1590
+ }
1267
1591
 
1268
1592
  // src/api/resources/signers.ts
1269
- var EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
1270
1593
  function validateCreateSignerPayload(payload) {
1271
1594
  if (!payload.full_name?.trim()) throw new ValidationError("Signer full name is required");
1272
- if (payload.email) assertEmail(payload.email);
1273
- }
1274
- function assertEmail(email) {
1275
- if (!email || !EMAIL_RE.test(email)) {
1276
- throw new ValidationError("Invalid email address", { email });
1277
- }
1595
+ if (payload.email !== void 0) requireEmail(payload.email);
1278
1596
  }
1279
1597
  var SignerResource = class extends BaseResource {
1280
1598
  /**
@@ -1337,6 +1655,10 @@ var SignerResource = class extends BaseResource {
1337
1655
  async update(signerId, payload, accountId) {
1338
1656
  const id = this.accountId(accountId);
1339
1657
  const sid = this.requireId(signerId, "Signer ID");
1658
+ if (payload.full_name !== void 0 && !payload.full_name.trim()) {
1659
+ throw new ValidationError("Signer full name cannot be blank");
1660
+ }
1661
+ if (payload.email !== void 0) requireEmail(payload.email);
1340
1662
  return this.call(
1341
1663
  "Failed to update signer",
1342
1664
  () => this.http.put(`/accounts/${id}/signers/${sid}`, normaliseSignerPayload(payload, true))
@@ -1353,11 +1675,15 @@ var SignerResource = class extends BaseResource {
1353
1675
  }
1354
1676
  /** Find a signer by email via the API's `search` parameter. Returns `null` if none match. */
1355
1677
  async findByEmail(email, accountId) {
1356
- assertEmail(email);
1678
+ requireEmail(email);
1357
1679
  try {
1358
- const { data } = await this.list({ search: email, per_page: 100 }, accountId);
1359
1680
  const lower = email.toLowerCase();
1360
- return data.find((s) => (s.email ?? "").toLowerCase() === lower) ?? null;
1681
+ for (let page = 1; ; page++) {
1682
+ const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
1683
+ const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
1684
+ if (match) return match;
1685
+ if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
1686
+ }
1361
1687
  } catch (err) {
1362
1688
  if (err instanceof ApiError && err.statusCode === 404) {
1363
1689
  return null;
@@ -1551,7 +1877,22 @@ var WebhookResource = class extends BaseResource {
1551
1877
  /** Register (or replace) the webhook subscription for the workspace. */
1552
1878
  async register(payload, accountId) {
1553
1879
  if (!payload.url) throw new ValidationError("Webhook URL is required");
1554
- if (!payload.email) throw new ValidationError("Webhook email is required");
1880
+ let webhookUrl;
1881
+ try {
1882
+ webhookUrl = new URL(payload.url);
1883
+ } catch {
1884
+ throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1885
+ }
1886
+ if (webhookUrl.protocol !== "http:" && webhookUrl.protocol !== "https:") {
1887
+ throw new ValidationError("Webhook URL must be a valid HTTP(S) URL");
1888
+ }
1889
+ requireEmail(payload.email);
1890
+ if (payload.events !== void 0 && (!Array.isArray(payload.events) || payload.events.some((event) => typeof event !== "string" || !event))) {
1891
+ throw new ValidationError("Webhook events must contain non-empty strings");
1892
+ }
1893
+ if (payload.is_active !== void 0 && typeof payload.is_active !== "boolean") {
1894
+ throw new ValidationError("Webhook is_active must be a boolean");
1895
+ }
1555
1896
  const id = this.accountId(accountId);
1556
1897
  const body = {
1557
1898
  url: payload.url,
@@ -1712,7 +2053,7 @@ function validateNotificationSender(value) {
1712
2053
  }
1713
2054
 
1714
2055
  // src/api/support/webhook-verifier.ts
1715
- var import_node_crypto = require("crypto");
2056
+ var import_node_crypto2 = require("crypto");
1716
2057
  var WebhookVerifier = class {
1717
2058
  constructor(webhookSecret, options = {}) {
1718
2059
  this.webhookSecret = webhookSecret;
@@ -1725,14 +2066,14 @@ var WebhookVerifier = class {
1725
2066
  /** Returns `true` if `signature` is a valid HMAC of `payload` under the configured scheme. */
1726
2067
  verify(payload, signature) {
1727
2068
  if (!this.webhookSecret || !signature) return false;
1728
- const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
1729
- const expected = (0, import_node_crypto.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
1730
- const provided = signature.trim();
1731
- const a = Buffer.from(expected, "utf8");
1732
- const b = Buffer.from(provided, "utf8");
1733
- if (a.length !== b.length) return false;
1734
2069
  try {
1735
- return (0, import_node_crypto.timingSafeEqual)(a, b);
2070
+ const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
2071
+ const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
2072
+ const provided = signature.trim();
2073
+ const a = Buffer.from(expected, "utf8");
2074
+ const b = Buffer.from(provided, "utf8");
2075
+ if (a.length !== b.length) return false;
2076
+ return (0, import_node_crypto2.timingSafeEqual)(a, b);
1736
2077
  } catch {
1737
2078
  return false;
1738
2079
  }
@@ -1751,7 +2092,8 @@ var WebhookVerifier = class {
1751
2092
  getEventType(event) {
1752
2093
  if (!event || typeof event !== "object") return null;
1753
2094
  const e = event;
1754
- return e.event ?? e.type ?? null;
2095
+ if (typeof e.event === "string") return e.event;
2096
+ return typeof e.type === "string" ? e.type : null;
1755
2097
  }
1756
2098
  /**
1757
2099
  * Extract the event data from an event envelope.
@@ -1773,6 +2115,9 @@ var WebhookVerifier = class {
1773
2115
 
1774
2116
  // src/api/client.ts
1775
2117
  var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
2118
+ function isLoopbackHost(hostname) {
2119
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
2120
+ }
1776
2121
  var AssinafyClient = class _AssinafyClient {
1777
2122
  axiosInstance;
1778
2123
  defaultAccountId;
@@ -1786,6 +2131,7 @@ var AssinafyClient = class _AssinafyClient {
1786
2131
  templates;
1787
2132
  tags;
1788
2133
  auth;
2134
+ oauth;
1789
2135
  fields;
1790
2136
  users;
1791
2137
  signerDocuments;
@@ -1793,9 +2139,12 @@ var AssinafyClient = class _AssinafyClient {
1793
2139
  constructor(options) {
1794
2140
  if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
1795
2141
  throw new ValidationError(
1796
- "An API key (options.apiKey) or legacy access token (options.token) is required."
2142
+ "An API key (options.apiKey) or access token (options.token) is required."
1797
2143
  );
1798
2144
  }
2145
+ if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
2146
+ throw new ValidationError("timeout must be a finite positive number");
2147
+ }
1799
2148
  this.defaultAccountId = options.accountId;
1800
2149
  this.logger = options.logger ?? createNoopLogger();
1801
2150
  this.webhookSecret = options.webhookSecret;
@@ -1806,13 +2155,17 @@ var AssinafyClient = class _AssinafyClient {
1806
2155
  } catch {
1807
2156
  throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
1808
2157
  }
1809
- if (!["https:", "http:"].includes(parsedBaseUrl.protocol)) {
1810
- throw new ValidationError("baseUrl must use HTTPS");
1811
- }
1812
- if (parsedBaseUrl.protocol !== "https:" && !options.allowInsecureHttp) {
1813
- throw new ValidationError(
1814
- "baseUrl must use HTTPS; set allowInsecureHttp only for isolated local development"
1815
- );
2158
+ if (parsedBaseUrl.protocol !== "https:") {
2159
+ if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
2160
+ throw new ValidationError(
2161
+ "baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
2162
+ );
2163
+ }
2164
+ if (!isLoopbackHost(parsedBaseUrl.hostname)) {
2165
+ throw new ValidationError(
2166
+ "allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
2167
+ );
2168
+ }
1816
2169
  }
1817
2170
  if (parsedBaseUrl.username || parsedBaseUrl.password) {
1818
2171
  throw new ValidationError("baseUrl must not contain embedded credentials");
@@ -1848,6 +2201,7 @@ var AssinafyClient = class _AssinafyClient {
1848
2201
  this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
1849
2202
  this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
1850
2203
  this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
2204
+ this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
1851
2205
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
1852
2206
  this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
1853
2207
  this.signerDocuments = new SignerDocumentsResource(
@@ -1883,13 +2237,22 @@ var AssinafyClient = class _AssinafyClient {
1883
2237
  /**
1884
2238
  * High-level helper that uploads a PDF, ensures it's processed, creates any
1885
2239
  * missing signers, and kicks off a virtual signature assignment.
2240
+ *
2241
+ * Once the upload succeeds the workflow owns real workspace resources, so any
2242
+ * later failure is rethrown as a {@link PartialWorkflowError} carrying the
2243
+ * document and signer IDs that already exist. Catch it to resume or clean up;
2244
+ * nothing is deleted automatically.
1886
2245
  */
1887
2246
  async uploadAndRequestSignatures(options) {
1888
- if (!options.signers || options.signers.length === 0) {
2247
+ if (!Array.isArray(options.signers) || options.signers.length === 0) {
1889
2248
  throw new ValidationError("At least one signer is required");
1890
2249
  }
1891
2250
  if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
1892
2251
  const preparedSigners = options.signers.map((signer) => {
2252
+ if (!signer || typeof signer !== "object") {
2253
+ throw new ValidationError("Each signer must be an object");
2254
+ }
2255
+ validateSignerOptions(signer);
1893
2256
  const payload = { full_name: signer.name };
1894
2257
  if (signer.email !== void 0) payload.email = signer.email;
1895
2258
  const phone = signer.whatsapp_phone_number ?? signer.phone;
@@ -1899,6 +2262,7 @@ var AssinafyClient = class _AssinafyClient {
1899
2262
  validateCreateSignerPayload(payload);
1900
2263
  return { signer, payload, phone };
1901
2264
  });
2265
+ validateSigningSteps(options.signers);
1902
2266
  this.logger.info("Starting upload + signature workflow", {
1903
2267
  signerCount: options.signers.length
1904
2268
  });
@@ -1906,33 +2270,46 @@ var AssinafyClient = class _AssinafyClient {
1906
2270
  if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
1907
2271
  if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
1908
2272
  const document = await this.documents.upload(options.source, uploadOpts);
1909
- if (options.waitForReady !== false) {
1910
- await this.documents.waitUntilReady(document.id);
1911
- }
1912
2273
  const signerIds = [];
1913
- const assignmentSigners = [];
1914
- for (const { signer, payload, phone } of preparedSigners) {
1915
- const created = await this.signers.create(payload, options.accountId);
1916
- signerIds.push(created.id);
1917
- const useWhatsapp = phone !== void 0 && signer.email === void 0;
1918
- assignmentSigners.push({
1919
- id: created.id,
1920
- verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
1921
- notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
1922
- step: signer.step
2274
+ try {
2275
+ if (options.waitForReady !== false) {
2276
+ await this.documents.waitUntilReady(document.id);
2277
+ }
2278
+ const assignmentSigners = [];
2279
+ for (const { signer, payload, phone } of preparedSigners) {
2280
+ const created = await this.signers.create(payload, options.accountId);
2281
+ signerIds.push(created.id);
2282
+ const useWhatsapp = phone !== void 0 && signer.email === void 0;
2283
+ assignmentSigners.push({
2284
+ id: created.id,
2285
+ verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
2286
+ notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
2287
+ step: signer.step
2288
+ });
2289
+ }
2290
+ const assignmentPayload = {
2291
+ method: "virtual",
2292
+ signers: assignmentSigners
2293
+ };
2294
+ if (options.message !== void 0) assignmentPayload.message = options.message;
2295
+ if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
2296
+ if (options.copyReceivers !== void 0)
2297
+ assignmentPayload.copy_receivers = options.copyReceivers;
2298
+ const assignment = await this.assignments.create(document.id, assignmentPayload);
2299
+ this.logger.info("Upload + signature workflow completed", { documentId: document.id });
2300
+ return { document, assignment, signer_ids: signerIds };
2301
+ } catch (err) {
2302
+ this.logger.error("Upload + signature workflow failed after creating resources", {
2303
+ documentId: document.id,
2304
+ signerIds
1923
2305
  });
2306
+ const reason = err instanceof Error ? err.message : String(err);
2307
+ throw new PartialWorkflowError(
2308
+ `${reason} (document ${document.id} exists; ${signerIds.length} signer(s) created or reused)`,
2309
+ { documentId: document.id, signerIds },
2310
+ { cause: err }
2311
+ );
1924
2312
  }
1925
- const assignmentPayload = {
1926
- method: "virtual",
1927
- signers: assignmentSigners
1928
- };
1929
- if (options.message !== void 0) assignmentPayload.message = options.message;
1930
- if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
1931
- if (options.copyReceivers !== void 0)
1932
- assignmentPayload.copy_receivers = options.copyReceivers;
1933
- const assignment = await this.assignments.create(document.id, assignmentPayload);
1934
- this.logger.info("Upload + signature workflow completed", { documentId: document.id });
1935
- return { document, assignment, signer_ids: signerIds };
1936
2313
  }
1937
2314
  /** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
1938
2315
  getAxiosInstance() {
@@ -1950,6 +2327,8 @@ var AssinafyClient = class _AssinafyClient {
1950
2327
  FieldsResource,
1951
2328
  NOTIFICATION_PREFERENCE_CODES,
1952
2329
  NetworkError,
2330
+ OAuthResource,
2331
+ PartialWorkflowError,
1953
2332
  SignerDocumentsResource,
1954
2333
  SignerResource,
1955
2334
  TagResource,