Skip to content
DocsMenu

Add e-signatures and clickwrap with Sinatra

View as Markdown

Open this page inChatGPTClaudeCursor

To add e-signatures and clickwrap with Sinatra, call the REST API from your routes with Net::HTTP and the secret key: there is no gem. One route creates the session and keeps the pinned versions in Sinatra's encrypted cookie session, another confirms the record, and 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 Sinatra. For Rails, use the Rails quickstart.

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

Add Esign Comply clickwrap to my Sinatra 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/sinatra.md (the steps and the tested code for Sinatra)
- https://esigncomply.com/setup.md (the order of API calls)
- https://esigncomply.com/auth.md (how to handle the keys)

Sinatra facts
- There is no Esign Comply gem. Do not install or invent one. The routes call 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.
- Sinatra 4 needs the rackup gem and a web server gem such as puma to start.
- Keep the signer ID and the pinned version IDs in session. Set session_secret from the environment, 64 bytes or more: without it Sinatra makes a new secret at every start and every session is lost.
- Rack::Protection does not refuse a POST with the Origin of another site: under Sinatra it empties the session and lets the request through. Never treat reaching a route as proof of where the request came from.
- In the development environment Sinatra answers 403 to a Host it does not know. In production any host is permitted unless host_authorization is set.
- ERB in Sinatra does not escape. Print the document HTML as it is, and escape everything else you print with Rack::Utils.escape_html.
- 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. Route for POST /api/ceremony: call POST /v1/sessions with an Idempotency-Key, save the signer ID and the pinned version IDs in session, and return only clientToken, apiUrl and documents.
4. Route for GET /legal/:slug: 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. Route for POST /api/signup/confirm: call GET /v1/records/{id} and require: status is "recorded", "timestamped" or "anchored"; livemode is as expected; the signer ID and version IDs equal the ones in session. 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:4567/signup --callback http://localhost:4567/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 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.
  • 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 Sinatra 4.2.2.
  • 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 Sinatra app calls the REST API directly with Net::HTTP from Ruby's standard library. Sinatra itself needs two more gems before it starts: rackup, and a web server, here Puma.

mkdir esigncomply-quickstart && cd esigncomply-quickstart
mkdir views
# Gemfile
source "https://rubygems.org"

gem "sinatra"
gem "rackup" # Sinatra 4 starts its server through rackup
gem "puma"   # the web server
bundle install

With only sinatra in the Gemfile, ruby app.rb printed Sinatra could not start, the required gems weren't found! and the command that adds them. With rackup and no web server it stopped with Couldn't find handler for: puma, falcon, thin, webrick.

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.

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

Sinatra encrypts its session cookie with a secret of its own, and step 4 keeps the pinned versions in that cookie. Add one to the same file:

printf 'SESSION_SECRET=%s\n' "$(ruby -rsecurerandom -e 'puts SecureRandom.hex(64)')" >> .env

That is 128 characters. A short secret stops the app: with 32 characters it ended at start with invalid secret: 32, must be >=64 (ArgumentError).

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

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}'
{
  "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. The rules for handling keys are in /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.

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:

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 checks that it does. With your own documents, publish the text you already have and change the notice to match. See Documents and Profiles.

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.

# app.rb
require "sinatra"
require "json"
require "net/http"
require "securerandom"

# 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")
LIVE = ENV["ESIGNCOMPLY_LIVE"] == "true" # set it in production only
SEALED = %w[recorded timestamped anchored].freeze
DOCUMENTS = { "terms" => ENV.fetch("ESIGNCOMPLY_TERMS_ID"), "privacy" => ENV.fetch("ESIGNCOMPLY_PRIVACY_ID") }.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

# Server-owned state: Sinatra's cookie session. The data travels in the cookie, encrypted with session_secret,
# so the browser carries it and cannot read or change it. Without a fixed secret Sinatra makes a new one at every start.
set :sessions, httponly: true, same_site: :lax, secure: LIVE
set :session_secret, ENV.fetch("SESSION_SECRET")

# One call to the Esign Comply API. Returns [status, parsed JSON].
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 #{ENV['ESIGNCOMPLY_API_KEY']}"
  request["Idempotency-Key"] = idempotency_key if idempotency_key
  if body
    request["Content-Type"] = "application/json"
    request.body = JSON.generate(body)
  end
  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, use_ssl: uri.scheme == "https", open_timeout: 5, read_timeout: 10) do |http|
      http.request(request)
    end
    # 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

def json(status_code, body)
  content_type :json
  status status_code
  JSON.generate(body)
end

