@esigncomply/browser
v1.0.4
Published
Headless browser SDK for Esign Comply. Observes the signing ceremony your page renders and reports it straight to the Esign Comply API.
Maintainers
Readme
@esigncomply/browser
The headless browser SDK for Esign Comply. It renders nothing. You build the notice, the links, the checkbox and the button. The SDK observes those elements, reports each ceremony step straight from the signer's browser to the Esign Comply API, and tells your code whether the ceremony can proceed.
- No dependencies. About 14 KB gzipped.
- No cookies, no
localStorage, nosessionStorage. The session token stays in memory. - Safe to import during server rendering.
attachitself must run in the browser.
Install
npm install @esigncomply/browserOr load the script build from its versioned URL. It defines one global, EsignComply:
<script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
<script>
EsignComply.attach({ clientToken }).then((ceremony) => { /* ... */ });
</script>How it fits together
- Your server creates a session with its secret key (
POST /v1/sessions) and passes two values to the page:client_tokenandapi_url. - Your page calls
EsignComply.attach({ clientToken, apiUrl }), presents the documents, and lets the SDK observe the assent controls. - In your real submit handler you call
ceremony.complete(). It resolves with{ recordId, receipt, verifyUrl, status }. - Your server confirms the record with
GET /v1/records/{id}before it grants anything. The browser's answer is never proof.
The secret key never reaches the browser. The client token is short-lived and works for one session only.
Signup form
<form id="signup">
<input id="email" type="email" name="email" />
<div id="assent">
<p>
By checking the box and clicking Create account, you agree to the
<a id="tos-link" href="/legal/terms">Terms of Service</a> and acknowledge the
<a id="privacy-link" href="/legal/privacy">Privacy Notice</a>.
</p>
<label><input id="agree" type="checkbox" /> I agree to the Terms of Service and Privacy Notice</label>
<button id="create-account" type="submit" disabled>Create account</button>
</div>
</form>import { EsignComply, EsignComplyError } from "@esigncomply/browser";
const ceremony = await EsignComply.attach({ clientToken, apiUrl });
await ceremony.presentDocument({ versionId: tosVersionId, mode: "hyperlink", link: document.querySelector("#tos-link") });
await ceremony.presentDocument({ versionId: privacyVersionId, mode: "hyperlink", link: document.querySelector("#privacy-link") });
ceremony.observeAssent({
region: document.querySelector("#assent"), // notice text, links, checkbox, button
checkbox: document.querySelector("#agree"),
submit: document.querySelector("#create-account"),
});
// Keep the button disabled until only the signing act is left.
const button = document.querySelector<HTMLButtonElement>("#create-account")!;
const sync = () => (button.disabled = ceremony.remainingSteps().some((step) => step !== "signature.applied"));
ceremony.on("change", sync);
sync();
document.querySelector("#signup")!.addEventListener("submit", async (event) => {
event.preventDefault();
try {
const result = await ceremony.complete(); // { recordId, receipt, verifyUrl, status }
await finishSignup(new FormData(event.target as HTMLFormElement), result.recordId); // your server confirms the record
} catch (err) {
if (err instanceof EsignComplyError) showError(err.message); // err.code, err.rule and err.fix say what to repair
}
});Each document page renders the registered version inside <article data-esc-document>. For a link on the same origin the SDK reads that page and reports the hash of its text, so the API can confirm the link shows the registered version.
Start the ceremony when the form mounts, not on submit: the notice is measured as the signer sees it, and the tick is recorded when it happens.
NDA with a typed name
const ceremony = await EsignComply.attach({ clientToken, apiUrl });
// 1. The pinned NDA, rendered inline from GET /v1/documents/{id}/versions/{version}/content.
await ceremony.presentDocument({ versionId, mode: "inline", container: document.querySelector("#nda") });
// 2. The review line shown before the final act.
await ceremony.reviewPresented({ container: document.querySelector("#review") });
// 3. Notice, empty name field and the signing button.
ceremony.observeAssent({
region: document.querySelector("#assent"),
typedName: document.querySelector("#full-name"),
submit: document.querySelector("#sign-nda"),
});
signForm.addEventListener("submit", async (event) => {
event.preventDefault();
const result = await ceremony.complete(); // the typed name leaves the page here, once
await confirmOnServer(result.recordId);
});
declineLink.addEventListener("click", () => ceremony.cancel());The notice for a signature reads, for example: "By typing your name and clicking Sign NDA, you agree to sign this agreement electronically and to be bound by it."
This is assurance level L1, the default: your app says who the signer is, and there is no code step.
Optional: signer verification (Unlimited and Enterprise)
Free and Starter record at L1: the signer's identity is what your app asserts. Unlimited and Enterprise add optional signer verification: a one-time code Esign Comply emails to the signer (L2), and passkeys (L3).
On a profile with assurance_level: "L2", run the code step before the signing act:
const sent = await ceremony.verify.start({ method: "email_otp" }); // sent.destination is the masked address
const check = await ceremony.verify.confirm({ code: codeField.value });
if (check.status === "failed") showError(`That code is not right. ${check.attemptsRemaining} tries left.`);On Free and Starter these calls reject with plan_feature_unavailable. See L2 verification.
Methods
| Method | What it does |
|---|---|
| EsignComply.attach({ clientToken, apiUrl? }) | Fetches the session and records client.attached. Resolves with the ceremony. |
| presentDocument({ versionId, mode, link \| container, downloadControl?, printControl? }) | Records document.presented. mode is "hyperlink", "inline" or "scrollbox". |
| presentDisclosure({ container }) | Records the electronic-records disclosure (consumer step S3). |
| accessSample() then demonstrateAccess({ code }) | Fetches the sample with the access code, and records that the signer could open it (S4). |
| giveEConsent({ checkbox }) | Watches the consent checkbox. Resolves when the tick is recorded (S5). |
| observeAssent({ region, checkbox?, typedName?, canvas?, submit, slots? }) | Records notice.captured now and intent.captured on the signer's action. |
| reviewPresented({ container, correctable? }) | Records the summary shown before the final act. |
| verify.start({ method }), verify.confirm({ code }), verify.passkey() | Optional email and passkey verification for L2 and L3 profiles, on Unlimited and Enterprise. |
| languageSelected(code), ageAttested({ checkbox }) | Optional events. |
| renewalTerms({ region, elements }), renewalConsent({ checkbox, region }) | Automatic-renewal terms and their own consent control. |
| electronicAgreement({ checkbox }), sensitiveCaptureConsent({ checkbox }), acknowledge({ checkbox }) | Separate consent controls some state packs require. |
| billingConfirm() | Call it immediately before your page submits a payment. |
| remainingSteps() | Steps still outstanding. Ready when only "signature.applied" is left. |
| requiredStrings() | Wording the session's jurisdiction packs ask the page to carry. |
| session | The last known session object. |
| complete({ typedName? }) | Sends the signing act. Resolves with { recordId, receipt, verifyUrl, status }. |
| cancel() | Cancels the session, for a decline control. |
| on(event, handler) | finding, stepRecorded, expired, error, change. Returns the unsubscribe function. |
| destroy() | Removes every listener and forgets the token. |
Methods that take a checkbox watch it. Call them when the control renders, not from its change handler. The SDK reads the state the control had at that moment and records the tick when the signer makes it. If the signer unticks the box, the step counts as outstanding again.
checkbox can be an <input type="checkbox"> or an element with role="checkbox" and aria-checked.
What counts as the signer's action
The SDK reports two facts about the assent control and leaves the judgement to the API (rule CR-01):
- How the page rendered it. A checkbox rendered ticked or a name field rendered filled is reported as
checkedorprefilled. The SDK never unticks or clears anything. - Whether it saw a trusted user event make the change. A tick made by a script, or made before the SDK was watching, is reported as not user-made. If the signer then unticks and ticks the box, that observed act is what gets reported.
So start watching before the signer can act: call observeAssent when the form renders. If your page starts the ceremony later, for example after an email address is entered, keep the checkbox and the button disabled until observeAssent has run. Add autocomplete="off" to the checkbox if you do not want the browser to restore an earlier tick on reload.
A test that drives your page has the same duty, and acts faster than a person. From 1.0.4, every control the SDK is watching carries a property that says so, with the steps it serves, for as long as it is watched. It is a property, not an attribute, so your markup is unchanged:
element[Symbol.for("esigncomply.watching")]; // ["intent.captured"], or undefined when not watched
// Playwright: wait for the SDK, not for a delay, before the first click.
await page.waitForFunction(() => document.querySelector("#agree")?.[Symbol.for("esigncomply.watching")]?.includes("intent.captured"));npx esigncomply check waits for it before it ticks the box.
The button text is read at the moment of the click, so a label your page swaps in while it submits ("Saving…") does not end up in the record.
The signing act
Call complete() from the handler of the signer's real click. It:
- waits for events already on their way and refuses in the browser, with
steps_incomplete, while steps remain; - sends the act with
Idempotency-Key: <session id>-complete; - on a network failure sends the same request again, up to two more times, then looks for the record on the session before it rejects.
A lost response therefore never asks the signer to act twice. If the record was found only on the session, status is "unknown" and receipt is null. Your server confirms the record in every case.
A rejected complete() means the agreement is not signed. Do not grant access.
Errors
Every method rejects with an EsignComplyError:
{
code: "steps_incomplete", // stable machine code
type: "ceremony_error",
message: "The ceremony is missing 1 required step: intent.captured.",
rule: "CR-01", // the rule to look up
missingSteps: ["intent.captured"],
fix: "Record the missing steps first: ceremony.observeAssent(...). Keep the action control disabled until ...",
status: 0, // HTTP status; 0 for a refusal made in the browser or a network failure
requestId: undefined,
docUrl: "https://esigncomply.com/docs/conformance#cr-01"
}Refusals made in the browser use the same shape as API errors: a missing submit element, an unknown version ID, complete() while steps remain. code is network_error when the API could not be reached.
Findings and test mode
The API checks each event against the conformance rules and answers with findings. Subscribe with ceremony.on("finding", handler). Each finding has rule, status (warn or block), message, fix and doc_url.
With a test-mode token the SDK also writes every event and every finding that did not pass to the console, with the rule ID, the fix and the documentation link:
[esigncomply] CR-01 block: The checkbox control was checked when the page loaded.
Fix: Render every checkbox unchecked and every typed-name field empty. Never prefill or pre-check an assent control.
https://esigncomply.com/docs/conformance#cr-01Test mode never blocks on a finding. Live mode can refuse the record. The SDK reports what the page did and never changes it: a pre-checked box is reported as pre-checked, and a tick made by a script is reported as not user-made.
Content Security Policy
The SDK works without unsafe-inline and without unsafe-eval. It needs one directive:
connect-src https://esigncomply.com https://api.eu.esigncomply.comAdd 'self' to connect-src if you want the SDK to read same-origin document pages and compare them with the registered version. If that read is blocked, the SDK skips it quietly.
What is captured
Only the elements you pass are read. Nothing outside them, and no screenshots.
| Captured | When |
|---|---|
| Page address without query string or fragment, viewport size, browser language, time zone | attach |
| Link text, address, visibility, underline, colour contrast against the surrounding text, font size, whether the signer opened it; hash of the linked page's document text | presentDocument, hyperlink |
| Hash of the document text on the page; whether a scroll box was scrolled to the end | presentDocument, inline and scroll box |
| Notice text, markup of the assent region (at most 100 KB), font size, contrast, position relative to the button, number of primary buttons, initial state of the checkbox or name field | observeAssent |
| Control type, label text, button text, initial state, whether a trusted user event made the change | The signer's action |
| The typed name | Once, with complete() |
| Drawn strokes as vector points, without timing or pressure | Only if you pass canvas |
| Hash and headings of a disclosure and how long it was on screen; text and prominence of renewal terms | presentDisclosure, renewalTerms |
Not captured: keystrokes, the content of other form fields, values of inputs inside the assent region, passwords, cookies, mouse movement, anything outside the elements you passed. Scripts, inline event handlers and input values are removed from captured markup.
Minimal capture
When the session has minimal_capture: true (EU, UK and Swiss packs, or a profile set to eu_minimal), the SDK takes no measurements. It sends no markup, styles, layout, link style, viewport, device fields or strokes, does not hash page text, does not track link opening, and takes no notice snapshot unless the session requires one. The ceremony still completes with the control type, the label and button text, and the initial state of the control.
Requirements
Current versions of Chrome, Edge, Firefox and Safari, and mobile web views. Hashing uses Web Crypto, which needs HTTPS or localhost.
Development
node packages/browser/build.mjs # dist/index.js, dist/index.d.ts, public/sdk/v1/esigncomply.js
npx vitest run packages/browser # unit tests
node packages/browser/test/e2e/run.mjs # real browser against a local API