@assinafy/cli 2.0.3 → 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.
- package/.env.example +54 -0
- package/CONTRIBUTING.md +29 -0
- package/README.en.md +559 -0
- package/README.md +307 -205
- package/SECURITY.md +10 -0
- package/dist/api.cjs +290 -44
- package/dist/api.cjs.map +1 -1
- package/dist/api.js +287 -43
- package/dist/api.js.map +1 -1
- package/dist/cli.cjs +564 -61
- package/dist/types/api/client.d.ts +7 -0
- package/dist/types/api/client.d.ts.map +1 -1
- package/dist/types/api/errors.d.ts +42 -1
- package/dist/types/api/errors.d.ts.map +1 -1
- package/dist/types/api/index.d.ts +1 -0
- package/dist/types/api/index.d.ts.map +1 -1
- package/dist/types/api/resources/oauth.d.ts +20 -0
- package/dist/types/api/resources/oauth.d.ts.map +1 -0
- package/dist/types/api/resources/signers.d.ts.map +1 -1
- package/dist/types/api/types.d.ts +90 -5
- package/dist/types/api/types.d.ts.map +1 -1
- package/dist/types/api/utils.d.ts +1 -1
- package/dist/types/api/utils.d.ts.map +1 -1
- package/docs/README.md +4 -2
- package/docs/api-operations.json +33 -1
- package/docs/api-reference.md +246 -12
- package/docs/migration-v2.md +6 -2
- package/docs/oauth-guide.md +343 -0
- package/docs/oauth.md +162 -0
- package/docs/releasing.md +12 -7
- package/docs/sdk-reference.md +52 -17
- package/install.ps1 +9 -2
- package/install.sh +5 -5
- package/package.json +5 -2
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
|
-
|
|
21447
|
+
validateSigningSteps(normalisedSigners);
|
|
21418
21448
|
}
|
|
21419
21449
|
return cleanParams({
|
|
21420
21450
|
method: payload.method ?? "virtual",
|
|
@@ -22181,6 +22211,174 @@ 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
|
+
throw new ValidationError("OAuth authorization was declined or failed");
|
|
22313
|
+
}
|
|
22314
|
+
return this.token({
|
|
22315
|
+
grant_type: "authorization_code",
|
|
22316
|
+
code: required(callback.searchParams.get("code"), "code"),
|
|
22317
|
+
client_id: request.client_id,
|
|
22318
|
+
client_secret: clientSecret,
|
|
22319
|
+
redirect_uri: request.redirect_uri,
|
|
22320
|
+
code_verifier: request.code_verifier,
|
|
22321
|
+
resource: request.resource
|
|
22322
|
+
});
|
|
22323
|
+
}
|
|
22324
|
+
/** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
|
|
22325
|
+
async token(payload) {
|
|
22326
|
+
required(payload.client_id, "client_id");
|
|
22327
|
+
if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
|
|
22328
|
+
if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
|
|
22329
|
+
if (payload.grant_type === "authorization_code") {
|
|
22330
|
+
required(payload.code, "code");
|
|
22331
|
+
httpsUrl(payload.redirect_uri, "redirect_uri");
|
|
22332
|
+
if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
|
|
22333
|
+
throw new ValidationError(
|
|
22334
|
+
"code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
|
|
22335
|
+
);
|
|
22336
|
+
}
|
|
22337
|
+
} else if (payload.grant_type === "refresh_token") {
|
|
22338
|
+
required(payload.refresh_token, "refresh_token");
|
|
22339
|
+
} else {
|
|
22340
|
+
throw new ValidationError("grant_type must be authorization_code or refresh_token");
|
|
22341
|
+
}
|
|
22342
|
+
return this.call(
|
|
22343
|
+
"OAuth token request failed",
|
|
22344
|
+
() => this.http.post("/oauth/token", payload, publicRequestConfig())
|
|
22345
|
+
);
|
|
22346
|
+
}
|
|
22347
|
+
/** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
|
|
22348
|
+
async revoke(payload) {
|
|
22349
|
+
required(payload.client_id, "client_id");
|
|
22350
|
+
required(payload.token, "token");
|
|
22351
|
+
if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
|
|
22352
|
+
if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
|
|
22353
|
+
throw new ValidationError("token_type_hint must be access_token or refresh_token");
|
|
22354
|
+
}
|
|
22355
|
+
await this.call(
|
|
22356
|
+
"OAuth revocation failed",
|
|
22357
|
+
() => this.http.post("/oauth/revoke", payload, publicRequestConfig())
|
|
22358
|
+
);
|
|
22359
|
+
}
|
|
22360
|
+
/** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
|
|
22361
|
+
async userinfo() {
|
|
22362
|
+
return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
|
|
22363
|
+
}
|
|
22364
|
+
};
|
|
22365
|
+
function required(value, name) {
|
|
22366
|
+
if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
|
|
22367
|
+
return value;
|
|
22368
|
+
}
|
|
22369
|
+
function httpsUrl(value, name) {
|
|
22370
|
+
let url2;
|
|
22371
|
+
try {
|
|
22372
|
+
url2 = new URL(value);
|
|
22373
|
+
} catch {
|
|
22374
|
+
throw new ValidationError(`${name} must be an absolute HTTPS URL`);
|
|
22375
|
+
}
|
|
22376
|
+
if (url2.protocol !== "https:" || url2.username || url2.password || url2.hash) {
|
|
22377
|
+
throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
|
|
22378
|
+
}
|
|
22379
|
+
return url2;
|
|
22380
|
+
}
|
|
22381
|
+
|
|
22184
22382
|
// src/api/resources/signer-documents.ts
|
|
22185
22383
|
var SignerDocumentsResource = class extends BaseResource {
|
|
22186
22384
|
/** `GET /signers/{signer_id}/document?signer-access-code=…` */
|
|
@@ -22259,7 +22457,7 @@ var SignerDocumentsResource = class extends BaseResource {
|
|
|
22259
22457
|
if (!Array.isArray(documentIds) || documentIds.length === 0) {
|
|
22260
22458
|
throw new ValidationError("documentIds must be a non-empty array");
|
|
22261
22459
|
}
|
|
22262
|
-
|
|
22460
|
+
validateDeclineReason(declineReason);
|
|
22263
22461
|
const code = this.requireId(signerAccessCode, "signer-access-code");
|
|
22264
22462
|
return this.call(
|
|
22265
22463
|
"Failed to decline multiple documents",
|
|
@@ -22389,7 +22587,7 @@ var SignerDocumentsResource = class extends BaseResource {
|
|
|
22389
22587
|
const did = this.requireId(documentId, "Document ID");
|
|
22390
22588
|
const aid = this.requireId(assignmentId, "Assignment ID");
|
|
22391
22589
|
const code = this.requireId(signerAccessCode, "signer-access-code");
|
|
22392
|
-
|
|
22590
|
+
validateDeclineReason(declineReason);
|
|
22393
22591
|
return this.call(
|
|
22394
22592
|
"Failed to decline assignment",
|
|
22395
22593
|
() => this.http.put(
|
|
@@ -22400,6 +22598,14 @@ var SignerDocumentsResource = class extends BaseResource {
|
|
|
22400
22598
|
);
|
|
22401
22599
|
}
|
|
22402
22600
|
};
|
|
22601
|
+
function validateDeclineReason(value) {
|
|
22602
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
22603
|
+
throw new ValidationError("declineReason is required");
|
|
22604
|
+
}
|
|
22605
|
+
if ([...value].length > 2e3) {
|
|
22606
|
+
throw new ValidationError("declineReason must contain at most 2000 characters");
|
|
22607
|
+
}
|
|
22608
|
+
}
|
|
22403
22609
|
|
|
22404
22610
|
// src/api/resources/signers.ts
|
|
22405
22611
|
function validateCreateSignerPayload(payload) {
|
|
@@ -22489,9 +22695,13 @@ var SignerResource = class extends BaseResource {
|
|
|
22489
22695
|
async findByEmail(email, accountId) {
|
|
22490
22696
|
requireEmail(email);
|
|
22491
22697
|
try {
|
|
22492
|
-
const { data } = await this.list({ search: email, per_page: 100 }, accountId);
|
|
22493
22698
|
const lower = email.toLowerCase();
|
|
22494
|
-
|
|
22699
|
+
for (let page = 1; ; page++) {
|
|
22700
|
+
const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
|
|
22701
|
+
const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
|
|
22702
|
+
if (match) return match;
|
|
22703
|
+
if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
|
|
22704
|
+
}
|
|
22495
22705
|
} catch (err) {
|
|
22496
22706
|
if (err instanceof ApiError && err.statusCode === 404) {
|
|
22497
22707
|
return null;
|
|
@@ -22861,7 +23071,7 @@ function validateNotificationSender(value) {
|
|
|
22861
23071
|
}
|
|
22862
23072
|
|
|
22863
23073
|
// src/api/support/webhook-verifier.ts
|
|
22864
|
-
var
|
|
23074
|
+
var import_node_crypto2 = require("crypto");
|
|
22865
23075
|
var WebhookVerifier = class {
|
|
22866
23076
|
constructor(webhookSecret, options = {}) {
|
|
22867
23077
|
this.webhookSecret = webhookSecret;
|
|
@@ -22876,12 +23086,12 @@ var WebhookVerifier = class {
|
|
|
22876
23086
|
if (!this.webhookSecret || !signature) return false;
|
|
22877
23087
|
try {
|
|
22878
23088
|
const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
|
|
22879
|
-
const expected = (0,
|
|
23089
|
+
const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
|
|
22880
23090
|
const provided = signature.trim();
|
|
22881
23091
|
const a2 = Buffer.from(expected, "utf8");
|
|
22882
23092
|
const b = Buffer.from(provided, "utf8");
|
|
22883
23093
|
if (a2.length !== b.length) return false;
|
|
22884
|
-
return (0,
|
|
23094
|
+
return (0, import_node_crypto2.timingSafeEqual)(a2, b);
|
|
22885
23095
|
} catch {
|
|
22886
23096
|
return false;
|
|
22887
23097
|
}
|
|
@@ -22923,6 +23133,9 @@ var WebhookVerifier = class {
|
|
|
22923
23133
|
|
|
22924
23134
|
// src/api/client.ts
|
|
22925
23135
|
var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
|
|
23136
|
+
function isLoopbackHost(hostname) {
|
|
23137
|
+
return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
|
|
23138
|
+
}
|
|
22926
23139
|
var AssinafyClient = class _AssinafyClient {
|
|
22927
23140
|
axiosInstance;
|
|
22928
23141
|
defaultAccountId;
|
|
@@ -22936,6 +23149,7 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
22936
23149
|
templates;
|
|
22937
23150
|
tags;
|
|
22938
23151
|
auth;
|
|
23152
|
+
oauth;
|
|
22939
23153
|
fields;
|
|
22940
23154
|
users;
|
|
22941
23155
|
signerDocuments;
|
|
@@ -22943,7 +23157,7 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
22943
23157
|
constructor(options) {
|
|
22944
23158
|
if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
|
|
22945
23159
|
throw new ValidationError(
|
|
22946
|
-
"An API key (options.apiKey) or
|
|
23160
|
+
"An API key (options.apiKey) or access token (options.token) is required."
|
|
22947
23161
|
);
|
|
22948
23162
|
}
|
|
22949
23163
|
if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
|
|
@@ -22959,13 +23173,17 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
22959
23173
|
} catch {
|
|
22960
23174
|
throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
|
|
22961
23175
|
}
|
|
22962
|
-
if (
|
|
22963
|
-
|
|
22964
|
-
|
|
22965
|
-
|
|
22966
|
-
|
|
22967
|
-
|
|
22968
|
-
)
|
|
23176
|
+
if (parsedBaseUrl.protocol !== "https:") {
|
|
23177
|
+
if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
|
|
23178
|
+
throw new ValidationError(
|
|
23179
|
+
"baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
|
|
23180
|
+
);
|
|
23181
|
+
}
|
|
23182
|
+
if (!isLoopbackHost(parsedBaseUrl.hostname)) {
|
|
23183
|
+
throw new ValidationError(
|
|
23184
|
+
"allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
|
|
23185
|
+
);
|
|
23186
|
+
}
|
|
22969
23187
|
}
|
|
22970
23188
|
if (parsedBaseUrl.username || parsedBaseUrl.password) {
|
|
22971
23189
|
throw new ValidationError("baseUrl must not contain embedded credentials");
|
|
@@ -23001,6 +23219,7 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
23001
23219
|
this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
|
|
23002
23220
|
this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
|
|
23003
23221
|
this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
|
|
23222
|
+
this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
|
|
23004
23223
|
this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
|
|
23005
23224
|
this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
|
|
23006
23225
|
this.signerDocuments = new SignerDocumentsResource(
|
|
@@ -23036,13 +23255,22 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
23036
23255
|
/**
|
|
23037
23256
|
* High-level helper that uploads a PDF, ensures it's processed, creates any
|
|
23038
23257
|
* missing signers, and kicks off a virtual signature assignment.
|
|
23258
|
+
*
|
|
23259
|
+
* Once the upload succeeds the workflow owns real workspace resources, so any
|
|
23260
|
+
* later failure is rethrown as a {@link PartialWorkflowError} carrying the
|
|
23261
|
+
* document and signer IDs that already exist. Catch it to resume or clean up;
|
|
23262
|
+
* nothing is deleted automatically.
|
|
23039
23263
|
*/
|
|
23040
23264
|
async uploadAndRequestSignatures(options) {
|
|
23041
|
-
if (!options.signers || options.signers.length === 0) {
|
|
23265
|
+
if (!Array.isArray(options.signers) || options.signers.length === 0) {
|
|
23042
23266
|
throw new ValidationError("At least one signer is required");
|
|
23043
23267
|
}
|
|
23044
23268
|
if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
|
|
23045
23269
|
const preparedSigners = options.signers.map((signer) => {
|
|
23270
|
+
if (!signer || typeof signer !== "object") {
|
|
23271
|
+
throw new ValidationError("Each signer must be an object");
|
|
23272
|
+
}
|
|
23273
|
+
validateSignerOptions(signer);
|
|
23046
23274
|
const payload = { full_name: signer.name };
|
|
23047
23275
|
if (signer.email !== void 0) payload.email = signer.email;
|
|
23048
23276
|
const phone = signer.whatsapp_phone_number ?? signer.phone;
|
|
@@ -23052,6 +23280,7 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
23052
23280
|
validateCreateSignerPayload(payload);
|
|
23053
23281
|
return { signer, payload, phone };
|
|
23054
23282
|
});
|
|
23283
|
+
validateSigningSteps(options.signers);
|
|
23055
23284
|
this.logger.info("Starting upload + signature workflow", {
|
|
23056
23285
|
signerCount: options.signers.length
|
|
23057
23286
|
});
|
|
@@ -23059,33 +23288,46 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
23059
23288
|
if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
|
|
23060
23289
|
if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
|
|
23061
23290
|
const document2 = await this.documents.upload(options.source, uploadOpts);
|
|
23062
|
-
if (options.waitForReady !== false) {
|
|
23063
|
-
await this.documents.waitUntilReady(document2.id);
|
|
23064
|
-
}
|
|
23065
23291
|
const signerIds = [];
|
|
23066
|
-
|
|
23067
|
-
|
|
23068
|
-
|
|
23069
|
-
|
|
23070
|
-
const
|
|
23071
|
-
|
|
23072
|
-
|
|
23073
|
-
|
|
23074
|
-
|
|
23075
|
-
|
|
23292
|
+
try {
|
|
23293
|
+
if (options.waitForReady !== false) {
|
|
23294
|
+
await this.documents.waitUntilReady(document2.id);
|
|
23295
|
+
}
|
|
23296
|
+
const assignmentSigners = [];
|
|
23297
|
+
for (const { signer, payload, phone } of preparedSigners) {
|
|
23298
|
+
const created = await this.signers.create(payload, options.accountId);
|
|
23299
|
+
signerIds.push(created.id);
|
|
23300
|
+
const useWhatsapp = phone !== void 0 && signer.email === void 0;
|
|
23301
|
+
assignmentSigners.push({
|
|
23302
|
+
id: created.id,
|
|
23303
|
+
verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
|
|
23304
|
+
notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
|
|
23305
|
+
step: signer.step
|
|
23306
|
+
});
|
|
23307
|
+
}
|
|
23308
|
+
const assignmentPayload = {
|
|
23309
|
+
method: "virtual",
|
|
23310
|
+
signers: assignmentSigners
|
|
23311
|
+
};
|
|
23312
|
+
if (options.message !== void 0) assignmentPayload.message = options.message;
|
|
23313
|
+
if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
|
|
23314
|
+
if (options.copyReceivers !== void 0)
|
|
23315
|
+
assignmentPayload.copy_receivers = options.copyReceivers;
|
|
23316
|
+
const assignment = await this.assignments.create(document2.id, assignmentPayload);
|
|
23317
|
+
this.logger.info("Upload + signature workflow completed", { documentId: document2.id });
|
|
23318
|
+
return { document: document2, assignment, signer_ids: signerIds };
|
|
23319
|
+
} catch (err) {
|
|
23320
|
+
this.logger.error("Upload + signature workflow failed after creating resources", {
|
|
23321
|
+
documentId: document2.id,
|
|
23322
|
+
signerIds
|
|
23076
23323
|
});
|
|
23324
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
23325
|
+
throw new PartialWorkflowError(
|
|
23326
|
+
`${reason} (document ${document2.id} exists; ${signerIds.length} signer(s) created or reused)`,
|
|
23327
|
+
{ documentId: document2.id, signerIds },
|
|
23328
|
+
{ cause: err }
|
|
23329
|
+
);
|
|
23077
23330
|
}
|
|
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
23331
|
}
|
|
23090
23332
|
/** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
|
|
23091
23333
|
getAxiosInstance() {
|
|
@@ -23113,8 +23355,22 @@ function normalizeError(err) {
|
|
|
23113
23355
|
message: err.message,
|
|
23114
23356
|
code: "api_error",
|
|
23115
23357
|
statusCode: err.statusCode,
|
|
23116
|
-
details: err.responseData ?? void 0
|
|
23358
|
+
details: err.responseData ?? void 0,
|
|
23359
|
+
...err.wwwAuthenticate ? { wwwAuthenticate: err.wwwAuthenticate } : {},
|
|
23360
|
+
...err.retryAfter ? { retryAfter: err.retryAfter } : {}
|
|
23361
|
+
};
|
|
23362
|
+
}
|
|
23363
|
+
if (err instanceof PartialWorkflowError) {
|
|
23364
|
+
const cause = normalizeError(err.cause);
|
|
23365
|
+
const normalized = {
|
|
23366
|
+
message: err.message,
|
|
23367
|
+
code: cause.code,
|
|
23368
|
+
details: err.context
|
|
23117
23369
|
};
|
|
23370
|
+
if (cause.statusCode !== void 0) normalized.statusCode = cause.statusCode;
|
|
23371
|
+
if (cause.wwwAuthenticate !== void 0) normalized.wwwAuthenticate = cause.wwwAuthenticate;
|
|
23372
|
+
if (cause.retryAfter !== void 0) normalized.retryAfter = cause.retryAfter;
|
|
23373
|
+
return normalized;
|
|
23118
23374
|
}
|
|
23119
23375
|
if (err instanceof ValidationError) {
|
|
23120
23376
|
return { message: err.message, code: "validation_error", details: err.errors };
|
|
@@ -23130,6 +23386,10 @@ function normalizeError(err) {
|
|
|
23130
23386
|
}
|
|
23131
23387
|
return { message: String(err), code: "unexpected_error" };
|
|
23132
23388
|
}
|
|
23389
|
+
function errorMessage(err, fallback = "An unexpected error occurred") {
|
|
23390
|
+
const normalized = normalizeError(err);
|
|
23391
|
+
return normalized.message || fallback;
|
|
23392
|
+
}
|
|
23133
23393
|
|
|
23134
23394
|
// src/lib/client.ts
|
|
23135
23395
|
function createClient(config, options = {}) {
|
|
@@ -23324,7 +23584,7 @@ function paginationFooter(result) {
|
|
|
23324
23584
|
}
|
|
23325
23585
|
|
|
23326
23586
|
// src/lib/config.ts
|
|
23327
|
-
var
|
|
23587
|
+
var import_node_crypto3 = require("crypto");
|
|
23328
23588
|
var import_node_fs3 = require("fs");
|
|
23329
23589
|
var import_node_os = __toESM(require("os"), 1);
|
|
23330
23590
|
var import_node_path3 = __toESM(require("path"), 1);
|
|
@@ -23379,7 +23639,7 @@ function writeConfigFile(config) {
|
|
|
23379
23639
|
(0, import_node_fs3.mkdirSync)(dir, { recursive: true, mode: 448 });
|
|
23380
23640
|
}
|
|
23381
23641
|
const file = configPath();
|
|
23382
|
-
const tmp = `${file}.${(0,
|
|
23642
|
+
const tmp = `${file}.${(0, import_node_crypto3.randomUUID)()}.tmp`;
|
|
23383
23643
|
try {
|
|
23384
23644
|
(0, import_node_fs3.writeFileSync)(tmp, `${JSON.stringify(config, null, 2)}
|
|
23385
23645
|
`, {
|
|
@@ -23402,9 +23662,14 @@ function resolveConfig2(globals) {
|
|
|
23402
23662
|
const profile = file.profiles?.[profileName] ?? {};
|
|
23403
23663
|
const pick = (flag, env, stored) => flag ?? env ?? stored;
|
|
23404
23664
|
const baseUrl = pick(globals.baseUrl, process.env.ASSINAFY_BASE_URL, profile.base_url) ?? DEFAULT_BASE_URL2;
|
|
23665
|
+
const credentials = [
|
|
23666
|
+
{ apiKey: globals.apiKey, token: globals.token },
|
|
23667
|
+
{ apiKey: process.env.ASSINAFY_API_KEY, token: process.env.ASSINAFY_TOKEN },
|
|
23668
|
+
{ apiKey: profile.api_key, token: profile.token }
|
|
23669
|
+
].find(({ apiKey, token }) => apiKey !== void 0 || token !== void 0);
|
|
23405
23670
|
return {
|
|
23406
|
-
apiKey:
|
|
23407
|
-
token:
|
|
23671
|
+
apiKey: credentials?.apiKey,
|
|
23672
|
+
token: credentials?.token,
|
|
23408
23673
|
accountId: pick(globals.accountId, process.env.ASSINAFY_ACCOUNT_ID, profile.account_id),
|
|
23409
23674
|
baseUrl: normalizeBaseUrl(baseUrl),
|
|
23410
23675
|
webhookSecret: pick(void 0, process.env.ASSINAFY_WEBHOOK_SECRET, profile.webhook_secret),
|
|
@@ -24519,13 +24784,13 @@ function displayWidth(text2) {
|
|
|
24519
24784
|
}
|
|
24520
24785
|
|
|
24521
24786
|
// src/commands/assignments.ts
|
|
24522
|
-
function resolveSigners(signersJson, signerIdsCsv,
|
|
24787
|
+
function resolveSigners(signersJson, signerIdsCsv, required2 = true) {
|
|
24523
24788
|
if (signersJson) {
|
|
24524
24789
|
return parseJsonArray(signersJson, "--signers");
|
|
24525
24790
|
}
|
|
24526
24791
|
const ids = splitList(signerIdsCsv);
|
|
24527
24792
|
if (!ids || ids.length === 0) {
|
|
24528
|
-
if (!
|
|
24793
|
+
if (!required2) return [];
|
|
24529
24794
|
throw new CliError("Provide signers with --signer-ids <id1,id2> or --signers <json>.");
|
|
24530
24795
|
}
|
|
24531
24796
|
return ids;
|
|
@@ -24869,10 +25134,12 @@ var setCommand = new Command("set").description(
|
|
|
24869
25134
|
let changed = false;
|
|
24870
25135
|
if (merged.apiKey !== void 0) {
|
|
24871
25136
|
profile.api_key = merged.apiKey;
|
|
25137
|
+
profile.token = void 0;
|
|
24872
25138
|
changed = true;
|
|
24873
25139
|
}
|
|
24874
25140
|
if (merged.token !== void 0) {
|
|
24875
25141
|
profile.token = merged.token;
|
|
25142
|
+
if (merged.apiKey === void 0) profile.api_key = void 0;
|
|
24876
25143
|
changed = true;
|
|
24877
25144
|
}
|
|
24878
25145
|
if (merged.accountId !== void 0) {
|
|
@@ -25038,17 +25305,26 @@ var uploadCommand = new Command("upload").description("Upload a PDF to the works
|
|
|
25038
25305
|
const uploadOptions = { accountId };
|
|
25039
25306
|
if (metadata) uploadOptions.metadata = metadata;
|
|
25040
25307
|
if (opts.name) uploadOptions.name = opts.name;
|
|
25041
|
-
|
|
25308
|
+
let doc = await withSpinner(
|
|
25042
25309
|
"Uploading document",
|
|
25043
25310
|
config,
|
|
25044
25311
|
() => client.documents.upload({ filePath: file }, uploadOptions)
|
|
25045
25312
|
);
|
|
25046
25313
|
if (opts.wait) {
|
|
25047
|
-
|
|
25048
|
-
|
|
25049
|
-
|
|
25050
|
-
|
|
25051
|
-
|
|
25314
|
+
try {
|
|
25315
|
+
const ready = await withSpinner(
|
|
25316
|
+
"Waiting for processing",
|
|
25317
|
+
config,
|
|
25318
|
+
() => client.documents.waitUntilReady(doc.id)
|
|
25319
|
+
);
|
|
25320
|
+
doc = { ...doc, ...ready };
|
|
25321
|
+
} catch (error) {
|
|
25322
|
+
throw new PartialWorkflowError(
|
|
25323
|
+
`${errorMessage(error)} (document ${doc.id} was uploaded)`,
|
|
25324
|
+
{ documentId: doc.id },
|
|
25325
|
+
{ cause: error }
|
|
25326
|
+
);
|
|
25327
|
+
}
|
|
25052
25328
|
}
|
|
25053
25329
|
printSuccess(`Uploaded document ${doc.id}`, config);
|
|
25054
25330
|
printData(
|
|
@@ -25609,6 +25885,230 @@ var logoutCommand = new Command("logout").description("Remove stored credentials
|
|
|
25609
25885
|
});
|
|
25610
25886
|
});
|
|
25611
25887
|
|
|
25888
|
+
// src/lib/oauth-browser.ts
|
|
25889
|
+
var import_node_child_process3 = require("child_process");
|
|
25890
|
+
var import_node_crypto4 = require("crypto");
|
|
25891
|
+
var import_node_events2 = require("events");
|
|
25892
|
+
var import_node_http = require("http");
|
|
25893
|
+
var CLI_OAUTH_REDIRECT_URI = "https://integrations.assinafy.com.br/assinafy-cli/oauth-callback";
|
|
25894
|
+
var clearHistory = "history.replaceState(null, '', '/');";
|
|
25895
|
+
var callbackPage = `<!doctype html><html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Assinafy CLI</title><script>${clearHistory}</script><h1>Return to your terminal</h1><p>The authorization response was received. Check the terminal for the connection result.</p></html>`;
|
|
25896
|
+
var callbackHeaders = {
|
|
25897
|
+
"Cache-Control": "no-store",
|
|
25898
|
+
"Referrer-Policy": "no-referrer",
|
|
25899
|
+
"X-Content-Type-Options": "nosniff",
|
|
25900
|
+
"Content-Security-Policy": `default-src 'none'; script-src 'sha256-${(0, import_node_crypto4.createHash)("sha256").update(clearHistory).digest("base64")}'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
|
|
25901
|
+
Connection: "close"
|
|
25902
|
+
};
|
|
25903
|
+
function openBrowser(url2) {
|
|
25904
|
+
const [executable, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["rundll32.exe", ["url.dll,FileProtocolHandler", url2]] : ["xdg-open", [url2]];
|
|
25905
|
+
return new Promise((resolve, reject) => {
|
|
25906
|
+
const child = (0, import_node_child_process3.spawn)(executable, args, {
|
|
25907
|
+
stdio: "ignore",
|
|
25908
|
+
detached: true,
|
|
25909
|
+
windowsHide: true
|
|
25910
|
+
});
|
|
25911
|
+
child.once("error", () => reject(new CliError("Could not open the system browser.")));
|
|
25912
|
+
child.once("spawn", () => {
|
|
25913
|
+
child.unref();
|
|
25914
|
+
resolve();
|
|
25915
|
+
});
|
|
25916
|
+
});
|
|
25917
|
+
}
|
|
25918
|
+
async function connectOAuth(oauth, options, onAuthorize, timeoutMs = 18e4) {
|
|
25919
|
+
if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e5) {
|
|
25920
|
+
throw new CliError("OAuth connection timeout must be between 1 and 600000 milliseconds.");
|
|
25921
|
+
}
|
|
25922
|
+
const request = await oauth.authorize(options);
|
|
25923
|
+
if (new URL(request.redirect_uri).search) {
|
|
25924
|
+
throw new CliError("The browser relay redirect URI must not contain query parameters.");
|
|
25925
|
+
}
|
|
25926
|
+
const server = (0, import_node_http.createServer)({ maxHeaderSize: 8192, requestTimeout: 5e3, headersTimeout: 5e3 });
|
|
25927
|
+
server.maxConnections = 8;
|
|
25928
|
+
server.setTimeout(5e3, (socket) => socket.destroy());
|
|
25929
|
+
let timer;
|
|
25930
|
+
let cancel2;
|
|
25931
|
+
let terminate;
|
|
25932
|
+
let callbackUrl;
|
|
25933
|
+
try {
|
|
25934
|
+
server.listen(0, "127.0.0.1");
|
|
25935
|
+
await (0, import_node_events2.once)(server, "listening");
|
|
25936
|
+
const address = server.address();
|
|
25937
|
+
if (!address || typeof address === "string") throw new CliError("No OAuth listener address.");
|
|
25938
|
+
const host = `127.0.0.1:${address.port}`;
|
|
25939
|
+
request.state += `.${address.port}`;
|
|
25940
|
+
const expectedState = Buffer.from(request.state);
|
|
25941
|
+
const authorization = new URL(request.authorization_url);
|
|
25942
|
+
authorization.searchParams.set("state", request.state);
|
|
25943
|
+
request.authorization_url = authorization.toString();
|
|
25944
|
+
callbackUrl = await new Promise((resolve, reject) => {
|
|
25945
|
+
let consumed = false;
|
|
25946
|
+
timer = setTimeout(
|
|
25947
|
+
() => reject(new CliError("OAuth connection timed out. Start again.")),
|
|
25948
|
+
timeoutMs
|
|
25949
|
+
);
|
|
25950
|
+
cancel2 = () => reject(new CliError("OAuth connection cancelled.", { exitCode: 130 }));
|
|
25951
|
+
terminate = () => reject(new CliError("OAuth connection terminated.", { exitCode: 143 }));
|
|
25952
|
+
process.once("SIGINT", cancel2);
|
|
25953
|
+
process.once("SIGTERM", terminate);
|
|
25954
|
+
server.once("error", reject);
|
|
25955
|
+
server.on("request", (incoming, response) => {
|
|
25956
|
+
const raw = incoming.url ?? "";
|
|
25957
|
+
const url2 = new URL(raw.startsWith("/callback?") ? raw : "/invalid", `http://${host}`);
|
|
25958
|
+
const query = url2.searchParams;
|
|
25959
|
+
const state = Buffer.from(query.get("state") ?? "");
|
|
25960
|
+
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());
|
|
25961
|
+
if (!valid) {
|
|
25962
|
+
response.writeHead(400, {
|
|
25963
|
+
...callbackHeaders,
|
|
25964
|
+
"Content-Type": "text/plain; charset=utf-8"
|
|
25965
|
+
});
|
|
25966
|
+
response.end("Invalid authorization response. Continue in the original browser session.");
|
|
25967
|
+
return;
|
|
25968
|
+
}
|
|
25969
|
+
consumed = true;
|
|
25970
|
+
const callback = new URL(request.redirect_uri);
|
|
25971
|
+
for (const key of ["code", "state", "iss", "error"]) {
|
|
25972
|
+
if (query.has(key)) callback.searchParams.set(key, query.get(key));
|
|
25973
|
+
}
|
|
25974
|
+
response.writeHead(200, { ...callbackHeaders, "Content-Type": "text/html; charset=utf-8" });
|
|
25975
|
+
response.end(callbackPage, () => resolve(callback.toString()));
|
|
25976
|
+
});
|
|
25977
|
+
void Promise.resolve().then(() => onAuthorize(request.authorization_url)).catch(reject);
|
|
25978
|
+
});
|
|
25979
|
+
} finally {
|
|
25980
|
+
clearTimeout(timer);
|
|
25981
|
+
if (cancel2) process.off("SIGINT", cancel2);
|
|
25982
|
+
if (terminate) process.off("SIGTERM", terminate);
|
|
25983
|
+
await new Promise((resolve) => {
|
|
25984
|
+
server.close(() => resolve());
|
|
25985
|
+
server.closeAllConnections();
|
|
25986
|
+
});
|
|
25987
|
+
}
|
|
25988
|
+
return oauth.exchangeCode(callbackUrl, request);
|
|
25989
|
+
}
|
|
25990
|
+
|
|
25991
|
+
// src/commands/oauth.ts
|
|
25992
|
+
var clientIdOption = () => new Option("--client-id <id>", "OAuth application client ID").env("ASSINAFY_OAUTH_CLIENT_ID").default("96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88");
|
|
25993
|
+
var clientSecretOption = () => new Option(
|
|
25994
|
+
"--client-secret <secret>",
|
|
25995
|
+
"Confidential application secret; omit for public applications"
|
|
25996
|
+
).env("ASSINAFY_OAUTH_CLIENT_SECRET");
|
|
25997
|
+
var connectCommand = new Command("connect").description(
|
|
25998
|
+
"Open browser consent for a public OAuth app, receive its loopback return, and print tokens"
|
|
25999
|
+
).addOption(clientIdOption()).option("--redirect-uri <uri>", "Exactly registered HTTPS relay URI", CLI_OAUTH_REDIRECT_URI).option(
|
|
26000
|
+
"--scope <scopes>",
|
|
26001
|
+
"Space-separated scopes; defaults to all supported OAuth scopes",
|
|
26002
|
+
"account:read documents:read documents:write templates:read templates:write openid profile email offline_access"
|
|
26003
|
+
).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) => {
|
|
26004
|
+
await runWithPublicClient(command, async ({ client, config }) => {
|
|
26005
|
+
const timeout = parseInteger(opts.timeout, "--timeout", { min: 1 });
|
|
26006
|
+
const tokens = await connectOAuth(
|
|
26007
|
+
client.oauth,
|
|
26008
|
+
{
|
|
26009
|
+
clientId: opts.clientId,
|
|
26010
|
+
redirectUri: opts.redirectUri,
|
|
26011
|
+
scopes: opts.scope.trim().split(/\s+/)
|
|
26012
|
+
},
|
|
26013
|
+
async (url2) => {
|
|
26014
|
+
process.stderr.write(
|
|
26015
|
+
`Open this URL in a browser on this computer:
|
|
26016
|
+
${sanitizeTerminalText(url2)}
|
|
26017
|
+
`
|
|
26018
|
+
);
|
|
26019
|
+
if (opts.browser) {
|
|
26020
|
+
await openBrowser(url2).catch(() => {
|
|
26021
|
+
process.stderr.write("Could not open the browser. Open the URL above manually.\n");
|
|
26022
|
+
});
|
|
26023
|
+
}
|
|
26024
|
+
},
|
|
26025
|
+
timeout * 1e3
|
|
26026
|
+
);
|
|
26027
|
+
printData(tokens, config);
|
|
26028
|
+
});
|
|
26029
|
+
});
|
|
26030
|
+
var metadataCommand = new Command("metadata").description("Read protected-resource metadata from the API origin").action(async (_opts, command) => {
|
|
26031
|
+
await runWithPublicClient(command, async ({ client, config }) => {
|
|
26032
|
+
printData(await client.oauth.metadata(), config);
|
|
26033
|
+
});
|
|
26034
|
+
});
|
|
26035
|
+
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) => {
|
|
26036
|
+
await runWithPublicClient(command, async ({ client, config }) => {
|
|
26037
|
+
printData(await client.oauth.discovery(issuer), config);
|
|
26038
|
+
});
|
|
26039
|
+
});
|
|
26040
|
+
var authorizeCommand = new Command("authorize").description(
|
|
26041
|
+
"Create an authorization URL and a sensitive PKCE/state request; save the JSON securely"
|
|
26042
|
+
).addOption(clientIdOption()).requiredOption("--redirect-uri <uri>", "Exactly registered HTTPS callback URI").requiredOption(
|
|
26043
|
+
"--scope <scopes>",
|
|
26044
|
+
"Space-separated scopes; offline_access requests refresh tokens"
|
|
26045
|
+
).action(async (opts, command) => {
|
|
26046
|
+
await runWithPublicClient(command, async ({ client, config }) => {
|
|
26047
|
+
printData(
|
|
26048
|
+
await client.oauth.authorize({
|
|
26049
|
+
clientId: opts.clientId,
|
|
26050
|
+
redirectUri: opts.redirectUri,
|
|
26051
|
+
scopes: opts.scope.trim().split(/\s+/)
|
|
26052
|
+
}),
|
|
26053
|
+
config
|
|
26054
|
+
);
|
|
26055
|
+
});
|
|
26056
|
+
});
|
|
26057
|
+
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(
|
|
26058
|
+
new Option("--callback-url <url>", "Complete callback URL with code, state, and iss").env("ASSINAFY_OAUTH_CALLBACK_URL").makeOptionMandatory()
|
|
26059
|
+
).addOption(clientSecretOption()).action(async (opts, command) => {
|
|
26060
|
+
await runWithPublicClient(command, async ({ client, config }) => {
|
|
26061
|
+
const request = parseJsonObject(
|
|
26062
|
+
readBinary(opts.request).toString("utf8"),
|
|
26063
|
+
"--request"
|
|
26064
|
+
);
|
|
26065
|
+
printData(
|
|
26066
|
+
await client.oauth.exchangeCode(opts.callbackUrl, request, opts.clientSecret),
|
|
26067
|
+
config
|
|
26068
|
+
);
|
|
26069
|
+
});
|
|
26070
|
+
});
|
|
26071
|
+
var refreshCommand = new Command("refresh").description("Rotate a refresh token once; securely persist the full response before using it").addOption(clientIdOption()).addOption(clientSecretOption()).addOption(
|
|
26072
|
+
new Option("--refresh-token <token>", "Current refresh token").env("ASSINAFY_OAUTH_REFRESH_TOKEN").makeOptionMandatory()
|
|
26073
|
+
).option("--resource <uri>", "Resource indicator used during authorization").action(async (opts, command) => {
|
|
26074
|
+
await runWithPublicClient(command, async ({ client, config }) => {
|
|
26075
|
+
printData(
|
|
26076
|
+
await client.oauth.token({
|
|
26077
|
+
grant_type: "refresh_token",
|
|
26078
|
+
client_id: opts.clientId,
|
|
26079
|
+
client_secret: opts.clientSecret,
|
|
26080
|
+
refresh_token: opts.refreshToken,
|
|
26081
|
+
resource: opts.resource
|
|
26082
|
+
}),
|
|
26083
|
+
config
|
|
26084
|
+
);
|
|
26085
|
+
});
|
|
26086
|
+
});
|
|
26087
|
+
var revokeCommand = new Command("revoke").description("Revoke an access or refresh token for this application").addOption(clientIdOption()).addOption(clientSecretOption()).addOption(
|
|
26088
|
+
new Option("--revoke-token <token>", "Token to revoke").env("ASSINAFY_OAUTH_REVOKE_TOKEN").makeOptionMandatory()
|
|
26089
|
+
).addOption(
|
|
26090
|
+
new Option("--token-type-hint <type>", "Type of token being revoked").choices([
|
|
26091
|
+
"access_token",
|
|
26092
|
+
"refresh_token"
|
|
26093
|
+
])
|
|
26094
|
+
).action(async (opts, command) => {
|
|
26095
|
+
await runWithPublicClient(command, async ({ client, config }) => {
|
|
26096
|
+
await client.oauth.revoke({
|
|
26097
|
+
token: opts.revokeToken,
|
|
26098
|
+
client_id: opts.clientId,
|
|
26099
|
+
client_secret: opts.clientSecret,
|
|
26100
|
+
token_type_hint: opts.tokenTypeHint
|
|
26101
|
+
});
|
|
26102
|
+
printData({ revoked: true }, config);
|
|
26103
|
+
});
|
|
26104
|
+
});
|
|
26105
|
+
var userinfoCommand = new Command("userinfo").description("Read OIDC claims using --token / ASSINAFY_TOKEN with openid scope").action(async (_opts, command) => {
|
|
26106
|
+
await runWithClient(command, async ({ client, config }) => {
|
|
26107
|
+
printData(await client.oauth.userinfo(), config);
|
|
26108
|
+
});
|
|
26109
|
+
});
|
|
26110
|
+
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);
|
|
26111
|
+
|
|
25612
26112
|
// src/commands/send.ts
|
|
25613
26113
|
function parseSignerSpec(spec) {
|
|
25614
26114
|
const match = spec.match(/^\s*(.*?)\s*<\s*([^>]*)\s*>\s*$/);
|
|
@@ -26538,7 +27038,7 @@ function handleStreamError(err, fallback, exit = process.exit) {
|
|
|
26538
27038
|
// package.json
|
|
26539
27039
|
var package_default = {
|
|
26540
27040
|
name: "@assinafy/cli",
|
|
26541
|
-
version: "2.
|
|
27041
|
+
version: "2.1.1",
|
|
26542
27042
|
description: "The official command-line interface for the Assinafy digital-signature API",
|
|
26543
27043
|
license: "MIT",
|
|
26544
27044
|
type: "module",
|
|
@@ -26567,6 +27067,10 @@ var package_default = {
|
|
|
26567
27067
|
"install.sh",
|
|
26568
27068
|
"install.ps1",
|
|
26569
27069
|
"README.md",
|
|
27070
|
+
"README.en.md",
|
|
27071
|
+
"CONTRIBUTING.md",
|
|
27072
|
+
"SECURITY.md",
|
|
27073
|
+
".env.example",
|
|
26570
27074
|
"LICENSE",
|
|
26571
27075
|
"THIRD_PARTY_NOTICES.md"
|
|
26572
27076
|
],
|
|
@@ -26597,7 +27101,6 @@ var package_default = {
|
|
|
26597
27101
|
lint: "biome check .",
|
|
26598
27102
|
"lint:fix": "biome check --write .",
|
|
26599
27103
|
test: "vitest run",
|
|
26600
|
-
"test:sandbox": "npm run build && node scripts/sandbox-smoke.mjs",
|
|
26601
27104
|
"test:watch": "vitest",
|
|
26602
27105
|
docs: "npm run build && node scripts/gen-docs.mjs",
|
|
26603
27106
|
"docs:api": "node scripts/gen-api-reference.mjs",
|
|
@@ -26639,7 +27142,7 @@ var program2 = new Command().name("assinafy").description("Assinafy CLI \u2014 t
|
|
|
26639
27142
|
`${sanitizeTerminalText(str).replace(/^error:/, () => import_picocolors7.default.red("error:"))}
|
|
26640
27143
|
`
|
|
26641
27144
|
)
|
|
26642
|
-
}).version(`${PACKAGE_NAME} v${VERSION3}`, "-v, --version", "Output the current version").option("--api-key <key>", "API key (overrides env/config)").option("--token <token>", "
|
|
27145
|
+
}).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
27146
|
"after",
|
|
26644
27147
|
`
|
|
26645
27148
|
${import_picocolors7.default.gray("Examples:")}
|
|
@@ -26651,7 +27154,7 @@ ${import_picocolors7.default.gray("Examples:")}
|
|
|
26651
27154
|
|
|
26652
27155
|
${import_picocolors7.default.gray("Sandbox:")} target it with ${import_picocolors7.default.blue("--base-url https://sandbox.assinafy.com.br/v1")}
|
|
26653
27156
|
`
|
|
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);
|
|
27157
|
+
).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
27158
|
program2.parseAsync().catch((err) => {
|
|
26656
27159
|
process.stderr.write(
|
|
26657
27160
|
`${import_picocolors7.default.red("error:")} ${sanitizeTerminalText(err instanceof Error ? err.message : String(err))}
|