get "/signup" do
  send_file File.join(settings.views, "signup.html")
end

# The document pages: each one renders a registered version, unmodified.
get "/legal/:slug" do
  document = DOCUMENTS[params[:slug]] or halt 404
  version = Rack::Utils.escape_path(params.fetch("v", "current"))
  status, content = esc(:get, "/documents/#{document}/versions/#{version}/content")
  halt 404 unless status == 200
  erb :legal, locals: { version_id: content["version_id"], html: content["html"] }
end

# Step 4: create the session with the secret key. The browser gets the client token only.
post "/api/ceremony" do
  # The page that runs the ceremony: the origin the browser reports, or the address Rack worked out.
  origin = request.env["HTTP_ORIGIN"] || request.base_url
  status, created = esc(:post, "/sessions",
    idempotency_key: "signup-#{SIGNER[:external_id]}-#{SecureRandom.uuid}",
    body: {
      profile: ENV["ESIGNCOMPLY_PROFILE_ID"],
      signer: SIGNER,
      documents: [
        { document: DOCUMENTS["terms"], version: "current" },
        { document: DOCUMENTS["privacy"], version: "current" }
      ],
      context: { url: "#{origin}/signup", locale: "en-US", purpose: "account_signup" }
    })
  halt json(502, error: created.dig("error", "code") || "unknown") unless status == 201

  session[:signer_id] = SIGNER[:external_id]
  session[:version_ids] = created["documents"].map { |d| d["version_id"] }.sort
  json 200, clientToken: created["client_token"], apiUrl: created["api_url"], documents: created["documents"]
end

# Step 6: confirm the record with the secret key before the account exists.
post "/api/signup/confirm" do
  body = JSON.parse(request.body.read) rescue {} # an empty or malformed body is refused below
  record_id = body.is_a?(Hash) && body["recordId"].is_a?(String) ? body["recordId"] : "missing"
  status, record = esc(:get, "/records/#{Rack::Utils.escape_path(record_id)}")

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

  logger.info(confirmed ? "confirmed #{record['id']} (#{record['status']})" : "refused")
  halt json(409, confirmed: false) unless confirmed

  # Only now create the account, and store record["id"] and record["receipt"] with it.
  json 200, confirmed: true, recordId: record["id"]
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.

Three things here are specific to Sinatra, and each one was seen in the test run.

The session is a cookie that holds the data itself. The browser got a cookie named rack.session, 532 characters long, HttpOnly and SameSite=Lax. Decoded from base64 it showed neither the signer ID nor a version ID: with rack-session 2.1.2 the cookie is encrypted. A cookie with one character changed was treated as empty, and the confirm route answered 409.

session_secret is set from the environment. With a fixed secret the session lives in the browser and a restart of the app changes nothing: the same cookie with a real record ID was answered 200 after a restart. Without session_secret, Sinatra made a secret of its own at start, and a value saved before a restart was gone after it. Sinatra's README says the same of several instances: each would have a different key.

The variables are read with ENV.fetch at the top of the file, so a missing one stops the app at start. With .env not loaded it ended with key not found: "ESIGNCOMPLY_TERMS_ID" (KeyError).

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.03 seconds.

context.url is built from the Origin header the browser sends with the POST. A request without one falls back to request.base_url, and both come from the client. A request with Origin: https://evil.example was refused by the API with domain_mismatch, and the route answered 502. What happens to a strange Host header depends on the environment. In development Sinatra answered 403 with Host not permitted before any route ran. In production it let the request through, and the API refused the session the same way.

Start the app from the shell that loaded .env:

bundle exec ruby app.rb
== Sinatra (v4.2.2) has taken the stage on 4567 for development with backup from Puma
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]
*  Environment: development
* Listening on http://127.0.0.1:4567

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 views/signup.html. The /signup route sends the file as it is:

<!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:4567/signup. The button stays disabled until the box is ticked. Tick it, click Create account, and the page shows:

Account created. Record rec_55Gxvmxrrw6cyq9D5f1T

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. In a test without disabled and with the session request held back, a box ticked in that time stayed ticked, and the SDK reported a finding for CR-01 at Block level: the control had already been used when the SDK started watching it. With disabled, the same early click 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. Its template is views/legal.erb:

<!doctype html><meta charset="utf-8"><article data-esc-document="<%= Rack::Utils.escape_html(version_id) %>"><%= html %></article>

ERB in Sinatra does not escape what <%= %> prints. 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 a value with a double quote in it was printed into the attribute unchanged. set :erb, escape_html: true changed nothing with Ruby's own ERB. With Rack::Utils.escape_html around the document, the page showed the tags as text and the SDK reported a finding for 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. POST /api/signup/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 session; and the document versions are exactly the ones this server pinned there. This step is never optional.

