@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/.env.example +54 -0
- package/CONTRIBUTING.md +29 -0
- package/README.en.md +561 -0
- package/README.md +309 -205
- package/SECURITY.md +10 -0
- package/dist/api.cjs +294 -44
- package/dist/api.cjs.map +1 -1
- package/dist/api.js +291 -43
- package/dist/api.js.map +1 -1
- package/dist/cli.cjs +637 -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 +347 -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/SECURITY.md
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# Security policy
|
|
2
|
+
|
|
3
|
+
Security fixes are supported on the latest published version.
|
|
4
|
+
|
|
5
|
+
Report vulnerabilities through the repository's private **Security → Report a
|
|
6
|
+
vulnerability** form. If private reporting is unavailable, ask a project maintainer
|
|
7
|
+
for a private reporting channel without disclosing details in a public issue.
|
|
8
|
+
|
|
9
|
+
Include affected versions, reproduction steps, impact, and any suggested mitigation.
|
|
10
|
+
Do not include real API keys, signer access codes, documents, or personal data.
|
package/dist/api.cjs
CHANGED
|
@@ -39,6 +39,8 @@ __export(api_exports, {
|
|
|
39
39
|
FieldsResource: () => FieldsResource,
|
|
40
40
|
NOTIFICATION_PREFERENCE_CODES: () => NOTIFICATION_PREFERENCE_CODES,
|
|
41
41
|
NetworkError: () => NetworkError,
|
|
42
|
+
OAuthResource: () => OAuthResource,
|
|
43
|
+
PartialWorkflowError: () => PartialWorkflowError,
|
|
42
44
|
SignerDocumentsResource: () => SignerDocumentsResource,
|
|
43
45
|
SignerResource: () => SignerResource,
|
|
44
46
|
TagResource: () => TagResource,
|
|
@@ -68,18 +70,35 @@ var AssinafyError = class extends Error {
|
|
|
68
70
|
var ApiError = class _ApiError extends AssinafyError {
|
|
69
71
|
statusCode;
|
|
70
72
|
responseData;
|
|
73
|
+
/** Bearer challenge, including insufficient_scope and resource_metadata when provided. */
|
|
74
|
+
wwwAuthenticate;
|
|
75
|
+
/** Server retry delay (seconds or HTTP date), when provided. */
|
|
76
|
+
retryAfter;
|
|
71
77
|
constructor(message, statusCode, responseData = null, options) {
|
|
72
78
|
super(message, { statusCode, responseData }, options);
|
|
73
79
|
this.name = "ApiError";
|
|
74
80
|
this.statusCode = statusCode;
|
|
75
81
|
this.responseData = responseData;
|
|
82
|
+
this.wwwAuthenticate = options?.wwwAuthenticate;
|
|
83
|
+
this.retryAfter = options?.retryAfter;
|
|
76
84
|
}
|
|
77
|
-
static fromResponse(statusCode, responseData) {
|
|
85
|
+
static fromResponse(statusCode, responseData, headers = {}) {
|
|
86
|
+
if (Buffer.isBuffer(responseData) || responseData instanceof ArrayBuffer) {
|
|
87
|
+
const text = (Buffer.isBuffer(responseData) ? responseData : Buffer.from(responseData)).toString("utf8");
|
|
88
|
+
try {
|
|
89
|
+
responseData = JSON.parse(text);
|
|
90
|
+
} catch {
|
|
91
|
+
responseData = text;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
78
94
|
const data = responseData ?? {};
|
|
79
95
|
const rawMessage = data.message;
|
|
80
96
|
const rawError = data.error;
|
|
81
97
|
const message = typeof rawMessage === "string" && rawMessage.length > 0 ? rawMessage : typeof rawError === "string" ? rawError : "API request failed";
|
|
82
|
-
return new _ApiError(message, statusCode, responseData
|
|
98
|
+
return new _ApiError(message, statusCode, responseData, {
|
|
99
|
+
wwwAuthenticate: typeof headers["www-authenticate"] === "string" ? headers["www-authenticate"] : void 0,
|
|
100
|
+
retryAfter: typeof headers["retry-after"] === "string" ? headers["retry-after"] : void 0
|
|
101
|
+
});
|
|
83
102
|
}
|
|
84
103
|
};
|
|
85
104
|
var ValidationError = class extends AssinafyError {
|
|
@@ -96,6 +115,19 @@ var NetworkError = class extends AssinafyError {
|
|
|
96
115
|
this.name = "NetworkError";
|
|
97
116
|
}
|
|
98
117
|
};
|
|
118
|
+
var PartialWorkflowError = class extends AssinafyError {
|
|
119
|
+
/** The document that was uploaded before the failure, if any. */
|
|
120
|
+
documentId;
|
|
121
|
+
/** IDs of every signer created (or reused) before the failure. */
|
|
122
|
+
signerIds;
|
|
123
|
+
constructor(message, created, options) {
|
|
124
|
+
const signerIds = created.signerIds ?? [];
|
|
125
|
+
super(message, { documentId: created.documentId, signerIds }, options);
|
|
126
|
+
this.name = "PartialWorkflowError";
|
|
127
|
+
this.documentId = created.documentId;
|
|
128
|
+
this.signerIds = signerIds;
|
|
129
|
+
}
|
|
130
|
+
};
|
|
99
131
|
|
|
100
132
|
// src/api/utils.ts
|
|
101
133
|
var import_axios = __toESM(require("axios"), 1);
|
|
@@ -130,7 +162,7 @@ function toSdkError(error, fallbackMessage) {
|
|
|
130
162
|
if (import_axios.default.isAxiosError(error)) {
|
|
131
163
|
const status = error.response?.status;
|
|
132
164
|
if (status) {
|
|
133
|
-
return ApiError.fromResponse(status, error.response?.data ?? null);
|
|
165
|
+
return ApiError.fromResponse(status, error.response?.data ?? null, error.response?.headers);
|
|
134
166
|
}
|
|
135
167
|
return new NetworkError(`${fallbackMessage}: ${error.message}`);
|
|
136
168
|
}
|
|
@@ -394,7 +426,7 @@ function buildAssignmentPayload(payload, options = {}) {
|
|
|
394
426
|
}
|
|
395
427
|
const normalisedSigners = signers.map((ref) => normaliseSignerRef(ref, options));
|
|
396
428
|
if (!options.skipDigitalCertificateStepValidation) {
|
|
397
|
-
|
|
429
|
+
validateSigningSteps(normalisedSigners);
|
|
398
430
|
}
|
|
399
431
|
return cleanParams({
|
|
400
432
|
method: payload.method ?? "virtual",
|
|
@@ -1161,6 +1193,178 @@ function validationConfig(signerAccessCode) {
|
|
|
1161
1193
|
return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
|
|
1162
1194
|
}
|
|
1163
1195
|
|
|
1196
|
+
// src/api/resources/oauth.ts
|
|
1197
|
+
var import_node_crypto = require("crypto");
|
|
1198
|
+
var OAuthResource = class extends BaseResource {
|
|
1199
|
+
/** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
|
|
1200
|
+
async metadata() {
|
|
1201
|
+
return this.call(
|
|
1202
|
+
"Failed to discover OAuth resource",
|
|
1203
|
+
() => this.http.get(
|
|
1204
|
+
"/.well-known/oauth-protected-resource",
|
|
1205
|
+
publicRequestConfig({
|
|
1206
|
+
baseURL: new URL(this.http.defaults.baseURL).origin
|
|
1207
|
+
})
|
|
1208
|
+
)
|
|
1209
|
+
);
|
|
1210
|
+
}
|
|
1211
|
+
/** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
|
|
1212
|
+
async discovery(issuer) {
|
|
1213
|
+
const url = httpsUrl(issuer, "issuer");
|
|
1214
|
+
if (url.search || url.pathname !== "/") {
|
|
1215
|
+
throw new ValidationError("issuer must be an HTTPS origin");
|
|
1216
|
+
}
|
|
1217
|
+
const metadata = await this.call(
|
|
1218
|
+
"Failed to discover OAuth authorization server",
|
|
1219
|
+
() => this.http.get(
|
|
1220
|
+
`${url.origin}/.well-known/oauth-authorization-server`,
|
|
1221
|
+
publicRequestConfig()
|
|
1222
|
+
)
|
|
1223
|
+
);
|
|
1224
|
+
if (metadata.issuer !== issuer) throw new ValidationError("OAuth issuer mismatch");
|
|
1225
|
+
httpsUrl(metadata.authorization_endpoint, "authorization_endpoint");
|
|
1226
|
+
return metadata;
|
|
1227
|
+
}
|
|
1228
|
+
/** Discover endpoints and create a fresh authorization URL, PKCE verifier, and state. */
|
|
1229
|
+
async authorize(options) {
|
|
1230
|
+
required(options.clientId, "clientId");
|
|
1231
|
+
httpsUrl(options.redirectUri, "redirectUri");
|
|
1232
|
+
if (!Array.isArray(options.scopes) || options.scopes.length === 0 || options.scopes.some(
|
|
1233
|
+
(scope) => typeof scope !== "string" || !/^[\x21\x23-\x5B\x5D-\x7E]+$/.test(scope)
|
|
1234
|
+
)) {
|
|
1235
|
+
throw new ValidationError("scopes must contain non-empty OAuth scope names");
|
|
1236
|
+
}
|
|
1237
|
+
const resource = await this.metadata();
|
|
1238
|
+
const issuer = resource.authorization_servers?.[0];
|
|
1239
|
+
if (!issuer) throw new ValidationError("OAuth metadata has no authorization server");
|
|
1240
|
+
httpsUrl(resource.resource, "resource");
|
|
1241
|
+
const server = await this.discovery(issuer);
|
|
1242
|
+
const codeVerifier = (0, import_node_crypto.randomBytes)(32).toString("base64url");
|
|
1243
|
+
const state = (0, import_node_crypto.randomBytes)(32).toString("base64url");
|
|
1244
|
+
const nonce = options.scopes.includes("openid") ? (0, import_node_crypto.randomBytes)(32).toString("base64url") : void 0;
|
|
1245
|
+
const url = new URL(server.authorization_endpoint);
|
|
1246
|
+
const params = {
|
|
1247
|
+
response_type: "code",
|
|
1248
|
+
client_id: options.clientId,
|
|
1249
|
+
redirect_uri: options.redirectUri,
|
|
1250
|
+
scope: options.scopes.join(" "),
|
|
1251
|
+
state,
|
|
1252
|
+
code_challenge: (0, import_node_crypto.createHash)("sha256").update(codeVerifier).digest("base64url"),
|
|
1253
|
+
code_challenge_method: "S256",
|
|
1254
|
+
resource: resource.resource
|
|
1255
|
+
};
|
|
1256
|
+
for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
|
|
1257
|
+
if (nonce) url.searchParams.set("nonce", nonce);
|
|
1258
|
+
return {
|
|
1259
|
+
authorization_url: url.toString(),
|
|
1260
|
+
code_verifier: codeVerifier,
|
|
1261
|
+
state,
|
|
1262
|
+
issuer,
|
|
1263
|
+
client_id: options.clientId,
|
|
1264
|
+
redirect_uri: options.redirectUri,
|
|
1265
|
+
resource: resource.resource,
|
|
1266
|
+
...nonce ? { nonce } : {}
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
/** Validate callback URI, state, and issuer before exchanging its one-time code. */
|
|
1270
|
+
async exchangeCode(callbackUrl, request, clientSecret) {
|
|
1271
|
+
const callback = httpsUrl(callbackUrl, "callbackUrl");
|
|
1272
|
+
const redirect = httpsUrl(request.redirect_uri, "redirect_uri");
|
|
1273
|
+
if (callback.origin !== redirect.origin || callback.pathname !== redirect.pathname || [...new Set(redirect.searchParams.keys())].some((key) => {
|
|
1274
|
+
const expected2 = redirect.searchParams.getAll(key);
|
|
1275
|
+
const actual2 = callback.searchParams.getAll(key);
|
|
1276
|
+
return expected2.length !== actual2.length || expected2.some((value, i) => value !== actual2[i]);
|
|
1277
|
+
})) {
|
|
1278
|
+
throw new ValidationError("OAuth callback does not match the registered redirect URI");
|
|
1279
|
+
}
|
|
1280
|
+
for (const key of ["state", "iss", "code", "error"]) {
|
|
1281
|
+
if (callback.searchParams.getAll(key).length > 1) {
|
|
1282
|
+
throw new ValidationError(`Duplicate OAuth callback parameter: ${key}`);
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
const actual = Buffer.from(callback.searchParams.get("state") ?? "");
|
|
1286
|
+
const expected = Buffer.from(required(request.state, "state"));
|
|
1287
|
+
if (actual.length !== expected.length || !(0, import_node_crypto.timingSafeEqual)(actual, expected)) {
|
|
1288
|
+
throw new ValidationError("OAuth state mismatch");
|
|
1289
|
+
}
|
|
1290
|
+
if (callback.searchParams.get("iss") !== request.issuer) {
|
|
1291
|
+
throw new ValidationError("OAuth issuer mismatch");
|
|
1292
|
+
}
|
|
1293
|
+
if (callback.searchParams.has("error")) {
|
|
1294
|
+
const error = callback.searchParams.get("error");
|
|
1295
|
+
const oauthError = error.length > 0 && error.length <= 64 && !/[^a-z_]/.test(error) ? error : "unknown_error";
|
|
1296
|
+
throw new ValidationError(`OAuth authorization was declined or failed: ${oauthError}`, {
|
|
1297
|
+
oauthError
|
|
1298
|
+
});
|
|
1299
|
+
}
|
|
1300
|
+
return this.token({
|
|
1301
|
+
grant_type: "authorization_code",
|
|
1302
|
+
code: required(callback.searchParams.get("code"), "code"),
|
|
1303
|
+
client_id: request.client_id,
|
|
1304
|
+
client_secret: clientSecret,
|
|
1305
|
+
redirect_uri: request.redirect_uri,
|
|
1306
|
+
code_verifier: request.code_verifier,
|
|
1307
|
+
resource: request.resource
|
|
1308
|
+
});
|
|
1309
|
+
}
|
|
1310
|
+
/** `POST /oauth/token` — code exchange or refresh; returns the flat OAuth JSON body. */
|
|
1311
|
+
async token(payload) {
|
|
1312
|
+
required(payload.client_id, "client_id");
|
|
1313
|
+
if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
|
|
1314
|
+
if (payload.resource !== void 0) httpsUrl(payload.resource, "resource");
|
|
1315
|
+
if (payload.grant_type === "authorization_code") {
|
|
1316
|
+
required(payload.code, "code");
|
|
1317
|
+
httpsUrl(payload.redirect_uri, "redirect_uri");
|
|
1318
|
+
if (typeof payload.code_verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(payload.code_verifier)) {
|
|
1319
|
+
throw new ValidationError(
|
|
1320
|
+
"code_verifier must contain 43\u2013128 RFC 7636 unreserved characters"
|
|
1321
|
+
);
|
|
1322
|
+
}
|
|
1323
|
+
} else if (payload.grant_type === "refresh_token") {
|
|
1324
|
+
required(payload.refresh_token, "refresh_token");
|
|
1325
|
+
} else {
|
|
1326
|
+
throw new ValidationError("grant_type must be authorization_code or refresh_token");
|
|
1327
|
+
}
|
|
1328
|
+
return this.call(
|
|
1329
|
+
"OAuth token request failed",
|
|
1330
|
+
() => this.http.post("/oauth/token", payload, publicRequestConfig())
|
|
1331
|
+
);
|
|
1332
|
+
}
|
|
1333
|
+
/** `POST /oauth/revoke` — revoke an access/refresh token; success has no required body. */
|
|
1334
|
+
async revoke(payload) {
|
|
1335
|
+
required(payload.client_id, "client_id");
|
|
1336
|
+
required(payload.token, "token");
|
|
1337
|
+
if (payload.client_secret !== void 0) required(payload.client_secret, "client_secret");
|
|
1338
|
+
if (payload.token_type_hint !== void 0 && !["access_token", "refresh_token"].includes(payload.token_type_hint)) {
|
|
1339
|
+
throw new ValidationError("token_type_hint must be access_token or refresh_token");
|
|
1340
|
+
}
|
|
1341
|
+
await this.call(
|
|
1342
|
+
"OAuth revocation failed",
|
|
1343
|
+
() => this.http.post("/oauth/revoke", payload, publicRequestConfig())
|
|
1344
|
+
);
|
|
1345
|
+
}
|
|
1346
|
+
/** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
|
|
1347
|
+
async userinfo() {
|
|
1348
|
+
return this.call("Failed to fetch OAuth userinfo", () => this.http.get("/oauth/userinfo"));
|
|
1349
|
+
}
|
|
1350
|
+
};
|
|
1351
|
+
function required(value, name) {
|
|
1352
|
+
if (typeof value !== "string" || !value.trim()) throw new ValidationError(`${name} is required`);
|
|
1353
|
+
return value;
|
|
1354
|
+
}
|
|
1355
|
+
function httpsUrl(value, name) {
|
|
1356
|
+
let url;
|
|
1357
|
+
try {
|
|
1358
|
+
url = new URL(value);
|
|
1359
|
+
} catch {
|
|
1360
|
+
throw new ValidationError(`${name} must be an absolute HTTPS URL`);
|
|
1361
|
+
}
|
|
1362
|
+
if (url.protocol !== "https:" || url.username || url.password || url.hash) {
|
|
1363
|
+
throw new ValidationError(`${name} must use HTTPS without credentials or a fragment`);
|
|
1364
|
+
}
|
|
1365
|
+
return url;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1164
1368
|
// src/api/resources/signer-documents.ts
|
|
1165
1369
|
var SignerDocumentsResource = class extends BaseResource {
|
|
1166
1370
|
/** `GET /signers/{signer_id}/document?signer-access-code=…` */
|
|
@@ -1239,7 +1443,7 @@ var SignerDocumentsResource = class extends BaseResource {
|
|
|
1239
1443
|
if (!Array.isArray(documentIds) || documentIds.length === 0) {
|
|
1240
1444
|
throw new ValidationError("documentIds must be a non-empty array");
|
|
1241
1445
|
}
|
|
1242
|
-
|
|
1446
|
+
validateDeclineReason(declineReason);
|
|
1243
1447
|
const code = this.requireId(signerAccessCode, "signer-access-code");
|
|
1244
1448
|
return this.call(
|
|
1245
1449
|
"Failed to decline multiple documents",
|
|
@@ -1369,7 +1573,7 @@ var SignerDocumentsResource = class extends BaseResource {
|
|
|
1369
1573
|
const did = this.requireId(documentId, "Document ID");
|
|
1370
1574
|
const aid = this.requireId(assignmentId, "Assignment ID");
|
|
1371
1575
|
const code = this.requireId(signerAccessCode, "signer-access-code");
|
|
1372
|
-
|
|
1576
|
+
validateDeclineReason(declineReason);
|
|
1373
1577
|
return this.call(
|
|
1374
1578
|
"Failed to decline assignment",
|
|
1375
1579
|
() => this.http.put(
|
|
@@ -1380,6 +1584,14 @@ var SignerDocumentsResource = class extends BaseResource {
|
|
|
1380
1584
|
);
|
|
1381
1585
|
}
|
|
1382
1586
|
};
|
|
1587
|
+
function validateDeclineReason(value) {
|
|
1588
|
+
if (typeof value !== "string" || !value.trim()) {
|
|
1589
|
+
throw new ValidationError("declineReason is required");
|
|
1590
|
+
}
|
|
1591
|
+
if ([...value].length > 2e3) {
|
|
1592
|
+
throw new ValidationError("declineReason must contain at most 2000 characters");
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1383
1595
|
|
|
1384
1596
|
// src/api/resources/signers.ts
|
|
1385
1597
|
function validateCreateSignerPayload(payload) {
|
|
@@ -1469,9 +1681,13 @@ var SignerResource = class extends BaseResource {
|
|
|
1469
1681
|
async findByEmail(email, accountId) {
|
|
1470
1682
|
requireEmail(email);
|
|
1471
1683
|
try {
|
|
1472
|
-
const { data } = await this.list({ search: email, per_page: 100 }, accountId);
|
|
1473
1684
|
const lower = email.toLowerCase();
|
|
1474
|
-
|
|
1685
|
+
for (let page = 1; ; page++) {
|
|
1686
|
+
const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
|
|
1687
|
+
const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
|
|
1688
|
+
if (match) return match;
|
|
1689
|
+
if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
|
|
1690
|
+
}
|
|
1475
1691
|
} catch (err) {
|
|
1476
1692
|
if (err instanceof ApiError && err.statusCode === 404) {
|
|
1477
1693
|
return null;
|
|
@@ -1841,7 +2057,7 @@ function validateNotificationSender(value) {
|
|
|
1841
2057
|
}
|
|
1842
2058
|
|
|
1843
2059
|
// src/api/support/webhook-verifier.ts
|
|
1844
|
-
var
|
|
2060
|
+
var import_node_crypto2 = require("crypto");
|
|
1845
2061
|
var WebhookVerifier = class {
|
|
1846
2062
|
constructor(webhookSecret, options = {}) {
|
|
1847
2063
|
this.webhookSecret = webhookSecret;
|
|
@@ -1856,12 +2072,12 @@ var WebhookVerifier = class {
|
|
|
1856
2072
|
if (!this.webhookSecret || !signature) return false;
|
|
1857
2073
|
try {
|
|
1858
2074
|
const buf = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
|
|
1859
|
-
const expected = (0,
|
|
2075
|
+
const expected = (0, import_node_crypto2.createHmac)(this.algorithm, this.webhookSecret).update(buf).digest(this.encoding);
|
|
1860
2076
|
const provided = signature.trim();
|
|
1861
2077
|
const a = Buffer.from(expected, "utf8");
|
|
1862
2078
|
const b = Buffer.from(provided, "utf8");
|
|
1863
2079
|
if (a.length !== b.length) return false;
|
|
1864
|
-
return (0,
|
|
2080
|
+
return (0, import_node_crypto2.timingSafeEqual)(a, b);
|
|
1865
2081
|
} catch {
|
|
1866
2082
|
return false;
|
|
1867
2083
|
}
|
|
@@ -1903,6 +2119,9 @@ var WebhookVerifier = class {
|
|
|
1903
2119
|
|
|
1904
2120
|
// src/api/client.ts
|
|
1905
2121
|
var DEFAULT_BASE_URL = "https://api.assinafy.com.br/v1";
|
|
2122
|
+
function isLoopbackHost(hostname) {
|
|
2123
|
+
return hostname === "localhost" || hostname === "[::1]" || /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/.test(hostname);
|
|
2124
|
+
}
|
|
1906
2125
|
var AssinafyClient = class _AssinafyClient {
|
|
1907
2126
|
axiosInstance;
|
|
1908
2127
|
defaultAccountId;
|
|
@@ -1916,6 +2135,7 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
1916
2135
|
templates;
|
|
1917
2136
|
tags;
|
|
1918
2137
|
auth;
|
|
2138
|
+
oauth;
|
|
1919
2139
|
fields;
|
|
1920
2140
|
users;
|
|
1921
2141
|
signerDocuments;
|
|
@@ -1923,7 +2143,7 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
1923
2143
|
constructor(options) {
|
|
1924
2144
|
if (!options.apiKey && !options.token && !options.allowUnauthenticated) {
|
|
1925
2145
|
throw new ValidationError(
|
|
1926
|
-
"An API key (options.apiKey) or
|
|
2146
|
+
"An API key (options.apiKey) or access token (options.token) is required."
|
|
1927
2147
|
);
|
|
1928
2148
|
}
|
|
1929
2149
|
if (options.timeout !== void 0 && (!Number.isFinite(options.timeout) || options.timeout <= 0)) {
|
|
@@ -1939,13 +2159,17 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
1939
2159
|
} catch {
|
|
1940
2160
|
throw new ValidationError("baseUrl must be an absolute HTTP(S) URL");
|
|
1941
2161
|
}
|
|
1942
|
-
if (
|
|
1943
|
-
|
|
1944
|
-
|
|
1945
|
-
|
|
1946
|
-
|
|
1947
|
-
|
|
1948
|
-
)
|
|
2162
|
+
if (parsedBaseUrl.protocol !== "https:") {
|
|
2163
|
+
if (parsedBaseUrl.protocol !== "http:" || !options.allowInsecureHttp) {
|
|
2164
|
+
throw new ValidationError(
|
|
2165
|
+
"baseUrl must use HTTPS; set allowInsecureHttp only for a loopback development server"
|
|
2166
|
+
);
|
|
2167
|
+
}
|
|
2168
|
+
if (!isLoopbackHost(parsedBaseUrl.hostname)) {
|
|
2169
|
+
throw new ValidationError(
|
|
2170
|
+
"allowInsecureHttp only permits a loopback baseUrl (localhost, 127.0.0.0/8, or ::1)"
|
|
2171
|
+
);
|
|
2172
|
+
}
|
|
1949
2173
|
}
|
|
1950
2174
|
if (parsedBaseUrl.username || parsedBaseUrl.password) {
|
|
1951
2175
|
throw new ValidationError("baseUrl must not contain embedded credentials");
|
|
@@ -1981,6 +2205,7 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
1981
2205
|
this.templates = new TemplateResource(this.axiosInstance, this.defaultAccountId, this.logger);
|
|
1982
2206
|
this.tags = new TagResource(this.axiosInstance, this.defaultAccountId, this.logger);
|
|
1983
2207
|
this.auth = new AuthenticationResource(this.axiosInstance, void 0, this.logger);
|
|
2208
|
+
this.oauth = new OAuthResource(this.axiosInstance, void 0, this.logger);
|
|
1984
2209
|
this.fields = new FieldsResource(this.axiosInstance, this.defaultAccountId, this.logger);
|
|
1985
2210
|
this.users = new UsersResource(this.axiosInstance, void 0, this.logger);
|
|
1986
2211
|
this.signerDocuments = new SignerDocumentsResource(
|
|
@@ -2016,13 +2241,22 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
2016
2241
|
/**
|
|
2017
2242
|
* High-level helper that uploads a PDF, ensures it's processed, creates any
|
|
2018
2243
|
* missing signers, and kicks off a virtual signature assignment.
|
|
2244
|
+
*
|
|
2245
|
+
* Once the upload succeeds the workflow owns real workspace resources, so any
|
|
2246
|
+
* later failure is rethrown as a {@link PartialWorkflowError} carrying the
|
|
2247
|
+
* document and signer IDs that already exist. Catch it to resume or clean up;
|
|
2248
|
+
* nothing is deleted automatically.
|
|
2019
2249
|
*/
|
|
2020
2250
|
async uploadAndRequestSignatures(options) {
|
|
2021
|
-
if (!options.signers || options.signers.length === 0) {
|
|
2251
|
+
if (!Array.isArray(options.signers) || options.signers.length === 0) {
|
|
2022
2252
|
throw new ValidationError("At least one signer is required");
|
|
2023
2253
|
}
|
|
2024
2254
|
if (options.expiresAt !== void 0) requireIso8601(options.expiresAt, "expiresAt");
|
|
2025
2255
|
const preparedSigners = options.signers.map((signer) => {
|
|
2256
|
+
if (!signer || typeof signer !== "object") {
|
|
2257
|
+
throw new ValidationError("Each signer must be an object");
|
|
2258
|
+
}
|
|
2259
|
+
validateSignerOptions(signer);
|
|
2026
2260
|
const payload = { full_name: signer.name };
|
|
2027
2261
|
if (signer.email !== void 0) payload.email = signer.email;
|
|
2028
2262
|
const phone = signer.whatsapp_phone_number ?? signer.phone;
|
|
@@ -2032,6 +2266,7 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
2032
2266
|
validateCreateSignerPayload(payload);
|
|
2033
2267
|
return { signer, payload, phone };
|
|
2034
2268
|
});
|
|
2269
|
+
validateSigningSteps(options.signers);
|
|
2035
2270
|
this.logger.info("Starting upload + signature workflow", {
|
|
2036
2271
|
signerCount: options.signers.length
|
|
2037
2272
|
});
|
|
@@ -2039,33 +2274,46 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
2039
2274
|
if (options.metadata !== void 0) uploadOpts.metadata = options.metadata;
|
|
2040
2275
|
if (options.accountId !== void 0) uploadOpts.accountId = options.accountId;
|
|
2041
2276
|
const document = await this.documents.upload(options.source, uploadOpts);
|
|
2042
|
-
if (options.waitForReady !== false) {
|
|
2043
|
-
await this.documents.waitUntilReady(document.id);
|
|
2044
|
-
}
|
|
2045
2277
|
const signerIds = [];
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
|
|
2049
|
-
|
|
2050
|
-
const
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2278
|
+
try {
|
|
2279
|
+
if (options.waitForReady !== false) {
|
|
2280
|
+
await this.documents.waitUntilReady(document.id);
|
|
2281
|
+
}
|
|
2282
|
+
const assignmentSigners = [];
|
|
2283
|
+
for (const { signer, payload, phone } of preparedSigners) {
|
|
2284
|
+
const created = await this.signers.create(payload, options.accountId);
|
|
2285
|
+
signerIds.push(created.id);
|
|
2286
|
+
const useWhatsapp = phone !== void 0 && signer.email === void 0;
|
|
2287
|
+
assignmentSigners.push({
|
|
2288
|
+
id: created.id,
|
|
2289
|
+
verification_method: signer.verification_method ?? (useWhatsapp ? "Whatsapp" : void 0),
|
|
2290
|
+
notification_methods: signer.notification_methods ?? (useWhatsapp ? ["Whatsapp"] : void 0),
|
|
2291
|
+
step: signer.step
|
|
2292
|
+
});
|
|
2293
|
+
}
|
|
2294
|
+
const assignmentPayload = {
|
|
2295
|
+
method: "virtual",
|
|
2296
|
+
signers: assignmentSigners
|
|
2297
|
+
};
|
|
2298
|
+
if (options.message !== void 0) assignmentPayload.message = options.message;
|
|
2299
|
+
if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
|
|
2300
|
+
if (options.copyReceivers !== void 0)
|
|
2301
|
+
assignmentPayload.copy_receivers = options.copyReceivers;
|
|
2302
|
+
const assignment = await this.assignments.create(document.id, assignmentPayload);
|
|
2303
|
+
this.logger.info("Upload + signature workflow completed", { documentId: document.id });
|
|
2304
|
+
return { document, assignment, signer_ids: signerIds };
|
|
2305
|
+
} catch (err) {
|
|
2306
|
+
this.logger.error("Upload + signature workflow failed after creating resources", {
|
|
2307
|
+
documentId: document.id,
|
|
2308
|
+
signerIds
|
|
2056
2309
|
});
|
|
2310
|
+
const reason = err instanceof Error ? err.message : String(err);
|
|
2311
|
+
throw new PartialWorkflowError(
|
|
2312
|
+
`${reason} (document ${document.id} exists; ${signerIds.length} signer(s) created or reused)`,
|
|
2313
|
+
{ documentId: document.id, signerIds },
|
|
2314
|
+
{ cause: err }
|
|
2315
|
+
);
|
|
2057
2316
|
}
|
|
2058
|
-
const assignmentPayload = {
|
|
2059
|
-
method: "virtual",
|
|
2060
|
-
signers: assignmentSigners
|
|
2061
|
-
};
|
|
2062
|
-
if (options.message !== void 0) assignmentPayload.message = options.message;
|
|
2063
|
-
if (options.expiresAt !== void 0) assignmentPayload.expires_at = options.expiresAt;
|
|
2064
|
-
if (options.copyReceivers !== void 0)
|
|
2065
|
-
assignmentPayload.copy_receivers = options.copyReceivers;
|
|
2066
|
-
const assignment = await this.assignments.create(document.id, assignmentPayload);
|
|
2067
|
-
this.logger.info("Upload + signature workflow completed", { documentId: document.id });
|
|
2068
|
-
return { document, assignment, signer_ids: signerIds };
|
|
2069
2317
|
}
|
|
2070
2318
|
/** Expose the underlying axios instance for advanced use cases (interceptors, custom endpoints). */
|
|
2071
2319
|
getAxiosInstance() {
|
|
@@ -2083,6 +2331,8 @@ var AssinafyClient = class _AssinafyClient {
|
|
|
2083
2331
|
FieldsResource,
|
|
2084
2332
|
NOTIFICATION_PREFERENCE_CODES,
|
|
2085
2333
|
NetworkError,
|
|
2334
|
+
OAuthResource,
|
|
2335
|
+
PartialWorkflowError,
|
|
2086
2336
|
SignerDocumentsResource,
|
|
2087
2337
|
SignerResource,
|
|
2088
2338
|
TagResource,
|