@assinafy/cli 2.0.3 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs CHANGED
@@ -21089,18 +21089,35 @@ var AssinafyError = class extends Error {
21089
21089
  var ApiError = class _ApiError extends AssinafyError {
21090
21090
  statusCode;
21091
21091
  responseData;
21092
+ /** Bearer challenge, including insufficient_scope and resource_metadata when provided. */
21093
+ wwwAuthenticate;
21094
+ /** Server retry delay (seconds or HTTP date), when provided. */
21095
+ retryAfter;
21092
21096
  constructor(message, statusCode, responseData = null, options) {
21093
21097
  super(message, { statusCode, responseData }, options);
21094
21098
  this.name = "ApiError";
21095
21099
  this.statusCode = statusCode;
21096
21100
  this.responseData = responseData;
21101
+ this.wwwAuthenticate = options?.wwwAuthenticate;
21102
+ this.retryAfter = options?.retryAfter;
21097
21103
  }
21098
- static fromResponse(statusCode, responseData) {
21104
+ static fromResponse(statusCode, responseData, headers = {}) {
21105
+ if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
21106
+ const text2 = (Buffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)).toString("utf8");
21107
+ try {
21108
+ responseData = JSON.parse(text2);
21109
+ } catch {
21110
+ responseData = text2;
21111
+ }
21112
+ }
21099
21113
  const data = responseData ?? {};
21100
21114
  const rawMessage = data.message;
21101
21115
  const rawError = data.error;
21102
21116
  const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
21103
- return new _ApiError(message, statusCode, responseData);
21117
+ return new _ApiError(message, statusCode, responseData, {
21118
+ wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
21119
+ retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
21120
+ });
21104
21121
  }
21105
21122
  };
21106
21123
  var ValidationError = class extends AssinafyError {
@@ -21117,6 +21134,19 @@ var NetworkError = class extends AssinafyError {
21117
21134
  this.name = "NetworkError";
21118
21135
  }
21119
21136
  };
21137
+ var PartialWorkflowError = class extends AssinafyError {
21138
+ /** The document that was uploaded before the failure, if any. */
21139
+ documentId;
21140
+ /** IDs of every signer created (or reused) before the failure. */
21141
+ signerIds;
21142
+ constructor(message, created, options) {
21143
+ const signerIds = created.signerIds ?? [];
21144
+ super(message, { documentId: created.documentId, signerIds }, options);
21145
+ this.name = "PartialWorkflowError";
21146
+ this.documentId = created.documentId;
21147
+ this.signerIds = signerIds;
21148
+ }
21149
+ };
21120
21150
 
21121
21151
  // src/api/utils.ts
