esigncomply 0.0.0-stage → 1.0.0
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/LICENSE +21 -0
- package/README.md +279 -2
- package/dist/cli/args.d.ts +16 -0
- package/dist/cli/browser.d.ts +17 -0
- package/dist/cli/check.d.ts +80 -0
- package/dist/cli/demo-page.d.ts +24 -0
- package/dist/cli/demo.d.ts +36 -0
- package/dist/cli/documents.d.ts +3 -0
- package/dist/cli/index.d.ts +9 -0
- package/dist/cli/io.d.ts +40 -0
- package/dist/cli/verify.d.ts +4 -0
- package/dist/cli/webhooks.d.ts +20 -0
- package/dist/cli.js +2393 -0
- package/dist/client.d.ts +75 -0
- package/dist/errors.d.ts +49 -0
- package/dist/index.d.ts +95 -0
- package/dist/index.js +825 -0
- package/dist/resources/account.d.ts +40 -0
- package/dist/resources/base.d.ts +7 -0
- package/dist/resources/certificates.d.ts +19 -0
- package/dist/resources/documents.d.ts +20 -0
- package/dist/resources/guidance.d.ts +26 -0
- package/dist/resources/jurisdictions.d.ts +12 -0
- package/dist/resources/profiles.d.ts +16 -0
- package/dist/resources/records.d.ts +47 -0
- package/dist/resources/sessions.d.ts +15 -0
- package/dist/resources/signers.d.ts +15 -0
- package/dist/resources/supplements.d.ts +33 -0
- package/dist/resources/webhooks.d.ts +48 -0
- package/dist/types.d.ts +1687 -0
- package/dist/version.d.ts +2 -0
- package/package.json +61 -3
package/dist/cli.js
ADDED
|
@@ -0,0 +1,2393 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// packages/esigncomply/src/cli/index.ts
|
|
4
|
+
import { realpathSync } from "node:fs";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
|
|
7
|
+
// packages/esigncomply/src/version.ts
|
|
8
|
+
var VERSION = "1.0.0";
|
|
9
|
+
|
|
10
|
+
// packages/esigncomply/src/cli/args.ts
|
|
11
|
+
var UsageError = class extends Error {
|
|
12
|
+
};
|
|
13
|
+
function parseArgs(argv, spec, aliases = {}) {
|
|
14
|
+
const out = { positionals: [], flags: {} };
|
|
15
|
+
for (let i = 0; i < argv.length; i++) {
|
|
16
|
+
const arg = argv[i];
|
|
17
|
+
if (arg === "--") {
|
|
18
|
+
out.positionals.push(...argv.slice(i + 1));
|
|
19
|
+
break;
|
|
20
|
+
}
|
|
21
|
+
if (!arg.startsWith("-") || arg === "-") {
|
|
22
|
+
out.positionals.push(arg);
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
let name = arg;
|
|
26
|
+
let inline;
|
|
27
|
+
const eq = arg.indexOf("=");
|
|
28
|
+
if (arg.startsWith("--") && eq > 0) {
|
|
29
|
+
name = arg.slice(0, eq);
|
|
30
|
+
inline = arg.slice(eq + 1);
|
|
31
|
+
}
|
|
32
|
+
name = aliases[name] ?? name;
|
|
33
|
+
if (!name.startsWith("--") || !(name.slice(2) in spec)) throw new UsageError(`Unknown option ${arg.split("=")[0]}.`);
|
|
34
|
+
const key = name.slice(2);
|
|
35
|
+
const kind = spec[key];
|
|
36
|
+
if (kind === "boolean") {
|
|
37
|
+
if (inline !== void 0 && inline !== "true" && inline !== "false") throw new UsageError(`${name} takes no value.`);
|
|
38
|
+
out.flags[key] = inline !== "false";
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
const value = inline ?? argv[++i];
|
|
42
|
+
if (value === void 0 || inline === void 0 && value.startsWith("--")) throw new UsageError(`${name} needs a value.`);
|
|
43
|
+
if (kind === "list") out.flags[key] = [...out.flags[key] ?? [], value];
|
|
44
|
+
else out.flags[key] = value;
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
function str(flags, key) {
|
|
49
|
+
const v = flags[key];
|
|
50
|
+
return typeof v === "string" ? v : void 0;
|
|
51
|
+
}
|
|
52
|
+
function list(flags, key) {
|
|
53
|
+
const v = flags[key];
|
|
54
|
+
return Array.isArray(v) ? v : [];
|
|
55
|
+
}
|
|
56
|
+
function bool(flags, key) {
|
|
57
|
+
return flags[key] === true;
|
|
58
|
+
}
|
|
59
|
+
function int(flags, key, fallback, min, max) {
|
|
60
|
+
const raw = str(flags, key);
|
|
61
|
+
if (raw === void 0) return fallback;
|
|
62
|
+
const n = Number(raw);
|
|
63
|
+
if (!Number.isInteger(n) || n < min || n > max) throw new UsageError(`--${key} must be a whole number from ${min} to ${max}.`);
|
|
64
|
+
return n;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// packages/esigncomply/src/cli/browser.ts
|
|
68
|
+
var INSTALL_PLAYWRIGHT = [
|
|
69
|
+
"This command drives a real browser with Playwright, which is not installed.",
|
|
70
|
+
"",
|
|
71
|
+
" npm install --save-dev playwright",
|
|
72
|
+
" npx playwright install chromium",
|
|
73
|
+
"",
|
|
74
|
+
"Then run the command again."
|
|
75
|
+
].join("\n");
|
|
76
|
+
async function launchBrowser() {
|
|
77
|
+
let chromium;
|
|
78
|
+
try {
|
|
79
|
+
const name = "playwright";
|
|
80
|
+
({ chromium } = await import(name));
|
|
81
|
+
} catch (err) {
|
|
82
|
+
return { ok: false, reason: "not_installed", detail: err instanceof Error ? err.message : String(err) };
|
|
83
|
+
}
|
|
84
|
+
const errors = [];
|
|
85
|
+
for (const options of [{ headless: true }, { headless: true, channel: "chrome", args: ["--no-sandbox"] }]) {
|
|
86
|
+
try {
|
|
87
|
+
return { ok: true, browser: await chromium.launch(options) };
|
|
88
|
+
} catch (err) {
|
|
89
|
+
errors.push((err instanceof Error ? err.message : String(err)).split("\n")[0]);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return { ok: false, reason: "no_browser", detail: errors.join(" | ") };
|
|
93
|
+
}
|
|
94
|
+
var INSTALL_BROWSER = [
|
|
95
|
+
"Playwright is installed but has no browser to drive.",
|
|
96
|
+
"",
|
|
97
|
+
" npx playwright install chromium",
|
|
98
|
+
"",
|
|
99
|
+
"Then run the command again."
|
|
100
|
+
].join("\n");
|
|
101
|
+
|
|
102
|
+
// packages/esigncomply/src/errors.ts
|
|
103
|
+
function ok(data) {
|
|
104
|
+
return { data, error: null };
|
|
105
|
+
}
|
|
106
|
+
function fail(error) {
|
|
107
|
+
return { data: null, error };
|
|
108
|
+
}
|
|
109
|
+
var STATUS_DEFAULTS = {
|
|
110
|
+
400: ["invalid_request_error", "invalid_request"],
|
|
111
|
+
401: ["authentication_error", "invalid_api_key"],
|
|
112
|
+
402: ["quota_error", "quota_exceeded"],
|
|
113
|
+
403: ["permission_error", "insufficient_permission"],
|
|
114
|
+
404: ["invalid_request_error", "not_found"],
|
|
115
|
+
409: ["conflict_error", "idempotency_conflict"],
|
|
116
|
+
421: ["invalid_request_error", "region_mismatch"],
|
|
117
|
+
422: ["invalid_request_error", "invalid_request"],
|
|
118
|
+
429: ["rate_limit_error", "rate_limit_exceeded"],
|
|
119
|
+
500: ["api_error", "internal_error"],
|
|
120
|
+
503: ["api_error", "service_unavailable"]
|
|
121
|
+
};
|
|
122
|
+
function isObject(v) {
|
|
123
|
+
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
124
|
+
}
|
|
125
|
+
function errorFromResponse(status, body, headers) {
|
|
126
|
+
const fallback = STATUS_DEFAULTS[status] ?? (status >= 500 ? STATUS_DEFAULTS[500] : STATUS_DEFAULTS[400]);
|
|
127
|
+
const envelope = isObject(body) && isObject(body.error) ? body.error : null;
|
|
128
|
+
const error = envelope ? {
|
|
129
|
+
...envelope,
|
|
130
|
+
type: typeof envelope.type === "string" ? envelope.type : fallback[0],
|
|
131
|
+
code: typeof envelope.code === "string" ? envelope.code : fallback[1],
|
|
132
|
+
message: typeof envelope.message === "string" ? envelope.message : `The API answered ${status}.`,
|
|
133
|
+
status
|
|
134
|
+
} : {
|
|
135
|
+
type: fallback[0],
|
|
136
|
+
code: fallback[1],
|
|
137
|
+
message: `The API answered ${status} without an error body. ${status === 404 ? "This endpoint may not exist on the server you are calling." : "This usually comes from a proxy in front of the API."}`,
|
|
138
|
+
status
|
|
139
|
+
};
|
|
140
|
+
if (error.request_id === void 0 && headers.requestId) error.request_id = headers.requestId;
|
|
141
|
+
if (headers.retryAfter !== null) error.retry_after = headers.retryAfter;
|
|
142
|
+
return error;
|
|
143
|
+
}
|
|
144
|
+
function networkError(err, context) {
|
|
145
|
+
const cause = err instanceof Error ? err.message : String(err);
|
|
146
|
+
const nested = err instanceof Error && err.cause instanceof Error ? ` (${err.cause.message})` : "";
|
|
147
|
+
return { type: "api_error", code: "network_error", message: `${context}: ${cause}${nested}`, status: 0 };
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// packages/esigncomply/src/client.ts
|
|
151
|
+
var US_BASE = "https://esigncomply.com/v1";
|
|
152
|
+
var MAX_RETRY_WAIT_MS = 6e4;
|
|
153
|
+
function baseUrlForKey(apiKey) {
|
|
154
|
+
const region = /^esc_(?:test|live)_([a-z]{2})_/.exec(apiKey)?.[1];
|
|
155
|
+
return region && region !== "us" ? `https://api.${region}.esigncomply.com/v1` : US_BASE;
|
|
156
|
+
}
|
|
157
|
+
function normalizeBaseUrl(url) {
|
|
158
|
+
const trimmed = url.trim().replace(/\/+$/, "");
|
|
159
|
+
try {
|
|
160
|
+
if (new URL(trimmed).pathname === "/") return `${trimmed}/v1`;
|
|
161
|
+
} catch {
|
|
162
|
+
}
|
|
163
|
+
return trimmed;
|
|
164
|
+
}
|
|
165
|
+
function keyMode(apiKey) {
|
|
166
|
+
if (apiKey.startsWith("esc_test_")) return "test";
|
|
167
|
+
if (apiKey.startsWith("esc_live_")) return "live";
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
function retryAfterSeconds(res) {
|
|
171
|
+
const header2 = res.headers.get("retry-after");
|
|
172
|
+
if (!header2) return null;
|
|
173
|
+
const seconds = Number(header2);
|
|
174
|
+
if (Number.isFinite(seconds) && seconds >= 0) return seconds;
|
|
175
|
+
const date = Date.parse(header2);
|
|
176
|
+
return Number.isNaN(date) ? null : Math.max(0, Math.ceil((date - Date.now()) / 1e3));
|
|
177
|
+
}
|
|
178
|
+
function backoffMs(attempt) {
|
|
179
|
+
const base = Math.min(8e3, 500 * 2 ** attempt);
|
|
180
|
+
return Math.round(base * (0.75 + Math.random() * 0.5));
|
|
181
|
+
}
|
|
182
|
+
function filename(res) {
|
|
183
|
+
const m = /filename\*?=(?:UTF-8'')?"?([^";]+)"?/i.exec(res.headers.get("content-disposition") ?? "");
|
|
184
|
+
return m ? decodeURIComponent(m[1]) : void 0;
|
|
185
|
+
}
|
|
186
|
+
var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
187
|
+
var HttpClient = class {
|
|
188
|
+
baseUrl;
|
|
189
|
+
apiKey;
|
|
190
|
+
apiVersion;
|
|
191
|
+
fetchImpl;
|
|
192
|
+
maxRetries;
|
|
193
|
+
timeoutMs;
|
|
194
|
+
sleep;
|
|
195
|
+
constructor(apiKey, options = {}) {
|
|
196
|
+
this.apiKey = (apiKey ?? process.env.ESIGNCOMPLY_API_KEY ?? "").trim();
|
|
197
|
+
this.baseUrl = normalizeBaseUrl(options.baseUrl || process.env.ESIGNCOMPLY_API_URL || baseUrlForKey(this.apiKey));
|
|
198
|
+
this.apiVersion = options.apiVersion;
|
|
199
|
+
this.fetchImpl = options.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
200
|
+
this.maxRetries = Number.isInteger(options.maxRetries) && options.maxRetries >= 0 ? options.maxRetries : 2;
|
|
201
|
+
this.timeoutMs = options.timeoutMs ?? 6e4;
|
|
202
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
203
|
+
}
|
|
204
|
+
/** A JSON request. */
|
|
205
|
+
request(req) {
|
|
206
|
+
return this.send(req, "json");
|
|
207
|
+
}
|
|
208
|
+
/** A request whose successful response is a file. */
|
|
209
|
+
requestBinary(req) {
|
|
210
|
+
return this.send(req, "binary");
|
|
211
|
+
}
|
|
212
|
+
/** A request that may answer with JSON or with a file, depending on the content type. */
|
|
213
|
+
requestEither(req) {
|
|
214
|
+
return this.send(req, "either");
|
|
215
|
+
}
|
|
216
|
+
/** Fetch a URL outside the API (a signed download or upload URL). The API key is never sent. */
|
|
217
|
+
async external(url, init, context) {
|
|
218
|
+
if (!this.fetchImpl) return fail(networkError(new Error("no fetch implementation is available"), context));
|
|
219
|
+
try {
|
|
220
|
+
const res = await this.fetchImpl(url, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
|
|
221
|
+
if (res.ok) return ok(res);
|
|
222
|
+
const text = await res.text().catch(() => "");
|
|
223
|
+
return fail({ type: "api_error", code: "service_unavailable", message: `${context}: the storage service answered ${res.status}. ${text.slice(0, 200)}`.trim(), status: res.status });
|
|
224
|
+
} catch (err) {
|
|
225
|
+
return fail(networkError(err, context));
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
async send(req, expect) {
|
|
229
|
+
try {
|
|
230
|
+
return await this.attempt(req, expect);
|
|
231
|
+
} catch (err) {
|
|
232
|
+
return fail(networkError(err, `${req.method} ${req.path}`));
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
async attempt(req, expect) {
|
|
236
|
+
const token = req.token ?? this.apiKey;
|
|
237
|
+
if (!token) {
|
|
238
|
+
return fail({
|
|
239
|
+
type: "authentication_error",
|
|
240
|
+
code: "missing_api_key",
|
|
241
|
+
message: "No API key. Pass it to new EsignComply(key) or set ESIGNCOMPLY_API_KEY. Keys are secret and belong on your server.",
|
|
242
|
+
status: 0
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
if (!this.fetchImpl) return fail(networkError(new Error("no fetch implementation is available; use Node 20 or later, or pass { fetch }"), `${req.method} ${req.path}`));
|
|
246
|
+
let url;
|
|
247
|
+
try {
|
|
248
|
+
const u = new URL(this.baseUrl + (req.path.startsWith("/") ? req.path : `/${req.path}`));
|
|
249
|
+
for (const [key, value] of Object.entries(req.query ?? {})) {
|
|
250
|
+
if (value === void 0 || value === null) continue;
|
|
251
|
+
if (Array.isArray(value)) for (const v of value) u.searchParams.append(key, String(v));
|
|
252
|
+
else u.searchParams.set(key, String(value));
|
|
253
|
+
}
|
|
254
|
+
url = u.toString();
|
|
255
|
+
} catch {
|
|
256
|
+
return fail({ type: "invalid_request_error", code: "invalid_request", message: `The API base URL "${this.baseUrl}" is not a valid URL.`, param: "baseUrl", status: 0 });
|
|
257
|
+
}
|
|
258
|
+
const headers = {
|
|
259
|
+
Authorization: `Bearer ${token}`,
|
|
260
|
+
Accept: expect === "json" ? "application/json" : "*/*",
|
|
261
|
+
"X-Esc-Sdk": `node/${VERSION}`,
|
|
262
|
+
"User-Agent": `esigncomply-node/${VERSION}`
|
|
263
|
+
};
|
|
264
|
+
const version = req.options?.apiVersion ?? this.apiVersion;
|
|
265
|
+
if (version) headers["Esign-Comply-Version"] = version;
|
|
266
|
+
const idempotencyKey = req.options?.idempotencyKey;
|
|
267
|
+
if (idempotencyKey && req.method === "POST") headers["Idempotency-Key"] = idempotencyKey;
|
|
268
|
+
let body;
|
|
269
|
+
if (req.body !== void 0 && req.method !== "GET") {
|
|
270
|
+
body = JSON.stringify(req.body);
|
|
271
|
+
headers["Content-Type"] = "application/json";
|
|
272
|
+
}
|
|
273
|
+
const repeatable = req.method === "GET" || req.method === "POST" && !!idempotencyKey;
|
|
274
|
+
const context = `${req.method} ${req.path}`;
|
|
275
|
+
for (let attempt = 0; ; attempt++) {
|
|
276
|
+
const canRetry = attempt < this.maxRetries;
|
|
277
|
+
let res;
|
|
278
|
+
try {
|
|
279
|
+
const timeout = AbortSignal.timeout(this.timeoutMs);
|
|
280
|
+
const signal = req.options?.signal ? AbortSignal.any([req.options.signal, timeout]) : timeout;
|
|
281
|
+
res = await this.fetchImpl(url, { method: req.method, headers, body, signal });
|
|
282
|
+
} catch (err) {
|
|
283
|
+
if (repeatable && canRetry && !req.options?.signal?.aborted) {
|
|
284
|
+
await this.sleep(backoffMs(attempt));
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
return fail(networkError(err, context));
|
|
288
|
+
}
|
|
289
|
+
const retryAfter = retryAfterSeconds(res);
|
|
290
|
+
if (canRetry && (res.status === 429 || res.status >= 500 && repeatable)) {
|
|
291
|
+
const wait = retryAfter !== null ? retryAfter * 1e3 : backoffMs(attempt);
|
|
292
|
+
if (wait <= MAX_RETRY_WAIT_MS) {
|
|
293
|
+
await res.arrayBuffer().catch(() => void 0);
|
|
294
|
+
await this.sleep(wait);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
return this.read(res, expect, retryAfter, context);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
async read(res, expect, retryAfter, context) {
|
|
302
|
+
const requestId = res.headers.get("x-request-id");
|
|
303
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
304
|
+
const isJson = /\bjson\b/i.test(contentType);
|
|
305
|
+
try {
|
|
306
|
+
if (res.status >= 200 && res.status < 300) {
|
|
307
|
+
if (expect === "binary" || expect === "either" && !isJson) {
|
|
308
|
+
const bytes = new Uint8Array(await res.arrayBuffer());
|
|
309
|
+
const name = filename(res);
|
|
310
|
+
return ok({ bytes, contentType: contentType || "application/octet-stream", ...name ? { filename: name } : {} });
|
|
311
|
+
}
|
|
312
|
+
const text2 = await res.text();
|
|
313
|
+
if (text2.trim() === "") return ok({});
|
|
314
|
+
try {
|
|
315
|
+
return ok(JSON.parse(text2));
|
|
316
|
+
} catch {
|
|
317
|
+
return fail({ type: "api_error", code: "invalid_response", message: `${context}: the API answered ${res.status} with a body that is not JSON.`, status: res.status, ...requestId ? { request_id: requestId } : {} });
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
const text = await res.text();
|
|
321
|
+
let parsed;
|
|
322
|
+
try {
|
|
323
|
+
parsed = JSON.parse(text);
|
|
324
|
+
} catch {
|
|
325
|
+
parsed = void 0;
|
|
326
|
+
}
|
|
327
|
+
return fail(errorFromResponse(res.status, parsed, { requestId, retryAfter }));
|
|
328
|
+
} catch (err) {
|
|
329
|
+
const error = networkError(err, `${context}: the response could not be read`);
|
|
330
|
+
return fail({ ...error, status: res.status, ...requestId ? { request_id: requestId } : {} });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
};
|
|
334
|
+
|
|
335
|
+
// packages/esigncomply/src/resources/base.ts
|
|
336
|
+
var Resource = class {
|
|
337
|
+
/** @internal */
|
|
338
|
+
constructor(client) {
|
|
339
|
+
this.client = client;
|
|
340
|
+
}
|
|
341
|
+
client;
|
|
342
|
+
/** @internal */
|
|
343
|
+
_get(path2, query, options) {
|
|
344
|
+
return this.client.request({ method: "GET", path: path2, query, options });
|
|
345
|
+
}
|
|
346
|
+
/** @internal */
|
|
347
|
+
_post(path2, body, options) {
|
|
348
|
+
return this.client.request({ method: "POST", path: path2, body: body ?? {}, options });
|
|
349
|
+
}
|
|
350
|
+
/** @internal */
|
|
351
|
+
_send(method, path2, body, options) {
|
|
352
|
+
return this.client.request({ method, path: path2, body, options });
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
function path(strings, ...ids) {
|
|
356
|
+
return strings.reduce((out, s, i) => out + s + (i < ids.length ? encodeURIComponent(String(ids[i])) : ""), "");
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// packages/esigncomply/src/resources/account.ts
|
|
360
|
+
var UsageResource = class extends Resource {
|
|
361
|
+
/** Events used in the subscription year, quota, period end; certificate allowance and spend; supplement storage. */
|
|
362
|
+
get() {
|
|
363
|
+
return this._get("/usage");
|
|
364
|
+
}
|
|
365
|
+
};
|
|
366
|
+
var Conformance = class extends Resource {
|
|
367
|
+
/** Run the conformance checker over recent test records (12.6). Findings are advisory statements about measurable design facts. */
|
|
368
|
+
run(body = {}, options) {
|
|
369
|
+
return this._post("/conformance/runs", body, options);
|
|
370
|
+
}
|
|
371
|
+
get(id) {
|
|
372
|
+
return this._get(path`/conformance/runs/${id}`);
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
var Prompts = class extends Resource {
|
|
376
|
+
/**
|
|
377
|
+
* Generate the integration prompt for an AI coding tool from wizard selections (section 12).
|
|
378
|
+
* Creates or reuses the ceremony profiles the prompt names and stores the prompt. Needs a `full_access` key.
|
|
379
|
+
*/
|
|
380
|
+
generate(body = {}, options) {
|
|
381
|
+
return this._post("/prompts/generate", body, options);
|
|
382
|
+
}
|
|
383
|
+
/** Prompts generated for this domain and environment, newest first. List items leave out the Markdown: read one prompt for its text. */
|
|
384
|
+
list(params = {}) {
|
|
385
|
+
return this._get("/prompts", params);
|
|
386
|
+
}
|
|
387
|
+
/** One stored prompt with its Markdown. Prompt IDs resolve permanently (BC-15). */
|
|
388
|
+
get(id) {
|
|
389
|
+
return this._get(path`/prompts/${id}`);
|
|
390
|
+
}
|
|
391
|
+
};
|
|
392
|
+
var Domains = class extends Resource {
|
|
393
|
+
create(body, options) {
|
|
394
|
+
return this._post("/domains", body, options);
|
|
395
|
+
}
|
|
396
|
+
get(id) {
|
|
397
|
+
return this._get(path`/domains/${id}`);
|
|
398
|
+
}
|
|
399
|
+
/** Trigger verification of the domain. */
|
|
400
|
+
verify(id) {
|
|
401
|
+
return this._post(path`/domains/${id}/verify`);
|
|
402
|
+
}
|
|
403
|
+
/** Change domain settings, for example `certificate_spend_limit` (OC-16). */
|
|
404
|
+
update(id, body) {
|
|
405
|
+
return this._send("PATCH", path`/domains/${id}`, body);
|
|
406
|
+
}
|
|
407
|
+
/** Watch jurisdiction codes without enabling their packs, to receive their notices (GD-14). Replaces the whole list and resolves to it. */
|
|
408
|
+
watchJurisdictions(id, jurisdictions) {
|
|
409
|
+
return this._send("PUT", path`/domains/${id}/watched-jurisdictions`, { jurisdictions });
|
|
410
|
+
}
|
|
411
|
+
};
|
|
412
|
+
var ApiKeys = class extends Resource {
|
|
413
|
+
/** Create a key. The full key is in the response once; only a prefix and a hash are stored. */
|
|
414
|
+
create(body, options) {
|
|
415
|
+
return this._post("/api-keys", body, options);
|
|
416
|
+
}
|
|
417
|
+
list() {
|
|
418
|
+
return this._get("/api-keys");
|
|
419
|
+
}
|
|
420
|
+
delete(id) {
|
|
421
|
+
return this._send("DELETE", path`/api-keys/${id}`);
|
|
422
|
+
}
|
|
423
|
+
};
|
|
424
|
+
|
|
425
|
+
// packages/esigncomply/src/resources/certificates.ts
|
|
426
|
+
var Certificates = class extends Resource {
|
|
427
|
+
/** Issue one certificate over a set of records selected by filter. Asynchronous: answers `processing`, then `certificate.issued` fires. */
|
|
428
|
+
create(body, options) {
|
|
429
|
+
return this._post("/certificates", body, options);
|
|
430
|
+
}
|
|
431
|
+
/** What a certificate request would cost. Issues nothing and charges nothing (OC-13). */
|
|
432
|
+
quote(body) {
|
|
433
|
+
return this._post("/certificates/quote", body);
|
|
434
|
+
}
|
|
435
|
+
list(filters = {}) {
|
|
436
|
+
return this._get("/certificates", filters);
|
|
437
|
+
}
|
|
438
|
+
get(id) {
|
|
439
|
+
return this._get(path`/certificates/${id}`);
|
|
440
|
+
}
|
|
441
|
+
/** The certificate as a PDF. */
|
|
442
|
+
pdf(id) {
|
|
443
|
+
return this.client.requestBinary({ method: "GET", path: path`/certificates/${id}/pdf` });
|
|
444
|
+
}
|
|
445
|
+
/** Create a time-limited share link that opens the certificate and runs verification without an account (OC-8). */
|
|
446
|
+
share(id, body, options) {
|
|
447
|
+
return this._post(path`/certificates/${id}/share`, body, options);
|
|
448
|
+
}
|
|
449
|
+
revokeShare(id) {
|
|
450
|
+
return this._send("DELETE", path`/certificates/${id}/share`);
|
|
451
|
+
}
|
|
452
|
+
};
|
|
453
|
+
|
|
454
|
+
// packages/esigncomply/src/resources/documents.ts
|
|
455
|
+
var DocumentVersions = class extends Resource {
|
|
456
|
+
/** Publish an immutable version: text or file, language, version label, effective date. Returns the content hash. */
|
|
457
|
+
create(documentId, body, options) {
|
|
458
|
+
return this._post(path`/documents/${documentId}/versions`, body, options);
|
|
459
|
+
}
|
|
460
|
+
list(documentId) {
|
|
461
|
+
return this._get(path`/documents/${documentId}/versions`);
|
|
462
|
+
}
|
|
463
|
+
get(documentId, versionId) {
|
|
464
|
+
return this._get(path`/documents/${documentId}/versions/${versionId}`);
|
|
465
|
+
}
|
|
466
|
+
/** The canonical content to render. `"current"` picks the version in force, by `locale` when translations exist. */
|
|
467
|
+
getContent(documentId, versionId, params = {}) {
|
|
468
|
+
return this._get(path`/documents/${documentId}/versions/${versionId}/content`, params);
|
|
469
|
+
}
|
|
470
|
+
};
|
|
471
|
+
var Documents = class extends Resource {
|
|
472
|
+
versions = new DocumentVersions(this.client);
|
|
473
|
+
create(body, options) {
|
|
474
|
+
return this._post("/documents", body, options);
|
|
475
|
+
}
|
|
476
|
+
list(params = {}) {
|
|
477
|
+
return this._get("/documents", params);
|
|
478
|
+
}
|
|
479
|
+
get(id) {
|
|
480
|
+
return this._get(path`/documents/${id}`);
|
|
481
|
+
}
|
|
482
|
+
};
|
|
483
|
+
|
|
484
|
+
// packages/esigncomply/src/resources/guidance.ts
|
|
485
|
+
var GuidanceNotices = class extends Resource {
|
|
486
|
+
/** Notices that reach this domain. Filters: jurisdiction, class, severity, kind, topic, since, affecting_profile. */
|
|
487
|
+
list(filters = {}) {
|
|
488
|
+
return this._get("/guidance/notices", filters);
|
|
489
|
+
}
|
|
490
|
+
get(id) {
|
|
491
|
+
return this._get(path`/guidance/notices/${id}`);
|
|
492
|
+
}
|
|
493
|
+
/** Mark a notice `read`, `applied` or `not_applicable`. Acknowledgment never gates recording (GD-10). */
|
|
494
|
+
acknowledge(id, body, options) {
|
|
495
|
+
return this._post(path`/guidance/notices/${id}/acknowledge`, body, options);
|
|
496
|
+
}
|
|
497
|
+
};
|
|
498
|
+
var GuidanceReleases = class extends Resource {
|
|
499
|
+
list(params = {}) {
|
|
500
|
+
return this._get("/guidance/releases", params);
|
|
501
|
+
}
|
|
502
|
+
/** One release with its changelog: items added, changed, retired. */
|
|
503
|
+
get(id) {
|
|
504
|
+
return this._get(path`/guidance/releases/${id}`);
|
|
505
|
+
}
|
|
506
|
+
};
|
|
507
|
+
var GuidanceUpdates = class extends Resource {
|
|
508
|
+
/** An update prompt: a short reviewed block that describes one change, to hand to a coding tool (GD-9). */
|
|
509
|
+
async get(id) {
|
|
510
|
+
const res = await this.client.requestEither({ method: "GET", path: path`/guidance/updates/${id}` });
|
|
511
|
+
if (res.error) return res;
|
|
512
|
+
if ("bytes" in res.data && res.data.bytes instanceof Uint8Array) {
|
|
513
|
+
return ok({ id, markdown: new TextDecoder().decode(res.data.bytes) });
|
|
514
|
+
}
|
|
515
|
+
return ok(res.data);
|
|
516
|
+
}
|
|
517
|
+
};
|
|
518
|
+
var Guidance = class extends Resource {
|
|
519
|
+
notices = new GuidanceNotices(this.client);
|
|
520
|
+
releases = new GuidanceReleases(this.client);
|
|
521
|
+
updates = new GuidanceUpdates(this.client);
|
|
522
|
+
};
|
|
523
|
+
|
|
524
|
+
// packages/esigncomply/src/resources/jurisdictions.ts
|
|
525
|
+
var Jurisdictions = class extends Resource {
|
|
526
|
+
/** The public catalogue of packs. Read it instead of hard-coding codes, so new packs need no SDK release (JR-1). */
|
|
527
|
+
list(params = {}) {
|
|
528
|
+
return this._get("/jurisdictions", params);
|
|
529
|
+
}
|
|
530
|
+
get(code) {
|
|
531
|
+
return this._get(path`/jurisdictions/${code}`);
|
|
532
|
+
}
|
|
533
|
+
/** Version history and changelog of one pack. */
|
|
534
|
+
versions(code) {
|
|
535
|
+
return this._get(path`/jurisdictions/${code}/versions`);
|
|
536
|
+
}
|
|
537
|
+
/** Dry run: the packs, rules, steps, strings and retention floor a session would get. Creates nothing and is not metered (JR-12). */
|
|
538
|
+
resolve(body) {
|
|
539
|
+
return this._post("/jurisdictions/resolve", body);
|
|
540
|
+
}
|
|
541
|
+
};
|
|
542
|
+
|
|
543
|
+
// packages/esigncomply/src/resources/profiles.ts
|
|
544
|
+
var Profiles = class extends Resource {
|
|
545
|
+
/** Create a ceremony profile: which packs, which method, which assurance level (13.12). */
|
|
546
|
+
create(body, options) {
|
|
547
|
+
return this._post("/profiles", body, options);
|
|
548
|
+
}
|
|
549
|
+
list() {
|
|
550
|
+
return this._get("/profiles");
|
|
551
|
+
}
|
|
552
|
+
get(id) {
|
|
553
|
+
return this._get(path`/profiles/${id}`);
|
|
554
|
+
}
|
|
555
|
+
/** Everything that applies to a profile now: record conditions, obligations, recommendations and reports (13.15). */
|
|
556
|
+
guidance(id) {
|
|
557
|
+
return this._get(path`/profiles/${id}/guidance`);
|
|
558
|
+
}
|
|
559
|
+
/** Move every pending record condition from advise to enforce (BC-6). Creates a new profile version. Body: `note`, optional. */
|
|
560
|
+
adopt(id, body = {}, options) {
|
|
561
|
+
return this._post(path`/profiles/${id}/adopt`, body, options);
|
|
562
|
+
}
|
|
563
|
+
/** Return to the previous baseline, within 90 days of adoption (BC-6). */
|
|
564
|
+
rollback(id, options) {
|
|
565
|
+
return this._post(path`/profiles/${id}/rollback`, {}, options);
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
|
|
569
|
+
// packages/esigncomply/src/resources/records.ts
|
|
570
|
+
var Records = class extends Resource {
|
|
571
|
+
/** Search records. Filters: signer, e-mail, document, version, creation time, status. */
|
|
572
|
+
list(filters = {}) {
|
|
573
|
+
return this._get("/records", filters);
|
|
574
|
+
}
|
|
575
|
+
/**
|
|
576
|
+
* Retrieve a record. This is the server-side confirmation of CP-3: before
|
|
577
|
+
* granting access, check that `status` is `recorded`, `timestamped` or
|
|
578
|
+
* `anchored`, that `livemode` is what you expect, and that the signer and
|
|
579
|
+
* the document versions match what your server asked for.
|
|
580
|
+
*/
|
|
581
|
+
get(id) {
|
|
582
|
+
return this._get(path`/records/${id}`);
|
|
583
|
+
}
|
|
584
|
+
/** The evidence report as a PDF. */
|
|
585
|
+
report(id) {
|
|
586
|
+
return this.client.requestBinary({ method: "GET", path: path`/records/${id}/report` });
|
|
587
|
+
}
|
|
588
|
+
async evidence(id, options = {}) {
|
|
589
|
+
const query = { ...options.inline ? { inline: "true" } : {}, ...options.supplements === false ? { supplements: "false" } : {} };
|
|
590
|
+
const res = await this.client.requestEither({ method: "GET", path: path`/records/${id}/evidence`, query });
|
|
591
|
+
if (res.error || !options.inline || "bytes" in res.data) return res;
|
|
592
|
+
const link = res.data;
|
|
593
|
+
const download = await this.client.external(link.url, { method: "GET" }, "Evidence package download");
|
|
594
|
+
if (download.error) return fail(download.error);
|
|
595
|
+
try {
|
|
596
|
+
const bytes = new Uint8Array(await download.data.arrayBuffer());
|
|
597
|
+
return ok({ bytes, contentType: download.data.headers.get("content-type") ?? "application/zip", filename: `${link.record_id}.zip` });
|
|
598
|
+
} catch (err) {
|
|
599
|
+
return fail({ type: "api_error", code: "network_error", message: `Evidence package download: ${err instanceof Error ? err.message : String(err)}`, status: 0 });
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
/** The signed receipt (JWS): the compact proof you can keep in your own database. */
|
|
603
|
+
receipt(id) {
|
|
604
|
+
return this._get(path`/records/${id}/receipt`);
|
|
605
|
+
}
|
|
606
|
+
/**
|
|
607
|
+
* Add a later fact: `superseded`, `legal_hold`, `legal_hold_released`,
|
|
608
|
+
* `note`, `paper_copy_requested`. Body: `type`, and optionally `data` and a
|
|
609
|
+
* free-text `note`. The earlier report types `notice.sent` and
|
|
610
|
+
* `cancellation.requested` are still accepted here and are stored as
|
|
611
|
+
* supplements (SM-12); new code sends those to `supplements.create`.
|
|
612
|
+
*/
|
|
613
|
+
annotate(id, body, options) {
|
|
614
|
+
return this._post(path`/records/${id}/annotations`, body, options);
|
|
615
|
+
}
|
|
616
|
+
/** Issue an on-request certificate for one record (13.13). Needs `confirm_charge: true` when a charge would result. */
|
|
617
|
+
certify(id, body = {}, options) {
|
|
618
|
+
return this._post(path`/records/${id}/certificates`, body, options);
|
|
619
|
+
}
|
|
620
|
+
/** Submit a deferred acceptance under `fail_open_deferred`. The record says it was reported, not observed. */
|
|
621
|
+
submitDeferred(body, options) {
|
|
622
|
+
return this._post("/records/deferred", body, options);
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
|
|
626
|
+
// packages/esigncomply/src/resources/sessions.ts
|
|
627
|
+
var Sessions = class extends Resource {
|
|
628
|
+
/**
|
|
629
|
+
* Start a ceremony for one signer and a bundle of document versions (13.4).
|
|
630
|
+
* Hand `client_token` to the browser SDK and read the steps from
|
|
631
|
+
* `required_steps`. Pass an `idempotencyKey` so a retry cannot start two.
|
|
632
|
+
*/
|
|
633
|
+
create(body, options) {
|
|
634
|
+
return this._post("/sessions", body, options);
|
|
635
|
+
}
|
|
636
|
+
/** State and remaining steps. `record_id` is set once the ceremony completed. */
|
|
637
|
+
get(id) {
|
|
638
|
+
return this._get(path`/sessions/${id}`);
|
|
639
|
+
}
|
|
640
|
+
cancel(id, options) {
|
|
641
|
+
return this._post(path`/sessions/${id}/cancel`, {}, options);
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
|
|
645
|
+
// packages/esigncomply/src/resources/signers.ts
|
|
646
|
+
var Signers = class extends Resource {
|
|
647
|
+
/** All records for one signer. */
|
|
648
|
+
records(externalId, params = {}) {
|
|
649
|
+
return this._get(path`/signers/${externalId}/records`, params);
|
|
650
|
+
}
|
|
651
|
+
/** For each document: the latest version accepted, and whether the current version is outstanding (DV-4). */
|
|
652
|
+
status(externalId) {
|
|
653
|
+
return this._get(path`/signers/${externalId}/status`);
|
|
654
|
+
}
|
|
655
|
+
/** Record that the signer withdrew consent to electronic records. Body: `record_id`, `scope`, `note`, all optional. */
|
|
656
|
+
withdrawConsent(externalId, body = {}, options) {
|
|
657
|
+
return this._post(path`/signers/${externalId}/consents/withdraw`, body, options);
|
|
658
|
+
}
|
|
659
|
+
/** Start a data-subject erasure or restriction workflow (17.3). Body: `scope` (`erasure` by default, or `restriction`) and `basis`. */
|
|
660
|
+
requestErasure(externalId, body = {}, options) {
|
|
661
|
+
return this._post(path`/signers/${externalId}/erasure-requests`, body, options);
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
|
|
665
|
+
// packages/esigncomply/src/resources/supplements.ts
|
|
666
|
+
import { createHash } from "node:crypto";
|
|
667
|
+
import { readFile } from "node:fs/promises";
|
|
668
|
+
import { basename } from "node:path";
|
|
669
|
+
function subjectFilter(subject) {
|
|
670
|
+
if (subject === void 0 || typeof subject === "string") return subject;
|
|
671
|
+
const [kind, id] = Object.entries(subject)[0] ?? [];
|
|
672
|
+
if (kind === "domain") return "domain";
|
|
673
|
+
return typeof id === "string" && id ? id : void 0;
|
|
674
|
+
}
|
|
675
|
+
var Supplements = class extends Resource {
|
|
676
|
+
/**
|
|
677
|
+
* Send what you have, in the shape you have it. At least one of `text`,
|
|
678
|
+
* `data` or `files`; nothing else is required. The seal shows that you sent
|
|
679
|
+
* it no later than `received_at`. Esign Comply does not verify its content.
|
|
680
|
+
*/
|
|
681
|
+
create(body, options) {
|
|
682
|
+
return this._post("/supplements", body, options);
|
|
683
|
+
}
|
|
684
|
+
list(filters = {}) {
|
|
685
|
+
return this._get("/supplements", { ...filters, subject: subjectFilter(filters.subject) });
|
|
686
|
+
}
|
|
687
|
+
get(id) {
|
|
688
|
+
return this._get(path`/supplements/${id}`);
|
|
689
|
+
}
|
|
690
|
+
/** Text, data and files as stored. */
|
|
691
|
+
content(id) {
|
|
692
|
+
return this._get(path`/supplements/${id}/content`);
|
|
693
|
+
}
|
|
694
|
+
/** Withdraw a supplement (CS-14). It stays listed, marked withdrawn. */
|
|
695
|
+
withdraw(id) {
|
|
696
|
+
return this._send("DELETE", path`/supplements/${id}`);
|
|
697
|
+
}
|
|
698
|
+
/** The public catalogue of recognised types with suggested fields. Any other type is accepted too (SM-3). */
|
|
699
|
+
types() {
|
|
700
|
+
return this._get("/supplement-types");
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
var Files = class extends Resource {
|
|
704
|
+
/**
|
|
705
|
+
* Upload a file to attach to a supplement. Performs the three steps of the
|
|
706
|
+
* upload flow (13.14): registers the file with its name, size, type and
|
|
707
|
+
* SHA-256; sends the bytes straight to storage; then reads the file back so
|
|
708
|
+
* `status` reflects what the API saw. A file not referenced by a supplement
|
|
709
|
+
* within 7 days is deleted.
|
|
710
|
+
*/
|
|
711
|
+
async upload(pathOrBytes, options = {}) {
|
|
712
|
+
let bytes;
|
|
713
|
+
let name = options.name;
|
|
714
|
+
if (typeof pathOrBytes === "string") {
|
|
715
|
+
try {
|
|
716
|
+
bytes = await readFile(pathOrBytes);
|
|
717
|
+
} catch (err) {
|
|
718
|
+
return fail({ type: "invalid_request_error", code: "invalid_request", message: `Cannot read ${pathOrBytes}: ${err instanceof Error ? err.message : String(err)}`, param: "file", status: 0 });
|
|
719
|
+
}
|
|
720
|
+
name ??= basename(pathOrBytes);
|
|
721
|
+
} else if (pathOrBytes instanceof Uint8Array) {
|
|
722
|
+
bytes = pathOrBytes;
|
|
723
|
+
} else {
|
|
724
|
+
return fail({ type: "invalid_request_error", code: "invalid_request", message: "files.upload takes a file path or the bytes (Uint8Array or Buffer).", param: "file", status: 0 });
|
|
725
|
+
}
|
|
726
|
+
if (!name) return fail({ type: "invalid_request_error", code: "invalid_request", message: "Give the file a name: files.upload(bytes, { name }).", param: "name", status: 0 });
|
|
727
|
+
const contentType = options.contentType ?? "application/octet-stream";
|
|
728
|
+
const created = await this._post("/files", { name, size: bytes.length, content_type: contentType, sha256: "sha256:" + createHash("sha256").update(bytes).digest("hex") });
|
|
729
|
+
if (created.error) return created;
|
|
730
|
+
const file = created.data;
|
|
731
|
+
if (!file.upload_url) {
|
|
732
|
+
return fail({ type: "api_error", code: "invalid_response", message: "The API registered the file but returned no upload_url.", status: 0 });
|
|
733
|
+
}
|
|
734
|
+
const put = await this.client.external(file.upload_url, { method: "PUT", headers: { "Content-Type": contentType }, body: bytes }, `Upload of ${name}`);
|
|
735
|
+
if (put.error) return fail(put.error);
|
|
736
|
+
await put.data.arrayBuffer().catch(() => void 0);
|
|
737
|
+
const stored = await this.get(file.id);
|
|
738
|
+
if (stored.error) return ok({ ...file, upload_url: void 0, resumable_url: void 0 });
|
|
739
|
+
return stored;
|
|
740
|
+
}
|
|
741
|
+
/** Upload status: `stored` once Esign Comply has recomputed the hash, `rejected` on a mismatch. */
|
|
742
|
+
get(id) {
|
|
743
|
+
return this._get(path`/files/${id}`);
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
// packages/esigncomply/src/resources/webhooks.ts
|
|
748
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
749
|
+
function header(headers, name) {
|
|
750
|
+
if (typeof headers.get === "function") return headers.get(name);
|
|
751
|
+
const record = headers;
|
|
752
|
+
for (const key of Object.keys(record)) {
|
|
753
|
+
if (key.toLowerCase() !== name) continue;
|
|
754
|
+
const value = record[key];
|
|
755
|
+
return Array.isArray(value) ? value[0] ?? null : value ?? null;
|
|
756
|
+
}
|
|
757
|
+
return null;
|
|
758
|
+
}
|
|
759
|
+
var refuse = (code, message) => fail({ type: "invalid_request_error", code, message, status: 0 });
|
|
760
|
+
function secretKey(secret) {
|
|
761
|
+
return Buffer.from(secret.startsWith("whsec_") ? secret.slice(6) : secret, "base64");
|
|
762
|
+
}
|
|
763
|
+
function signWebhookPayload(secret, id, timestamp, body) {
|
|
764
|
+
return `v1,${createHmac("sha256", secretKey(secret)).update(`${id}.${timestamp}.${body}`).digest("base64")}`;
|
|
765
|
+
}
|
|
766
|
+
function verifyWebhookSignature(rawBody, headers, secret, options = {}) {
|
|
767
|
+
try {
|
|
768
|
+
if (typeof secret !== "string" || secret.length === 0) return refuse("webhook_signature_invalid", "No webhook secret. Pass the endpoint's whsec_\u2026 secret.");
|
|
769
|
+
if (typeof rawBody !== "string" && !(rawBody instanceof Uint8Array)) {
|
|
770
|
+
return refuse("webhook_payload_invalid", "Pass the raw request body exactly as received (a string or bytes), not a parsed object: the signature covers the bytes.");
|
|
771
|
+
}
|
|
772
|
+
const body = typeof rawBody === "string" ? rawBody : Buffer.from(rawBody).toString("utf8");
|
|
773
|
+
const id = header(headers, "webhook-id");
|
|
774
|
+
const timestamp = header(headers, "webhook-timestamp");
|
|
775
|
+
const signature = header(headers, "webhook-signature");
|
|
776
|
+
if (!id || !timestamp || !signature) {
|
|
777
|
+
return refuse("webhook_signature_missing", "The request lacks webhook-id, webhook-timestamp or webhook-signature. It did not come from Esign Comply, or a proxy removed the headers.");
|
|
778
|
+
}
|
|
779
|
+
const seconds = Number(timestamp);
|
|
780
|
+
const now = (options.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3;
|
|
781
|
+
const tolerance = options.toleranceSeconds ?? 300;
|
|
782
|
+
if (!/^\d+$/.test(timestamp) || !Number.isFinite(seconds) || Math.abs(now - seconds) > tolerance) {
|
|
783
|
+
return refuse("webhook_timestamp_out_of_tolerance", `The delivery's timestamp is more than ${tolerance} seconds from now. Old deliveries are refused so a captured request cannot be replayed.`);
|
|
784
|
+
}
|
|
785
|
+
const expected = createHmac("sha256", secretKey(secret)).update(`${id}.${timestamp}.${body}`).digest();
|
|
786
|
+
let matched = false;
|
|
787
|
+
for (const part of signature.split(" ")) {
|
|
788
|
+
const comma = part.indexOf(",");
|
|
789
|
+
if (comma < 0 || part.slice(0, comma) !== "v1") continue;
|
|
790
|
+
const got = Buffer.from(part.slice(comma + 1), "base64");
|
|
791
|
+
if (got.length === expected.length && timingSafeEqual(got, expected)) matched = true;
|
|
792
|
+
}
|
|
793
|
+
if (!matched) return refuse("webhook_signature_invalid", "The signature does not match. Check that the secret belongs to this endpoint and that the body is the raw, unparsed request body.");
|
|
794
|
+
let event;
|
|
795
|
+
try {
|
|
796
|
+
event = JSON.parse(body);
|
|
797
|
+
} catch {
|
|
798
|
+
return refuse("webhook_payload_invalid", "The signature is valid but the body is not JSON.");
|
|
799
|
+
}
|
|
800
|
+
if (typeof event !== "object" || event === null || Array.isArray(event)) return refuse("webhook_payload_invalid", "The signature is valid but the body is not an event object.");
|
|
801
|
+
return ok(event);
|
|
802
|
+
} catch (err) {
|
|
803
|
+
return refuse("webhook_signature_invalid", `The delivery could not be verified: ${err instanceof Error ? err.message : String(err)}`);
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
var Webhooks = class extends Resource {
|
|
807
|
+
/**
|
|
808
|
+
* Verify a delivery and return its event. Pass the raw body exactly as
|
|
809
|
+
* received. Deliveries older than 5 minutes are refused (WH-2). Deliveries
|
|
810
|
+
* are at-least-once: make your handler idempotent on `event.id` (WH-4), and
|
|
811
|
+
* ignore event types you do not know (WH-6).
|
|
812
|
+
*/
|
|
813
|
+
async verify(rawBody, headers, secret, options) {
|
|
814
|
+
return verifyWebhookSignature(rawBody, headers, secret, options);
|
|
815
|
+
}
|
|
816
|
+
/** Register an endpoint. The response carries the signing `secret` once. */
|
|
817
|
+
create(body, options) {
|
|
818
|
+
return this._post("/webhooks", body, options);
|
|
819
|
+
}
|
|
820
|
+
list() {
|
|
821
|
+
return this._get("/webhooks");
|
|
822
|
+
}
|
|
823
|
+
update(id, body) {
|
|
824
|
+
return this._send("PATCH", path`/webhooks/${id}`, body);
|
|
825
|
+
}
|
|
826
|
+
delete(id) {
|
|
827
|
+
return this._send("DELETE", path`/webhooks/${id}`);
|
|
828
|
+
}
|
|
829
|
+
/**
|
|
830
|
+
* Delivery history with response codes. `since` returns deliveries created
|
|
831
|
+
* after that time, oldest first; `include: "payload"` adds each event.
|
|
832
|
+
* Used by `esigncomply webhooks listen`.
|
|
833
|
+
*/
|
|
834
|
+
listDeliveries(params = {}) {
|
|
835
|
+
return this._get("/webhooks/deliveries", params);
|
|
836
|
+
}
|
|
837
|
+
};
|
|
838
|
+
|
|
839
|
+
// packages/esigncomply/src/index.ts
|
|
840
|
+
var EsignComply = class {
|
|
841
|
+
documents;
|
|
842
|
+
profiles;
|
|
843
|
+
jurisdictions;
|
|
844
|
+
sessions;
|
|
845
|
+
records;
|
|
846
|
+
certificates;
|
|
847
|
+
supplements;
|
|
848
|
+
files;
|
|
849
|
+
guidance;
|
|
850
|
+
signers;
|
|
851
|
+
webhooks;
|
|
852
|
+
usage;
|
|
853
|
+
conformance;
|
|
854
|
+
prompts;
|
|
855
|
+
domains;
|
|
856
|
+
apiKeys;
|
|
857
|
+
client;
|
|
858
|
+
/**
|
|
859
|
+
* @param apiKey A secret key (`esc_test_us_…`, `esc_live_eu_…`). Default: the `ESIGNCOMPLY_API_KEY` environment variable.
|
|
860
|
+
* The region code in the key selects the API host.
|
|
861
|
+
*/
|
|
862
|
+
constructor(apiKey, options = {}) {
|
|
863
|
+
if (typeof window !== "undefined") {
|
|
864
|
+
throw new Error(
|
|
865
|
+
"The esigncomply server SDK was loaded in a browser. Your secret API key must never reach client code: anyone who opens the page could read it. Create the session on your server with esc.sessions.create() and pass only its client_token to @esigncomply/browser."
|
|
866
|
+
);
|
|
867
|
+
}
|
|
868
|
+
const client = new HttpClient(apiKey, options);
|
|
869
|
+
this.client = client;
|
|
870
|
+
this.documents = new Documents(client);
|
|
871
|
+
this.profiles = new Profiles(client);
|
|
872
|
+
this.jurisdictions = new Jurisdictions(client);
|
|
873
|
+
this.sessions = new Sessions(client);
|
|
874
|
+
this.records = new Records(client);
|
|
875
|
+
this.certificates = new Certificates(client);
|
|
876
|
+
this.supplements = new Supplements(client);
|
|
877
|
+
this.files = new Files(client);
|
|
878
|
+
this.guidance = new Guidance(client);
|
|
879
|
+
this.signers = new Signers(client);
|
|
880
|
+
this.webhooks = new Webhooks(client);
|
|
881
|
+
this.usage = new UsageResource(client);
|
|
882
|
+
this.conformance = new Conformance(client);
|
|
883
|
+
this.prompts = new Prompts(client);
|
|
884
|
+
this.domains = new Domains(client);
|
|
885
|
+
this.apiKeys = new ApiKeys(client);
|
|
886
|
+
}
|
|
887
|
+
/** The API base URL in use, e.g. `https://api.eu.esigncomply.com/v1`. */
|
|
888
|
+
get baseUrl() {
|
|
889
|
+
return this.client.baseUrl;
|
|
890
|
+
}
|
|
891
|
+
/**
|
|
892
|
+
* Ask the API whether a record matches its seal. Pass one of:
|
|
893
|
+
*
|
|
894
|
+
* - the full signed receipt (a compact JWS, three dot-separated parts), sent
|
|
895
|
+
* as `receipt`: anyone holding it may ask;
|
|
896
|
+
* - a record hash (`sha256:…`, or the 64 hexadecimal digits alone), sent as `record_hash`;
|
|
897
|
+
* - a record ID (`rec_…`), sent as `record_id`.
|
|
898
|
+
*
|
|
899
|
+
* A hash or an ID is answered only for a record of the domain and
|
|
900
|
+
* environment of the secret key this client was created with. The answer is
|
|
901
|
+
* proof status only: an ID or hash alone never reveals that a record exists
|
|
902
|
+
* (10.7).
|
|
903
|
+
*
|
|
904
|
+
* To verify without the API at all, use `esigncomply-verify`.
|
|
905
|
+
*/
|
|
906
|
+
verify(receiptOrHash) {
|
|
907
|
+
const value = String(receiptOrHash ?? "").trim();
|
|
908
|
+
const isHash = value.startsWith("sha256:") || /^[0-9a-f]{64}$/i.test(value);
|
|
909
|
+
const body = value.split(".").length === 3 ? { receipt: value } : isHash ? { record_hash: value } : { record_id: value };
|
|
910
|
+
return this.client.request({ method: "POST", path: "/verify", body });
|
|
911
|
+
}
|
|
912
|
+
/**
|
|
913
|
+
* Call an endpoint this SDK version has no method for. Same contract as
|
|
914
|
+
* every other method: resolves to `{ data, error }`, never throws.
|
|
915
|
+
*
|
|
916
|
+
* `token` authenticates with a session client token instead of the API key,
|
|
917
|
+
* which is how a server reports the steps of a `server_only` session.
|
|
918
|
+
*/
|
|
919
|
+
request(method, path2, params = {}) {
|
|
920
|
+
const { query, body, token, ...options } = params;
|
|
921
|
+
return this.client.request({ method, path: path2, query, body: body ?? (method === "POST" ? {} : void 0), token, options });
|
|
922
|
+
}
|
|
923
|
+
};
|
|
924
|
+
|
|
925
|
+
// packages/esigncomply/src/cli/io.ts
|
|
926
|
+
function processIo() {
|
|
927
|
+
return {
|
|
928
|
+
out: (t) => process.stdout.write(t),
|
|
929
|
+
err: (t) => process.stderr.write(t),
|
|
930
|
+
env: process.env,
|
|
931
|
+
isTTY: process.stdout.isTTY === true && !process.env.NO_COLOR
|
|
932
|
+
};
|
|
933
|
+
}
|
|
934
|
+
var CODES = { green: 32, red: 31, yellow: 33, dim: 2, bold: 1 };
|
|
935
|
+
function paint(io, color, text) {
|
|
936
|
+
return io.isTTY ? `\x1B[${CODES[color]}m${text}\x1B[0m` : text;
|
|
937
|
+
}
|
|
938
|
+
function line(io, text = "") {
|
|
939
|
+
io.out(text + "\n");
|
|
940
|
+
}
|
|
941
|
+
function clientFromEnv(io, options = {}) {
|
|
942
|
+
const key = (io.env.ESIGNCOMPLY_API_KEY ?? "").trim();
|
|
943
|
+
if (!key) {
|
|
944
|
+
throw new UsageError("Set ESIGNCOMPLY_API_KEY to a test key (esc_test_\u2026). Create one in the dashboard under API keys, then: export ESIGNCOMPLY_API_KEY=esc_test_\u2026");
|
|
945
|
+
}
|
|
946
|
+
if (options.testOnly) {
|
|
947
|
+
const mode = keyMode(key);
|
|
948
|
+
if (mode === "live") throw new UsageError(`${options.testOnly} Use a test key (esc_test_\u2026); live keys are refused.`);
|
|
949
|
+
if (mode !== "test") throw new UsageError(`ESIGNCOMPLY_API_KEY does not look like an Esign Comply key (esc_test_\u2026). ${options.testOnly}`);
|
|
950
|
+
}
|
|
951
|
+
return new EsignComply(key, { baseUrl: io.env.ESIGNCOMPLY_API_URL || void 0, maxRetries: 5 });
|
|
952
|
+
}
|
|
953
|
+
function describeError(error) {
|
|
954
|
+
const parts = [error.message];
|
|
955
|
+
if (error.param) parts.push(`(field: ${error.param})`);
|
|
956
|
+
if (error.missing_steps?.length) parts.push(`Missing steps: ${error.missing_steps.join(", ")}.`);
|
|
957
|
+
if (error.rule) parts.push(`Rule ${error.rule}.`);
|
|
958
|
+
parts.push(`[${error.code}${error.status ? `, HTTP ${error.status}` : ""}${error.request_id ? `, request ${error.request_id}` : ""}]`);
|
|
959
|
+
return parts.join(" ");
|
|
960
|
+
}
|
|
961
|
+
var CommandError = class extends Error {
|
|
962
|
+
constructor(message, exitCode = 1) {
|
|
963
|
+
super(message);
|
|
964
|
+
this.exitCode = exitCode;
|
|
965
|
+
}
|
|
966
|
+
exitCode;
|
|
967
|
+
};
|
|
968
|
+
function must(result, doing) {
|
|
969
|
+
if (result.error) throw new CommandError(`${doing} failed: ${describeError(result.error)}`);
|
|
970
|
+
return result.data;
|
|
971
|
+
}
|
|
972
|
+
function appOrigin(baseUrl) {
|
|
973
|
+
try {
|
|
974
|
+
const u = new URL(baseUrl);
|
|
975
|
+
if (/^api(\.[a-z]{2})?\.esigncomply\.com$/.test(u.hostname)) return "https://esigncomply.com";
|
|
976
|
+
return u.origin;
|
|
977
|
+
} catch {
|
|
978
|
+
return "https://esigncomply.com";
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
|
|
982
|
+
// packages/esigncomply/src/cli/check.ts
|
|
983
|
+
var CHECK_HELP = `esigncomply check --url <page> [--region US-CA \u2026] [--json]
|
|
984
|
+
|
|
985
|
+
The active conformance checker (spec 12.6). It opens your page in a headless
|
|
986
|
+
browser at 390x844, 768x1024 and 1440x900, runs the ceremony with a test
|
|
987
|
+
signer at each size, and reports the findings for the test sessions it saw.
|
|
988
|
+
It also tries things that must be refused: submitting with the checkbox
|
|
989
|
+
untouched, a programmatic click, and completing from another origin.
|
|
990
|
+
|
|
991
|
+
--url <page> The page that runs the ceremony, for example http://localhost:3000/signup.
|
|
992
|
+
--region <code> Dry-run the jurisdiction resolution for a signer in this region (JR-12),
|
|
993
|
+
for example --region US-CA --region US-NY. Repeatable. Works without --url.
|
|
994
|
+
--profile <id> Profile for the dry run. Default: the domain's only profile.
|
|
995
|
+
--purpose <purpose> context.purpose for the dry run, for example auto_renewal.
|
|
996
|
+
--signer-class <c> consumer (default), business or employee, for the dry run.
|
|
997
|
+
--checkbox <css> The assent checkbox, when the checker cannot find it.
|
|
998
|
+
--submit <css> The button that performs the signing act.
|
|
999
|
+
--fill <css=value> Fill a field before submitting. Repeatable. Empty text, e-mail and
|
|
1000
|
+
password fields are filled with test values on their own.
|
|
1001
|
+
--callback <url> Your server's confirmation endpoint. The checker posts a forged
|
|
1002
|
+
success to it and expects a refusal (CC-3).
|
|
1003
|
+
--timeout <seconds> How long to wait for the ceremony to complete at each size. Default 20.
|
|
1004
|
+
--json Print the report as JSON.
|
|
1005
|
+
|
|
1006
|
+
Environment
|
|
1007
|
+
ESIGNCOMPLY_API_KEY A test key (esc_test_\u2026) for the domain the page uses. Live keys are refused.
|
|
1008
|
+
ESIGNCOMPLY_API_URL API base URL, for local development.
|
|
1009
|
+
|
|
1010
|
+
Exit codes
|
|
1011
|
+
0 no blocking finding
|
|
1012
|
+
1 a blocking finding, a violation that was not refused, or a ceremony that did not complete
|
|
1013
|
+
2 the check could not run (bad arguments, Playwright not installed)
|
|
1014
|
+
|
|
1015
|
+
Findings are advisory statements about measurable design facts. The checker
|
|
1016
|
+
does not state that a flow is lawful or enforceable.
|
|
1017
|
+
`;
|
|
1018
|
+
var VIEWPORTS = [
|
|
1019
|
+
{ width: 390, height: 844 },
|
|
1020
|
+
{ width: 768, height: 1024 },
|
|
1021
|
+
{ width: 1440, height: 900 }
|
|
1022
|
+
];
|
|
1023
|
+
var ADVISORY = "Findings are advisory statements about measurable design facts. The checker does not state that a flow is lawful or enforceable.";
|
|
1024
|
+
var size = (v) => `${v.width}x${v.height}`;
|
|
1025
|
+
var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
1026
|
+
function observe(page, viewport, purpose, sessions) {
|
|
1027
|
+
page.on("response", (response) => {
|
|
1028
|
+
void (async () => {
|
|
1029
|
+
const request = response.request();
|
|
1030
|
+
if (request.method() !== "POST") return;
|
|
1031
|
+
let target;
|
|
1032
|
+
try {
|
|
1033
|
+
target = new URL(response.url());
|
|
1034
|
+
} catch {
|
|
1035
|
+
return;
|
|
1036
|
+
}
|
|
1037
|
+
const m = /^(.*\/v1)\/sessions\/([^/]+)\/(events|complete)$/.exec(target.pathname);
|
|
1038
|
+
if (!m) return;
|
|
1039
|
+
const id = decodeURIComponent(m[2]);
|
|
1040
|
+
const session = sessions.get(id) ?? { id, viewport, purpose, apiBase: target.origin + m[1], token: null, events: 0, findings: [], recordId: null, completeStatus: null, completeError: null };
|
|
1041
|
+
sessions.set(id, session);
|
|
1042
|
+
const auth = request.headers()["authorization"];
|
|
1043
|
+
if (auth?.startsWith("Bearer ")) session.token = auth.slice(7);
|
|
1044
|
+
const body = await response.json().catch(() => null);
|
|
1045
|
+
if (m[3] === "events") {
|
|
1046
|
+
session.events++;
|
|
1047
|
+
const conformance = body?.conformance;
|
|
1048
|
+
const errorFindings = body?.error?.findings;
|
|
1049
|
+
for (const f of [...conformance?.findings ?? [], ...errorFindings ?? []]) {
|
|
1050
|
+
session.findings.push({ ...f, viewport, session_id: id, event_type: String(f.event_type ?? body?.type ?? "") || void 0 });
|
|
1051
|
+
}
|
|
1052
|
+
} else {
|
|
1053
|
+
session.completeStatus = response.status();
|
|
1054
|
+
if (response.status() >= 200 && response.status() < 300 && typeof body?.id === "string") session.recordId = body.id;
|
|
1055
|
+
else session.completeError = String(body?.error?.code ?? response.status());
|
|
1056
|
+
}
|
|
1057
|
+
})();
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
async function findControls(page, flags) {
|
|
1061
|
+
const first = async (selectors) => {
|
|
1062
|
+
for (const selector of selectors) {
|
|
1063
|
+
const el = page.locator(selector).first();
|
|
1064
|
+
if (await el.count() > 0 && await el.isVisible().catch(() => false)) return selector;
|
|
1065
|
+
}
|
|
1066
|
+
return null;
|
|
1067
|
+
};
|
|
1068
|
+
return {
|
|
1069
|
+
checkbox: flags.checkbox ?? await first(['input[type="checkbox"]', '[role="checkbox"]']),
|
|
1070
|
+
submit: flags.submit ?? await first(['button[type="submit"]', 'input[type="submit"]', "form button", "button"])
|
|
1071
|
+
};
|
|
1072
|
+
}
|
|
1073
|
+
async function fillFields(page, fills) {
|
|
1074
|
+
for (const pair of fills) {
|
|
1075
|
+
const eq = pair.indexOf("=");
|
|
1076
|
+
if (eq <= 0) throw new UsageError(`--fill takes selector=value, got "${pair}".`);
|
|
1077
|
+
await page.fill(pair.slice(0, eq), pair.slice(eq + 1));
|
|
1078
|
+
}
|
|
1079
|
+
const tag = Math.random().toString(36).slice(2, 8);
|
|
1080
|
+
const defaults = [
|
|
1081
|
+
['input[type="email"]', `conformance.check+${tag}@example.com`],
|
|
1082
|
+
['input[type="password"]', `Check-${tag}-Aa1!`],
|
|
1083
|
+
['input[type="tel"]', "+15555550100"],
|
|
1084
|
+
['input[type="text"], input:not([type])', "Conformance Check"]
|
|
1085
|
+
];
|
|
1086
|
+
for (const [selector, value] of defaults) {
|
|
1087
|
+
const fields = page.locator(selector);
|
|
1088
|
+
const count = await fields.count();
|
|
1089
|
+
for (let i = 0; i < count; i++) {
|
|
1090
|
+
const field = fields.nth(i);
|
|
1091
|
+
if (!await field.isVisible().catch(() => false) || !await field.isEditable().catch(() => false)) continue;
|
|
1092
|
+
if (await field.inputValue().catch(() => "x") === "") await field.fill(value).catch(() => void 0);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
async function load(browser, url, viewport, purpose, sessions, settleMs) {
|
|
1097
|
+
const context = await browser.newContext({ viewport: { width: viewport.width, height: viewport.height } });
|
|
1098
|
+
const page = await context.newPage();
|
|
1099
|
+
observe(page, size(viewport), purpose, sessions);
|
|
1100
|
+
await page.goto(url, { waitUntil: "load", timeout: 3e4 });
|
|
1101
|
+
await page.waitForLoadState("networkidle", { timeout: settleMs }).catch(() => void 0);
|
|
1102
|
+
return { page, close: () => context.close().catch(() => void 0) };
|
|
1103
|
+
}
|
|
1104
|
+
async function waitUntilEnabled(page, selectors, timeoutMs) {
|
|
1105
|
+
const until = Date.now() + timeoutMs;
|
|
1106
|
+
for (const selector of selectors) {
|
|
1107
|
+
if (!selector) continue;
|
|
1108
|
+
const el = page.locator(selector).first();
|
|
1109
|
+
while (!await el.isEnabled().catch(() => true)) {
|
|
1110
|
+
if (Date.now() > until) return false;
|
|
1111
|
+
await delay(100);
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
return true;
|
|
1115
|
+
}
|
|
1116
|
+
function sessionsOf(sessions, viewport, purpose) {
|
|
1117
|
+
return [...sessions.values()].filter((s) => s.viewport === viewport && s.purpose === purpose);
|
|
1118
|
+
}
|
|
1119
|
+
async function waitForCompletion(sessions, viewport, purpose, timeoutMs) {
|
|
1120
|
+
const until = Date.now() + timeoutMs;
|
|
1121
|
+
while (Date.now() < until) {
|
|
1122
|
+
const done = sessionsOf(sessions, viewport, purpose).find((s) => s.completeStatus !== null);
|
|
1123
|
+
if (done) return done;
|
|
1124
|
+
await delay(150);
|
|
1125
|
+
}
|
|
1126
|
+
return null;
|
|
1127
|
+
}
|
|
1128
|
+
async function violationAttempts(browser, url, flags, sessions, settleMs) {
|
|
1129
|
+
const attempts = [];
|
|
1130
|
+
const viewport = VIEWPORTS[0];
|
|
1131
|
+
const made = (purpose) => sessionsOf(sessions, size(viewport), purpose).find((s) => s.recordId);
|
|
1132
|
+
const verdict = (id, title, purpose, what) => {
|
|
1133
|
+
const record = made(purpose);
|
|
1134
|
+
if (!record) return { id, title, outcome: "refused", detail: "No record was made." };
|
|
1135
|
+
const blocks = [...new Set(record.findings.filter((f) => f.status === "block").map((f) => f.rule))];
|
|
1136
|
+
if (blocks.length > 0) {
|
|
1137
|
+
return { id, title, outcome: "refused", detail: `Flagged as blocking (${blocks.join(", ")}). Test mode still made record ${record.recordId} so the finding can be seen; live mode refuses it.` };
|
|
1138
|
+
}
|
|
1139
|
+
return { id, title, outcome: "accepted", detail: `Record ${record.recordId} was made ${what}, and no rule flagged it.` };
|
|
1140
|
+
};
|
|
1141
|
+
{
|
|
1142
|
+
const title = "Submit with the checkbox untouched";
|
|
1143
|
+
const { page, close } = await load(browser, url, viewport, "untouched", sessions, settleMs);
|
|
1144
|
+
try {
|
|
1145
|
+
const controls = await findControls(page, flags);
|
|
1146
|
+
if (!controls.checkbox || !controls.submit) {
|
|
1147
|
+
attempts.push({ id: "untouched_checkbox", title, outcome: "skipped", detail: "No checkbox and submit button were found on the page. Name them with --checkbox and --submit." });
|
|
1148
|
+
} else {
|
|
1149
|
+
await fillFields(page, flags.fill);
|
|
1150
|
+
await page.click(controls.submit, { timeout: 3e3 }).catch(() => void 0);
|
|
1151
|
+
await waitForCompletion(sessions, size(viewport), "untouched", 2500);
|
|
1152
|
+
attempts.push(verdict("untouched_checkbox", title, "untouched", "although the signer never ticked the box"));
|
|
1153
|
+
}
|
|
1154
|
+
const title3 = "Completion from another origin";
|
|
1155
|
+
const seen = sessionsOf(sessions, size(viewport), "untouched").find((s) => s.token);
|
|
1156
|
+
if (!seen?.token) {
|
|
1157
|
+
attempts.push({ id: "foreign_origin", title: title3, outcome: "skipped", detail: "The page made no ceremony call on load, so there was no session to try." });
|
|
1158
|
+
} else {
|
|
1159
|
+
const res = await fetch(`${seen.apiBase}/sessions/${encodeURIComponent(seen.id)}/complete`, {
|
|
1160
|
+
method: "POST",
|
|
1161
|
+
headers: { Authorization: `Bearer ${seen.token}`, "Content-Type": "application/json", Origin: "https://conformance-check.invalid" },
|
|
1162
|
+
body: "{}",
|
|
1163
|
+
signal: AbortSignal.timeout(15e3)
|
|
1164
|
+
}).catch(() => null);
|
|
1165
|
+
const body = await res?.json().catch(() => null);
|
|
1166
|
+
const code = body?.error?.code ?? "";
|
|
1167
|
+
if (!res) attempts.push({ id: "foreign_origin", title: title3, outcome: "skipped", detail: "The API could not be reached from this process." });
|
|
1168
|
+
else if (res.status === 403 && code === "domain_mismatch") attempts.push({ id: "foreign_origin", title: title3, outcome: "refused", detail: "The API answered 403 domain_mismatch." });
|
|
1169
|
+
else if (res.status >= 200 && res.status < 300) attempts.push({ id: "foreign_origin", title: title3, outcome: "accepted", detail: "The API completed the ceremony for a call from https://conformance-check.invalid." });
|
|
1170
|
+
else attempts.push({ id: "foreign_origin", title: title3, outcome: "accepted", detail: `The API did not refuse the origin: it answered ${res.status} ${code}. An origin outside the registered domain and the test allowlist must get 403 domain_mismatch.` });
|
|
1171
|
+
}
|
|
1172
|
+
} finally {
|
|
1173
|
+
await close();
|
|
1174
|
+
}
|
|
1175
|
+
}
|
|
1176
|
+
{
|
|
1177
|
+
const title = "Programmatic click";
|
|
1178
|
+
const { page, close } = await load(browser, url, viewport, "programmatic", sessions, settleMs);
|
|
1179
|
+
try {
|
|
1180
|
+
const controls = await findControls(page, flags);
|
|
1181
|
+
if (!controls.checkbox || !controls.submit) {
|
|
1182
|
+
attempts.push({ id: "programmatic_click", title, outcome: "skipped", detail: "No checkbox and submit button were found on the page." });
|
|
1183
|
+
} else {
|
|
1184
|
+
await fillFields(page, flags.fill);
|
|
1185
|
+
await waitUntilEnabled(page, [controls.checkbox], settleMs);
|
|
1186
|
+
await page.evaluate(
|
|
1187
|
+
([checkbox, submit]) => {
|
|
1188
|
+
document.querySelector(checkbox)?.click();
|
|
1189
|
+
document.querySelector(submit)?.click();
|
|
1190
|
+
},
|
|
1191
|
+
[controls.checkbox, controls.submit]
|
|
1192
|
+
);
|
|
1193
|
+
await waitForCompletion(sessions, size(viewport), "programmatic", 4e3);
|
|
1194
|
+
attempts.push(verdict("programmatic_click", title, "programmatic", "from clicks a script produced"));
|
|
1195
|
+
}
|
|
1196
|
+
} finally {
|
|
1197
|
+
await close();
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
attempts.push({ id: "altered_document", title: "Altered document text", outcome: "skipped", detail: "Not attempted by this version of the checker." });
|
|
1201
|
+
attempts.push({ id: "skipped_verification", title: "Skipped verification step", outcome: "skipped", detail: "Not attempted by this version of the checker." });
|
|
1202
|
+
return attempts;
|
|
1203
|
+
}
|
|
1204
|
+
async function forgedCallback(callback) {
|
|
1205
|
+
const title = "Forged success posted to your callback";
|
|
1206
|
+
if (!callback) return { id: "forged_callback", title, outcome: "skipped", detail: "Pass --callback <url> to post a forged success to your server and expect a refusal (CC-3)." };
|
|
1207
|
+
const forged = { record_id: "rec_forgedByConformanceCheck", recordId: "rec_forgedByConformanceCheck", receipt: "forged.by.conformance-check", status: "recorded" };
|
|
1208
|
+
try {
|
|
1209
|
+
const res = await fetch(callback, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(forged), redirect: "manual", signal: AbortSignal.timeout(15e3) });
|
|
1210
|
+
await res.arrayBuffer().catch(() => void 0);
|
|
1211
|
+
return res.status >= 200 && res.status < 300 ? { id: "forged_callback", title, outcome: "accepted", detail: `${callback} answered ${res.status} to a record that does not exist. Confirm every record with esc.records.get() before granting access (CP-3).` } : { id: "forged_callback", title, outcome: "refused", detail: `${callback} answered ${res.status}.` };
|
|
1212
|
+
} catch (err) {
|
|
1213
|
+
return { id: "forged_callback", title, outcome: "skipped", detail: `${callback} could not be reached: ${err instanceof Error ? err.message : String(err)}` };
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
async function runCeremony(browser, url, viewport, flags, sessions, timeoutMs) {
|
|
1217
|
+
const { page, close } = await load(browser, url, viewport, "ceremony", sessions, timeoutMs);
|
|
1218
|
+
try {
|
|
1219
|
+
const controls = await findControls(page, flags);
|
|
1220
|
+
if (!controls.submit) return "no submit button was found; name it with --submit";
|
|
1221
|
+
await fillFields(page, flags.fill);
|
|
1222
|
+
if (controls.checkbox) {
|
|
1223
|
+
if (!await waitUntilEnabled(page, [controls.checkbox], timeoutMs)) return "the checkbox stayed disabled";
|
|
1224
|
+
const box = page.locator(controls.checkbox).first();
|
|
1225
|
+
if (!await box.isChecked().catch(() => false)) await box.click({ timeout: 5e3 });
|
|
1226
|
+
await page.waitForLoadState("networkidle", { timeout: 3e3 }).catch(() => void 0);
|
|
1227
|
+
}
|
|
1228
|
+
await page.click(controls.submit, { timeout: 5e3 });
|
|
1229
|
+
const done = await waitForCompletion(sessions, size(viewport), "ceremony", timeoutMs);
|
|
1230
|
+
if (!done) return sessionsOf(sessions, size(viewport), "ceremony").length === 0 ? "the page made no call to the Esign Comply API" : "the ceremony did not reach completion in time";
|
|
1231
|
+
if (!done.recordId) return `the API refused completion (${done.completeError})`;
|
|
1232
|
+
return null;
|
|
1233
|
+
} catch (err) {
|
|
1234
|
+
return (err instanceof Error ? err.message : String(err)).split("\n")[0];
|
|
1235
|
+
} finally {
|
|
1236
|
+
await close();
|
|
1237
|
+
}
|
|
1238
|
+
}
|
|
1239
|
+
async function dryRuns(esc, regions, flags, problems) {
|
|
1240
|
+
if (regions.length === 0) return [];
|
|
1241
|
+
let profile = flags.profile;
|
|
1242
|
+
if (!profile) {
|
|
1243
|
+
const profiles = await esc.profiles.list();
|
|
1244
|
+
if (profiles.error) throw new UsageError(`The dry run needs a profile, and listing profiles failed: ${describeError(profiles.error)}`);
|
|
1245
|
+
if (profiles.data.data.length === 0) throw new UsageError("The dry run needs a profile and this domain has none. Create one, or pass --profile <id>.");
|
|
1246
|
+
if (profiles.data.data.length > 1) problems.push(`--profile was not given; the dry run used ${profiles.data.data[0].id} (${profiles.data.data[0].name}).`);
|
|
1247
|
+
profile = profiles.data.data[0].id;
|
|
1248
|
+
}
|
|
1249
|
+
const out = [];
|
|
1250
|
+
for (const region of regions) {
|
|
1251
|
+
const country = /^[A-Za-z]{2}-/.test(region) ? region.slice(0, 2).toUpperCase() : void 0;
|
|
1252
|
+
const res = await esc.jurisdictions.resolve({ profile, signer: { class: flags.signerClass ?? "consumer", ...country ? { country } : {}, region }, ...flags.purpose ? { context: { purpose: flags.purpose } } : {} });
|
|
1253
|
+
if (res.error) {
|
|
1254
|
+
const unavailable = res.error.status === 404 && res.error.code === "not_found" && !res.error.request_id;
|
|
1255
|
+
out.push({ region, resolution: null, error: unavailable ? "The dry-run endpoint (POST /v1/jurisdictions/resolve) is not available on this API." : describeError(res.error) });
|
|
1256
|
+
} else {
|
|
1257
|
+
out.push({ region, resolution: res.data, error: null });
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
return out;
|
|
1261
|
+
}
|
|
1262
|
+
async function collectFindings(esc, sessions) {
|
|
1263
|
+
const problems = [];
|
|
1264
|
+
const ceremonies = sessions.filter((s) => s.purpose === "ceremony");
|
|
1265
|
+
const runs = [];
|
|
1266
|
+
const findings = [];
|
|
1267
|
+
let available = true;
|
|
1268
|
+
for (const s of ceremonies) {
|
|
1269
|
+
const started = await esc.conformance.run({ session_ids: [s.id] });
|
|
1270
|
+
if (started.error) {
|
|
1271
|
+
available = false;
|
|
1272
|
+
if (started.error.status !== 404) problems.push(`The conformance run for ${s.viewport} failed: ${describeError(started.error)}`);
|
|
1273
|
+
break;
|
|
1274
|
+
}
|
|
1275
|
+
let run2 = started.data;
|
|
1276
|
+
for (let i = 0; i < 30 && (run2.status === "queued" || run2.status === "running"); i++) {
|
|
1277
|
+
await delay(2e3);
|
|
1278
|
+
const next = await esc.conformance.get(run2.id);
|
|
1279
|
+
if (next.error) break;
|
|
1280
|
+
run2 = next.data;
|
|
1281
|
+
}
|
|
1282
|
+
runs.push({ viewport: s.viewport, run: run2 });
|
|
1283
|
+
for (const f of run2.findings ?? []) {
|
|
1284
|
+
findings.push({
|
|
1285
|
+
rule: f.rule,
|
|
1286
|
+
status: f.status,
|
|
1287
|
+
state: f.state,
|
|
1288
|
+
message: f.message,
|
|
1289
|
+
measurement: f.measurement,
|
|
1290
|
+
...f.fix ? { fix: f.fix } : {},
|
|
1291
|
+
...f.selector ? { selector: f.selector } : {},
|
|
1292
|
+
...f.prompt_instruction ? { prompt_instruction: f.prompt_instruction } : {},
|
|
1293
|
+
viewport: s.viewport,
|
|
1294
|
+
session_id: s.id,
|
|
1295
|
+
...s.recordId ? { record_id: s.recordId } : {}
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
if (available) return { available, runs, findings, problems };
|
|
1300
|
+
findings.length = 0;
|
|
1301
|
+
for (const s of ceremonies) {
|
|
1302
|
+
if (!s.recordId) continue;
|
|
1303
|
+
const record = await esc.records.get(s.recordId);
|
|
1304
|
+
if (record.error) {
|
|
1305
|
+
problems.push(`Reading ${s.recordId} failed: ${describeError(record.error)}`);
|
|
1306
|
+
continue;
|
|
1307
|
+
}
|
|
1308
|
+
for (const r of record.data.conformance?.results ?? []) {
|
|
1309
|
+
const m = r.measurement ?? {};
|
|
1310
|
+
findings.push({ rule: r.rule, status: r.status, state: "enforce", message: r.message, measurement: m, ...typeof m.fix === "string" ? { fix: m.fix } : {}, viewport: s.viewport, record_id: s.recordId, session_id: s.id });
|
|
1311
|
+
}
|
|
1312
|
+
for (const a of record.data.advisories ?? []) {
|
|
1313
|
+
findings.push({ rule: a.rule, status: "warn", state: "advise", message: a.finding, viewport: s.viewport, record_id: s.recordId, session_id: s.id });
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
const known = new Set(findings.map((f) => `${f.viewport}|${f.rule}|${f.status}`));
|
|
1317
|
+
for (const s of ceremonies) {
|
|
1318
|
+
for (const f of s.findings) {
|
|
1319
|
+
const key = `${f.viewport}|${f.rule}|${f.status}`;
|
|
1320
|
+
if (known.has(key)) continue;
|
|
1321
|
+
known.add(key);
|
|
1322
|
+
findings.push({ ...f, ...s.recordId ? { record_id: s.recordId } : {} });
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
return { available: false, runs: [], findings, problems };
|
|
1326
|
+
}
|
|
1327
|
+
function measurement(m) {
|
|
1328
|
+
if (!m) return "";
|
|
1329
|
+
const parts = Object.entries(m).filter(([k, v]) => v !== null && typeof v !== "object" && k !== "fix" && k !== "event_type").slice(0, 4).map(([k, v]) => `${k}=${String(v)}`);
|
|
1330
|
+
return parts.join(", ");
|
|
1331
|
+
}
|
|
1332
|
+
function printReport(io, report) {
|
|
1333
|
+
if (report.dry_runs.length > 0) {
|
|
1334
|
+
line(io, paint(io, "bold", "Jurisdiction dry run"));
|
|
1335
|
+
for (const d of report.dry_runs) {
|
|
1336
|
+
if (!d.resolution) {
|
|
1337
|
+
line(io, ` ${d.region}: ${d.error}`);
|
|
1338
|
+
continue;
|
|
1339
|
+
}
|
|
1340
|
+
const r = d.resolution;
|
|
1341
|
+
line(io, ` ${d.region}`);
|
|
1342
|
+
line(io, ` packs ${r.applied_jurisdictions.map((p) => `${p.code} ${p.version} (${p.reason})`).join(", ") || "none"}`);
|
|
1343
|
+
line(io, ` steps ${r.required_steps.join(", ")}`);
|
|
1344
|
+
line(io, ` strings ${r.required_strings.map((s) => `${s.slot} (${s.rule})`).join(", ") || "none"}`);
|
|
1345
|
+
line(io, ` rules ${r.rules_fired.length} fired, rule set ${r.rule_set_version}, guidance ${r.guidance_release}`);
|
|
1346
|
+
if (r.advisories.length > 0) line(io, ` advisory ${r.advisories.map((a) => `${a.rule}: ${a.finding}`).join("; ")}`);
|
|
1347
|
+
if (r.warnings.length > 0) line(io, ` warnings ${r.warnings.join(", ")}`);
|
|
1348
|
+
}
|
|
1349
|
+
line(io);
|
|
1350
|
+
}
|
|
1351
|
+
if (!report.url) return;
|
|
1352
|
+
line(io, paint(io, "bold", `Conformance check of ${report.url}`));
|
|
1353
|
+
line(io, `Window sizes: ${report.viewports.join(", ")}`);
|
|
1354
|
+
line(io);
|
|
1355
|
+
line(io, "Violations that must be refused");
|
|
1356
|
+
const width = Math.max(...report.attempts.map((a) => a.title.length));
|
|
1357
|
+
for (const a of report.attempts) {
|
|
1358
|
+
const label = a.outcome === "refused" ? paint(io, "green", "REFUSED ") : a.outcome === "accepted" ? paint(io, "red", "ACCEPTED") : paint(io, "dim", "SKIPPED ");
|
|
1359
|
+
line(io, ` ${label} ${a.title.padEnd(width)} ${a.detail}`);
|
|
1360
|
+
}
|
|
1361
|
+
line(io);
|
|
1362
|
+
line(io, "Ceremonies");
|
|
1363
|
+
for (const s of report.sessions.filter((x) => x.purpose === "ceremony")) {
|
|
1364
|
+
line(io, ` ${s.viewport.padEnd(9)} ${s.recordId ? `record ${s.recordId}` : `no record (${s.completeError ?? "not completed"})`} session ${s.id}, ${s.events} events`);
|
|
1365
|
+
}
|
|
1366
|
+
line(io);
|
|
1367
|
+
if (report.run_endpoint_available === false) {
|
|
1368
|
+
line(io, "The conformance run endpoint (POST /v1/conformance/runs) was unavailable. The findings below were read from");
|
|
1369
|
+
line(io, "the records (GET /v1/records/{id}) and from the API's answers to each ceremony event.");
|
|
1370
|
+
line(io);
|
|
1371
|
+
}
|
|
1372
|
+
line(io, "Findings");
|
|
1373
|
+
const notable = report.findings.filter((f) => f.status !== "pass");
|
|
1374
|
+
if (notable.length === 0) line(io, " None that need attention.");
|
|
1375
|
+
for (const f of notable) {
|
|
1376
|
+
const label = f.status === "block" ? paint(io, "red", "BLOCK") : paint(io, "yellow", "WARN ");
|
|
1377
|
+
line(io, ` ${label} ${f.rule.padEnd(6)} ${(f.viewport ?? "").padEnd(9)} ${f.message}${f.state === "advise" ? " (advise)" : ""}`);
|
|
1378
|
+
const m = measurement(f.measurement);
|
|
1379
|
+
if (m) line(io, ` measured: ${m}`);
|
|
1380
|
+
if (f.selector) line(io, ` element: ${f.selector}`);
|
|
1381
|
+
if (f.fix) line(io, ` fix: ${f.fix}`);
|
|
1382
|
+
if (f.prompt_instruction) line(io, ` prompt: ${f.prompt_instruction}`);
|
|
1383
|
+
}
|
|
1384
|
+
line(io);
|
|
1385
|
+
for (const p of report.problems) line(io, paint(io, "yellow", `Note: ${p}`));
|
|
1386
|
+
line(io, `Summary: ${report.summary.block} block, ${report.summary.warn} warn, ${report.summary.pass} pass.`);
|
|
1387
|
+
line(io, report.note);
|
|
1388
|
+
}
|
|
1389
|
+
async function checkCommand(argv, io, deps = {}) {
|
|
1390
|
+
const { positionals, flags } = parseArgs(
|
|
1391
|
+
argv,
|
|
1392
|
+
{ url: "string", region: "list", profile: "string", purpose: "string", "signer-class": "string", checkbox: "string", submit: "string", fill: "list", callback: "string", timeout: "string", json: "boolean", help: "boolean" },
|
|
1393
|
+
{ "-h": "--help" }
|
|
1394
|
+
);
|
|
1395
|
+
if (bool(flags, "help")) {
|
|
1396
|
+
io.out(CHECK_HELP);
|
|
1397
|
+
return 0;
|
|
1398
|
+
}
|
|
1399
|
+
if (positionals.length > 0) throw new UsageError(`Unexpected argument "${positionals[0]}". The page goes in --url.`);
|
|
1400
|
+
const url = str(flags, "url");
|
|
1401
|
+
const regions = list(flags, "region");
|
|
1402
|
+
if (!url && regions.length === 0) throw new UsageError("Name the page to check: esigncomply check --url http://localhost:3000/signup");
|
|
1403
|
+
if (url) {
|
|
1404
|
+
try {
|
|
1405
|
+
const u = new URL(url);
|
|
1406
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") throw new Error("protocol");
|
|
1407
|
+
} catch {
|
|
1408
|
+
throw new UsageError(`--url "${url}" is not an http or https URL.`);
|
|
1409
|
+
}
|
|
1410
|
+
}
|
|
1411
|
+
const timeoutSeconds = Number(str(flags, "timeout") ?? "20");
|
|
1412
|
+
if (!Number.isFinite(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 300) throw new UsageError("--timeout is a number of seconds from 1 to 300.");
|
|
1413
|
+
const esc = deps.client ?? clientFromEnv(io, { testOnly: "The checker runs test ceremonies." });
|
|
1414
|
+
const problems = [];
|
|
1415
|
+
const report = {
|
|
1416
|
+
url: url ?? null,
|
|
1417
|
+
viewports: VIEWPORTS.map(size),
|
|
1418
|
+
dry_runs: await dryRuns(esc, regions, { profile: str(flags, "profile"), purpose: str(flags, "purpose"), signerClass: str(flags, "signer-class") }, problems),
|
|
1419
|
+
attempts: [],
|
|
1420
|
+
sessions: [],
|
|
1421
|
+
run_endpoint_available: null,
|
|
1422
|
+
runs: [],
|
|
1423
|
+
findings: [],
|
|
1424
|
+
summary: { pass: 0, warn: 0, block: 0 },
|
|
1425
|
+
problems,
|
|
1426
|
+
note: ADVISORY
|
|
1427
|
+
};
|
|
1428
|
+
let failed = report.dry_runs.some((d) => d.error !== null && !d.error.includes("not available"));
|
|
1429
|
+
if (!url && report.dry_runs.length > 0 && report.dry_runs.every((d) => d.resolution === null)) failed = true;
|
|
1430
|
+
if (url) {
|
|
1431
|
+
const launch = await (deps.launch ?? launchBrowser)();
|
|
1432
|
+
if (!launch.ok) {
|
|
1433
|
+
io.err((launch.reason === "not_installed" ? INSTALL_PLAYWRIGHT : `${INSTALL_BROWSER}
|
|
1434
|
+
|
|
1435
|
+
${launch.detail}`) + "\n");
|
|
1436
|
+
return 2;
|
|
1437
|
+
}
|
|
1438
|
+
const browser = launch.browser;
|
|
1439
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
1440
|
+
const pageFlags = { checkbox: str(flags, "checkbox"), submit: str(flags, "submit"), fill: list(flags, "fill") };
|
|
1441
|
+
try {
|
|
1442
|
+
report.attempts = await violationAttempts(browser, url, pageFlags, sessions, timeoutSeconds * 1e3);
|
|
1443
|
+
report.attempts.push(await forgedCallback(str(flags, "callback")));
|
|
1444
|
+
for (const viewport of VIEWPORTS) {
|
|
1445
|
+
const problem = await runCeremony(browser, url, viewport, pageFlags, sessions, timeoutSeconds * 1e3);
|
|
1446
|
+
if (problem) {
|
|
1447
|
+
problems.push(`At ${size(viewport)} the ceremony did not complete: ${problem}.`);
|
|
1448
|
+
failed = true;
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
} finally {
|
|
1452
|
+
await browser.close().catch(() => void 0);
|
|
1453
|
+
}
|
|
1454
|
+
const observed = [...sessions.values()];
|
|
1455
|
+
report.sessions = observed.map((s) => ({ id: s.id, viewport: s.viewport, purpose: s.purpose, apiBase: s.apiBase, events: s.events, recordId: s.recordId, completeStatus: s.completeStatus, completeError: s.completeError }));
|
|
1456
|
+
const collected = await collectFindings(esc, observed);
|
|
1457
|
+
report.run_endpoint_available = collected.available;
|
|
1458
|
+
report.runs = collected.runs;
|
|
1459
|
+
report.findings = collected.findings;
|
|
1460
|
+
problems.push(...collected.problems);
|
|
1461
|
+
if (report.attempts.some((a) => a.outcome === "accepted")) failed = true;
|
|
1462
|
+
}
|
|
1463
|
+
for (const f of report.findings) {
|
|
1464
|
+
if (f.status === "block") report.summary.block++;
|
|
1465
|
+
else if (f.status === "warn") report.summary.warn++;
|
|
1466
|
+
else if (f.status === "pass") report.summary.pass++;
|
|
1467
|
+
}
|
|
1468
|
+
if (report.summary.block > 0) failed = true;
|
|
1469
|
+
if (bool(flags, "json")) line(io, JSON.stringify(report, null, 2));
|
|
1470
|
+
else printReport(io, report);
|
|
1471
|
+
return failed ? 1 : 0;
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
// packages/esigncomply/src/cli/demo.ts
|
|
1475
|
+
import { randomBytes } from "node:crypto";
|
|
1476
|
+
import { createServer } from "node:http";
|
|
1477
|
+
|
|
1478
|
+
// packages/esigncomply/src/cli/demo-page.ts
|
|
1479
|
+
function escapeHtml(text) {
|
|
1480
|
+
return text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
1481
|
+
}
|
|
1482
|
+
var STYLE = String.raw`
|
|
1483
|
+
:root { color-scheme: light; }
|
|
1484
|
+
* { box-sizing: border-box; }
|
|
1485
|
+
body { margin: 0; font: 16px/1.5 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; color: #16181d; background: #f4f5f7; }
|
|
1486
|
+
main { max-width: 440px; margin: 0 auto; padding: 24px 20px 48px; }
|
|
1487
|
+
.banner { font-size: 14px; color: #3d4350; background: #e6e9ef; border-radius: 6px; padding: 8px 12px; margin: 0 0 20px; }
|
|
1488
|
+
h1 { font-size: 26px; line-height: 1.2; margin: 0 0 16px; }
|
|
1489
|
+
.card { background: #fff; border: 1px solid #d5d9e0; border-radius: 10px; padding: 20px; }
|
|
1490
|
+
dl { margin: 0 0 16px; display: grid; grid-template-columns: auto 1fr; gap: 4px 12px; font-size: 15px; }
|
|
1491
|
+
dt { color: #4a5160; } dd { margin: 0; }
|
|
1492
|
+
#assent { border-top: 1px solid #e3e6eb; padding-top: 16px; }
|
|
1493
|
+
#notice { font-size: 16px; margin: 0 0 12px; color: #16181d; }
|
|
1494
|
+
a { color: #1668dc; text-decoration: underline; }
|
|
1495
|
+
.check { display: flex; gap: 10px; align-items: flex-start; font-size: 16px; margin: 0 0 12px; cursor: pointer; }
|
|
1496
|
+
.check input { width: 20px; height: 20px; margin: 2px 0 0; flex: none; }
|
|
1497
|
+
button { font: inherit; font-weight: 600; width: 100%; padding: 12px 16px; border: 0; border-radius: 8px; background: #0b4fb3; color: #fff; cursor: pointer; }
|
|
1498
|
+
button[disabled] { background: #8a93a3; cursor: default; }
|
|
1499
|
+
#status { min-height: 24px; font-size: 15px; margin: 16px 0 0; }
|
|
1500
|
+
body[data-state="error"] #status { color: #a11616; }
|
|
1501
|
+
#result { margin-top: 16px; font-size: 15px; }
|
|
1502
|
+
#result code { font: 14px ui-monospace, SFMono-Regular, Menlo, monospace; word-break: break-all; }
|
|
1503
|
+
article { background: #fff; border: 1px solid #d5d9e0; border-radius: 10px; padding: 20px; }
|
|
1504
|
+
`;
|
|
1505
|
+
var SCRIPT = String.raw`
|
|
1506
|
+
(function () {
|
|
1507
|
+
"use strict";
|
|
1508
|
+
var cfg = window.__ESC_DEMO__;
|
|
1509
|
+
var $ = function (id) { return document.getElementById(id); };
|
|
1510
|
+
var checkbox = $("agree"), button = $("submit"), form = $("signup"), region = $("assent");
|
|
1511
|
+
|
|
1512
|
+
function setState(state, message) {
|
|
1513
|
+
document.body.setAttribute("data-state", state);
|
|
1514
|
+
$("status").textContent = message || "";
|
|
1515
|
+
}
|
|
1516
|
+
function fail(err) {
|
|
1517
|
+
var text = err && err.message ? err.message : String(err);
|
|
1518
|
+
if (err && err.rule) text += " (rule " + err.rule + ")";
|
|
1519
|
+
setState("error", text);
|
|
1520
|
+
button.disabled = false;
|
|
1521
|
+
}
|
|
1522
|
+
function json(url, body) {
|
|
1523
|
+
return fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) }).then(function (r) {
|
|
1524
|
+
return r.json().then(function (j) { if (!r.ok) throw new Error(j.error || ("Request failed: " + r.status)); return j; });
|
|
1525
|
+
});
|
|
1526
|
+
}
|
|
1527
|
+
function loadSdk(url) {
|
|
1528
|
+
return new Promise(function (resolve) {
|
|
1529
|
+
var s = document.createElement("script");
|
|
1530
|
+
var done = function () {
|
|
1531
|
+
var g = window.EsignComply;
|
|
1532
|
+
var sdk = g && typeof g.attach === "function" ? g : g && g.EsignComply && typeof g.EsignComply.attach === "function" ? g.EsignComply : g && g.default && typeof g.default.attach === "function" ? g.default : null;
|
|
1533
|
+
resolve(sdk);
|
|
1534
|
+
};
|
|
1535
|
+
s.src = url; s.async = true; s.onload = done; s.onerror = function () { resolve(null); };
|
|
1536
|
+
setTimeout(function () { resolve(null); }, 8000);
|
|
1537
|
+
document.head.appendChild(s);
|
|
1538
|
+
});
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
// ---- measurements for the fetch fallback ------------------------------------------
|
|
1542
|
+
function rgb(value) {
|
|
1543
|
+
var m = /rgba?\(([^)]+)\)/.exec(value || "");
|
|
1544
|
+
if (!m) return null;
|
|
1545
|
+
var p = m[1].split(",").map(function (x) { return parseFloat(x); });
|
|
1546
|
+
return { r: p[0], g: p[1], b: p[2], a: p.length > 3 ? p[3] : 1 };
|
|
1547
|
+
}
|
|
1548
|
+
function luminance(c) {
|
|
1549
|
+
var f = function (v) { v = v / 255; return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4); };
|
|
1550
|
+
return 0.2126 * f(c.r) + 0.7152 * f(c.g) + 0.0722 * f(c.b);
|
|
1551
|
+
}
|
|
1552
|
+
function background(el) {
|
|
1553
|
+
for (var node = el; node && node.nodeType === 1; node = node.parentElement) {
|
|
1554
|
+
var c = rgb(getComputedStyle(node).backgroundColor);
|
|
1555
|
+
if (c && c.a > 0.99) return c;
|
|
1556
|
+
}
|
|
1557
|
+
return { r: 255, g: 255, b: 255, a: 1 };
|
|
1558
|
+
}
|
|
1559
|
+
function ratio(x, y) {
|
|
1560
|
+
if (!x || !y) return null;
|
|
1561
|
+
var a = luminance(x), b = luminance(y);
|
|
1562
|
+
return Math.round(((Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05)) * 100) / 100;
|
|
1563
|
+
}
|
|
1564
|
+
// Text against what is behind it (notice legibility).
|
|
1565
|
+
function contrast(el) { return ratio(rgb(getComputedStyle(el).color), background(el)); }
|
|
1566
|
+
// A link against the text around it (is the link recognisable as one).
|
|
1567
|
+
function linkContrast(link) { return ratio(rgb(getComputedStyle(link).color), rgb(getComputedStyle(link.parentElement || document.body).color)); }
|
|
1568
|
+
function fontPx(el) { return Math.round(parseFloat(getComputedStyle(el).fontSize) * 10) / 10; }
|
|
1569
|
+
function visible(el) {
|
|
1570
|
+
var r = el.getBoundingClientRect(), s = getComputedStyle(el);
|
|
1571
|
+
return r.width > 0 && r.height > 0 && s.visibility !== "hidden" && s.display !== "none" && parseFloat(s.opacity) > 0;
|
|
1572
|
+
}
|
|
1573
|
+
function viewport() { return { width: window.innerWidth, height: window.innerHeight }; }
|
|
1574
|
+
function renderHash(html) {
|
|
1575
|
+
// Same normalization as the API: NFC, then all white space and zero-width characters removed.
|
|
1576
|
+
var holder = document.createElement("div");
|
|
1577
|
+
holder.innerHTML = html;
|
|
1578
|
+
var text = (holder.textContent || "").normalize("NFC").replace(/[\s\u200B-\u200D\uFEFF]+/g, "");
|
|
1579
|
+
return crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)).then(function (buf) {
|
|
1580
|
+
return "sha256:" + Array.prototype.map.call(new Uint8Array(buf), function (b) { return ("0" + b.toString(16)).slice(-2); }).join("");
|
|
1581
|
+
});
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
function confirmRecord(session, recordId, channel) {
|
|
1585
|
+
return json("/api/confirm", { session_id: session.id, record_id: recordId, channel: channel }).then(function (res) {
|
|
1586
|
+
$("result").hidden = false;
|
|
1587
|
+
$("record-id").textContent = res.record_id;
|
|
1588
|
+
$("record-status").textContent = res.status;
|
|
1589
|
+
$("verify-link").href = res.verify_url; $("verify-link").textContent = res.verify_url;
|
|
1590
|
+
setState("done", "Account created. Your server confirmed the record with its secret key before granting access.");
|
|
1591
|
+
});
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
// ---- the ceremony through the browser SDK -----------------------------------------
|
|
1595
|
+
function runWithSdk(sdk, session) {
|
|
1596
|
+
document.body.setAttribute("data-channel", "sdk");
|
|
1597
|
+
return sdk.attach({ clientToken: session.client_token, apiUrl: session.api_url }).then(function (ceremony) {
|
|
1598
|
+
var chain = Promise.resolve();
|
|
1599
|
+
session.documents.forEach(function (d) {
|
|
1600
|
+
chain = chain.then(function () {
|
|
1601
|
+
return ceremony.presentDocument({ versionId: d.version_id, mode: "hyperlink", link: $("link-" + d.version_id) });
|
|
1602
|
+
});
|
|
1603
|
+
});
|
|
1604
|
+
return chain.then(function () {
|
|
1605
|
+
return ceremony.observeAssent({ region: region, checkbox: checkbox, submit: button });
|
|
1606
|
+
}).then(function () {
|
|
1607
|
+
form.addEventListener("submit", function (e) {
|
|
1608
|
+
e.preventDefault();
|
|
1609
|
+
if (!checkbox.checked) { setState("ready", "Tick the box to agree before creating the account."); return; }
|
|
1610
|
+
button.disabled = true; setState("submitting", "Recording your agreement…");
|
|
1611
|
+
ceremony.complete().then(function (result) { return confirmRecord(session, result.recordId, "sdk"); }).catch(fail);
|
|
1612
|
+
});
|
|
1613
|
+
});
|
|
1614
|
+
});
|
|
1615
|
+
}
|
|
1616
|
+
|
|
1617
|
+
// ---- the same steps with fetch, when the SDK bundle is not available --------------
|
|
1618
|
+
function runWithFetch(session) {
|
|
1619
|
+
document.body.setAttribute("data-channel", "fetch");
|
|
1620
|
+
var base = session.api_url + "/sessions/" + encodeURIComponent(session.id);
|
|
1621
|
+
var call = function (path, body, idempotencyKey) {
|
|
1622
|
+
var headers = { Authorization: "Bearer " + session.client_token, "Content-Type": "application/json" };
|
|
1623
|
+
if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey;
|
|
1624
|
+
return fetch(base + path, { method: "POST", headers: headers, body: JSON.stringify(body) }).then(function (r) {
|
|
1625
|
+
return r.json().then(function (j) {
|
|
1626
|
+
if (!r.ok) { var e = new Error(j && j.error ? j.error.message : "The API answered " + r.status); e.rule = j && j.error && j.error.rule; throw e; }
|
|
1627
|
+
return j;
|
|
1628
|
+
});
|
|
1629
|
+
});
|
|
1630
|
+
};
|
|
1631
|
+
var required = session.required_steps || [];
|
|
1632
|
+
var needs = function (step) { return required.indexOf(step) !== -1; };
|
|
1633
|
+
var label = $("agree-label").textContent.trim();
|
|
1634
|
+
var noticeEl = $("notice");
|
|
1635
|
+
var chain = Promise.resolve();
|
|
1636
|
+
if (needs("client.attached")) {
|
|
1637
|
+
chain = chain.then(function () {
|
|
1638
|
+
return call("/events", { type: "client.attached", data: { sdk_version: "cli-demo-fetch", page_url: location.href, viewport: viewport() } });
|
|
1639
|
+
});
|
|
1640
|
+
}
|
|
1641
|
+
session.documents.forEach(function (d) {
|
|
1642
|
+
chain = chain.then(function () {
|
|
1643
|
+
var link = $("link-" + d.version_id);
|
|
1644
|
+
return fetch("/documents/" + encodeURIComponent(d.version_id) + "/fragment").then(function (r) { return r.json(); }).then(function (doc) {
|
|
1645
|
+
return doc.html ? renderHash(doc.html) : null;
|
|
1646
|
+
}).catch(function () { return null; }).then(function (targetHash) {
|
|
1647
|
+
var data = {
|
|
1648
|
+
mode: "hyperlink", link_text: link.textContent.trim(), link_href: link.href, link_visible: visible(link),
|
|
1649
|
+
link_style: { underlined: getComputedStyle(link).textDecorationLine.indexOf("underline") !== -1, contrast_ratio: linkContrast(link), font_px: fontPx(link) }
|
|
1650
|
+
};
|
|
1651
|
+
if (targetHash) data.link_target_render_hash = targetHash;
|
|
1652
|
+
return call("/events", { type: "document.presented", version_id: d.version_id, client_time: new Date().toISOString(), data: data });
|
|
1653
|
+
});
|
|
1654
|
+
});
|
|
1655
|
+
});
|
|
1656
|
+
if (needs("notice.captured")) {
|
|
1657
|
+
chain = chain.then(function () {
|
|
1658
|
+
var n = noticeEl.getBoundingClientRect(), b = button.getBoundingClientRect(), v = viewport();
|
|
1659
|
+
return call("/events", { type: "notice.captured", client_time: new Date().toISOString(), data: {
|
|
1660
|
+
text: noticeEl.textContent.replace(/\s+/g, " ").trim(),
|
|
1661
|
+
styles: { font_px: fontPx(noticeEl), body_font_px: fontPx(document.body), contrast_ratio: contrast(noticeEl) },
|
|
1662
|
+
layout: { same_viewport: n.top >= 0 && b.bottom <= v.height, notice_above_action: n.bottom <= b.top, notice_to_action_px: Math.max(0, Math.round(b.top - n.bottom)), viewport: v },
|
|
1663
|
+
controls: { primary_buttons: document.querySelectorAll("button[type=submit]").length, competing_controls: 0, checkbox: { initial_checked: checkbox.defaultChecked, label_text: label }, submit: { label: button.textContent.trim() } }
|
|
1664
|
+
} });
|
|
1665
|
+
});
|
|
1666
|
+
}
|
|
1667
|
+
return chain.then(function () {
|
|
1668
|
+
var intent = null;
|
|
1669
|
+
checkbox.addEventListener("change", function (e) {
|
|
1670
|
+
if (!checkbox.checked || intent) return;
|
|
1671
|
+
intent = call("/events", { type: "intent.captured", client_time: new Date().toISOString(), data: { control: "checkbox", label_text: label, initial_state: "unchecked", trusted: e.isTrusted === true } }).catch(function (err) { intent = null; fail(err); });
|
|
1672
|
+
});
|
|
1673
|
+
form.addEventListener("submit", function (e) {
|
|
1674
|
+
e.preventDefault();
|
|
1675
|
+
if (!checkbox.checked || !intent) { setState("ready", "Tick the box to agree before creating the account."); return; }
|
|
1676
|
+
button.disabled = true; setState("submitting", "Recording your agreement…");
|
|
1677
|
+
intent.then(function () {
|
|
1678
|
+
return call("/complete", { signature: { method: "checkbox", label_text: label, button_text: button.textContent.trim() }, client_time: new Date().toISOString() }, session.id + "-complete");
|
|
1679
|
+
}).then(function (record) { return confirmRecord(session, record.id, "fetch"); }).catch(fail);
|
|
1680
|
+
});
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
json("/api/session").then(function (session) {
|
|
1685
|
+
return loadSdk(cfg.sdkUrl).then(function (sdk) {
|
|
1686
|
+
$("channel").textContent = sdk ? "Browser SDK loaded from " + cfg.sdkUrl : "Browser SDK not found at " + cfg.sdkUrl + "; this page reports the steps itself with fetch.";
|
|
1687
|
+
return sdk ? runWithSdk(sdk, session) : runWithFetch(session);
|
|
1688
|
+
});
|
|
1689
|
+
}).then(function () {
|
|
1690
|
+
// The controls open only once the ceremony is watching them, so nobody can agree before it is recorded.
|
|
1691
|
+
checkbox.disabled = false;
|
|
1692
|
+
button.disabled = false;
|
|
1693
|
+
setState("ready", "");
|
|
1694
|
+
}).catch(fail);
|
|
1695
|
+
})();
|
|
1696
|
+
`;
|
|
1697
|
+
function demoPage(config, documents) {
|
|
1698
|
+
const links = documents.map((d) => `<a id="link-${escapeHtml(d.version_id)}" href="/documents/${encodeURIComponent(d.version_id)}" target="_blank" rel="noopener">${escapeHtml(d.title)}</a>`);
|
|
1699
|
+
const linkText = links.length === 2 ? `agree to the ${links[0]} and acknowledge the ${links[1]}` : `agree to ${links.join(", ")}`;
|
|
1700
|
+
return `<!doctype html>
|
|
1701
|
+
<html lang="en">
|
|
1702
|
+
<head>
|
|
1703
|
+
<meta charset="utf-8">
|
|
1704
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1705
|
+
<title>Create your account (Esign Comply demo)</title>
|
|
1706
|
+
<style>${STYLE}</style>
|
|
1707
|
+
</head>
|
|
1708
|
+
<body data-state="loading">
|
|
1709
|
+
<main>
|
|
1710
|
+
<p class="banner">Esign Comply demo, test mode. Nothing here creates a real account.</p>
|
|
1711
|
+
<h1>Create your account</h1>
|
|
1712
|
+
<form id="signup" class="card" novalidate>
|
|
1713
|
+
<dl>
|
|
1714
|
+
<dt>Name</dt><dd>Demo Signer</dd>
|
|
1715
|
+
<dt>Email</dt><dd>demo.signer@example.com</dd>
|
|
1716
|
+
</dl>
|
|
1717
|
+
<div id="assent">
|
|
1718
|
+
<p id="notice">${escapeHtml(config.noticePrefix)} ${linkText}.</p>
|
|
1719
|
+
<label class="check"><input type="checkbox" id="agree" name="agree" disabled><span id="agree-label">${escapeHtml(config.checkboxLabel)}</span></label>
|
|
1720
|
+
<button type="submit" id="submit" disabled>${escapeHtml(config.buttonLabel)}</button>
|
|
1721
|
+
</div>
|
|
1722
|
+
</form>
|
|
1723
|
+
<p id="status" role="status" aria-live="polite">Starting the session\u2026</p>
|
|
1724
|
+
<section id="result" class="card" hidden>
|
|
1725
|
+
<dl>
|
|
1726
|
+
<dt>Record</dt><dd><code id="record-id"></code></dd>
|
|
1727
|
+
<dt>Status</dt><dd id="record-status"></dd>
|
|
1728
|
+
<dt>Verify</dt><dd><a id="verify-link" href="#" target="_blank" rel="noopener"></a></dd>
|
|
1729
|
+
</dl>
|
|
1730
|
+
</section>
|
|
1731
|
+
<p id="channel" class="banner" style="margin-top:20px"></p>
|
|
1732
|
+
</main>
|
|
1733
|
+
<script>window.__ESC_DEMO__ = ${JSON.stringify({ sdkUrl: config.sdkUrl }).replace(/</g, "\\u003c")};</script>
|
|
1734
|
+
<script>${SCRIPT}</script>
|
|
1735
|
+
</body>
|
|
1736
|
+
</html>
|
|
1737
|
+
`;
|
|
1738
|
+
}
|
|
1739
|
+
function documentPage(title, html, versionId) {
|
|
1740
|
+
return `<!doctype html>
|
|
1741
|
+
<html lang="en">
|
|
1742
|
+
<head>
|
|
1743
|
+
<meta charset="utf-8">
|
|
1744
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1745
|
+
<title>${escapeHtml(title)}</title>
|
|
1746
|
+
<style>${STYLE}</style>
|
|
1747
|
+
</head>
|
|
1748
|
+
<body>
|
|
1749
|
+
<main>
|
|
1750
|
+
<p class="banner">Esign Comply demo, test mode.</p>
|
|
1751
|
+
<article id="document" data-esc-document="${escapeHtml(versionId)}">${html}</article>
|
|
1752
|
+
</main>
|
|
1753
|
+
</body>
|
|
1754
|
+
</html>
|
|
1755
|
+
`;
|
|
1756
|
+
}
|
|
1757
|
+
|
|
1758
|
+
// packages/esigncomply/src/cli/demo.ts
|
|
1759
|
+
var DEMO_HELP = `esigncomply demo [--port 4310] [--auto]
|
|
1760
|
+
|
|
1761
|
+
Record a first test signature without writing any code. The command creates a
|
|
1762
|
+
demo Terms of Service, a demo Privacy Notice and a profile in test mode (or
|
|
1763
|
+
reuses the ones it made before), serves a signup page on localhost, and waits.
|
|
1764
|
+
Tick the box and click "Create account": the page runs a real ceremony against
|
|
1765
|
+
the API, this process confirms the record with the secret key, and prints the
|
|
1766
|
+
record ID, the verify URL and the dashboard link.
|
|
1767
|
+
|
|
1768
|
+
--port <port> Port for the local page. Default 4310.
|
|
1769
|
+
--auto Do not wait for a person. Drive the page with Playwright when it
|
|
1770
|
+
is installed; otherwise report the ceremony from this process as
|
|
1771
|
+
a server_only session, and say so.
|
|
1772
|
+
|
|
1773
|
+
Environment
|
|
1774
|
+
ESIGNCOMPLY_API_KEY A test key (esc_test_\u2026). Live keys are refused.
|
|
1775
|
+
ESIGNCOMPLY_API_URL API base URL, for local development.
|
|
1776
|
+
|
|
1777
|
+
The secret key stays in this process. The page receives only the session's
|
|
1778
|
+
client token.
|
|
1779
|
+
`;
|
|
1780
|
+
var TERMS = { name: "Demo Terms of Service", type: "terms", format: "markdown", text: "# Demo Terms of Service\n\nThese terms exist to demonstrate Esign Comply. They create no rights and no obligations.\n\n1. This is a test document.\n2. Nothing here is a real agreement.\n" };
|
|
1781
|
+
var PRIVACY = { name: "Demo Privacy Notice", type: "privacy_notice", format: "text", text: "Demo Privacy Notice\n\nThis notice exists to demonstrate Esign Comply. The demo collects no personal data beyond the fixed demo signer shown on the page." };
|
|
1782
|
+
var PROFILE_NAME = "Demo signup";
|
|
1783
|
+
var SIGNER = { name: "Demo Signer", email: "demo.signer@example.com" };
|
|
1784
|
+
var NOTICE_PREFIX = "By checking the box and clicking Create account, you";
|
|
1785
|
+
var CHECKBOX_LABEL = "I agree to the Demo Terms of Service and Demo Privacy Notice";
|
|
1786
|
+
var BUTTON_LABEL = "Create account";
|
|
1787
|
+
var ACCEPTED = ["recorded", "timestamped", "anchored"];
|
|
1788
|
+
async function ensureDemoSetup(esc) {
|
|
1789
|
+
const created = [];
|
|
1790
|
+
const existing = must(await esc.documents.list({ limit: 100 }), "Listing documents").data;
|
|
1791
|
+
const documents = [];
|
|
1792
|
+
for (const spec of [TERMS, PRIVACY]) {
|
|
1793
|
+
let doc = existing.find((d) => d.name === spec.name && !d.archived);
|
|
1794
|
+
if (!doc) {
|
|
1795
|
+
doc = must(await esc.documents.create({ name: spec.name, type: spec.type }), `Creating "${spec.name}"`);
|
|
1796
|
+
created.push(spec.name);
|
|
1797
|
+
}
|
|
1798
|
+
const versions = must(await esc.documents.versions.list(doc.id), `Reading versions of "${spec.name}"`).data;
|
|
1799
|
+
let version = versions.find((v) => v.language === "en") ?? versions[0];
|
|
1800
|
+
if (!version) {
|
|
1801
|
+
version = must(
|
|
1802
|
+
await esc.documents.versions.create(doc.id, { version_label: (/* @__PURE__ */ new Date()).toISOString().slice(0, 10), language: "en", content: { format: spec.format, text: spec.text } }, { idempotencyKey: `cli-demo-${doc.id}-v1` }),
|
|
1803
|
+
`Publishing "${spec.name}"`
|
|
1804
|
+
);
|
|
1805
|
+
}
|
|
1806
|
+
documents.push({ document_id: doc.id, version_id: version.id, title: spec.name });
|
|
1807
|
+
}
|
|
1808
|
+
const profiles = must(await esc.profiles.list(), "Listing profiles").data;
|
|
1809
|
+
let profile = profiles.find((p) => p.name === PROFILE_NAME);
|
|
1810
|
+
if (!profile) {
|
|
1811
|
+
profile = must(await esc.profiles.create({ name: PROFILE_NAME, jurisdictions: ["US-FED"], method: "checkbox", assurance_level: "L1" }), "Creating the demo profile");
|
|
1812
|
+
created.push(`profile "${PROFILE_NAME}"`);
|
|
1813
|
+
}
|
|
1814
|
+
return { documents, profileId: profile.id, created };
|
|
1815
|
+
}
|
|
1816
|
+
function newSessionBody(setup, externalId, pageUrl, captureMode) {
|
|
1817
|
+
return {
|
|
1818
|
+
profile: setup.profileId,
|
|
1819
|
+
signer: { external_id: externalId, name: SIGNER.name, email: SIGNER.email, class: "consumer", country: "US" },
|
|
1820
|
+
documents: setup.documents.map((d) => ({ document: d.document_id, version: d.version_id })),
|
|
1821
|
+
context: { ...pageUrl ? { url: pageUrl } : {}, locale: "en-US", purpose: "account_signup", notes: "Created by `esigncomply demo`." },
|
|
1822
|
+
metadata: { source: "esigncomply-cli-demo" },
|
|
1823
|
+
...captureMode === "server_only" ? { capture_mode: "server_only" } : {}
|
|
1824
|
+
};
|
|
1825
|
+
}
|
|
1826
|
+
async function confirmRecord(esc, recordId, expected) {
|
|
1827
|
+
const record = must(await esc.records.get(recordId), "Confirming the record");
|
|
1828
|
+
if (record.livemode) throw new CommandError(`Record ${recordId} is a live record; the demo only makes test records.`);
|
|
1829
|
+
if (!ACCEPTED.includes(record.status)) throw new CommandError(`Record ${recordId} has status "${record.status}". Access is granted only on recorded, timestamped or anchored.`);
|
|
1830
|
+
if (record.signer.external_id !== expected.externalId) throw new CommandError(`Record ${recordId} belongs to another signer.`);
|
|
1831
|
+
const versions = record.documents.map((d) => d.version_id).sort().join(",");
|
|
1832
|
+
if (versions !== [...expected.versionIds].sort().join(",")) throw new CommandError(`Record ${recordId} covers other document versions than the ones requested.`);
|
|
1833
|
+
return record;
|
|
1834
|
+
}
|
|
1835
|
+
function printRecord(io, esc, record, channel) {
|
|
1836
|
+
line(io);
|
|
1837
|
+
line(io, paint(io, "green", "Record sealed."));
|
|
1838
|
+
line(io, ` Record ID ${record.id}`);
|
|
1839
|
+
line(io, ` Status ${record.status} (test mode: sealed with the test key, no attestation)`);
|
|
1840
|
+
line(io, ` Verify ${record.verify_url}`);
|
|
1841
|
+
line(io, ` Dashboard ${appOrigin(esc.baseUrl)}/dashboard/records/${record.id}`);
|
|
1842
|
+
line(io, ` Captured ${channel}`);
|
|
1843
|
+
line(io);
|
|
1844
|
+
line(io, "Confirm it from your own server the same way this command did:");
|
|
1845
|
+
line(io, ` const { data: record } = await esc.records.get("${record.id}");`);
|
|
1846
|
+
}
|
|
1847
|
+
async function runServerOnly(esc, setup) {
|
|
1848
|
+
const externalId = `demo_${randomBytes(5).toString("hex")}`;
|
|
1849
|
+
const session = must(await esc.sessions.create(newSessionBody(setup, externalId, null, "server_only"), { idempotencyKey: `cli-demo-${externalId}` }), "Creating the session");
|
|
1850
|
+
const event = (body) => esc.request(`POST`, `/sessions/${encodeURIComponent(session.id)}/events`, { body });
|
|
1851
|
+
for (const step of session.required_steps) {
|
|
1852
|
+
const [type, versionId] = step.split(":");
|
|
1853
|
+
if (type === "signature.applied") continue;
|
|
1854
|
+
const title = setup.documents.find((d) => d.version_id === versionId)?.title;
|
|
1855
|
+
const data = type === "document.presented" ? { mode: "hyperlink", link_text: title ?? versionId } : type === "intent.captured" ? { control: "checkbox", label_text: CHECKBOX_LABEL, initial_state: "unchecked" } : type === "notice.captured" ? { text: `${NOTICE_PREFIX} agree to the ${TERMS.name} and acknowledge the ${PRIVACY.name}.` } : {};
|
|
1856
|
+
must(await event({ type, ...versionId ? { version_id: versionId } : {}, client_time: (/* @__PURE__ */ new Date()).toISOString(), data }), `Recording ${step}`);
|
|
1857
|
+
}
|
|
1858
|
+
const completed = must(
|
|
1859
|
+
await esc.request("POST", `/sessions/${encodeURIComponent(session.id)}/complete`, {
|
|
1860
|
+
body: { signature: { method: "checkbox", label_text: CHECKBOX_LABEL, button_text: BUTTON_LABEL }, client_time: (/* @__PURE__ */ new Date()).toISOString() },
|
|
1861
|
+
idempotencyKey: `${session.id}-complete`
|
|
1862
|
+
}),
|
|
1863
|
+
"Completing the ceremony"
|
|
1864
|
+
);
|
|
1865
|
+
return confirmRecord(esc, completed.id, { externalId, versionIds: setup.documents.map((d) => d.version_id) });
|
|
1866
|
+
}
|
|
1867
|
+
async function readBody(req) {
|
|
1868
|
+
const chunks = [];
|
|
1869
|
+
let size2 = 0;
|
|
1870
|
+
for await (const chunk of req) {
|
|
1871
|
+
size2 += chunk.length;
|
|
1872
|
+
if (size2 > 64 * 1024) throw new Error("request body too large");
|
|
1873
|
+
chunks.push(chunk);
|
|
1874
|
+
}
|
|
1875
|
+
if (chunks.length === 0) return {};
|
|
1876
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
1877
|
+
return typeof parsed === "object" && parsed !== null ? parsed : {};
|
|
1878
|
+
}
|
|
1879
|
+
async function startDemoServer(esc, setup, port, io) {
|
|
1880
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
1881
|
+
let finish;
|
|
1882
|
+
const done = new Promise((resolve) => finish = resolve);
|
|
1883
|
+
let origin = `http://localhost:${port}`;
|
|
1884
|
+
const sdkUrl = `${new URL(esc.baseUrl).origin}/sdk/v1/esigncomply.js`;
|
|
1885
|
+
const contents = /* @__PURE__ */ new Map();
|
|
1886
|
+
const contentOf = (doc) => {
|
|
1887
|
+
let pending = contents.get(doc.version_id);
|
|
1888
|
+
if (!pending) {
|
|
1889
|
+
pending = esc.documents.versions.getContent(doc.document_id, doc.version_id);
|
|
1890
|
+
contents.set(doc.version_id, pending);
|
|
1891
|
+
void pending.then((r) => {
|
|
1892
|
+
if (r.error) contents.delete(doc.version_id);
|
|
1893
|
+
});
|
|
1894
|
+
}
|
|
1895
|
+
return pending;
|
|
1896
|
+
};
|
|
1897
|
+
for (const doc of setup.documents) await contentOf(doc);
|
|
1898
|
+
const send = (res, status, type, body) => {
|
|
1899
|
+
res.writeHead(status, { "Content-Type": type, "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", "Referrer-Policy": "no-referrer" });
|
|
1900
|
+
res.end(body);
|
|
1901
|
+
};
|
|
1902
|
+
const json = (res, status, body) => send(res, status, "application/json; charset=utf-8", JSON.stringify(body));
|
|
1903
|
+
const handle = async (req, res) => {
|
|
1904
|
+
const url = new URL(req.url ?? "/", origin);
|
|
1905
|
+
const host = (req.headers.host ?? "").replace(/:\d+$/, "");
|
|
1906
|
+
if (host !== "localhost" && host !== "127.0.0.1") return send(res, 403, "text/plain", "The demo answers on localhost only.");
|
|
1907
|
+
if (req.method === "POST" && req.headers.origin && new URL(req.headers.origin).host !== req.headers.host) return send(res, 403, "text/plain", "Cross-origin requests are refused.");
|
|
1908
|
+
if (req.method === "GET" && url.pathname === "/") {
|
|
1909
|
+
return send(res, 200, "text/html; charset=utf-8", demoPage({ sdkUrl, noticePrefix: NOTICE_PREFIX, checkboxLabel: CHECKBOX_LABEL, buttonLabel: BUTTON_LABEL }, setup.documents));
|
|
1910
|
+
}
|
|
1911
|
+
const docMatch = /^\/documents\/([^/]+)(\/fragment)?$/.exec(url.pathname);
|
|
1912
|
+
if (req.method === "GET" && docMatch) {
|
|
1913
|
+
const doc = setup.documents.find((d) => d.version_id === decodeURIComponent(docMatch[1]));
|
|
1914
|
+
if (!doc) return send(res, 404, "text/plain", "No such document.");
|
|
1915
|
+
const content = await contentOf(doc);
|
|
1916
|
+
if (content.error) return send(res, 502, "text/plain", describeError(content.error));
|
|
1917
|
+
const html = content.data.html ?? "";
|
|
1918
|
+
return docMatch[2] ? json(res, 200, { title: doc.title, html }) : send(res, 200, "text/html; charset=utf-8", documentPage(doc.title, html, doc.version_id));
|
|
1919
|
+
}
|
|
1920
|
+
if (req.method === "POST" && url.pathname === "/api/session") {
|
|
1921
|
+
const externalId = `demo_${randomBytes(5).toString("hex")}`;
|
|
1922
|
+
const created = await esc.sessions.create(newSessionBody(setup, externalId, `${origin}/`, "direct"), { idempotencyKey: `cli-demo-${externalId}` });
|
|
1923
|
+
if (created.error) {
|
|
1924
|
+
io.err(`Creating a session failed: ${describeError(created.error)}
|
|
1925
|
+
`);
|
|
1926
|
+
return json(res, 502, { error: created.error.message });
|
|
1927
|
+
}
|
|
1928
|
+
const s = created.data;
|
|
1929
|
+
sessions.set(s.id, { externalId });
|
|
1930
|
+
return json(res, 200, { id: s.id, client_token: s.client_token, api_url: s.api_url ?? esc.baseUrl, required_steps: s.required_steps, documents: s.documents.map((d) => ({ version_id: d.version_id, title: d.title, render_hash: d.render_hash })) });
|
|
1931
|
+
}
|
|
1932
|
+
if (req.method === "POST" && url.pathname === "/api/confirm") {
|
|
1933
|
+
const body = await readBody(req);
|
|
1934
|
+
const known = sessions.get(String(body.session_id ?? ""));
|
|
1935
|
+
const recordId = String(body.record_id ?? "");
|
|
1936
|
+
if (!known || !/^rec_[A-Za-z0-9]+$/.test(recordId)) return json(res, 400, { error: "Unknown session or record." });
|
|
1937
|
+
try {
|
|
1938
|
+
const record = await confirmRecord(esc, recordId, { externalId: known.externalId, versionIds: setup.documents.map((d) => d.version_id) });
|
|
1939
|
+
const channel = body.channel === "sdk" ? "in the browser, by the browser SDK (direct channel)" : "in the browser, by the demo page's own fetch calls (the browser SDK bundle was not available)";
|
|
1940
|
+
res.once("finish", () => finish({ record, channel }));
|
|
1941
|
+
json(res, 200, { ok: true, record_id: record.id, status: record.status, verify_url: record.verify_url });
|
|
1942
|
+
} catch (err) {
|
|
1943
|
+
json(res, 409, { error: err instanceof Error ? err.message : String(err) });
|
|
1944
|
+
}
|
|
1945
|
+
return;
|
|
1946
|
+
}
|
|
1947
|
+
if (req.method === "GET" && url.pathname === "/favicon.ico") {
|
|
1948
|
+
res.writeHead(204);
|
|
1949
|
+
res.end();
|
|
1950
|
+
return;
|
|
1951
|
+
}
|
|
1952
|
+
send(res, 404, "text/plain", "Not found.");
|
|
1953
|
+
};
|
|
1954
|
+
const server = createServer((req, res) => {
|
|
1955
|
+
handle(req, res).catch((err) => {
|
|
1956
|
+
if (!res.headersSent) json(res, 500, { error: err instanceof Error ? err.message : String(err) });
|
|
1957
|
+
else res.end();
|
|
1958
|
+
});
|
|
1959
|
+
});
|
|
1960
|
+
await new Promise((resolve, reject) => {
|
|
1961
|
+
server.once("error", (err) => {
|
|
1962
|
+
reject(new CommandError(err.code === "EADDRINUSE" ? `Port ${port} is in use. Choose another with --port.` : `The local page could not start: ${err.message}`, 2));
|
|
1963
|
+
});
|
|
1964
|
+
server.listen(port, "127.0.0.1", resolve);
|
|
1965
|
+
});
|
|
1966
|
+
const address = server.address();
|
|
1967
|
+
if (address && typeof address === "object") origin = `http://localhost:${address.port}`;
|
|
1968
|
+
return { server, url: `${origin}/`, done };
|
|
1969
|
+
}
|
|
1970
|
+
async function driveWithPlaywright(url, io) {
|
|
1971
|
+
const launch = await launchBrowser();
|
|
1972
|
+
if (!launch.ok) {
|
|
1973
|
+
line(io, launch.reason === "not_installed" ? "Playwright is not installed, so no browser is available to drive the page." : `Playwright found no browser to drive (${launch.detail}).`);
|
|
1974
|
+
return "unavailable";
|
|
1975
|
+
}
|
|
1976
|
+
const browser = launch.browser;
|
|
1977
|
+
try {
|
|
1978
|
+
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
|
|
1979
|
+
await page.goto(url, { waitUntil: "domcontentloaded" });
|
|
1980
|
+
await page.waitForSelector('body[data-state="ready"], body[data-state="error"]', { timeout: 3e4 });
|
|
1981
|
+
if (await page.getAttribute("body", "data-state") === "error") throw new CommandError(`The demo page reported: ${await page.textContent("#status")}`);
|
|
1982
|
+
await page.click("#agree");
|
|
1983
|
+
await page.click("#submit");
|
|
1984
|
+
await page.waitForSelector('body[data-state="done"], body[data-state="error"]', { timeout: 3e4 });
|
|
1985
|
+
if (await page.getAttribute("body", "data-state") === "error") throw new CommandError(`The demo page reported: ${await page.textContent("#status")}`);
|
|
1986
|
+
return "driven";
|
|
1987
|
+
} finally {
|
|
1988
|
+
await browser.close().catch(() => void 0);
|
|
1989
|
+
}
|
|
1990
|
+
}
|
|
1991
|
+
async function demoCommand(argv, io) {
|
|
1992
|
+
const { positionals, flags } = parseArgs(argv, { port: "string", auto: "boolean", help: "boolean" }, { "-h": "--help" });
|
|
1993
|
+
if (bool(flags, "help")) {
|
|
1994
|
+
io.out(DEMO_HELP);
|
|
1995
|
+
return 0;
|
|
1996
|
+
}
|
|
1997
|
+
if (positionals.length > 0) throw new UsageError(`Unexpected argument "${positionals[0]}".`);
|
|
1998
|
+
const port = int(flags, "port", 4310, 0, 65535);
|
|
1999
|
+
const esc = clientFromEnv(io, { testOnly: "The demo records a test signature." });
|
|
2000
|
+
line(io, paint(io, "bold", "Esign Comply demo") + " (test mode)");
|
|
2001
|
+
const setup = await ensureDemoSetup(esc);
|
|
2002
|
+
line(io, ` Documents ${setup.documents.map((d) => `${d.title} (${d.version_id})`).join(", ")}`);
|
|
2003
|
+
line(io, ` Profile ${PROFILE_NAME} (${setup.profileId})`);
|
|
2004
|
+
if (setup.created.length > 0) line(io, paint(io, "dim", ` Created ${setup.created.join(", ")}`));
|
|
2005
|
+
line(io);
|
|
2006
|
+
const demo = await startDemoServer(esc, setup, port, io);
|
|
2007
|
+
try {
|
|
2008
|
+
if (bool(flags, "auto")) {
|
|
2009
|
+
line(io, `Serving the signup page at ${demo.url}`);
|
|
2010
|
+
const driven = await driveWithPlaywright(demo.url, io);
|
|
2011
|
+
if (driven === "unavailable") {
|
|
2012
|
+
line(io, "Running the ceremony over the API instead, as a server_only session: this process reports each step with the secret key.");
|
|
2013
|
+
line(io, "No browser was involved, so every step in the record is tagged asserted rather than observed.");
|
|
2014
|
+
const record2 = await runServerOnly(esc, setup);
|
|
2015
|
+
printRecord(io, esc, record2, "by this process (server_only): asserted, not observed");
|
|
2016
|
+
return 0;
|
|
2017
|
+
}
|
|
2018
|
+
const { record, channel } = await demo.done;
|
|
2019
|
+
printRecord(io, esc, record, `${channel}, driven by Playwright`);
|
|
2020
|
+
return 0;
|
|
2021
|
+
}
|
|
2022
|
+
line(io, `Open ${paint(io, "bold", demo.url)} and create the account: tick the box, then click "${BUTTON_LABEL}".`);
|
|
2023
|
+
line(io, paint(io, "dim", "Waiting for the signature. Stop with Ctrl+C."));
|
|
2024
|
+
const interrupted = new Promise((resolve) => process.once("SIGINT", () => resolve(null)));
|
|
2025
|
+
const result = await Promise.race([demo.done, interrupted]);
|
|
2026
|
+
if (!result) {
|
|
2027
|
+
line(io, "\nStopped before a record was made.");
|
|
2028
|
+
return 130;
|
|
2029
|
+
}
|
|
2030
|
+
printRecord(io, esc, result.record, result.channel);
|
|
2031
|
+
return 0;
|
|
2032
|
+
} finally {
|
|
2033
|
+
await new Promise((resolve) => {
|
|
2034
|
+
demo.server.close(() => resolve());
|
|
2035
|
+
demo.server.closeAllConnections?.();
|
|
2036
|
+
});
|
|
2037
|
+
}
|
|
2038
|
+
}
|
|
2039
|
+
|
|
2040
|
+
// packages/esigncomply/src/cli/documents.ts
|
|
2041
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
2042
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
2043
|
+
import { extname } from "node:path";
|
|
2044
|
+
var DOCUMENTS_HELP = `esigncomply documents publish <file> --document <doc_id> --label <version label> [options]
|
|
2045
|
+
|
|
2046
|
+
Publish a file as a new, immutable version of a document. The API returns the
|
|
2047
|
+
content hash that every record of this version will name.
|
|
2048
|
+
|
|
2049
|
+
--document <doc_id> The document to add the version to (required).
|
|
2050
|
+
--label <label> Version label, for example 2026-11-21 (required).
|
|
2051
|
+
--language <code> Language of this version. Default: en.
|
|
2052
|
+
--material Mark the change as material: earlier acceptances become
|
|
2053
|
+
outstanding in the signer status (DV-4).
|
|
2054
|
+
--summary <text> Summary of changes, shown to signers asked to accept again.
|
|
2055
|
+
--effective-at <time> RFC 3339 time from which the version is current. Default: now.
|
|
2056
|
+
--format <format> markdown, html, text or pdf. Default: from the file extension.
|
|
2057
|
+
--json Print the version object as JSON.
|
|
2058
|
+
|
|
2059
|
+
Environment
|
|
2060
|
+
ESIGNCOMPLY_API_KEY A test or live key with document write access.
|
|
2061
|
+
ESIGNCOMPLY_API_URL API base URL, for local development.
|
|
2062
|
+
|
|
2063
|
+
Running the command again with the same file, document, label and language
|
|
2064
|
+
returns the version already published: the call carries an idempotency key
|
|
2065
|
+
derived from them.
|
|
2066
|
+
`;
|
|
2067
|
+
var FORMATS = { ".md": "markdown", ".markdown": "markdown", ".html": "html", ".htm": "html", ".txt": "text", ".pdf": "pdf" };
|
|
2068
|
+
async function documentsCommand(argv, io) {
|
|
2069
|
+
const [sub, ...rest] = argv;
|
|
2070
|
+
if (!sub || sub === "--help" || sub === "-h" || rest.includes("--help") || rest.includes("-h")) {
|
|
2071
|
+
io.out(DOCUMENTS_HELP);
|
|
2072
|
+
return sub ? 0 : 2;
|
|
2073
|
+
}
|
|
2074
|
+
if (sub !== "publish") throw new UsageError(`Unknown documents command "${sub}". The command is: esigncomply documents publish <file> \u2026`);
|
|
2075
|
+
const { positionals, flags } = parseArgs(rest, { document: "string", label: "string", language: "string", material: "boolean", summary: "string", "effective-at": "string", format: "string", json: "boolean" });
|
|
2076
|
+
const file = positionals[0];
|
|
2077
|
+
const documentId = str(flags, "document");
|
|
2078
|
+
const label = str(flags, "label");
|
|
2079
|
+
if (!file || positionals.length > 1) throw new UsageError("Name one file to publish: esigncomply documents publish <file> --document <doc_id> --label <version label>");
|
|
2080
|
+
if (!documentId) throw new UsageError("--document <doc_id> is required.");
|
|
2081
|
+
if (!label) throw new UsageError("--label <version label> is required.");
|
|
2082
|
+
const format = str(flags, "format") ?? FORMATS[extname(file).toLowerCase()];
|
|
2083
|
+
if (!format || !["markdown", "html", "text", "pdf"].includes(format)) {
|
|
2084
|
+
throw new UsageError(`Cannot tell the format of ${file}. Pass --format markdown, html, text or pdf.`);
|
|
2085
|
+
}
|
|
2086
|
+
let bytes;
|
|
2087
|
+
try {
|
|
2088
|
+
bytes = await readFile2(file);
|
|
2089
|
+
} catch (err) {
|
|
2090
|
+
throw new UsageError(`Cannot read ${file}: ${err instanceof Error ? err.message : String(err)}`);
|
|
2091
|
+
}
|
|
2092
|
+
const content = format === "pdf" ? { format: "pdf", data_base64: bytes.toString("base64") } : { format, text: bytes.toString("utf8") };
|
|
2093
|
+
const language = str(flags, "language") ?? "en";
|
|
2094
|
+
const esc = clientFromEnv(io);
|
|
2095
|
+
const digest = createHash2("sha256").update(bytes).digest("hex");
|
|
2096
|
+
const version = must(
|
|
2097
|
+
await esc.documents.versions.create(
|
|
2098
|
+
documentId,
|
|
2099
|
+
{
|
|
2100
|
+
version_label: label,
|
|
2101
|
+
language,
|
|
2102
|
+
content,
|
|
2103
|
+
...bool(flags, "material") ? { material_change: true } : {},
|
|
2104
|
+
...str(flags, "summary") ? { summary_of_changes: str(flags, "summary") } : {},
|
|
2105
|
+
...str(flags, "effective-at") ? { effective_at: str(flags, "effective-at") } : {}
|
|
2106
|
+
},
|
|
2107
|
+
{ idempotencyKey: `cli-publish-${documentId}-${label}-${language}-${digest.slice(0, 32)}` }
|
|
2108
|
+
),
|
|
2109
|
+
"Publishing the version"
|
|
2110
|
+
);
|
|
2111
|
+
if (bool(flags, "json")) {
|
|
2112
|
+
line(io, JSON.stringify(version, null, 2));
|
|
2113
|
+
return 0;
|
|
2114
|
+
}
|
|
2115
|
+
line(io, `Published ${version.id} (${version.version_label}, ${version.language}) of ${version.document_id}`);
|
|
2116
|
+
line(io, ` content hash ${version.content_hash}`);
|
|
2117
|
+
line(io, ` render hash ${version.render_hash ?? "none"}`);
|
|
2118
|
+
line(io, ` effective ${version.effective_at}`);
|
|
2119
|
+
line(io, ` material ${version.material_change ? "yes: earlier acceptances are now outstanding" : "no"}`);
|
|
2120
|
+
line(io, ` mode ${version.livemode ? "live" : "test"}`);
|
|
2121
|
+
for (const w of version.warnings ?? []) line(io, ` warning ${w}`);
|
|
2122
|
+
return 0;
|
|
2123
|
+
}
|
|
2124
|
+
|
|
2125
|
+
// packages/esigncomply/src/cli/verify.ts
|
|
2126
|
+
var VERIFY_HELP = `esigncomply verify <package.zip | directory> [--jwks <file or https URL>] [--tsa-roots <pem file>] [--json]
|
|
2127
|
+
esigncomply verify <certificate.json> --evidence <package.zip>
|
|
2128
|
+
|
|
2129
|
+
Verify an evidence package offline. This runs the open-source verifier,
|
|
2130
|
+
esigncomply-verify: no API key, no account and no network are needed, and
|
|
2131
|
+
nothing is fetched unless --jwks is an https URL.
|
|
2132
|
+
|
|
2133
|
+
--jwks <file | https URL> Check signatures against these sealing keys instead of the bundled ones.
|
|
2134
|
+
--tsa-roots <pem file> Trust anchors for the timestamp authority's certificate chain.
|
|
2135
|
+
--evidence <zip | dir> With a certificate: the evidence package of a record it covers.
|
|
2136
|
+
--json Print the report as JSON.
|
|
2137
|
+
|
|
2138
|
+
Exit code 0 when verified, 1 when not, 2 when the command could not run.
|
|
2139
|
+
|
|
2140
|
+
A passing verification shows that the record matches its seal and bounds when it
|
|
2141
|
+
existed. It does not establish who signed or whether any agreement is valid or
|
|
2142
|
+
enforceable.
|
|
2143
|
+
`;
|
|
2144
|
+
async function verifyCommand(argv, io) {
|
|
2145
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
2146
|
+
io.out(VERIFY_HELP);
|
|
2147
|
+
return 0;
|
|
2148
|
+
}
|
|
2149
|
+
let run2;
|
|
2150
|
+
try {
|
|
2151
|
+
({ run: run2 } = await import("esigncomply-verify/cli"));
|
|
2152
|
+
} catch (err) {
|
|
2153
|
+
io.err(`The verifier could not be loaded (${err instanceof Error ? err.message : String(err)}). Install it with: npm install esigncomply-verify
|
|
2154
|
+
`);
|
|
2155
|
+
return 2;
|
|
2156
|
+
}
|
|
2157
|
+
return run2(argv, { stdout: io.out, stderr: io.err });
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
// packages/esigncomply/src/cli/webhooks.ts
|
|
2161
|
+
var WEBHOOKS_HELP = `esigncomply webhooks listen --forward <local URL> [options]
|
|
2162
|
+
|
|
2163
|
+
Forward test-mode webhook deliveries to a server on your machine, so you can
|
|
2164
|
+
build the handler before your endpoint is reachable from the internet. Each
|
|
2165
|
+
event is posted to the URL with the body Esign Comply delivers and the
|
|
2166
|
+
webhook-id, webhook-timestamp and webhook-signature headers.
|
|
2167
|
+
|
|
2168
|
+
--forward <url> Where to post deliveries, for example
|
|
2169
|
+
http://localhost:3000/api/esigncomply/webhook (required).
|
|
2170
|
+
--secret <whsec_\u2026> The signing secret of your test endpoint. The API does not
|
|
2171
|
+
return the signature it sent, so the command signs each
|
|
2172
|
+
forwarded delivery with this secret, the way Esign Comply
|
|
2173
|
+
signs it, and esc.webhooks.verify() accepts it. Without a
|
|
2174
|
+
secret, deliveries are forwarded unsigned.
|
|
2175
|
+
--endpoint <id> Forward the deliveries of this endpoint only.
|
|
2176
|
+
--interval <ms> How often to ask for new deliveries. Default 2000, minimum 1000.
|
|
2177
|
+
--since <time> Start from this RFC 3339 time instead of now.
|
|
2178
|
+
--once Ask once, forward what is there, and exit.
|
|
2179
|
+
|
|
2180
|
+
Environment
|
|
2181
|
+
ESIGNCOMPLY_API_KEY A full-access test key (esc_test_\u2026). Live deliveries are never forwarded.
|
|
2182
|
+
ESIGNCOMPLY_WEBHOOK_SECRET Used when --secret is not given.
|
|
2183
|
+
ESIGNCOMPLY_API_URL API base URL, for local development.
|
|
2184
|
+
|
|
2185
|
+
Deliveries exist only for registered endpoints: create a test endpoint first
|
|
2186
|
+
(esc.webhooks.create({ url }), or the dashboard) and keep the secret it returns.
|
|
2187
|
+
Stop with Ctrl+C.
|
|
2188
|
+
`;
|
|
2189
|
+
function forwardedRequest(d, secret, now) {
|
|
2190
|
+
const body = typeof d.body === "string" ? d.body : JSON.stringify(d.payload ?? {});
|
|
2191
|
+
const headers = { "Content-Type": "application/json", "User-Agent": "EsignComply-CLI-Forwarder/1.0" };
|
|
2192
|
+
const original = typeof d.headers === "object" && d.headers !== null ? d.headers : {};
|
|
2193
|
+
for (const [name, value] of Object.entries(original)) {
|
|
2194
|
+
if (/^webhook-(id|timestamp|signature)$/i.test(name) && typeof value === "string") headers[name.toLowerCase()] = value;
|
|
2195
|
+
}
|
|
2196
|
+
if (headers["webhook-id"] && headers["webhook-timestamp"] && headers["webhook-signature"]) return { body, headers, signed: true };
|
|
2197
|
+
const id = d.webhook_id ?? d.id;
|
|
2198
|
+
headers["webhook-id"] = id;
|
|
2199
|
+
if (!secret) return { body, headers, signed: false };
|
|
2200
|
+
const timestamp = Math.floor(now.getTime() / 1e3);
|
|
2201
|
+
headers["webhook-timestamp"] = String(timestamp);
|
|
2202
|
+
headers["webhook-signature"] = signWebhookPayload(secret, id, timestamp, body);
|
|
2203
|
+
return { body, headers, signed: true };
|
|
2204
|
+
}
|
|
2205
|
+
async function webhooksCommand(argv, io, deps = {}) {
|
|
2206
|
+
const [sub, ...rest] = argv;
|
|
2207
|
+
if (!sub || sub === "--help" || sub === "-h" || rest.includes("--help") || rest.includes("-h")) {
|
|
2208
|
+
io.out(WEBHOOKS_HELP);
|
|
2209
|
+
return sub ? 0 : 2;
|
|
2210
|
+
}
|
|
2211
|
+
if (sub !== "listen") throw new UsageError(`Unknown webhooks command "${sub}". The command is: esigncomply webhooks listen --forward <url>`);
|
|
2212
|
+
const { positionals, flags } = parseArgs(rest, { forward: "string", secret: "string", endpoint: "string", interval: "string", since: "string", once: "boolean" });
|
|
2213
|
+
if (positionals.length > 0) throw new UsageError(`Unexpected argument "${positionals[0]}".`);
|
|
2214
|
+
const forward = str(flags, "forward");
|
|
2215
|
+
if (!forward) throw new UsageError("--forward <url> is required, for example --forward http://localhost:3000/api/esigncomply/webhook");
|
|
2216
|
+
let target;
|
|
2217
|
+
try {
|
|
2218
|
+
target = new URL(forward);
|
|
2219
|
+
} catch {
|
|
2220
|
+
throw new UsageError(`--forward "${forward}" is not a URL.`);
|
|
2221
|
+
}
|
|
2222
|
+
if (target.protocol !== "http:" && target.protocol !== "https:") throw new UsageError("--forward must be an http or https URL.");
|
|
2223
|
+
const interval = int(flags, "interval", 2e3, 1e3, 6e5);
|
|
2224
|
+
let since = str(flags, "since") ?? (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString();
|
|
2225
|
+
if (Number.isNaN(Date.parse(since))) throw new UsageError("--since must be an RFC 3339 time.");
|
|
2226
|
+
const secret = str(flags, "secret") ?? (io.env.ESIGNCOMPLY_WEBHOOK_SECRET || void 0);
|
|
2227
|
+
const endpoint = str(flags, "endpoint");
|
|
2228
|
+
const esc = deps.client ?? clientFromEnv(io, { testOnly: "Only test-mode deliveries can be forwarded." });
|
|
2229
|
+
const post = deps.fetch ?? globalThis.fetch;
|
|
2230
|
+
const sleep = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
|
|
2231
|
+
let stopped = false;
|
|
2232
|
+
const stop = deps.stop ?? new Promise((resolve) => {
|
|
2233
|
+
process.once("SIGINT", resolve);
|
|
2234
|
+
process.once("SIGTERM", resolve);
|
|
2235
|
+
});
|
|
2236
|
+
void stop.then(() => {
|
|
2237
|
+
stopped = true;
|
|
2238
|
+
});
|
|
2239
|
+
line(io, `Forwarding test webhook deliveries to ${target.toString()}`);
|
|
2240
|
+
line(io, paint(io, "dim", `Asking ${esc.baseUrl} every ${interval} ms. Stop with Ctrl+C.`));
|
|
2241
|
+
if (!secret) {
|
|
2242
|
+
line(io, "No signing secret was given, so deliveries are forwarded without webhook-signature and your handler's verification will refuse them.");
|
|
2243
|
+
line(io, "Pass --secret whsec_\u2026 (the secret of your test endpoint) to have each forwarded delivery signed.");
|
|
2244
|
+
}
|
|
2245
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2246
|
+
let forwarded = 0;
|
|
2247
|
+
let failures = 0;
|
|
2248
|
+
for (let first = true; !stopped; first = false) {
|
|
2249
|
+
const res = await esc.webhooks.listDeliveries({ since, limit: 100, include: "payload", ...endpoint ? { endpoint } : {} });
|
|
2250
|
+
if (res.error) {
|
|
2251
|
+
if (res.error.status === 404) {
|
|
2252
|
+
io.err(
|
|
2253
|
+
"This API does not serve test webhook deliveries yet: GET /v1/webhooks/deliveries answered 404.\nNothing can be forwarded. Until the endpoint is available, register a public test endpoint with esc.webhooks.create(), for example through a tunnel to your machine.\n"
|
|
2254
|
+
);
|
|
2255
|
+
return 1;
|
|
2256
|
+
}
|
|
2257
|
+
if (first || res.error.type === "authentication_error" || res.error.type === "permission_error") {
|
|
2258
|
+
io.err(`Reading deliveries failed: ${describeError(res.error)}
|
|
2259
|
+
`);
|
|
2260
|
+
return 1;
|
|
2261
|
+
}
|
|
2262
|
+
io.err(paint(io, "yellow", `Reading deliveries failed, trying again: ${describeError(res.error)}`) + "\n");
|
|
2263
|
+
} else {
|
|
2264
|
+
const deliveries = [...res.data.data ?? []].sort((a, b) => String(a.created_at).localeCompare(String(b.created_at)));
|
|
2265
|
+
for (const d of deliveries) {
|
|
2266
|
+
if (stopped) break;
|
|
2267
|
+
if (d.created_at && d.created_at > since) since = d.created_at;
|
|
2268
|
+
const key = endpoint ? d.id : d.webhook_id ?? d.id;
|
|
2269
|
+
if (seen.has(key)) continue;
|
|
2270
|
+
seen.add(key);
|
|
2271
|
+
const type = String(d.type ?? d.event_type ?? d.payload?.type ?? "event");
|
|
2272
|
+
const stamp = (deps.now?.() ?? /* @__PURE__ */ new Date()).toISOString().slice(11, 19);
|
|
2273
|
+
if (d.payload === void 0 && typeof d.body !== "string") {
|
|
2274
|
+
failures++;
|
|
2275
|
+
line(io, `${stamp} ${type.padEnd(28)} ${d.webhook_id ?? d.id} -> ${paint(io, "red", "skipped")} (the API returned no payload for this delivery)`);
|
|
2276
|
+
continue;
|
|
2277
|
+
}
|
|
2278
|
+
const request = forwardedRequest(d, secret, deps.now?.() ?? /* @__PURE__ */ new Date());
|
|
2279
|
+
try {
|
|
2280
|
+
const out = await post(target, { method: "POST", headers: request.headers, body: request.body, signal: AbortSignal.timeout(1e4) });
|
|
2281
|
+
await out.arrayBuffer().catch(() => void 0);
|
|
2282
|
+
const okay = out.status >= 200 && out.status < 300;
|
|
2283
|
+
if (okay) forwarded++;
|
|
2284
|
+
else failures++;
|
|
2285
|
+
line(io, `${stamp} ${type.padEnd(28)} ${d.webhook_id ?? d.id} -> ${paint(io, okay ? "green" : "red", String(out.status))}${request.signed ? "" : " (unsigned)"}`);
|
|
2286
|
+
} catch (err) {
|
|
2287
|
+
failures++;
|
|
2288
|
+
line(io, `${stamp} ${type.padEnd(28)} ${d.webhook_id ?? d.id} -> ${paint(io, "red", "no answer")} (${err instanceof Error ? err.message : String(err)})`);
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
}
|
|
2292
|
+
if (bool(flags, "once")) break;
|
|
2293
|
+
await Promise.race([sleep(interval), stop]);
|
|
2294
|
+
}
|
|
2295
|
+
line(io, `Forwarded ${forwarded} deliver${forwarded === 1 ? "y" : "ies"}${failures > 0 ? `, ${failures} not accepted by ${target.host}` : ""}.`);
|
|
2296
|
+
return 0;
|
|
2297
|
+
}
|
|
2298
|
+
|
|
2299
|
+
// packages/esigncomply/src/cli/index.ts
|
|
2300
|
+
var HELP = `esigncomply ${VERSION}
|
|
2301
|
+
|
|
2302
|
+
Usage
|
|
2303
|
+
esigncomply <command> [options]
|
|
2304
|
+
|
|
2305
|
+
Commands
|
|
2306
|
+
demo Serve a local signup page, run a test ceremony, print the record ID.
|
|
2307
|
+
check Conformance check of your page at three window sizes; exit code for CI.
|
|
2308
|
+
documents publish Publish a file as a new version of a document.
|
|
2309
|
+
webhooks listen Forward test webhook deliveries to a server on your machine.
|
|
2310
|
+
verify Verify an evidence package offline.
|
|
2311
|
+
|
|
2312
|
+
esigncomply <command> --help Options of one command.
|
|
2313
|
+
esigncomply --version
|
|
2314
|
+
|
|
2315
|
+
Environment
|
|
2316
|
+
ESIGNCOMPLY_API_KEY Your secret key. demo, check and webhooks listen take test keys only.
|
|
2317
|
+
ESIGNCOMPLY_API_URL API base URL. Default: the host for the region in the key.
|
|
2318
|
+
`;
|
|
2319
|
+
var COMMAND_HELP = { demo: DEMO_HELP, check: CHECK_HELP, documents: DOCUMENTS_HELP, webhooks: WEBHOOKS_HELP, verify: VERIFY_HELP };
|
|
2320
|
+
async function run(argv, io = processIo()) {
|
|
2321
|
+
const [command, ...rest] = argv;
|
|
2322
|
+
try {
|
|
2323
|
+
if (!command || command === "--help" || command === "-h") {
|
|
2324
|
+
io.out(HELP);
|
|
2325
|
+
return command ? 0 : 2;
|
|
2326
|
+
}
|
|
2327
|
+
if (command === "--version" || command === "-v") {
|
|
2328
|
+
io.out(`${VERSION}
|
|
2329
|
+
`);
|
|
2330
|
+
return 0;
|
|
2331
|
+
}
|
|
2332
|
+
if (command === "help") {
|
|
2333
|
+
const topic = rest[0];
|
|
2334
|
+
if (topic && !(topic in COMMAND_HELP)) throw new UsageError(`Unknown command "${topic}".`);
|
|
2335
|
+
io.out(topic ? COMMAND_HELP[topic] : HELP);
|
|
2336
|
+
return 0;
|
|
2337
|
+
}
|
|
2338
|
+
switch (command) {
|
|
2339
|
+
case "demo":
|
|
2340
|
+
return await demoCommand(rest, io);
|
|
2341
|
+
case "check":
|
|
2342
|
+
return await checkCommand(rest, io);
|
|
2343
|
+
case "documents":
|
|
2344
|
+
return await documentsCommand(rest, io);
|
|
2345
|
+
case "webhooks":
|
|
2346
|
+
return await webhooksCommand(rest, io);
|
|
2347
|
+
case "verify":
|
|
2348
|
+
return await verifyCommand(rest, io);
|
|
2349
|
+
default:
|
|
2350
|
+
throw new UsageError(`Unknown command "${command}".`);
|
|
2351
|
+
}
|
|
2352
|
+
} catch (err) {
|
|
2353
|
+
if (err instanceof UsageError) {
|
|
2354
|
+
const topic = command && command in COMMAND_HELP ? ` ${command}` : "";
|
|
2355
|
+
io.err(`${err.message}
|
|
2356
|
+
Run esigncomply${topic} --help for usage.
|
|
2357
|
+
`);
|
|
2358
|
+
return 2;
|
|
2359
|
+
}
|
|
2360
|
+
if (err instanceof CommandError) {
|
|
2361
|
+
io.err(`${err.message}
|
|
2362
|
+
`);
|
|
2363
|
+
return err.exitCode;
|
|
2364
|
+
}
|
|
2365
|
+
io.err(`esigncomply: ${err instanceof Error ? err.message : String(err)}
|
|
2366
|
+
`);
|
|
2367
|
+
return 1;
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
function isMain() {
|
|
2371
|
+
try {
|
|
2372
|
+
return !!process.argv[1] && realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url));
|
|
2373
|
+
} catch {
|
|
2374
|
+
return false;
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
if (isMain()) {
|
|
2378
|
+
run(process.argv.slice(2)).then(
|
|
2379
|
+
(code) => {
|
|
2380
|
+
process.exitCode = code;
|
|
2381
|
+
setTimeout(() => process.exit(code), 250).unref();
|
|
2382
|
+
},
|
|
2383
|
+
(err) => {
|
|
2384
|
+
process.stderr.write(`esigncomply: ${err instanceof Error ? err.message : String(err)}
|
|
2385
|
+
`);
|
|
2386
|
+
process.exit(1);
|
|
2387
|
+
}
|
|
2388
|
+
);
|
|
2389
|
+
}
|
|
2390
|
+
export {
|
|
2391
|
+
HELP,
|
|
2392
|
+
run
|
|
2393
|
+
};
|