esigncomply
v1.0.5
Published
Server SDK and CLI for Esign Comply: documents, sessions, records, supplements, certificates, guidance and webhook verification.
Maintainers
Readme
esigncomply
Server SDK and command-line tool for Esign Comply: an independent, tamper-evident record of what a person was shown and what they agreed to on your own signup, checkout and signing pages.
This package runs on your server. It holds your secret API key, creates
sessions, confirms records and verifies webhooks. The signer's browser never
sees the key: it gets a short-lived session token and uses @esigncomply/browser.
npm install esigncomplyNode 20.19 or later. ES modules. No runtime dependencies beyond the offline
verifier, esigncomply-verify.
Try it first
export ESIGNCOMPLY_API_KEY=esc_test_us_...
npx esigncomply@latest demodemo serves a signup page on localhost, runs a real test ceremony when you
tick the box and click "Create account", and prints the record ID.
Every method returns { data, error }
No method throws. Exactly one of data and error is null.
import { EsignComply } from "esigncomply";
const esc = new EsignComply(process.env.ESIGNCOMPLY_API_KEY!);
const { data, error } = await esc.records.get("rec_Z4m8");
if (error) {
// error.type, error.code, error.message, error.status, error.request_id
// and, where they apply: error.param, error.missing_steps, error.rule, error.quote, error.retry_after
return;
}
data.status; // "recorded"Branch on error.type first. Codes can be added at any time, so treat a
code you do not know as its type. A network failure comes back as
{ type: "api_error", code: "network_error" }.
The constructor is the one place that throws: it refuses to run in a browser, because the secret key must never reach client code.
Record an agreement
1. Your server starts a session for one signer and the documents they will see, and hands the page the client token.
// POST /api/esigncomply/session on your server
const { data: session, error } = await esc.sessions.create(
{
profile: "prof_signup_us",
signer: { external_id: user.id, email: user.email, name: user.name, class: "consumer", country: "US", region: "US-CA" },
documents: [
{ document: "doc_8Hq2", version: "current" }, // Terms of Service
{ document: "doc_Pv71", version: "current" }, // Privacy Notice
],
context: { url: "https://app.example.com/signup", locale: "en-US", purpose: "account_signup" },
},
{ idempotencyKey: `signup-${user.id}` },
);
if (error) return Response.json({ error: error.message }, { status: 502 });
// Keep what you asked for, so you can check the record against it later.
await db.pendingSignups.set(session.id, { userId: user.id, versions: session.documents.map((d) => d.version_id) });
// The browser gets the token, the API URL and the steps. Never the API key.
return Response.json({ clientToken: session.client_token, apiUrl: session.api_url, documents: session.documents });session.required_steps is the authoritative list of steps for this session.
Read it; do not hard-code steps.
2. The page runs the ceremony with @esigncomply/browser and the client
token, and gets back a record ID when the signer acts.
3. Your server confirms the record before granting access. The page's word is not enough: anyone can post a made-up record ID to your endpoint. Read the record with the secret key and compare it with what your server asked for.
// POST /api/esigncomply/confirm on your server, called by your page with { sessionId, recordId }
const pending = await db.pendingSignups.get(sessionId);
const { data: record, error } = await esc.records.get(recordId);
const confirmed =
!error &&
pending !== undefined &&
["recorded", "timestamped", "anchored"].includes(record.status) &&
record.livemode === (process.env.NODE_ENV === "production") &&
record.signer.external_id === pending.userId &&
record.documents.map((d) => d.version_id).sort().join() === [...pending.versions].sort().join();
if (!confirmed) return Response.json({ error: "No valid record of acceptance." }, { status: 403 });
await grantAccess(pending.userId, record.id);A record with status pending_seal is committed but not yet signed. Wait for
the record.completed webhook, which fires once the receipt exists.
Webhooks
Deliveries follow the Standard Webhooks convention: headers webhook-id,
webhook-timestamp and webhook-signature, an HMAC-SHA256 over
id.timestamp.body. Verify against the raw body, exactly as received.
// app/api/esigncomply/webhook/route.ts (Next.js)
import { EsignComply } from "esigncomply";
const esc = new EsignComply(process.env.ESIGNCOMPLY_API_KEY!);
export async function POST(request: Request) {
const rawBody = await request.text(); // not request.json(): the signature covers the bytes
const { data: event, error } = await esc.webhooks.verify(rawBody, request.headers, process.env.ESIGNCOMPLY_WEBHOOK_SECRET!);
if (error) return new Response(error.message, { status: 400 });
// Deliveries are at-least-once: do each event once.
if (await db.webhookEvents.seen(event.id)) return new Response("ok");
switch (event.type) {
case "record.completed": {
// Payloads carry IDs and status only. Fetch the record for details.
const { data: record } = await esc.records.get(String(event.data.record_id));
if (record && record.status !== "pending_seal") await grantAccess(record.signer.external_id, record.id);
break;
}
case "consent.withdrawn":
case "record.disputed":
await flagForReview(String(event.data.record_id));
break;
default:
// New event types can be added at any time. Ignore the ones you do not know.
}
await db.webhookEvents.mark(event.id);
return new Response("ok");
}verify accepts a fetch Headers object or a plain record (req.headers in
Node and Express). It refuses deliveries whose timestamp is more than five
minutes from now, so a captured request cannot be replayed, and compares
signatures in constant time.
Idempotency and retries
- Pass
{ idempotencyKey }on any call that creates something. A repeat with the same key and body returns the original response, for 24 hours. - The SDK retries up to twice (
maxRetries): always after a429, waiting the interval inRetry-After; and after a5xxor a network error only when the call is aGETor carries an idempotency key, so nothing is ever done twice.
const esc = new EsignComply(process.env.ESIGNCOMPLY_API_KEY!, {
apiVersion: "2026-11-21", // sent as Esign-Comply-Version; default: the version the key is pinned to
maxRetries: 2,
baseUrl: undefined, // default: from the key's region, or ESIGNCOMPLY_API_URL
});The host follows the region code in the key: esc_…_us_… calls
https://esigncomply.com/v1, esc_…_eu_… calls
https://api.eu.esigncomply.com/v1. For local development set
ESIGNCOMPLY_API_URL=http://localhost:3000/v1.
What is on the client
| Resource | Methods |
|---|---|
| esc.documents | create, list, get |
| esc.documents.versions | create(documentId, body), list, get, getContent(documentId, versionId \| "current") |
| esc.profiles | create, list, get, guidance(id), adopt(id, { note }), rollback(id) |
| esc.jurisdictions | list, get(code), versions(code), resolve(body) (dry run) |
| esc.sessions | create(body, { idempotencyKey }), get, cancel |
| esc.records | list(filters), get(id), report(id), evidence(id, { inline }), receipt(id), annotate(id, { type, data, note }), certify(id, body), submitDeferred(body) |
| esc.certificates | create, quote, list, get, pdf(id), share(id, body), revokeShare(id) |
| esc.supplements | create(body, { idempotencyKey }), list(filters), get, content(id), withdraw(id), types() |
| esc.files | upload(pathOrBytes, { name, contentType }), get(id) |
| esc.guidance | notices.list / get / acknowledge, releases.list / get, updates.get(id) |
| esc.signers | records(externalId), status(externalId), withdrawConsent(externalId, { record_id, scope, note }), requestErasure(externalId, { scope, basis }) |
| esc.webhooks | verify(rawBody, headers, secret), create, list, update, delete, listDeliveries |
| esc.usage | get() |
| esc.conformance | run(body), get(id) |
| esc.prompts | generate(body), list(), get(id) |
| esc.domains | create, get, verify(id), update, watchJurisdictions(id, codes) (resolves to the watched list) |
| esc.apiKeys | create, list, delete |
| esc.verify(receiptOrIdOrHash) | Ask the API whether a record matches its seal. A signed receipt is sent as receipt, a sha256: hash as record_hash, anything else as record_id. A hash or an ID is answered only for a record of your key's own domain. |
| esc.request(method, path, { body, query, idempotencyKey, token }) | Any endpoint without a method yet. Same { data, error } contract. |
Types ship with the package. Enumerations are open strings: the API can add
values without a new SDK, so a switch needs a default.
Files. records.report(id) and certificates.pdf(id) resolve to
{ bytes: Uint8Array, contentType }. records.evidence(id) resolves to a
signed download link; with { inline: true } it resolves to the ZIP bytes.
import { verifyPackage } from "esigncomply-verify";
const { data: zip } = await esc.records.evidence("rec_Z4m8", { inline: true });
const report = await verifyPackage(zip!.bytes); // offline: no API callCustomer-supplied material. Send what you have, in the shape you have it.
files.upload registers the file, sends the bytes straight to storage, and
returns the file once Esign Comply has re-hashed it.
const { data: file } = await esc.files.upload("./renewal-notice.eml", { contentType: "message/rfc822" });
await esc.supplements.create(
{ subject: { record: "rec_Z4m8" }, type: "notice.sent", text: "Renewal reminder emailed.", files: [file!.id] },
{ idempotencyKey: "renewal-notice-usr_1842-2027-01" },
);Server-only sessions. With capture_mode: "server_only" your server
reports the steps itself. There is no named method for that yet; use
esc.request("POST", /sessions/${id}/events, { body }) and
esc.request("POST", /sessions/${id}/complete, { body, idempotencyKey }).
Every step of such a record is tagged asserted, not observed.
Command line
esigncomply <command> [options]Every command takes --help. Output is plain text; colour appears only when
stdout is a terminal. The commands read ESIGNCOMPLY_API_KEY and, for local
development, ESIGNCOMPLY_API_URL.
| Command | What it does |
|---|---|
| esigncomply demo [--port 4310] [--auto] | Creates (or reuses) a demo Terms of Service, Privacy Notice and profile in test mode, serves a signup page on localhost, and prints the record ID, the verify URL and the dashboard link once you sign. --auto drives the page with Playwright when it is installed; otherwise it reports the ceremony from the command itself as a server_only session and says so. Test keys only. |
| esigncomply check --url <page> [--region US-CA …] [--json] | The conformance checker. Opens the page at 390x844, 768x1024 and 1440x900 with Playwright, runs the ceremony at each size, tries violations that must be refused (untouched checkbox, programmatic click, another origin), and reports the findings of a conformance run for each size. It ticks and clicks only once the browser SDK on the page is watching the control; a page that does not get there is reported as not ready at that size, which is not a finding against the page. --fill 'select[name="country"]=US' gives a field a value (text, a select's option, true or false for a checkbox, a radio's value); a required field the checker has no value for is named in the report with the --fill that sets it, and is not a finding either. --region dry-runs the jurisdiction resolution for a signer in that region. Exit code 1 on a blocking finding, 2 when it cannot run. Test keys only. |
| esigncomply documents publish <file> --document <doc_id> --label <label> [--language en] [--material] | Publishes a Markdown, HTML, text or PDF file as a new immutable version and prints its content hash. Safe to run twice. |
| esigncomply webhooks listen --forward <url> [--secret whsec_…] | Forwards test-mode webhook deliveries to a server on your machine, signed with your test endpoint's secret so your handler's verification runs for real. Test keys only. |
| esigncomply verify <package.zip> | Verifies an evidence package offline. Runs esigncomply-verify; needs no key and no network. |
check needs Playwright, which is an optional dependency:
npm install --save-dev playwright
npx playwright install chromiumIn CI:
npx esigncomply check --url http://localhost:3000/signup || exit 1
npx esigncomply check --region US-CA --region US-NYFindings are advisory statements about measurable design facts. The checker does not state that a flow is lawful or enforceable.
Development
pnpm --filter esigncomply-verify build # the CLI's verify command and the live test import it
pnpm --filter esigncomply test
pnpm --filter esigncomply buildtest/live.test.ts runs a whole flow against a real API and is skipped unless
both variables are set. It needs a test key and creates test-mode objects only.
ESIGNCOMPLY_API_KEY=esc_test_... ESIGNCOMPLY_API_URL=http://localhost:3000/v1 pnpm --filter esigncomply test