The app logs one line for each confirmation:

I, [2026-11-26T11:34:40.802216 #1]  INFO -- : confirmed rec_55Gxvmxrrw6cyq9D5f1T (recorded)

A record ID that was made up is refused with status 409. So is a real record ID sent without the session cookie, or with a cookie that was changed:

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

That request carried no token of any kind. Sinatra runs Rack::Protection in front of every route, and what it does to a POST from another site is not a refusal. In the test, a POST with a valid session cookie, a real record ID and Origin: https://evil.example reached the route with an empty session, and the route answered 409: Sinatra sets the reaction of Rack::Protection to drop_session. With a Referer of another site and no Origin, the route ran the same way, and Rack::Protection then replaced its JSON answer with 403 Forbidden. What refuses a forged confirmation here is the check itself.

See Server confirmation 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:

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

The report for this page's code, shortened:

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:4567/api/signup/confirm answered 409.

Ceremonies
  390x844    record rec_CVYGhmJRAqESBQdmDjLh  session ses_suSWGac9vLbGoLTkkyNg, 5 events
  768x1024   record rec_vRSCkwtjVrUiMSGDPZDL  session ses_TbPhZjo3k9eGk40WNke7, 5 events
  1440x900   record rec_JtghURGXtTmX8y7rxqnN  session ses_5YACPemdRYXHqr58vkwd, 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, and every flag of the command is on the CLI page.

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.
  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.

In production the app runs under a web server, from a config.ru:

# config.ru
require_relative "app"

run Sinatra::Application

Then switch the server over:

  • Start it with APP_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. From then on the confirm route refuses every test record there, and the session cookie is Secure.
  • A Secure session cookie needs a request that Rack sees as HTTPS. In the test with ESIGNCOMPLY_LIVE=true, a request over plain HTTP got no session cookie at all, and the same request with X-Forwarded-Proto: https got one marked secure. Behind a proxy that terminates TLS, make sure it sends that header, or every confirmation is answered 409.
  • In production Sinatra permits any Host header: its README says so, and in the test a request with Host: evil.example reached the session route there. The README names the setting that restricts it: host_authorization with permitted_hosts.
  • Keep one SESSION_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

  • key not found: "ESIGNCOMPLY_TERMS_ID" (KeyError) when the app starts. The variables are not in the environment of the shell that starts Ruby. Run set -a; . ./.env; set +a in that shell first. With the IDs set and the key itself empty, the app started and the session route answered 502 with missing_api_key.
  • 403 and Host not permitted. The page was opened under a host name Sinatra does not know. In development it permits localhost, names ending in .localhost or .test, and IP addresses. Sinatra's README names the setting for more: host_authorization with permitted_hosts. Add the host to Domains in the dashboard too: a host that is not on the test allowlist is refused by the API with 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. The API's log showed why: two reads got 429 and passed on the next attempt, a second later. See rate_limit_exceeded. When the route answers 409 for a real record, the causes are a SESSION_SECRET that changed, and a Secure cookie on a request Rack sees as HTTP.

Questions about the Sinatra quickstart

Is there an Esign Comply gem for Sinatra?

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

Why does Sinatra need rackup and puma?

Because Sinatra 4 does not ship a web server. Its README installs all three gems together. In the test, an app with only sinatra in its Gemfile printed that the required gems were not found, and one with rackup and no server stopped because no handler was found for puma, falcon, thin or webrick.

Does the session survive a restart of the app?

Yes, when session_secret is fixed. The pinned versions are in the cookie, not in the memory of the app. In the test the same cookie confirmed a real record before and after a restart. With no session_secret set, Sinatra made a new secret at start, and a value saved before a restart was gone.

Does Rack::Protection stop a POST from another site?

Not by refusing it. In the test a POST with the Origin of another site reached the confirm route with an empty session, because Sinatra sets the reaction to drop_session. The route answered 409, since there were no pinned versions to compare with. The session route is safe for another reason: the API refuses a page address that is not yours.

Does the Sinatra 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

Run on 2026-11-26 with Sinatra 4.2.2, Rack 3.2.9, rack-session 2.1.2, rack-protection 4.2.2, rackup 2.3.1 and Puma 8.1.3 on Ruby 3.4.13 (the official Ruby container image), under ruby app.rb and under Puma with config.ru, with the browser SDK script build and the conformance check from esigncomply 1.0.4, against the API in test mode.

Last updated · API version 2026-11-21