@assinafy/cli 2.3.0 → 2.4.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.
package/README.en.md CHANGED
@@ -31,6 +31,7 @@ This document reads top to bottom: install, authenticate, send your first signat
31
31
  ## Requirements
32
32
 
33
33
  - Node.js `>=22.12.0`. Node.js 24 LTS is recommended and is what CI publishes with; CI also tests 22 and 26.
34
+ - HTTPS with TLS 1.2 or higher to reach the Assinafy API; supported Node.js versions use that minimum by default.
34
35
  - An Assinafy account and an API key (see [Authentication](#authentication)).
35
36
  - Linux, macOS, or Windows. Release archives ship for `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `windows-x64`, and `windows-arm64`.
36
37
 
@@ -110,7 +111,7 @@ The CLI includes the official application's public client ID and uses PKCE S256
110
111
  https://integrations.assinafy.com.br/assinafy-cli/oauth-callback
111
112
  ```
112
113
 
113
- The CLI requests all nine scopes by default: `account:read documents:read documents:write templates:read templates:write openid profile email offline_access`, including template read/write access. The application registration must permit all nine; existing connections need fresh consent to gain additional permissions. An explicit `--scope` requests a smaller set.
114
+ The CLI requests all ten published scopes by default: `account:read documents:read documents:write templates:read templates:write webhooks:write openid profile email offline_access`, including template read/write access and `webhooks:write` for the webhook write commands. The application registration must permit all ten; existing connections need fresh consent to gain additional permissions. An explicit `--scope` requests a smaller set.
114
115
 
115
116
  No `ASSINAFY_OAUTH_CLIENT_ID` configuration is needed for the official application. For your own application or another environment, use `--client-id` or that variable; the flag takes precedence. Register the callback URI and scopes for the selected application. In a private directory outside the repository:
116
117
 
@@ -570,7 +571,7 @@ The [release runbook](./docs/releasing.md) covers tags, trusted publishing, and
570
571
 
571
572
  - The production OpenAPI publishes 93 operations and the SDK implements all of them. Sandbox deployments can lag individual routes — account/user statistics and user notification preferences may return route-level 404s there despite being documented in production.
572
573
  - The SDK keeps two platform-compatible template routes (`GET /accounts/{id}/templates/{id}` and its page download) that are absent from the published OpenAPI paths.
573
- - The API's digital-certificate prose mentions certificate start/complete routes that are not defined as OpenAPI paths. The SDK does not invent contracts for them.
574
+ - Certificate start/complete are deployed production extensions of the public signing frontend, exposed as `signerDocuments.startCertificate(accessCode)` and `signerDocuments.completeCertificate(accessCode, token)`. Start posts `{ "signer-access-code": code }` and returns `{ token }`; complete posts `{ "signer-access-code": code, token }` and returns `{ signerName }`. Both also carry the access code in the query string and strip owner credentials. They supplement, but are not part of, the 93 OpenAPI operations.
574
575
  - Both the published and legacy `send-token` payloads are supported for compatible deployments.
575
576
  - `WebhookVerifier` is **experimental**. Assinafy does not publish the signature header, algorithm, encoding, timestamp, or replay-protection scheme, so it is not a production trust boundary until the exact scheme is published or independently verified against real deliveries.
576
577
 
package/README.md CHANGED
@@ -23,7 +23,7 @@ Este guia segue o fluxo de uma integração: instalação, autenticação, envio
23
23
 
24
24
  ## Requisitos e instalação
25
25
 
26
- Use [Node.js 24 LTS](https://nodejs.org/en/about/previous-releases) atualizado. O mínimo suportado é `22.12.0`; a CI também verifica as linhas 22 e 26. A CLI funciona em Linux, macOS e Windows, em x64 e ARM64. Os arquivos de release incluem o executável JavaScript e exigem Node.js instalado.
26
+ Use [Node.js 24 LTS](https://nodejs.org/en/about/previous-releases) atualizado. O mínimo suportado é `22.12.0`; a CI também verifica as linhas 22 e 26. A CLI funciona em Linux, macOS e Windows, em x64 e ARM64. Os arquivos de release incluem o executável JavaScript e exigem Node.js instalado. A API Assinafy exige HTTPS com TLS 1.2 ou superior, o mínimo padrão das versões suportadas do Node.js.
27
27
 
28
28
  Instale uma versão publicada e fixe essa versão nas automações:
29
29
 
@@ -94,7 +94,7 @@ A CLI já inclui o ID público da aplicação oficial e usa PKCE S256, sem segre
94
94
  https://integrations.assinafy.com.br/assinafy-cli/oauth-callback
95
95
  ```
96
96
 
97
- A CLI solicita os nove escopos `account:read documents:read documents:write templates:read templates:write openid profile email offline_access` por padrão, incluindo leitura e alteração de templates. O cadastro da aplicação deve permitir os nove; uma conexão existente precisa de novo consentimento para obter permissões adicionais. `--scope` permite solicitar um conjunto menor explicitamente.
97
+ A CLI solicita por padrão os dez escopos publicados: `account:read documents:read documents:write templates:read templates:write webhooks:write openid profile email offline_access`, incluindo leitura e alteração de templates e `webhooks:write` para os comandos que alteram webhooks. O cadastro da aplicação deve permitir os dez; uma conexão existente precisa de novo consentimento para obter permissões adicionais. `--scope` permite solicitar um conjunto menor explicitamente.
98
98
 
99
99
  Não é necessário configurar `ASSINAFY_OAUTH_CLIENT_ID` para usar a aplicação oficial. Para uma aplicação própria ou outro ambiente, use `--client-id` ou essa variável; a flag tem precedência. A aplicação escolhida precisa ter a URI de retorno e os escopos cadastrados. Em um diretório privado fora do repositório:
100
100
 
package/dist/api.cjs CHANGED
@@ -51,7 +51,9 @@ __export(api_exports, {
51
51
  WebhookVerifier: () => WebhookVerifier,
52
52
  WorkspaceResource: () => WorkspaceResource,
53
53
  buildAssignmentPayload: () => buildAssignmentPayload,
54
- normalizeBaseUrl: () => normalizeBaseUrl
54
+ normalizeBaseUrl: () => normalizeBaseUrl,
55
+ requireDocumentArtifactName: () => requireDocumentArtifactName,
56
+ requireSignerImageType: () => requireSignerImageType
55
57
  });
56
58
  module.exports = __toCommonJS(api_exports);
57
59
 
@@ -188,6 +190,19 @@ function cleanParams(params) {
188
190
  }
189
191
  return out;
190
192
  }
193
+ function stripEmpty(body) {
194
+ const out = {};
195
+ for (const [key, value] of Object.entries(body)) {
196
+ if (value !== void 0 && value !== null) {
197
+ out[key] = value;
198
+ }
199
+ }
200
+ return out;
201
+ }
202
+ function appendFilePart(form, data, contentType, fileName) {
203
+ const view = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
204
+ form.append("file", new Blob([view], { type: contentType }), fileName);
205
+ }
191
206
  function publicRequestConfig(config = {}) {
192
207
  return {
193
208
  ...config,
@@ -428,7 +443,7 @@ function buildAssignmentPayload(payload, options = {}) {
428
443
  if (!options.skipDigitalCertificateStepValidation) {
429
444
  validateSigningSteps(normalisedSigners);
430
445
  }
431
- return cleanParams({
446
+ return stripEmpty({
432
447
  method: payload.method ?? "virtual",
433
448
  signers: normalisedSigners,
434
449
  message: payload.message,
@@ -459,7 +474,7 @@ function normaliseSignerRef(ref, options) {
459
474
  const input = ref;
460
475
  const id = input.id ?? input.signer_id;
461
476
  validateSignerOptions(input);
462
- const normalised = cleanParams({
477
+ const normalised = stripEmpty({
463
478
  id,
464
479
  verification_method: input.verification_method,
465
480
  notification_methods: input.notification_methods,
@@ -658,6 +673,7 @@ var AuthenticationResource = class extends BaseResource {
658
673
  var import_node_fs = require("fs");
659
674
  var import_node_path = __toESM(require("path"), 1);
660
675
  var MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
676
+ var DOCUMENT_SORTS = ["name", "-name", "updated_at", "-updated_at"];
661
677
  var READY_STATUSES = /* @__PURE__ */ new Set([
662
678
  "metadata_ready",
663
679
  "pending_signature",
@@ -705,7 +721,7 @@ var DocumentResource = class extends BaseResource {
705
721
  */
706
722
  async list(params = {}, accountId) {
707
723
  const id = this.accountId(accountId);
708
- requireSort(params.sort, ["name", "-name", "updated_at", "-updated_at"]);
724
+ requireSort(params.sort, DOCUMENT_SORTS);
709
725
  return this.callList(
710
726
  "Failed to list documents",
711
727
  () => this.http.get(`/accounts/${id}/documents`, {
@@ -723,7 +739,7 @@ var DocumentResource = class extends BaseResource {
723
739
  */
724
740
  async search(params = {}, accountId) {
725
741
  const id = this.accountId(accountId);
726
- requireSort(params.sort, ["name", "-name", "updated_at", "-updated_at"]);
742
+ requireSort(params.sort, DOCUMENT_SORTS);
727
743
  return this.callList(
728
744
  "Failed to search documents",
729
745
  () => this.http.get(`/accounts/${id}/documents/search`, {
@@ -1078,8 +1094,7 @@ function validateUpload(buffer, fileName) {
1078
1094
  }
1079
1095
  function buildUploadForm(buffer, fileName, name, metadata) {
1080
1096
  const form = new FormData();
1081
- const view = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1082
- form.append("file", new Blob([view], { type: "application/pdf" }), fileName);
1097
+ appendFilePart(form, buffer, "application/pdf", fileName);
1083
1098
  form.append("name", name);
1084
1099
  if (metadata) {
1085
1100
  form.append("metadata", JSON.stringify(metadata));
@@ -1194,18 +1209,26 @@ function validationConfig(signerAccessCode) {
1194
1209
 
1195
1210
  // src/api/resources/oauth.ts
1196
1211
  var import_node_crypto = require("crypto");
1212
+ function formRequestConfig() {
1213
+ return publicRequestConfig({
1214
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
1215
+ });
1216
+ }
1197
1217
  var OAuthResource = class extends BaseResource {
1198
1218
  /** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
1199
1219
  async metadata() {
1200
- return this.call(
1201
- "Failed to discover OAuth resource",
1202
- () => this.http.get(
1220
+ return this.call("Failed to discover OAuth resource", () => {
1221
+ const baseURL = this.http.defaults.baseURL;
1222
+ if (!baseURL) {
1223
+ throw new ValidationError("A base URL is required to discover OAuth metadata");
1224
+ }
1225
+ return this.http.get(
1203
1226
  "/.well-known/oauth-protected-resource",
1204
1227
  publicRequestConfig({
1205
- baseURL: new URL(this.http.defaults.baseURL).origin
1228
+ baseURL: new URL(baseURL).origin
1206
1229
  })
1207
- )
1208
- );
1230
+ );
1231
+ });
1209
1232
  }
1210
1233
  /** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
1211
1234
  async discovery(issuer) {
@@ -1306,7 +1329,10 @@ var OAuthResource = class extends BaseResource {
1306
1329
  resource: request.resource
1307
1330
  });
1308
1331
  }
1309
- /** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
1332
+ /**
1333
+ * `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body.
1334
+ * A refresh must return a new `refresh_token`; otherwise this throws `ValidationError`.
1335
+ */
1310
1336
  async token(payload) {
1311
1337
  required(payload.client_id, "client_id");
1312
1338
  if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
@@ -1324,10 +1350,18 @@ var OAuthResource = class extends BaseResource {
1324
1350
  } else {
1325
1351
  throw new ValidationError("grant_type must be authorization_code or refresh_token");
1326
1352
  }
1327
- return this.call(
1353
+ const tokens = await this.call(
1328
1354
  "OAuth token request failed",
1329
- () => this.http.post("/oauth/token", payload, publicRequestConfig())
1355
+ () => this.http.post("/oauth/token", payload, formRequestConfig())
1330
1356
  );
1357
+ const next = tokens?.refresh_token;
1358
+ if (payload.grant_type === "refresh_token" && (typeof next !== "string" || !next.trim() || next === payload.refresh_token)) {
1359
+ throw new ValidationError(
1360
+ "OAuth refresh response has no new refresh_token; the submitted refresh token may already be retired, so do not reuse it: reconnect instead",
1361
+ { field: "refresh_token" }
1362
+ );
1363
+ }
1364
+ return tokens;
1331
1365
  }
1332
1366
  /** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
1333
1367
  async revoke(payload) {
@@ -1339,7 +1373,7 @@ var OAuthResource = class extends BaseResource {
1339
1373
  }
1340
1374
  await this.call(
1341
1375
  "OAuth revocation failed",
1342
- () => this.http.post("/oauth/revoke", payload, publicRequestConfig())
1376
+ () => this.http.post("/oauth/revoke", payload, formRequestConfig())
1343
1377
  );
1344
1378
  }
1345
1379
  /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
@@ -1737,12 +1771,18 @@ var SignerResource = class extends BaseResource {
1737
1771
  requireEmail(email);
1738
1772
  try {
1739
1773
  const lower = email.toLowerCase();
1740
- for (let page = 1; ; page++) {
1774
+ for (let page = 1; page <= MAX_SEARCH_PAGES; page++) {
1741
1775
  const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
1742
1776
  const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
1743
1777
  if (match) return match;
1744
- if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
1778
+ if (!data.length) return null;
1779
+ if (meta?.last_page !== void 0) {
1780
+ if (page >= meta.last_page) return null;
1781
+ } else if (data.length < 100) {
1782
+ return null;
1783
+ }
1745
1784
  }
1785
+ throw new ValidationError("Signer email search exceeded the maximum page count");
1746
1786
  } catch (err) {
1747
1787
  if (err instanceof ApiError && err.statusCode === 404) {
1748
1788
  return null;
@@ -1751,6 +1791,7 @@ var SignerResource = class extends BaseResource {
1751
1791
  }
1752
1792
  }
1753
1793
  };
1794
+ var MAX_SEARCH_PAGES = 100;
1754
1795
  function normaliseSignerPayload(payload, useGovernmentId = false) {
1755
1796
  const normalised = {
1756
1797
  full_name: payload.full_name,
@@ -1765,7 +1806,7 @@ function normaliseSignerPayload(payload, useGovernmentId = false) {
1765
1806
  if ("metadata" in payload && payload.metadata !== void 0) {
1766
1807
  normalised.metadata = payload.metadata;
1767
1808
  }
1768
- return cleanParams(normalised);
1809
+ return stripEmpty(normalised);
1769
1810
  }
1770
1811
 
1771
1812
  // src/api/resources/tags.ts
@@ -1786,7 +1827,7 @@ var TagResource = class extends BaseResource {
1786
1827
  const id = this.accountId(accountId);
1787
1828
  return this.call(
1788
1829
  "Failed to create tag",
1789
- () => this.http.post(`/accounts/${id}/tags`, cleanParams({ ...payload }))
1830
+ () => this.http.post(`/accounts/${id}/tags`, stripEmpty({ ...payload }))
1790
1831
  );
1791
1832
  }
1792
1833
  /**
@@ -2059,9 +2100,8 @@ var WorkspaceResource = class extends BaseResource {
2059
2100
  throw new ValidationError("Logo buffer is required");
2060
2101
  }
2061
2102
  const contentType = options.contentType ?? "image/png";
2062
- const view = new Uint8Array(logo.buffer, logo.byteOffset, logo.byteLength);
2063
2103
  const form = new FormData();
2064
- form.append("file", new Blob([view], { type: contentType }), options.fileName ?? "logo.png");
2104
+ appendFilePart(form, logo, contentType, options.fileName ?? "logo.png");
2065
2105
  return this.call(
2066
2106
  "Failed to upload workspace logo",
2067
2107
  () => this.http.post(`/accounts/${id}/logo`, form, {
@@ -2398,6 +2438,8 @@ var AssinafyClient = class _AssinafyClient {
2398
2438
  WebhookVerifier,
2399
2439
  WorkspaceResource,
2400
2440
  buildAssignmentPayload,
2401
- normalizeBaseUrl
2441
+ normalizeBaseUrl,
2442
+ requireDocumentArtifactName,
2443
+ requireSignerImageType
2402
2444
  });
2403
2445
  //# sourceMappingURL=api.cjs.map