21122
21152
  var DOCUMENT_ARTIFACT_NAMES = [
@@ -21150,7 +21180,7 @@ function toSdkError(error, fallbackMessage) {
21150
21180
  if (axios_default.isAxiosError(error)) {
21151
21181
  const status = error.response?.status;
21152
21182
  if (status) {
21153
- return ApiError.fromResponse(status, error.response?.data ?? null);
21183
+ return ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);
21154
21184
  }
21155
21185
  return new NetworkError(`${fallbackMessage}: ${error.message}`);
21156
21186
  }
@@ -21414,7 +21444,7 @@ function buildAssignmentPayload(payload, options = {}) {
21414
21444
  }
21415
21445
  const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
21416
21446
  if (!options.skipDigitalCertificateStepValidation) {
21417
- validateDigitalCertificateSteps(normalisedSigners);
21447
+ validateSigningSteps(normalisedSigners);
21418
21448
  }
21419
21449
  return cleanParams({
21420
21450
  method: payload.method ?? "virtual",
@@ -22181,6 +22211,178 @@ function validationConfig(signerAccessCode) {
22181
22211
  return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
22182
22212
  }
22183
22213
 
22214
+ // src/api/resources/oauth.ts
22215
+ var import_node_crypto = require("crypto");
22216
+ var OAuthResource = class extends BaseResource {
22217
+ /** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
22218
+ async metadata() {
22219
+ return this.call(
22220
+ "Failed to discover OAuth resource",
22221
+ () => this.http.get(
22222
+ "/.well-known/oauth-protected-resource",
22223
+ publicRequestConfig({
22224
+ baseURL: new URL(this.http.defaults.baseURL).origin
22225
+ })
22226
+ )
22227
+ );
22228
+ }
22229
+ /** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
22230
+ async discovery(issuer) {
22231
+ const url2 = httpsUrl(issuer, "issuer");
22232
+ if (url2.search || url2.pathname !== "/") {
22233
+ throw new ValidationError("issuer must be an HTTPS origin");
22234
+ }
22235
+ const metadata = await this.call(
22236
+ "Failed to discover OAuth authorization server",
22237
+ () => this.http.get(
22238
+ `${url2.origin}/.well-known/oauth-authorization-server`,
22239
+ publicRequestConfig()
22240
+ )
22241
+ );
22242
+ if (metadata.issuer !== issuer) throw new ValidationError("OAuth issuer mismatch");
22243
+ httpsUrl(metadata.authorization_endpoint, "authorization_endpoint");
22244
+ return metadata;
22245
+ }
22246
+ /** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */
22247
+ async authorize(options) {
22248
+ required(options.clientId, "clientId");
22249
+ httpsUrl(options.redirectUri, "redirectUri");
22250
+ if (!Array.isArray(options.scopes) || options.scopes.length === 0 || options.scopes.some(
22251
+ (scope) => typeof scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)
22252
+ )) {
22253
+ throw new ValidationError("scopes must contain non-empty OAuth scope names");
22254
+ }
22255
+ const resource = await this.metadata();
22256
+ const issuer = resource.authorization_servers?.[0];
22257
+ if (!issuer) throw new ValidationError("OAuth metadata has no authorization server");
22258
+ httpsUrl(resource.resource, "resource");
22259
+ const server = await this.discovery(issuer);
22260
+ const codeVerifier = (0, import_node_crypto.randomBytes)(32).toString("base64url");
22261
+ const state = (0, import_node_crypto.randomBytes)(32).toString("base64url");
22262
+ const nonce = options.scopes.includes("openid") ? (0, import_node_crypto.randomBytes)(32).toString("base64url") : void 0;
22263
+ const url2 = new URL(server.authorization_endpoint);
22264
+ const params = {
22265
+ response_type: "code",
22266
+ client_id: options.clientId,
22267
+ redirect_uri: options.redirectUri,
22268
+ scope: options.scopes.join(" "),
22269
+ state,
22270
+ code_challenge: (0, import_node_crypto.createHash)("sha256").update(codeVerifier).digest("base64url"),
22271
+ code_challenge_method: "S256",
22272
+ resource: resource.resource
22273
+ };
22274
+ for (const [key, value] of Object.entries(params)) url2.searchParams.set(key, value);
22275
+ if (nonce) url2.searchParams.set("nonce", nonce);
22276
+ return {
22277
+ authorization_url: url2.toString(),
22278
+ code_verifier: codeVerifier,
22279
+ state,
22280
+ issuer,
22281
+ client_id: options.clientId,
22282
+ redirect_uri: options.redirectUri,
22283
+ resource: resource.resource,
22284
+ ...nonce ? { nonce } : {}
22285
+ };
22286
+ }
22287
+ /** Validate callback URI, state, and issuer before exchanging its one-time code. */
22288
+ async exchangeCode(callbackUrl, request, clientSecret) {
22289
+ const callback = httpsUrl(callbackUrl, "callbackUrl");
22290
+ const redirect = httpsUrl(request.redirect_uri, "redirect_uri");
22291
+ if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname || [...new Set(redirect.searchParams.keys())].some((key) => {
22292
+ const expected2 = redirect.searchParams.getAll(key);
22293
+ const actual2 = callback.searchParams.getAll(key);
22294
+ return expected2.length !== actual2.length || expected2.some((value, i2) => value !== actual2[i2]);
22295
+ })) {
22296
+ throw new ValidationError("OAuth callback does not match the registered redirect URI");
22297
+ }
22298
+ for (const key of ["state", "iss", "code", "error"]) {
22299
+ if (callback.searchParams.getAll(key).length > 1) {
22300
+ throw new ValidationError(`Duplicate OAuth callback parameter: ${key}`);
22301
+ }
22302
+ }
22303
+ const actual = Buffer.from(callback.searchParams.get("state") ?? "");
22304
+ const expected = Buffer.from(required(request.state, "state"));
22305
+ if (actual.length !== expected.length || !(0, import_node_crypto.timingSafeEqual)(actual, expected)) {
22306
+ throw new ValidationError("OAuth state mismatch");
22307
+ }
22308
+ if (callback.searchParams.get("iss") !== request.issuer) {
22309
+ throw new ValidationError("OAuth issuer mismatch");
22310
+ }
22311
+ if (callback.searchParams.has("error")) {
22312
+ const error = callback.searchParams.get("error");
22313
+ const oauthError = error.length > 0 && error.length <= 64 && !/[^a-z_]/.test(error) ? error : "unknown_error";
22314
+ throw new ValidationError(`OAuth authorization was declined or failed: ${oauthError}`, {
22315
+ oauthError
22316
+ });
22317
+ }
22318
+ return this.token({
22319
+ grant_type: "authorization_code",
22320
+ code: required(callback.searchParams.get("code"), "code"),
22321
+ client_id: request.client_id,
22322
+ client_secret: clientSecret,
22323
+ redirect_uri: request.redirect_uri,
22324
+ code_verifier: request.code_verifier,
22325
+ resource: request.resource
22326
+ });
22327
+ }
22328
+ /** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
22329
+ async token(payload) {
22330
+ required(payload.client_id, "client_id");
22331
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
22332
+ if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
22333
+ if (payload.grant_type === "authorization_code") {
22334
+ required(payload.code, "code");
22335
+ httpsUrl(payload.redirect_uri, "redirect_uri");
22336
+ if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
22337
+ throw new ValidationError(
22338
+ "code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
22339
+ );
22340
+ }
22341
+ } else if (payload.grant_type === "refresh_token") {
22342
+ required(payload.refresh_token, "refresh_token");
22343
+ } else {
22344
+ throw new ValidationError("grant_type must be authorization_code or refresh_token");
22345
+ }
22346
+ return this.call(
22347
+ "OAuth token request failed",
22348
+ () => this.http.post("/oauth/token", payload, publicRequestConfig())
22349
+ );
22350
+ }
22351
+ /** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
22352
+ async revoke(payload) {
22353
+ required(payload.client_id, "client_id");
22354
+ required(payload.token, "token");
22355
+ if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
22356
+ if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
22357
+ throw new ValidationError("token_type_hint must be access_token or refresh_token");
22358
+ }
22359
+ await this.call(
22360
+ "OAuth revocation failed",
22361
+ () => this.http.post("/oauth/revoke", payload, publicRequestConfig())
22362
+ );
22363
+ }
22364
+ /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
22365
+ async userinfo() {
22366
+ return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
22367
+ }
22368
+ };
22369
+ function required(value, name) {
22370
+ if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
22371
+ return value;
22372
+ }
22373
+ function httpsUrl(value, name) {
22374
+ let url2;
22375
+ try {
22376
+ url2 = new URL(value);
22377
+ } catch {
22378
+ throw new ValidationError(`${name} must be an absolute HTTPS URL`);
22379
+ }
22380
+ if (url2.protocol !== "https:" || url2.username || url2.password || url2.hash) {
22381
+ throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
22382
+ }
22383
+ return url2;
22384
+ }
22385
+
22184
22386
  // src/api/resources/signer-documents.ts
22185
22387
  var SignerDocumentsResource = class extends BaseResource {
22186
22388
  /** `GET /signers/{signer_id}/document?signer-access-code=…` */
@@ -22259,7 +22461,7 @@ var SignerDocumentsResource = class extends BaseResource {
22259
22461
  if (!Array.isArray(documentIds) || documentIds.length === 0) {
22260
22462
  throw new ValidationError("documentIds must be a non-empty array");
22261
22463
  }
22262
- if (!declineReason) throw new ValidationError("declineReason is required");
22464
+ validateDeclineReason(declineReason);
22263
22465
  const code = this.requireId(signerAccessCode, "signer-access-code");
22264
22466
  return this.call(
22265
22467
  "Failed to decline multiple documents",
@@ -22389,7 +22591,7 @@ var SignerDocumentsResource = class extends BaseResource {
22389
22591
  const did = this.requireId(documentId, "Document ID");
22390
22592
  const aid = this.requireId(assignmentId, "Assignment ID");
22391
22593
  const code = this.requireId(signerAccessCode, "signer-access-code");
22392
- if (!declineReason) throw new ValidationError("declineReason is required");
22594
+ validateDeclineReason(declineReason);
22393
22595
  return this.call(
22394
22596
  "Failed to decline assignment",
22395
22597
  () => this.http.put(
@@ -22400,6 +22602,14 @@ var SignerDocumentsResource = class extends BaseResource {
22400
22602
  );
22401
22603
  }
22402
22604
  };
22605
+ function validateDeclineReason(value) {
22606
+ if (typeof value !== "string" || !value.trim()) {
22607
+ throw new ValidationError("declineReason is required");
22608
+ }
22609
+ if ([...value].length > 2e3) {
22610
+ throw new ValidationError("declineReason must contain at most 2000 characters");
22611
+ }
22612
+ }
22403
22613
 
22404
22614
  // src/api/resources/signers.ts
22405
22615
  function validateCreateSignerPayload(payload) {
@@ -22489,9 +22699,13 @@ var SignerResource = class extends BaseResource {
22489
22699
  async findByEmail(email, accountId) {
22490
22700
  requireEmail(email);
22491
22701
  try {
22492
- const { data } = await this.list({ search: email, per_page: 100 }, accountId);
22493
22702
  const lower = email.toLowerCase();
22494
- return data.find((s) => (s.email ?? "").toLowerCase() === lower) ?? null;
22703
+ for (let page = 1; ; page++) {
22704
+ const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
22705
+ const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
22706
+ if (match) return match;
22707
+ if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
22708
+ }
22495
22709
  } catch (err) {
22496
22710
  if (err instanceof ApiError && err.statusCode === 404) {
22497
22711
  return null;
@@ -22861,7 +23075,7 @@ function validateNotificationSender(value) {
22861
23075
  }
22862
23076
 
22863
23077
  // src/api/support/webhook-verifier.ts
22864
- var import_node_crypto = require("crypto");
23078
+ var import_node_crypto2 = require("crypto");
22865
23079
  var WebhookVerifier = class {
22866
23080
  constructor(webhookSecret, options = {}) {
22867
23081
  this.webhookSecret = webhookSecret;
@@ -22876,12 +23090,12 @@ var WebhookVerifier = class {
22876
23090
  if (!this.webhookSecret || !signature) return false;
22877
23091
  try {
22878
23092
  const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
22879
- const expected = (0, import_node_crypto.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
23093
+ const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
22880
23094
  const provided = signature.trim();
22881
23095
  const a2 = Buffer.from(expected, "utf8");
22882
23096
  const b = Buffer.from(provided, "utf8");
22883
23097
  if (a2.length !== b.length) return false;
22884
- return (0, import_node_crypto.timingSafeEqual)(a2, b);
23098
+ return (0, import_node_crypto2.timingSafeEqual)(a2, b);
22885
23099
  } catch {
22886
23100
  return false;
22887
23101
  }
@@ -22923,6 +23137,9 @@ var WebhookVerifier = class {
22923
23137
 
22924
23138
  // src/api/client.ts
22925
23139
  var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
23140
+ function isLoopbackHost(hostname) {
23141
+ return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
23142
+ }
22926
23143
  var AssinafyClient = class _AssinafyClient {
22927
23144
  axiosInstance;
22928
23145
  defaultAccountId;
@@ -22936,6 +23153,7 @@ var AssinafyClient = class _AssinafyClient {
22936
23153
  templates;
22937
23154
  tags;
22938
23155
  auth;
23156
+ oauth;
22939
23157
  fields;
22940
23158
  users;
22941
23159
  signerDocuments;
@@ -22943,7 +23161,7 @@ var AssinafyClient = class _AssinafyClient {
22943
23161
  constructor(options) {
22944
23162
  if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
22945
23163
  throw new ValidationError(
22946
- "An API key (options.apiKey) or legacy access token (options.token) is required."
23164
+ "An API key (options.apiKey) or access token (options.token) is required."
22947
23165
  );
22948
23166
  }
22949
23167
  if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
@@ -22959,13 +23177,17 @@ var AssinafyClient = class _AssinafyClient {
22959
23177
  } catch {
22960
23178
  throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
22961
23179
  }
22962
- if (!["https:", "http:"].includes(parsedBaseUrl.protocol)) {
22963
- throw new ValidationError("baseUrl must use HTTPS");
22964
- }
22965
- if (parsedBaseUrl.protocol !== "https:" && !options.allowInsecureHttp) {
22966
- throw new ValidationError(
22967
- "baseUrl must use HTTPS; set allowInsecureHttp only for isolated local development"
22968
- );
23180
+ if (parsedBaseUrl.protocol !== "https:") {
23181
+ if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
23182
+ throw new ValidationError(
23183
+ "baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
23184
+ );
23185
+ }
23186
+ if (!isLoopbackHost(parsedBaseUrl.hostname)) {
23187
+ throw new ValidationError(
23188
+ "allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
23189
+ );
23190
+ }
22969
23191
  }
22970
23192
  if (parsedBaseUrl.username || parsedBaseUrl.password) {
22971
23193
  throw new ValidationError("baseUrl must not contain embedded credentials");
@@ -23001,6 +23223,7 @@ var AssinafyClient = class _AssinafyClient {
23001
23223
  this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
23002
23224
  this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
23003
23225
  this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
23226
+ this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
23004
23227
  this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
23005
23228
  this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
23006
23229
  this.signerDocuments = new SignerDocumentsResource(
@@ -23036,13 +23259,22 @@ var AssinafyClient = class _AssinafyClient {
23036
23259
  /**
23037
23260
  * High-level helper that uploads a PDF, ensures it's processed, creates any
23038
23261
  * missing signers, and kicks off a virtual signature assignment.
23262
+ *
23263
+ * Once the upload succeeds the workflow owns real workspace resources, so any
23264
+ * later failure is rethrown as a {@link PartialWorkflowError} carrying the
23265
+ * document and signer IDs that already exist. Catch it to resume or clean up;
23266
+ * nothing is deleted automatically.
23039
23267
  */
23040
23268
  async uploadAndRequestSignatures(options) {
23041
- if (!options.signers || options.signers.length === 0) {
23269
+ if (!Array.isArray(options.signers) || options.signers.length === 0) {
23042
23270
  throw new ValidationError("At least one signer is required");
23043
23271
  }
23044
23272
  if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
23045
23273
  const preparedSigners = options.signers.map((signer) => {
23274
+ if (!signer || typeof signer !== "object") {
23275
+ throw new ValidationError("Each signer must be an object");
23276
+ }
23277
+ validateSignerOptions(signer);
23046
23278
  const payload = { full_name: signer.name };
23047
23279
  if (signer.email !== void 0) payload.email = signer.email;
23048
23280
  const phone = signer.whatsapp_phone_number ?? signer.phone;
@@ -23052,6 +23284,7 @@ var AssinafyClient = class _AssinafyClient {
23052
23284
  validateCreateSignerPayload(payload);
23053
23285
  return { signer, payload, phone };
23054
23286
  });
23287
+ validateSigningSteps(options.signers);
23055
23288
  this.logger.info("Starting upload + signature workflow", {
23056
23289
  signerCount: options.signers.length
23057
23290
  });
@@ -23059,33 +23292,46 @@ var AssinafyClient = class _AssinafyClient {
23059
23292
  if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
23060
23293
  if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
23061
23294
  const document2 = await this.documents.upload(options.source, uploadOpts);
23062
- if (options.waitForReady !== false) {
23063
- await this.documents.waitUntilReady(document2.id);
23064
- }
23065
23295
  const signerIds = [];
23066
- const assignmentSigners = [];
23067
- for (const { signer, payload, phone } of preparedSigners) {
23068
- const created = await this.signers.create(payload, options.accountId);
23069
- signerIds.push(created.id);
23070
- const useWhatsapp = phone !== void 0 && signer.email === void 0;
23071
- assignmentSigners.push({
23072
- id: created.id,
23073
- verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
23074
- notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
23075
- step: signer.step
23296
+ try {
23297
+ if (options.waitForReady !== false) {
23298
+ await this.documents.waitUntilReady(document2.id);
23299
+ }
23300
+ const assignmentSigners = [];
23301
+ for (const { signer, payload, phone } of preparedSigners) {
23302
+ const created = await this.signers.create(payload, options.accountId);
23303
+ signerIds.push(created.id);
23304
+ const useWhatsapp = phone !== void 0 && signer.email === void 0;
23305
+ assignmentSigners.push({
23306
+ id: created.id,
23307
+ verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
23308
+ notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
23309
+ step: signer.step
23310
+ });
23311
+ }
23312
+ const assignmentPayload = {
23313
+ method: "virtual",
23314
+ signers: assignmentSigners
23315
+ };
23316
+ if (options.message !== void 0) assignmentPayload.message = options.message;
23317
+ if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
23318
+ if (options.copyReceivers !== void 0)
23319
+ assignmentPayload.copy_receivers = options.copyReceivers;
23320
+ const assignment = await this.assignments.create(document2.id, assignmentPayload);
23321
+ this.logger.info("Upload + signature workflow completed", { documentId: document2.id });
23322
+ return { document: document2, assignment, signer_ids: signerIds };
23323
+ } catch (err) {
23324
+ this.logger.error("Upload + signature workflow failed after creating resources", {
23325
+ documentId: document2.id,
23326
+ signerIds
23076
23327
  });
23328
+ const reason = err instanceof Error ? err.message : String(err);
23329
+ throw new PartialWorkflowError(
23330
+ `${reason} (document ${document2.id} exists; ${signerIds.length} signer(s) created or reused)`,
23331
+ { documentId: document2.id, signerIds },
23332
+ { cause: err }
23333
+ );
23077
23334
  }
23078
- const assignmentPayload = {
23079
- method: "virtual",
23080
- signers: assignmentSigners
23081
- };
23082
- if (options.message !== void 0) assignmentPayload.message = options.message;
23083
- if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
23084
- if (options.copyReceivers !== void 0)
23085
- assignmentPayload.copy_receivers = options.copyReceivers;
23086
- const assignment = await this.assignments.create(document2.id, assignmentPayload);
23087
- this.logger.info("Upload + signature workflow completed", { documentId: document2.id });
23088
- return { document: document2, assignment, signer_ids: signerIds };
23089
23335
  }
23090
23336
  /** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
23091
23337
  getAxiosInstance() {
@@ -23113,9 +23359,23 @@ function normalizeError(err) {
23113
23359
  message: err.message,
23114
23360
  code: "api_error",
23115
23361
  statusCode: err.statusCode,
23116
- details: err.responseData ?? void 0
23362
+ details: err.responseData ?? void 0,
23363
+ ...err.wwwAuthenticate ? { wwwAuthenticate: err.wwwAuthenticate } : {},
23364
+ ...err.retryAfter ? { retryAfter: err.retryAfter } : {}
23117
23365
  };
23118
23366
  }
23367
+ if (err instanceof PartialWorkflowError) {
23368
+ const cause = normalizeError(err.cause);
23369
+ const normalized = {
23370
+ message: err.message,
23371
+ code: cause.code,
23372
+ details: err.context
23373
+ };
23374
+ if (cause.statusCode !== void 0) normalized.statusCode = cause.statusCode;
23375
+ if (cause.wwwAuthenticate !== void 0) normalized.wwwAuthenticate = cause.wwwAuthenticate;
23376
+ if (cause.retryAfter !== void 0) normalized.retryAfter = cause.retryAfter;
23377
+ return normalized;
23378
+ }
23119
23379
  if (err instanceof ValidationError) {
23120
23380
  return { message: err.message, code: "validation_error", details: err.errors };
23121
23381
  }
@@ -23130,6 +23390,10 @@ function normalizeError(err) {
23130
23390
  }
23131
23391
  return { message: String(err), code: "unexpected_error" };
23132
23392
  }
23393
+ function errorMessage(err, fallback = "An unexpected error occurred") {
23394
+ const normalized = normalizeError(err);
23395
+ return normalized.message || fallback;
23396
+ }
23133
23397
 
23134
23398
  // src/lib/client.ts
23135
23399
  function createClient(config, options = {}) {
@@ -23324,7 +23588,7 @@ function paginationFooter(result) {
23324
23588
  }
23325
23589
 
23326
23590
  // src/lib/config.ts
23327
- var import_node_crypto2 = require("crypto");
23591
+ var import_node_crypto3 = require("crypto");
23328
23592
  var import_node_fs3 = require("fs");
23329
23593
  var import_node_os = __toESM(require("os"), 1);
23330
23594
  var import_node_path3 = __toESM(require("path"), 1);
@@ -23379,7 +23643,7 @@ function writeConfigFile(config) {
23379
23643
  (0, import_node_fs3.mkdirSync)(dir, { recursive: true, mode: 448 });
23380
23644
  }
23381
23645
  const file = configPath();
23382
- const tmp = `${file}.${(0, import_node_crypto2.randomUUID)()}.tmp`;
23646
+ const tmp = `${file}.${(0, import_node_crypto3.randomUUID)()}.tmp`;
23383
23647
  try {
23384
23648
  (0, import_node_fs3.writeFileSync)(tmp, `${JSON.stringify(config, null, 2)}
23385
23649
  `, {
@@ -23402,9 +23666,14 @@ function resolveConfig2(globals) {
23402
23666
  const profile = file.profiles?.[profileName] ?? {};
23403
23667
  const pick = (flag, env, stored) => flag ?? env ?? stored;
23404
23668
  const baseUrl = pick(globals.baseUrl, process.env.ASSINAFY_BASE_URL, profile.base_url) ?? DEFAULT_BASE_URL2;
23669
+ const credentials = [
23670
+ { apiKey: globals.apiKey, token: globals.token },
23671
+ { apiKey: process.env.ASSINAFY_API_KEY, token: process.env.ASSINAFY_TOKEN },
23672
+ { apiKey: profile.api_key, token: profile.token }
23673
+ ].find(({ apiKey, token }) => apiKey !== void 0 || token !== void 0);
23405
23674
  return {
23406
- apiKey: pick(globals.apiKey, process.env.ASSINAFY_API_KEY, profile.api_key),
23407
- token: pick(globals.token, process.env.ASSINAFY_TOKEN, profile.token),
23675
+ apiKey: credentials?.apiKey,
23676
+ token: credentials?.token,
23408
23677
  accountId: pick(globals.accountId, process.env.ASSINAFY_ACCOUNT_ID, profile.account_id),
23409
23678
  baseUrl: normalizeBaseUrl(baseUrl),
23410
23679
  webhookSecret: pick(void 0, process.env.ASSINAFY_WEBHOOK_SECRET, profile.webhook_secret),
@@ -24519,13 +24788,13 @@ function displayWidth(text2) {
24519
24788
  }
24520
24789
 
24521
24790
  // src/commands/assignments.ts
24522
- function resolveSigners(signersJson, signerIdsCsv, required = true) {
24791
+ function resolveSigners(signersJson, signerIdsCsv, required2 = true) {
24523
24792
  if (signersJson) {
24524
24793
  return parseJsonArray(signersJson, "--signers");
24525
24794
  }
24526
24795
  const ids = splitList(signerIdsCsv);
24527
24796
  if (!ids || ids.length === 0) {
24528
- if (!required) return [];
24797
+ if (!required2) return [];
24529
24798
  throw new CliError("Provide signers with --signer-ids <id1,id2> or --signers <json>.");
24530
24799
  }
24531
24800
  return ids;
@@ -24869,10 +25138,12 @@ var setCommand = new Command("set").description(
24869
25138
  let changed = false;
24870
25139
  if (merged.apiKey !== void 0) {
24871
25140
  profile.api_key = merged.apiKey;
25141
+ profile.token = void 0;
24872
25142
  changed = true;
24873
25143
  }
24874
25144
  if (merged.token !== void 0) {
24875
25145
  profile.token = merged.token;
25146
+ if (merged.apiKey === void 0) profile.api_key = void 0;
24876
25147
  changed = true;
24877
25148
  }
24878
25149
  if (merged.accountId !== void 0) {
@@ -25038,17 +25309,26 @@ var uploadCommand = new Command("upload").description("Upload a PDF to the works
25038
25309
  const uploadOptions = { accountId };
25039
25310
  if (metadata) uploadOptions.metadata = metadata;
25040
25311
  if (opts.name) uploadOptions.name = opts.name;
25041
- const doc = await withSpinner(
25312
+ let doc = await withSpinner(
25042
25313
  "Uploading document",
25043
25314
  config,
25044
25315
  () => client.documents.upload({ filePath: file }, uploadOptions)
25045
25316
  );
25046
25317
  if (opts.wait) {
25047
- await withSpinner(
25048
- "Waiting for processing",
25049
- config,
25050
- () => client.documents.waitUntilReady(doc.id)
25051
- );
25318
+ try {
25319
+ const ready = await withSpinner(
25320
+ "Waiting for processing",
25321
+ config,
25322
+ () => client.documents.waitUntilReady(doc.id)
25323
+ );
25324
+ doc = { ...doc, ...ready };
25325
+ } catch (error) {
25326
+ throw new PartialWorkflowError(
25327
+ `${errorMessage(error)} (document ${doc.id} was uploaded)`,
25328
+ { documentId: doc.id },
25329
+ { cause: error }
25330
+ );
25331
+ }
25052
25332
  }
25053
25333
  printSuccess(`Uploaded document ${doc.id}`, config);
25054
25334
  printData(
@@ -25609,6 +25889,299 @@ var logoutCommand = new Command("logout").description("Remove stored credentials
25609
25889
  });
25610
25890
  });
25611
25891
 
25892
+ // src/lib/oauth-browser.ts
25893
+ var import_node_child_process3 = require("child_process");
25894
+ var import_node_crypto4 = require("crypto");
25895
+ var import_node_events2 = require("events");
25896
+ var import_node_http = require("http");
25897
+ var CLI_OAUTH_REDIRECT_URI = "https://integrations.assinafy.com.br/assinafy-cli/oauth-callback";
25898
+ var clearHistory = "history.replaceState(null, '', '/');";
25899
+ var brandOrigin = "https://integrations.assinafy.com.br";
25900
+ var callbackCopy = {
25901
+ received: {
25902
+ heading: "Volte ao terminal.",
25903
+ status: "A resposta de autoriza\xE7\xE3o foi recebida. Confira no terminal se a conex\xE3o foi conclu\xEDda."
25904
+ },
25905
+ denied: {
25906
+ heading: "Conex\xE3o n\xE3o autorizada.",
25907
+ status: "A autoriza\xE7\xE3o n\xE3o foi conclu\xEDda. Confira o erro no terminal e inicie uma nova conex\xE3o."
25908
+ },
25909
+ invalid: {
25910
+ heading: "Retorno inv\xE1lido.",
25911
+ status: "Continue na janela original de autoriza\xE7\xE3o. Se ela expirou, inicie uma nova conex\xE3o no terminal."
25912
+ }
25913
+ };
25914
+ function callbackPage(status) {
25915
+ const copy = callbackCopy[status];
25916
+ return `<!doctype html>
25917
+ <html lang="pt-BR">
25918
+ <head>
25919
+ <meta charset="utf-8">
25920
+ <meta name="viewport" content="width=device-width,initial-scale=1">
25921
+ <meta name="referrer" content="no-referrer">
25922
+ <meta name="robots" content="noindex, nofollow, noarchive">
25923
+ <title>${copy.heading} | Assinafy CLI</title>
25924
+ <script>${clearHistory}</script>
25925
+ <link rel="icon" href="${brandOrigin}/brand/assinafy-icon.png">
25926
+ <link rel="stylesheet" href="${brandOrigin}/brand/colors.css">
25927
+ <link rel="stylesheet" href="${brandOrigin}/brand/site.css">
25928
+ <link rel="stylesheet" href="${brandOrigin}/oauth-callback.css">
25929
+ </head>
25930
+ <body>
25931
+ <a class="skip-link" href="#conteudo">Pular para o conte\xFAdo</a>
25932
+ <header class="site-header wrap">
25933
+ <a class="brand" href="${brandOrigin}" aria-label="Assinafy Integra\xE7\xF5es, in\xEDcio">
25934
+ <img src="${brandOrigin}/brand/assinafy-logotype.svg" width="148" height="32" alt="Assinafy">
25935
+ <span class="brand-section">integra\xE7\xF5es</span>
25936
+ </a>
25937
+ </header>
25938
+ <main id="conteudo" class="hero wrap">
25939
+ <div>
25940
+ <p class="eyebrow"><img src="${brandOrigin}/assinafy-cli/cli-icon.svg" width="24" height="24" alt="">Conex\xE3o com a Assinafy CLI</p>
25941
+ <h1>${copy.heading}</h1>
25942
+ <p class="hero-description" role="status">${copy.status}</p>
25943
+ <a class="button button-primary" href="${brandOrigin}/assinafy-cli">Ajuda para conectar<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12h16m-7-7 7 7-7 7"/></svg></a>
25944
+ </div>
25945
+ <figure class="connection-art">
25946
+ <div class="connection-map" role="img" aria-label="Retorno de autoriza\xE7\xE3o: Assinafy para Assinafy CLI.">
25947
+ <svg class="connection-lines" viewBox="0 0 480 240" preserveAspectRatio="none" fill="none" aria-hidden="true">
25948
+ <path class="connection-route" d="M120 106H240"/>
25949
+ <path class="connection-complete" d="M240 106H374m-64-5 5 5-5 5"/>
25950
+ </svg>
25951
+ <div class="connection-node connection-assinafy" aria-hidden="true">
25952
+ <span class="connection-tile"><img src="${brandOrigin}/brand/assinafy-icon.png" width="60" height="60" alt=""></span>
25953
+ <span class="connection-label">Assinafy</span>
25954
+ </div>
25955
+ <div class="connection-node connection-application" aria-hidden="true">
25956
+ <span class="connection-tile"><img src="${brandOrigin}/assinafy-cli/cli-icon.svg" width="36" height="36" alt=""></span>
25957
+ <span class="connection-label">Assinafy CLI</span>
25958
+ </div>
25959
+ </div>
25960
+ <figcaption class="connection-caption">Continue no terminal que iniciou a conex\xE3o.</figcaption>
25961
+ </figure>
25962
+ </main>
25963
+ <footer class="site-footer wrap"><span>Assinafy. Assinaturas que conectam.</span></footer>
25964
+ </body>
25965
+ </html>`;
25966
+ }
25967
+ var callbackHeaders = {
25968
+ "Content-Type": "text/html; charset=utf-8",
25969
+ "Cache-Control": "no-store",
25970
+ "Referrer-Policy": "no-referrer",
25971
+ "X-Content-Type-Options": "nosniff",
25972
+ "X-Robots-Tag": "noindex, nofollow, noarchive",
25973
+ "Content-Security-Policy": `default-src 'none'; script-src 'sha256-${(0, import_node_crypto4.createHash)("sha256").update(clearHistory).digest("base64")}'; style-src ${brandOrigin}; img-src ${brandOrigin}; font-src ${brandOrigin}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
25974
+ Connection: "close"
25975
+ };
25976
+ function openBrowser(url2) {
25977
+ const [executable, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["rundll32.exe", ["url.dll,FileProtocolHandler", url2]] : ["xdg-open", [url2]];
25978
+ return new Promise((resolve, reject) => {
25979
+ const child = (0, import_node_child_process3.spawn)(executable, args, {
25980
+ stdio: "ignore",
25981
+ detached: true,
25982
+ windowsHide: true
25983
+ });
25984
+ child.once("error", () => reject(new CliError("Could not open the system browser.")));
25985
+ child.once("spawn", () => {
25986
+ child.unref();
25987
+ resolve();
25988
+ });
25989
+ });
25990
+ }
25991
+ async function connectOAuth(oauth, options, onAuthorize, timeoutMs = 18e4) {
25992
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e5) {
25993
+ throw new CliError("OAuth connection timeout must be between 1 and 600000 milliseconds.");
25994
+ }
25995
+ const request = await oauth.authorize(options);
25996
+ if (new URL(request.redirect_uri).search) {
25997
+ throw new CliError("The browser relay redirect URI must not contain query parameters.");
25998
+ }
25999
+ const server = (0, import_node_http.createServer)({ maxHeaderSize: 8192, requestTimeout: 5e3, headersTimeout: 5e3 });
26000
+ server.maxConnections = 8;
26001
+ server.setTimeout(5e3, (socket) => socket.destroy());
26002
+ let timer;
26003
+ let cancel2;
26004
+ let terminate;
26005
+ let callbackUrl;
26006
+ try {
26007
+ server.listen(0, "127.0.0.1");
26008
+ await (0, import_node_events2.once)(server, "listening");
26009
+ const address = server.address();
26010
+ if (!address || typeof address === "string") throw new CliError("No OAuth listener address.");
26011
+ const host = `127.0.0.1:${address.port}`;
26012
+ request.state += `.${address.port}`;
26013
+ const expectedState = Buffer.from(request.state);
26014
+ const authorization = new URL(request.authorization_url);
26015
+ authorization.searchParams.set("state", request.state);
26016
+ request.authorization_url = authorization.toString();
26017
+ callbackUrl = await new Promise((resolve, reject) => {
26018
+ let consumed = false;
26019
+ timer = setTimeout(
26020
+ () => reject(new CliError("OAuth connection timed out. Start again.")),
26021
+ timeoutMs
26022
+ );
26023
+ cancel2 = () => reject(new CliError("OAuth connection cancelled.", { exitCode: 130 }));
26024
+ terminate = () => reject(new CliError("OAuth connection terminated.", { exitCode: 143 }));
26025
+ process.once("SIGINT", cancel2);
26026
+ process.once("SIGTERM", terminate);
26027
+ server.once("error", reject);
26028
+ server.on("request", (incoming, response) => {
26029
+ const raw = incoming.url ?? "";
26030
+ const url2 = new URL(raw.startsWith("/callback?") ? raw : "/invalid", `http://${host}`);
26031
+ const query = url2.searchParams;
26032
+ const state = Buffer.from(query.get("state") ?? "");
26033
+ const valid = !consumed && incoming.method === "GET" && incoming.headers.host === host && raw.startsWith("/callback?") && raw.length <= 8192 && url2.origin === `http://${host}` && url2.pathname === "/callback" && !url2.hash && [...query.keys()].every((key) => query.getAll(key).length === 1) && state.length === expectedState.length && (0, import_node_crypto4.timingSafeEqual)(state, expectedState) && query.get("iss") === request.issuer && query.has("code") !== query.has("error") && Boolean((query.get("code") ?? query.get("error"))?.trim());
26034
+ if (!valid) {
26035
+ response.writeHead(400, callbackHeaders);
26036
+ response.end(callbackPage("invalid"));
26037
+ return;
26038
+ }
26039
+ consumed = true;
26040
+ const callback = new URL(request.redirect_uri);
26041
+ for (const key of ["code", "state", "iss", "error"]) {
26042
+ if (query.has(key)) callback.searchParams.set(key, query.get(key));
26043
+ }
26044
+ response.writeHead(200, callbackHeaders);
26045
+ response.end(
26046
+ callbackPage(query.has("error") ? "denied" : "received"),
26047
+ () => resolve(callback.toString())
26048
+ );
26049
+ });
26050
+ void Promise.resolve().then(() => onAuthorize(request.authorization_url)).catch(reject);
26051
+ });
26052
+ } finally {
26053
+ clearTimeout(timer);
26054
+ if (cancel2) process.off("SIGINT", cancel2);
26055
+ if (terminate) process.off("SIGTERM", terminate);
26056
+ await new Promise((resolve) => {
26057
+ server.close(() => resolve());
26058
+ server.closeAllConnections();
26059
+ });
26060
+ }
26061
+ return oauth.exchangeCode(callbackUrl, request);
26062
+ }
26063
+
26064
+ // src/commands/oauth.ts
26065
+ var clientIdOption = () => new Option("--client-id <id>", "OAuth application client ID").env("ASSINAFY_OAUTH_CLIENT_ID").default("96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88");
26066
+ var clientSecretOption = () => new Option(
26067
+ "--client-secret <secret>",
26068
+ "Confidential application secret; omit for public applications"
26069
+ ).env("ASSINAFY_OAUTH_CLIENT_SECRET");
26070
+ var connectCommand = new Command("connect").description(
26071
+ "Open browser consent for a public OAuth app, receive its loopback return, and print tokens"
26072
+ ).addOption(clientIdOption()).option("--redirect-uri <uri>", "Exactly registered HTTPS relay URI", CLI_OAUTH_REDIRECT_URI).option(
26073
+ "--scope <scopes>",
26074
+ "Space-separated scopes; defaults to all supported OAuth scopes",
26075
+ "account:read documents:read documents:write templates:read templates:write openid profile email offline_access"
26076
+ ).option("--timeout <seconds>", "Wait for browser consent (1\u2013600 seconds)", "180").option("--no-browser", "Print the authorization URL without opening the system browser").action(async (opts, command) => {
26077
+ await runWithPublicClient(command, async ({ client, config }) => {
26078
+ const timeout = parseInteger(opts.timeout, "--timeout", { min: 1 });
26079
+ const tokens = await connectOAuth(
26080
+ client.oauth,
26081
+ {
26082
+ clientId: opts.clientId,
26083
+ redirectUri: opts.redirectUri,
26084
+ scopes: opts.scope.trim().split(/\s+/)
26085
+ },
26086
+ async (url2) => {
26087
+ process.stderr.write(
26088
+ `Open this URL in a browser on this computer:
26089
+ ${sanitizeTerminalText(url2)}
26090
+ `
26091
+ );
26092
+ if (opts.browser) {
26093
+ await openBrowser(url2).catch(() => {
26094
+ process.stderr.write("Could not open the browser. Open the URL above manually.\n");
26095
+ });
26096
+ }
26097
+ },
26098
+ timeout * 1e3
26099
+ );
26100
+ printData(tokens, config);
26101
+ });
26102
+ });
26103
+ var metadataCommand = new Command("metadata").description("Read protected-resource metadata from the API origin").action(async (_opts, command) => {
26104
+ await runWithPublicClient(command, async ({ client, config }) => {
26105
+ printData(await client.oauth.metadata(), config);
26106
+ });
26107
+ });
26108
+ var discoveryCommand = new Command("discovery").description("Read authorization-server metadata from an HTTPS issuer").argument("<issuer>", "Issuer from protected-resource metadata").action(async (issuer, _opts, command) => {
26109
+ await runWithPublicClient(command, async ({ client, config }) => {
26110
+ printData(await client.oauth.discovery(issuer), config);
26111
+ });
26112
+ });
26113
+ var authorizeCommand = new Command("authorize").description(
26114
+ "Create an authorization URL and a sensitive PKCE/state request; save the JSON securely"
26115
+ ).addOption(clientIdOption()).requiredOption("--redirect-uri <uri>", "Exactly registered HTTPS callback URI").requiredOption(
26116
+ "--scope <scopes>",
26117
+ "Space-separated scopes; offline_access requests refresh tokens"
26118
+ ).action(async (opts, command) => {
26119
+ await runWithPublicClient(command, async ({ client, config }) => {
26120
+ printData(
26121
+ await client.oauth.authorize({
26122
+ clientId: opts.clientId,
26123
+ redirectUri: opts.redirectUri,
26124
+ scopes: opts.scope.trim().split(/\s+/)
26125
+ }),
26126
+ config
26127
+ );
26128
+ });
26129
+ });
26130
+ var exchangeCommand = new Command("exchange").description("Validate the callback against a saved authorization request and exchange its code").requiredOption("--request <path>", "Private JSON file returned by oauth authorize").addOption(
26131
+ new Option("--callback-url <url>", "Complete callback URL with code, state, and iss").env("ASSINAFY_OAUTH_CALLBACK_URL").makeOptionMandatory()
26132
+ ).addOption(clientSecretOption()).action(async (opts, command) => {
26133
+ await runWithPublicClient(command, async ({ client, config }) => {
26134
+ const request = parseJsonObject(
26135
+ readBinary(opts.request).toString("utf8"),
26136
+ "--request"
26137
+ );
26138
+ printData(
26139
+ await client.oauth.exchangeCode(opts.callbackUrl, request, opts.clientSecret),
26140
+ config
26141
+ );
26142
+ });
26143
+ });
26144
+ var refreshCommand = new Command("refresh").description("Rotate a refresh token once; securely persist the full response before using it").addOption(clientIdOption()).addOption(clientSecretOption()).addOption(
26145
+ new Option("--refresh-token <token>", "Current refresh token").env("ASSINAFY_OAUTH_REFRESH_TOKEN").makeOptionMandatory()
26146
+ ).option("--resource <uri>", "Resource indicator used during authorization").action(async (opts, command) => {
26147
+ await runWithPublicClient(command, async ({ client, config }) => {
26148
+ printData(
26149
+ await client.oauth.token({
26150
+ grant_type: "refresh_token",
26151
+ client_id: opts.clientId,
26152
+ client_secret: opts.clientSecret,
26153
+ refresh_token: opts.refreshToken,
26154
+ resource: opts.resource
26155
+ }),
26156
+ config
26157
+ );
26158
+ });
26159
+ });
26160
+ var revokeCommand = new Command("revoke").description("Revoke an access or refresh token for this application").addOption(clientIdOption()).addOption(clientSecretOption()).addOption(
26161
+ new Option("--revoke-token <token>", "Token to revoke").env("ASSINAFY_OAUTH_REVOKE_TOKEN").makeOptionMandatory()
26162
+ ).addOption(
26163
+ new Option("--token-type-hint <type>", "Type of token being revoked").choices([
26164
+ "access_token",
26165
+ "refresh_token"
26166
+ ])
26167
+ ).action(async (opts, command) => {
26168
+ await runWithPublicClient(command, async ({ client, config }) => {
26169
+ await client.oauth.revoke({
26170
+ token: opts.revokeToken,
26171
+ client_id: opts.clientId,
26172
+ client_secret: opts.clientSecret,
26173
+ token_type_hint: opts.tokenTypeHint
26174
+ });
26175
+ printData({ revoked: true }, config);
26176
+ });
26177
+ });
26178
+ var userinfoCommand = new Command("userinfo").description("Read OIDC claims using --token / ASSINAFY_TOKEN with openid scope").action(async (_opts, command) => {
26179
+ await runWithClient(command, async ({ client, config }) => {
26180
+ printData(await client.oauth.userinfo(), config);
26181
+ });
26182
+ });
26183
+ var oauthCommand = new Command("oauth").description("OAuth 2.1 authorization, PKCE, token rotation, and OpenID Connect").addCommand(connectCommand).addCommand(metadataCommand).addCommand(discoveryCommand).addCommand(authorizeCommand).addCommand(exchangeCommand).addCommand(refreshCommand).addCommand(revokeCommand).addCommand(userinfoCommand);
26184
+
25612
26185
  // src/commands/send.ts
25613
26186
  function parseSignerSpec(spec) {
25614
26187
  const match = spec.match(/^\s*(.*?)\s*<\s*([^>]*)\s*>\s*$/);
@@ -26538,7 +27111,7 @@ function handleStreamError(err, fallback, exit = process.exit) {
26538
27111
  // package.json
26539
27112
  var package_default = {
26540
27113
  name: "@assinafy/cli",
26541
- version: "2.0.3",
27114
+ version: "2.1.2",
26542
27115
  description: "The official command-line interface for the Assinafy digital-signature API",
26543
27116
  license: "MIT",
26544
27117
  type: "module",
@@ -26567,6 +27140,10 @@ var package_default = {
26567
27140
  "install.sh",
26568
27141
  "install.ps1",
26569
27142
  "README.md",
27143
+ "README.en.md",
27144
+ "CONTRIBUTING.md",
27145
+ "SECURITY.md",
27146
+ ".env.example",
26570
27147
  "LICENSE",
26571
27148
  "THIRD_PARTY_NOTICES.md"
26572
27149
  ],
@@ -26597,7 +27174,6 @@ var package_default = {
26597
27174
  lint: "biome check .",
26598
27175
  "lint:fix": "biome check --write .",
26599
27176
  test: "vitest run",
26600
- "test:sandbox": "npm run build && node scripts/sandbox-smoke.mjs",
26601
27177
  "test:watch": "vitest",
26602
27178
  docs: "npm run build && node scripts/gen-docs.mjs",
26603
27179
  "docs:api": "node scripts/gen-api-reference.mjs",
@@ -26639,7 +27215,7 @@ var program2 = new Command().name("assinafy").description("Assinafy CLI \u2014 t
26639
27215
  `${sanitizeTerminalText(str).replace(/^error:/, () => import_picocolors7.default.red("error:"))}
26640
27216
  `
26641
27217
  )
26642
- }).version(`${PACKAGE_NAME} v${VERSION3}`, "-v, --version", "Output the current version").option("--api-key <key>", "API key (overrides env/config)").option("--token <token>", "Legacy JWT access token (overrides env/config)").option("--account-id <id>", "Default account/workspace ID (overrides env/config)").option("--base-url <url>", "API base URL (overrides env/config)").option("-p, --profile <name>", "Config profile to use (overrides ASSINAFY_PROFILE)").option("--json", "Output machine-readable JSON").option("-q, --quiet", "Suppress spinners and status messages").addHelpText(
27218
+ }).version(`${PACKAGE_NAME} v${VERSION3}`, "-v, --version", "Output the current version").option("--api-key <key>", "API key (overrides env/config)").option("--token <token>", "OAuth access token or user JWT (overrides env/config)").option("--account-id <id>", "Default account/workspace ID (overrides env/config)").option("--base-url <url>", "API base URL (overrides env/config)").option("-p, --profile <name>", "Config profile to use (overrides ASSINAFY_PROFILE)").option("--json", "Output machine-readable JSON").option("-q, --quiet", "Suppress spinners and status messages").addHelpText(
26643
27219
  "after",
26644
27220
  `
26645
27221
  ${import_picocolors7.default.gray("Examples:")}
@@ -26651,7 +27227,7 @@ ${import_picocolors7.default.gray("Examples:")}
26651
27227
 
26652
27228
  ${import_picocolors7.default.gray("Sandbox:")} target it with ${import_picocolors7.default.blue("--base-url https://sandbox.assinafy.com.br/v1")}
26653
27229
  `
26654
- ).addCommand(sendCommand).addCommand(documentsCommand).addCommand(signersCommand).addCommand(assignmentsCommand).addCommand(templatesCommand).addCommand(tagsCommand2).addCommand(fieldsCommand).addCommand(webhooksCommand).addCommand(workspacesCommand).addCommand(usersCommand).addCommand(signerCommand).addCommand(authCommand).addCommand(loginCommand2).addCommand(logoutCommand).addCommand(whoamiCommand).addCommand(configCommand).addCommand(docsCommand);
27230
+ ).addCommand(sendCommand).addCommand(documentsCommand).addCommand(signersCommand).addCommand(assignmentsCommand).addCommand(templatesCommand).addCommand(tagsCommand2).addCommand(fieldsCommand).addCommand(webhooksCommand).addCommand(workspacesCommand).addCommand(usersCommand).addCommand(signerCommand).addCommand(authCommand).addCommand(oauthCommand).addCommand(loginCommand2).addCommand(logoutCommand).addCommand(whoamiCommand).addCommand(configCommand).addCommand(docsCommand);
26655
27231
  program2.parseAsync().catch((err) => {
26656
27232
  process.stderr.write(
26657
27233
  `${import_picocolors7.default.red("error:")} ${sanitizeTerminalText(err instanceof Error ? err.message : String(err))}