# Add e-signatures and clickwrap with Ruby

> Build a signup clickwrap in plain Ruby with Net::HTTP, a cookie signed with OpenSSL and one Rack app on Puma, calling the Esign Comply REST API. No API gem.

Source: https://esigncomply.com/docs/quickstart/ruby

Last updated November 26, 2026

To add e-signatures and clickwrap with Ruby, call the REST API with `Net::HTTP` and the secret key: there is no gem. One Rack app with no framework creates the session, keeps the pinned versions in a cookie signed with OpenSSL, and confirms the record. The browser SDK attaches to your checkbox. Esign Comply seals each acceptance as an independent record.

Follow the steps and each signature your app records is a valid electronic signature under the ESIGN Act, state UETA laws and New York's ESRA, and your clickwrap is built the way courts require: clear notice of the terms, an unmistakable act of assent, and a sealed record of both.

This page is plain Ruby with no framework. With a framework, use the [Sinatra quickstart](https://esigncomply.com/docs/quickstart/sinatra.md) or the [Rails quickstart](https://esigncomply.com/docs/quickstart/rails.md).

Paste this prompt into Cursor, Claude Code or another AI coding tool to have it build the same integration:

```text copy="Copy prompt" open="cursor"
Add Esign Comply clickwrap to my Ruby app: a signup form where the user accepts the Terms of Service and the Privacy Notice with a checkbox and a button.

Read these first and follow them exactly. If something conflicts with existing code, or you are unsure how to implement a step, stop and ask. Do not invent API methods, packages or legal wording.
- https://esigncomply.com/docs/quickstart/ruby.md (the steps and the tested code for Ruby)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Ruby facts
- There is no Esign Comply gem. Do not install or invent one. The server calls the REST API at https://esigncomply.com/v1 with Net::HTTP, Authorization: Bearer and the secret key.
- The browser SDK is a script tag: https://esigncomply.com/sdk/v1/esigncomply.js. It defines the global EsignComply.
- The secret key is in the environment variable ESIGNCOMPLY_API_KEY. Ruby does not read .env files on its own. Never print the key.
- Ruby has shipped no web server since 3.0. Use the server the project already has. The quickstart is one object that answers call(env), run by Puma from config.ru, with no framework and no rack gem.
- Net::HTTP: pass use_ssl for an https address (it turns certificate verification on, never set VERIFY_NONE), set open_timeout and read_timeout (each is 60 seconds otherwise), and set max_retries to 0 (otherwise it sends a GET a second time after a timeout). It does not raise on 4xx and 5xx: read the status and the error envelope.
- JSON.parse returns string keys: record["status"], never record[:status].
- Keep the signer ID and the pinned version IDs in a cookie signed with OpenSSL::HMAC, and compare the signature with OpenSSL.secure_compare. The visitor can read a signed cookie: put nothing secret in it. Do not require "base64" unless the Gemfile lists it: pack("m0") does the same.
- String interpolation escapes nothing. Print the document HTML as it is, and escape everything else you print with ERB::Util.html_escape.
- The page is on screen before the script has a session: render the checkbox disabled and enable it when observeAssent has resolved.

Build
1. Verify the key: GET /v1/usage with ESIGNCOMPLY_API_KEY. Stop if it fails.
2. Register the Terms of Service and the Privacy Notice as documents and publish one version of each from the documents in this project. If the project has none, register short sample documents and say so in your report. Never write or change the wording of the real documents. Create a profile: jurisdictions ["US-FED"], method "checkbox", assurance_level "L1".
3. Server: POST /api/ceremony calls POST /v1/sessions with an Idempotency-Key, saves the signer ID and the pinned version IDs in the signed cookie, and returns only clientToken, apiUrl and documents.
4. Server: GET /legal/terms and /legal/privacy render the html from GET /v1/documents/{id}/versions/{version_id}/content inside <article data-esc-document>, unmodified.
5. Browser: EsignComply.attach({ clientToken, apiUrl }), presentDocument for each link, observeAssent({ region, checkbox, submit }), then complete() from the user's real click.
6. Server: POST /api/signup/confirm calls GET /v1/records/{id} and requires: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in the signed cookie. Only then create the account.

Never
- Never pre-check the box, auto-submit, or call .click() on the user's behalf.
- Never use "By continuing" or "By clicking below" wording. The notice names the button by its label and each document by its registered name.
- Never put the secret key, or any call that uses it, in code that reaches the browser.
- Never show "signed" or "accepted" before the server has confirmed the record.
- Never fall back to an acceptance with no record when a session is refused.

Check before you report success
- Run: npx esigncomply check --url http://localhost:9292/signup --callback http://localhost:9292/api/signup/confirm
  Fix every finding marked "block". List every finding marked "warn".
- Report the files you created or changed, anything you did not implement and why, and the conformance summary.

Then add the rules block to this project's instruction file: https://esigncomply.com/rules.md
```

The rest of this page is the same integration by hand, in eight steps.

## Before you start

- A test API key. [Create an account](https://esigncomply.com/signup) with your email, no card, then choose **Create test key** in the dashboard. The key is shown once and starts with `esc_test_`. An AI agent with an agent token creates it with `POST /v1/agent/api-keys`: see the [agent account API](https://esigncomply.com/docs/api/agent.md).
- Nothing else from Esign Comply. Test mode works on `localhost` with no card and no domain, and the Free plan includes it in full.
- Ruby with Bundler. This page was run on Ruby 3.4.13 with Puma 8.1.3 as the only gem in the Gemfile.
- `curl` and `jq` for steps 2 and 3, and Node.js 20.19 or later for the conformance check in step 7.

## Step 1. Install

There is no gem for the API. The server SDK exists for Node.js only, so a Ruby server calls the REST API directly with `Net::HTTP`. JSON and OpenSSL come with Ruby too. The one thing Ruby does not bring is a web server.

```bash
mkdir esigncomply-quickstart && cd esigncomply-quickstart
mkdir public
```

```ruby file="Gemfile"
# Gemfile
source "https://rubygems.org"

gem "puma" # the web server. Nothing for the API: Net::HTTP, JSON and OpenSSL come with Ruby.
```

```bash
bundle install
```

Bundler installed two gems: Puma 8.1.3 and nio4r 2.7.5, which Puma depends on.

Why Puma and not WEBrick. Ruby has shipped no web server since 3.0: its release notes list `webrick` among the libraries that are no longer bundled gems or standard libraries. WEBrick's own README says it is intended for testing and local development, not for production use, and not to receive traffic from untrusted sources. A signup page takes exactly that traffic. Puma runs any object that answers `call(env)`, so the app on this page needs no framework and no `rack` gem: in the test Puma read `config.ru` with nothing else installed.

## Step 2. Set the key

Put the key in `.env` in the project folder. Ruby does not read this file: you load it into the shell that starts the app, and the app reads the variables from `ENV`.

```bash
# .env (never commit this file)
ESIGNCOMPLY_API_KEY=esc_test_us_...
```

Step 4 keeps the pinned versions in a cookie that the app signs. Add the secret it signs with to the same file:

```bash
printf 'COOKIE_SECRET=%s\n' "$(ruby -rsecurerandom -e 'puts SecureRandom.hex(32)')" >> .env
```

Load the file into your shell for the commands in steps 2, 3 and 7, then check that the key works:

```bash
set -a; . ./.env; set +a
curl -s ${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}/usage \
  -H "Authorization: Bearer $ESIGNCOMPLY_API_KEY" | jq '{plan_name, test_events}'
```

```json
{
  "plan_name": "Free",
  "test_events": {
    "used_this_month": 0,
    "quota_per_month": 500
  }
}
```

A `401` means the key is wrong or revoked: see [`invalid_api_key`](https://esigncomply.com/docs/api/errors.md#invalid_api_key). The rules for handling keys are in [/auth.md](https://esigncomply.com/auth.md).

## Step 3. Register a document version

Every record pins the exact version of each document by hash, so the documents are registered first. This block registers a Terms of Service and a Privacy Notice with one version each, and creates a profile: the Federal pack, a checkbox with a button, level L1. It is the same for every stack and needs `curl` and `jq`.

```bash
ESC=${ESIGNCOMPLY_API_URL:-https://esigncomply.com/v1}
KEY="Authorization: Bearer $ESIGNCOMPLY_API_KEY"
JSON="Content-Type: application/json"

# Two sample documents, one version each.
TERMS=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Terms of Service","type":"terms"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$TERMS/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Terms of Service\n\nThese are sample terms for a test."},"material_change":true}' \
  | jq -r .id; sleep 1
PRIVACY=$(curl -s $ESC/documents -H "$KEY" -H "$JSON" \
  -d '{"name":"Privacy Notice","type":"privacy_notice"}' | jq -r .id); sleep 1
curl -s $ESC/documents/$PRIVACY/versions -H "$KEY" -H "$JSON" \
  -d '{"version_label":"1","language":"en","content":{"format":"markdown","text":"# Privacy Notice\n\nThis is a sample privacy notice for a test."}}' \
  | jq -r .id; sleep 1

# A profile: Federal pack, checkbox plus button, L1.
PROFILE=$(curl -s $ESC/profiles -H "$KEY" -H "$JSON" \
  -d '{"name":"Signup","jurisdictions":["US-FED"],"method":"checkbox","assurance_level":"L1"}' | jq -r .id)

printf 'ESIGNCOMPLY_PROFILE_ID=%s\nESIGNCOMPLY_TERMS_ID=%s\nESIGNCOMPLY_PRIVACY_ID=%s\n' "$PROFILE" "$TERMS" "$PRIVACY"
```

It prints the two version IDs, then three lines with your own IDs:

```text
dv_YiWs9cmWoVSGp7ALPeZS
dv_bAYeA7QigKUH0iLhPpV7
ESIGNCOMPLY_PROFILE_ID=prof_SPVEgBT8a8Ror3mJ8M99
ESIGNCOMPLY_TERMS_ID=doc_bDgYFndAoC8tkeYibAVy
ESIGNCOMPLY_PRIVACY_ID=doc_mb2hnWKS0Qa7SKtucDW9
```

Add the three lines to `.env`, then load the file into your shell again. The pauses keep the script under the Free plan's 2 requests per second. Keep the names `Terms of Service` and `Privacy Notice`: the notice on your page names each document by its registered name, and rule [CR-02](https://esigncomply.com/docs/conformance.md#cr-02) checks that it does. With your own documents, publish the text you already have and change the notice to match. See [Documents](https://esigncomply.com/docs/api/documents.md) and [Profiles](https://esigncomply.com/docs/api/profiles.md).

## Step 4. Create a session on the server

`app.rb` is the whole server: the signup page, the two document pages, the route that creates the session, and the route that confirms the record. The `esc` method is the entire client: one HTTPS call with the secret key that returns the status and the parsed JSON, sent again only when the API answers `429`.

```ruby file="app.rb"
# app.rb
require "json"
require "net/http"
require "openssl"
require "securerandom"
require "erb"

# There is no gem for the API: these are plain HTTPS calls with the secret key, made with Net::HTTP.
API = ENV.fetch("ESIGNCOMPLY_API_URL", "https://esigncomply.com/v1")
API_KEY = ENV.fetch("ESIGNCOMPLY_API_KEY")
PROFILE = ENV.fetch("ESIGNCOMPLY_PROFILE_ID")
DOCUMENTS = { "terms" => ENV.fetch("ESIGNCOMPLY_TERMS_ID"), "privacy" => ENV.fetch("ESIGNCOMPLY_PRIVACY_ID") }.freeze
COOKIE_SECRET = ENV.fetch("COOKIE_SECRET")
LIVE = ENV["ESIGNCOMPLY_LIVE"] == "true" # set it in production only
SEALED = %w[recorded timestamped anchored].freeze
SIGNUP_PAGE = File.read(File.join(__dir__, "public", "signup.html")).freeze

# The signer. In your app this is the signed-in user, or the account you are about to create.
SIGNER = {
  external_id: "user_7c1d",
  email: "dana@example.org",
  name: "Dana Whitfield",
  class: "consumer",
  country: "US",
  region: "US-CA"
}.freeze

# One call to the Esign Comply API. Returns [status, parsed JSON]. JSON.parse gives string keys: record["status"].
def esc(method, path, body: nil, idempotency_key: nil)
  uri = URI("#{API}#{path}")
  request = (method == :post ? Net::HTTP::Post : Net::HTTP::Get).new(uri)
  request["Authorization"] = "Bearer #{API_KEY}"
  request["Idempotency-Key"] = idempotency_key if idempotency_key
  if body
    request["Content-Type"] = "application/json"
    request.body = JSON.generate(body)
  end
  # use_ssl turns certificate verification on. The timeouts are 60 seconds each unless set, and max_retries is 1:
  # Net::HTTP would send a GET a second time by itself after a timeout.
  options = { use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10, max_retries: 0 }
  response = nil
  3.times do |attempt|
    # Net::HTTP does not raise on 4xx and 5xx: the status is here, and the error envelope is the body.
    response = Net::HTTP.start(uri.host, uri.port, **options) { |http| http.request(request) }
    # Over the rate limit: wait for Retry-After (1 to 5 seconds) and try again, twice at most. Nothing else is retried.
    break unless response.code == "429" && attempt < 2
    sleep response["Retry-After"].to_f.clamp(1, 5)
  end
  [response.code.to_i, JSON.parse(response.body)]
end

# Server-owned state: a cookie this file signs with HMAC-SHA256. The visitor can read it and cannot change it.
def sign(payload)
  OpenSSL::HMAC.hexdigest("SHA256", COOKIE_SECRET, payload)
end

def pinned_cookie(pinned)
  payload = [JSON.generate(pinned)].pack("m0") # Base64 without the base64 gem
  "esc_signup=#{payload}.#{sign(payload)}; Path=/; HttpOnly; SameSite=Lax#{'; Secure' if LIVE}"
end

def pinned(env)
  cookie = env["HTTP_COOKIE"].to_s[/(?:\A|;\s*)esc_signup=([^;]*)/, 1].to_s
  payload, _, signature = cookie.rpartition(".")
  # Compared in constant time. A cookie that fails is the same as no cookie.
  return {} unless OpenSSL.secure_compare(sign(payload), signature)
  JSON.parse(payload.unpack1("m0"))
end

def reply(status, body, headers = {})
  [status, { "content-type" => "application/json" }.merge(headers), [JSON.generate(body)]]
end

# The document pages: each one renders a registered version, unmodified.
def legal(env)
  document = DOCUMENTS.fetch(env["PATH_INFO"].delete_prefix("/legal/"))
  version = env["QUERY_STRING"].to_s[/(?:\A|&)v=(\w+)/, 1] || "current"
  status, content = esc(:get, "/documents/#{document}/versions/#{version}/content")
  return reply(404, error: "not_found") unless status == 200
  # Interpolation escapes nothing. The version ID goes into an attribute, so it is escaped. The document HTML is printed as it is.
  page = %(<!doctype html><meta charset="utf-8"><article data-esc-document="#{ERB::Util.html_escape(content['version_id'])}">#{content['html']}</article>)
  [200, { "content-type" => "text/html; charset=utf-8" }, [page]]
end

# Step 4: create the session with the secret key. The browser gets the client token only.
def ceremony(env)
  # The page that runs the ceremony: the origin the browser reports, or the scheme and host of the request.
  origin = env["HTTP_ORIGIN"] || "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}"
  status, created = esc(:post, "/sessions",
    idempotency_key: "signup-#{SIGNER[:external_id]}-#{SecureRandom.uuid}",
    body: {
      profile: PROFILE,
      signer: SIGNER,
      documents: [
        { document: DOCUMENTS["terms"], version: "current" },
        { document: DOCUMENTS["privacy"], version: "current" }
      ],
      context: { url: "#{origin}/signup", locale: "en-US", purpose: "account_signup" }
    })
  return reply(502, error: created.dig("error", "code") || "unknown") unless status == 201

  pinned = { signer_id: SIGNER[:external_id], version_ids: created["documents"].map { |d| d["version_id"] }.sort }
  reply(200, { clientToken: created["client_token"], apiUrl: created["api_url"], documents: created["documents"] },
    "set-cookie" => pinned_cookie(pinned))
end

# Step 6: confirm the record with the secret key before the account exists.
def confirm(env)
  body = JSON.parse(env["rack.input"].read) rescue nil # an empty or malformed body is refused below
  record_id = body.is_a?(Hash) && body["recordId"].is_a?(String) ? body["recordId"] : "missing"
  expected = pinned(env)
  status, record = esc(:get, "/records/#{ERB::Util.url_encode(record_id)}")

  confirmed = status == 200 &&
              SEALED.include?(record["status"]) &&
              record["livemode"] == LIVE &&
              !expected["signer_id"].nil? && record.dig("signer", "external_id") == expected["signer_id"] &&
              record["documents"].map { |d| d["version_id"] }.sort == expected["version_ids"]

  warn(confirmed ? "confirmed #{record['id']} (#{record['status']})" : "refused")
  return reply(409, confirmed: false) unless confirmed

  # Only now create the account, and store record["id"] and record["receipt"] with it.
  reply(200, confirmed: true, recordId: record["id"])
end

# The app: an object that answers call(env) with a status, headers and a body. Puma runs it from config.ru.
APP = lambda do |env|
  case [env["REQUEST_METHOD"], env["PATH_INFO"]]
  in ["GET", "/signup"] then [200, { "content-type" => "text/html; charset=utf-8" }, [SIGNUP_PAGE]]
  in ["GET", "/legal/terms" | "/legal/privacy"] then legal(env)
  in ["POST", "/api/ceremony"] then ceremony(env)
  in ["POST", "/api/signup/confirm"] then confirm(env)
  else reply(404, error: "not_found")
  end
rescue StandardError => error
  # Without this, Puma answers for you, and in development it prints the backtrace into the response.
  warn "#{error.class}: #{error.message}"
  reply(500, error: "internal_error")
end
```

The signer is a fixed test person here. In your app it is the signed-in user or the account you are about to create.

`config.ru` hands the app to the server:

```ruby file="config.ru"
# config.ru
require_relative "app"

run APP
```

Seven things here are specific to plain Ruby, and each one was seen in the test run.

`Net::HTTP` waits 60 seconds to connect and 60 seconds to read unless you set the timeouts, and its `max_retries` is 1. In a test against a server that accepts a request and never answers, with `read_timeout` at 2 seconds, a `GET` failed after 4.01 seconds and the server had received it twice. With `max_retries: 0` it failed after 2.0 seconds and the server had received it once. A `POST` was sent once either way. `esc` sets `open_timeout`, `read_timeout` and `max_retries`, so the only request sent twice is the one the API answered with `429`.

`use_ssl` is what turns certificate verification on. Against a test server with a self-signed certificate, `Net::HTTP.start` with `use_ssl: true` ended with `certificate verify failed (self-signed certificate)`. And `Net::HTTP` does not raise on a refusal: a made-up record ID came back as status `404` with the error envelope in the body.

`JSON.parse` returns string keys. For a record whose `record["status"]` was `"recorded"`, `record[:status]` was `nil`. A confirm route written with symbols raises nothing: it refuses every record with `409`.

The state is a cookie the app signs. The browser got a cookie named `esc_signup`, 189 characters long, `HttpOnly` and `SameSite=Lax`. It is signed, not encrypted: decoded from Base64, the part before the dot showed the signer ID and the two version IDs. The visitor can read them and cannot change them. With one character of the signature changed, with the signature cut to 10 characters, and with another signer ID in the payload, the confirm route answered `409`. With `COOKIE_SECRET` fixed, the same cookie confirmed a real record after a restart. The signature is compared with `OpenSSL.secure_compare`, in constant time. `OpenSSL.fixed_length_secure_compare` raised `ArgumentError: inputs must be of equal length` for the cut signature.

The cookie is encoded with `pack("m0")`, which is Base64 from Ruby's core. With this Gemfile, `require "base64"` under `bundle exec` ended with `LoadError: cannot load such file -- base64`, after a warning that base64 is not part of the default gems starting from Ruby 3.4.0.

Nothing stands between an exception and the server, so `APP` ends with a `rescue`. In a test with an app that raised, Puma in development answered `500` with `Puma caught this error: boom in the app (RuntimeError)` and the backtrace in the body. With `RACK_ENV=production` the body was empty. With the `rescue`, and the API address on a closed port, the session route answered `500` with `{"error":"internal_error"}`, the log showed `Errno::ECONNREFUSED`, and the next request was answered `200`.

When the API answers `429`, `esc` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and sends the request again, up to twice. `sleep` holds one of Puma's threads for that time. Puma started with at most five threads here: in the test, page requests sent while four confirmations were in flight were answered in under 0.001 seconds.

`context.url` is built from the `Origin` header the browser sends with the `POST`. A request without one falls back to the scheme and the `Host` header of the request, and all of it comes from the client. A request with `Origin: https://evil.example` was refused by the API with `domain_mismatch`, and the route answered `502`. So was a request with `Host: evil.example` and no `Origin`: nothing in front of a plain Rack app checks the host. Puma set `rack.url_scheme` to `https` for a request that carried `X-Forwarded-Proto: https`, whoever sent it.

Start the app from the shell that loaded `.env`:

```bash
bundle exec puma
```

```text
Puma starting in single mode...
* Puma version: 8.1.3 ("Puma Psychosis")
* Ruby version: ruby 3.4.13 (2026-11-19 revision 48857d6f2e) +PRISM [x86_64-linux]
*  Min threads: 0
*  Max threads: 5
*  Environment: development
* Listening on http://[::]:9292
```

That is every interface of the machine. `bundle exec puma -b tcp://127.0.0.1:9292` listened on `127.0.0.1` only.

## Step 5. Attach the ceremony in the browser

The browser SDK renders nothing. It observes the checkbox, the notice, the links and the button you built, and reports each step from the signer's browser straight to Esign Comply. Save the page as `public/signup.html`. The app reads the file once, when it starts:

```html file="public/signup.html"
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Create account</title>
    <style>
      body { font: 16px/1.5 system-ui, sans-serif; max-width: 480px; margin: 48px auto; padding: 0 20px; }
      a { color: #0b57d0; text-decoration: underline; }
      button { font: inherit; padding: 10px 16px; }
    </style>
  </head>
  <body>
    <h1>Create account</h1>
    <form id="signup">
      <div id="assent">
        <!-- The page is on screen before the script has a session, so the box stays disabled until the SDK watches it. -->
        <label><input id="agree" type="checkbox" disabled /> I agree to the Terms of Service and Privacy Notice</label>
        <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>
        <button id="create-account" type="submit" disabled>Create account</button>
      </div>
      <p id="message" role="alert"></p>
    </form>

    <script src="https://esigncomply.com/sdk/v1/esigncomply.js"></script>
    <script type="module">
      const agree = document.querySelector("#agree");
      const submit = document.querySelector("#create-account");
      const message = document.querySelector("#message");

      // Your server creates the session and returns only the client token and the pinned documents.
      const response = await fetch("/api/ceremony", { method: "POST" });
      const { clientToken, apiUrl, documents } = await response.json();

      const ceremony = await EsignComply.attach({ clientToken, apiUrl });
      ceremony.on("change", ({ remainingSteps }) => {
        submit.disabled = remainingSteps.some((step) => step !== "signature.applied");
      });

      // Point each link at the exact version this session pinned, then report it.
      const links = [document.querySelector("#tos-link"), document.querySelector("#privacy-link")];
      for (const [i, link] of links.entries()) {
        link.search = "?v=" + documents[i].version_id;
        await ceremony.presentDocument({ versionId: documents[i].version_id, mode: "hyperlink", link });
      }
      await ceremony.observeAssent({
        region: document.querySelector("#assent"), // notice, links, checkbox, button
        checkbox: agree,
        submit,
      });
      agree.disabled = false; // the SDK watches the box from here on. Only the user ticks it.

      document.querySelector("#signup").addEventListener("submit", async (event) => {
        event.preventDefault();
        try {
          const result = await ceremony.complete(); // the signing act, from the signer's own click
          // The result came to the browser. Your server confirms the record before anything is granted.
          const confirmed = await fetch("/api/signup/confirm", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ recordId: result.recordId }),
          });
          message.textContent = confirmed.ok
            ? `Account created. Record ${result.recordId}`
            : "We could not confirm whether your acceptance was recorded. Please wait while we check.";
        } catch (error) {
          message.textContent = error.message;
        }
      });
    </script>
  </body>
</html>
```

Open [http://localhost:9292/signup](http://localhost:9292/signup). The button stays disabled until the box is ticked. Tick it, click **Create account**, and the page shows:

```text
Account created. Record rec_F234hHS4TVJWC7M88h54
```

The checkbox starts unchecked and disabled. The page is on screen before the script has a session, and the script enables the box once the SDK observes it: a box ticked before that fails [CR-01](https://esigncomply.com/docs/conformance.md#cr-01). In a test with the session request held back, a click on the box did nothing. One page load sent one `POST /api/ceremony`.

Each link opens a document page on your own server that renders the registered version. `legal` builds that page with string interpolation, which escapes nothing. The document arrives as it is, which is what this page needs, and the version ID is escaped by hand because it goes into an attribute. In a test with `ERB::Util.html_escape` around the document, the page showed the tags as text and the SDK reported a finding for [CR-08](https://esigncomply.com/docs/conformance.md#cr-08) at Block level: the page behind the link did not match the registered version.

## Step 6. Confirm the record on the server

The result of `complete()` was delivered to the browser, so your server does not trust it. `confirm` in `app.rb` reads the record with the secret key and grants access only when four things hold: the status is `recorded`, `timestamped` or `anchored`; `livemode` is what this deployment expects; the signer is the one in the signed cookie; and the document versions are exactly the ones this server pinned there. This step is never optional.

The app writes one line for each confirmation to standard error:

```text
confirmed rec_F234hHS4TVJWC7M88h54 (recorded)
```

A record ID that was made up is refused with status `409`. So is a real record ID sent without the cookie, a body that is not JSON, and an empty body:

```bash
curl -s -X POST http://localhost:9292/api/signup/confirm \
  -H "Content-Type: application/json" -d '{"recordId":"rec_made_up"}'
```

```json
{"confirmed":false}
```

See [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md) for the webhook that backs this route up when the browser closes early.

## Step 7. Check the result

Open the dashboard and choose **Records**. The test record is there with what was observed, what was asserted, and its evidence report, watermarked TEST.

Then run the conformance check against the page. It opens the page in headless Chromium at three window sizes, signs as a visitor would, and tries four things that must be refused. One of them posts a made-up record ID to your confirm route. The checker is a Node.js command line tool, so it needs Node.js 20.19 or later, in a folder of its own:

```bash
mkdir -p esc-check && cd esc-check
npm init -y && npm install esigncomply playwright
npx playwright install chromium
npx esigncomply check --url http://localhost:9292/signup --callback http://localhost:9292/api/signup/confirm
```

The report for this page's code, shortened:

```text
Violations that must be refused
  REFUSED   Submit with the checkbox untouched      No record was made.
  REFUSED   Completion from another origin          The API answered 403 domain_mismatch.
  REFUSED   Programmatic click                      No record was made.
  REFUSED   Forged success posted to your callback  http://localhost:9292/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_sf46uw5UiYuuUUiCZMBk  session ses_TcNAXBFq7agiYyNLYmFh, 5 events
  768x1024   record rec_1asLJnuk3VdPQkDqHkMo  session ses_JN7a6YZucktEo0AEYKfv, 5 events
  1440x900   record rec_rMjmDx46ePprCFLVovvZ  session ses_h8eX0K06RHsMTYsE1vKH, 5 events

Summary: 0 block, 0 warn, 27 pass.
```

The app logged a `confirmed` line for each of the three records.

Fix every finding marked `block` and read every finding marked `warn`. Each one names the rule the screen missed, the measurement and the fix. In test mode a finding never stops a record from being sealed, so read the report. The rules are on [Conformance rules](https://esigncomply.com/docs/conformance.md), and every flag of the command is on the [CLI page](https://esigncomply.com/docs/sdk/cli.md).

## Step 8. Go live

Going live takes three steps on the Esign Comply side. There is no plan to choose and no checkout: the Free plan records 10 live signatures a month.

1. Register your production domain and verify it. See [Register a domain](https://esigncomply.com/docs/guides/domains.md).
2. Add your organization's legal name, country and address under **Go live** in the dashboard.
3. Create a live key. It is shown once and starts with `esc_live_`.

Test and live share nothing, so create the documents and the profile again with the live key, or copy them to live from the dashboard, and use the live IDs in production.

Then switch the server over:

- Start it with `RACK_ENV=production bundle exec puma`. In the test this ran the app in the production environment, and it recorded the signature shown in step 5.
- Set the live key as `ESIGNCOMPLY_API_KEY` and set `ESIGNCOMPLY_LIVE=true` in production only. In the test with that variable set, the confirm route refused a test record with `409`, and the cookie was marked `Secure`.
- The app adds `Secure` itself and does not look at the request: in the test the header carried it over plain HTTP too. Serve the site over HTTPS.
- Keep one `COOKIE_SECRET` for every instance and every restart, and store the record ID and the receipt beside the user.

In live mode `context.url` must be inside your registered domain, and browser calls are accepted only from it. By default a live signature with a finding at Block level is recorded and you are told at once which rule failed. Turn on blocking, on the dashboard's Conformance page, and it is refused before it is sealed. Run the check from step 7 until no finding is at Block level before you switch keys.

## Troubleshooting

- **`Unable to load application: KeyError: key not found: "ESIGNCOMPLY_API_KEY"` when Puma starts.** The variables are not in the environment of the shell that starts Puma. Run `set -a; . ./.env; set +a` in that shell first. With the variable set and empty, the app started and the session route answered `502` with [`missing_api_key`](https://esigncomply.com/docs/api/errors.md#missing_api_key).
- **`domain_mismatch` from `/api/ceremony`.** `context.url` is built from the `Origin` or `Host` header, and that host is not on the test allowlist. Test keys work on `localhost` and `127.0.0.1` at any port. Add other hosts under Domains in the dashboard. See [`domain_mismatch`](https://esigncomply.com/docs/api/errors.md#domain_mismatch).
- **`429` when the confirm route reads the record.** `esc` waits for the seconds in `Retry-After`, 1 at least and 5 at most, and sends the request again, up to twice. Nothing else is retried. In the test, four confirmations sent at once from the session that signed all answered `200`, two of them a second later than the others. The API's log showed why: two reads got `429` and passed on the next attempt. See [`rate_limit_exceeded`](https://esigncomply.com/docs/api/errors.md#rate_limit_exceeded). When the route answers `409` for a real record, the cause is a `COOKIE_SECRET` that changed.

## Questions about the Ruby quickstart

### Is there an Esign Comply gem for Ruby?

No. The server SDK exists for Node.js only. A Ruby server calls the REST API directly, and this quickstart does it with `Net::HTTP` in one method. The Gemfile lists Puma, the web server, and nothing for the API.

### Why Puma and not WEBrick?

Because WEBrick is for development only. Ruby stopped shipping it with version 3.0, and its README says it is not intended for production use or for traffic from untrusted sources. Puma runs the same `config.ru` in development and in production, and in the test it needed no framework and no `rack` gem.

### Can the visitor read the cookie?

Yes, and that is safe. The cookie is signed, not encrypted: decoded from Base64 it showed the signer ID and the two version IDs, and nothing else is in it. The visitor cannot change it. In the test a cookie with a changed signature or a changed payload was refused with status 409.

### Why does the code not require base64?

Because base64 is no longer a default gem. In the test on Ruby 3.4.13, requiring it under Bundler with a Gemfile that does not list it ended with a LoadError. The cookie is encoded with `pack("m0")` and decoded with `unpack1("m0")`, which are part of Ruby's core.

### When is the Sinatra or the Rails quickstart the better start?

When your app already runs on one of them. Sinatra and Rails bring a session, routing and templates, and their quickstarts use them. This page is for a Rack app with no framework, a script, or a service where four routes do not justify one.

### Does the Ruby quickstart need a domain or a card?

No. Test mode works on `localhost` with a test key, no card and no domain. You register and verify a domain only when you go live, and the Free plan then records 10 live signatures a month.

## Next steps

- [E-signatures and clickwrap for Ruby](https://esigncomply.com/ruby): what the integration gives you on this stack, with the things to watch for.
- [Add e-signatures and clickwrap with Sinatra](https://esigncomply.com/docs/quickstart/sinatra.md): the same calls with routes, ERB and the encrypted cookie session.
- [Add e-signatures and clickwrap with Rails](https://esigncomply.com/docs/quickstart/rails.md): the same calls in a Rails controller, with the CSRF token.
- [Server confirmation](https://esigncomply.com/docs/guides/server-confirmation.md): the checks in step 6 and the `record.completed` webhook.
- [Sessions API](https://esigncomply.com/docs/api/sessions.md) and [Records API](https://esigncomply.com/docs/api/records.md): every field of the two calls this app makes.
- [All quickstarts](https://esigncomply.com/docs/quickstart.md#quickstarts-by-stack-and-platform).
