Countersign

Self-hosted e-signatures for Phoenix: no DocuSign, no per-envelope fees.

Countersign sends a signing link to a person who is not signed in to your app, proves they control the address it went to with a one-time code, records their consent to sign electronically, and records their signature against the exact content they were sent. Your app keeps the documents, the data and the audit trail; Countersign keeps the workflow.

It is a library, not a service: it runs inside your Phoenix app, on your Postgres, and talks to the outside world only through three behaviours you implement.

Status: 0.1.0. The data model, the behaviours and the core path (send, open, code, consent, sign), the sender's side (resend, revoke, supersede), delivery with the daily reminder and expiry, the signing pages (code, consent, review, sign, decline, copy), the signing certificate and the PDF seal. Breaking changes are allowed in 0.x and are recorded in CHANGELOG.md.

The Getting started guide takes a Phoenix app from no Countersign to a signed document.

How it works

  1. Your app calls Countersign.Requests.send/3 for a subject (a contract, a consent form) and one or more signers. Countersign stores a request per signer, with the subject's content hash, the address encrypted, and the link token only as a hash.
  2. The signer opens https://your.app/sign/<token> and asks for a code, which goes to the same address. Entering it proves control of that address.
  3. The signer reads the document, accepts the electronic-records disclosure, and signs. Countersign re-checks the content hash under your lock and calls your record_signature/4 in the same transaction.

Installation

def deps do
  [
    {:countersign, "~> 0.1"}
  ]
end

Then generate and run the migration that creates signing_requests and signing_codes:

mix countersign.gen.migration
mix ecto.migrate

The generated migration calls Countersign.Migrations.up/1 at the current version and down(version: 1). A host that already ran an earlier version adds a migration for the new one only (up(version: 2), down(version: 2)); the versions are listed in Countersign.Migrations. Every statement is idempotent, so a migration that is retried after a dropped connection succeeds.

Countersign needs PostgreSQL 15 or later (NULLS NOT DISTINCT).

The three behaviours

behaviour what your module answers
Countersign.Host Is signing on for this scope, how long links live, the name messages show, rate limiting, audit, notifications, HTML to PDF, the clock, and lock_subject/4, the per-subject lock every send and signature takes first.
Countersign.Signable Fetch the subject, its content hash, whether it still takes signatures, render it as a PDF, the name of its kind and the label of a role, record_signature/4 (write the signature into your own records) and store_document/4 (keep the signing certificate).
Countersign.Delivery Deliver a link or a code by the request's channel (email or sms), and whether the address is still reachable.

A scope is your tenant (an account, an organisation), or nil in a single-tenant app. Every request carries it as scope_id.

Configuration

Countersign reads no application env, no OS env and no :persistent_term. You build a Countersign.Config in one function at your boundary and pass it to every call:

defmodule MyApp.Signing do
  def config do
    Countersign.Config.new!(
      repo: MyApp.Repo,
      host: MyApp.Signing.Host,
      signable: MyApp.Signing.Signable,
      delivery: MyApp.Signing.Delivery,
      base_url: MyAppWeb.Endpoint.url(),
      secret_key_base: MyAppWeb.Endpoint.config(:secret_key_base),
      disclosure: %{version: 1, text: "You agree to sign electronically. ..."}
    )
  end
end

Countersign.Config.new!/1 raises when a key is missing or a module does not export every callback of its behaviour, so a wiring mistake fails at boot, not at the first signature.

A minimal host

defmodule MyApp.Signing.Host do
  @behaviour Countersign.Host

  @impl true
  def enabled?(_scope_id), do: true
  @impl true
  def link_days(_scope_id), do: 14
  @impl true
  def reminder_days(_scope_id), do: 3
  @impl true
  def codes_per_day(_scope_id), do: 200
  @impl true
  def display_name(_scope_id), do: "My App"
  @impl true
  def check_rate(key, scale_ms, limit), do: MyApp.RateLimit.hit(key, scale_ms, limit)
  @impl true
  def audit(event, request, meta), do: MyApp.Audit.log(event, request.id, meta)
  @impl true
  def notify(_event, _request), do: :ok
  @impl true
  def html_to_pdf(html), do: MyApp.Pdf.from_html(html)
  @impl true
  def now, do: DateTime.utc_now()

  @impl true
  def lock_subject(repo, _scope_id, type, id) do
    repo.query!("SELECT pg_advisory_xact_lock(hashtext($1))", ["#{type}:#{id}"])
    :ok
  end
end

examples/demo/lib/demo/signing/ has a complete Signable and Delivery next to this host.

Delivery and the daily sweep

Two Oban workers carry the links and run the daily sweep. Each is a use in a module of yours that names your config:

defmodule MyApp.Signing.DeliveryWorker do
  use Countersign.Workers.Delivery, queue: :notifications, max_attempts: 5

  @impl true
  def config, do: MyApp.Signing.config()
end

defmodule MyApp.Signing.DailyWorker do
  use Countersign.Workers.Daily, delivery: MyApp.Signing.DeliveryWorker

  @impl true
  def config, do: MyApp.Signing.config()
end

Insert MyApp.Signing.DeliveryWorker.job(request) for each request a send or a resend answers (the :after_insert and :after_resend hooks run in the same transaction), and schedule the daily worker with Oban's cron plugin. Its job args carry no token and no address. While enabled?/1 answers false for a scope, a delivery snoozes and no reminder goes out, but links still expire on their date. A link that cannot be delivered after the last attempt fails the request.

The signer's pages

Countersign.Router.countersign_routes/2 mounts the landing page, the code request and the code check (Countersign.Web.LinkController) under the config's :sign_path:

import Countersign.Router

pipeline :signing do
  plug :accepts, ["html"]
  plug :fetch_session
  plug :protect_from_forgery
  plug :put_secure_browser_headers, %{"referrer-policy" => "no-referrer"}
  plug :put_root_layout, html: {MyAppWeb.Layouts, :signing}
end

scope "/" do
  pipe_through :signing
  countersign_routes "/sign", MyApp.Signing
end

MyApp.Signing.config/0 answers the config. The two POST routes carry the code and are declared with log: false; keep the token's paths out of your request log too. A verified code puts %{"request_id", "verified_at"} in the session under :session_key, and the controller redirects to <sign_path>/<token>/review (or /copy for a request already signed, for 30 days after signing). Name a module that uses Countersign.Workers.Code as :code_worker to send codes from a job instead of the request.

Quick start: the demo app

examples/demo is a small Phoenix app that signs one kind of thing, an agreement, end to end, with email delivered to Swoosh's local mailbox.

cd examples/demo
mix setup          # deps, database, migrations, one sample agreement
mix phx.server
  1. Open http://localhost:4000, pick the sample agreement, and send it to any name and email address.
  2. Open http://localhost:4000/dev/mailbox and follow the link in the email.
  3. Press "Send me a code", read the code from the mailbox, and enter it.
  4. Tick "I agree to sign electronically", type your name, and sign.

The demo needs a local PostgreSQL with a postgres user whose password is postgres (see examples/demo/config/dev.exs).

Countersign implements the mechanics the US ESIGN Act and UETA describe for electronic signatures: consent to electronic records with a disclosure the signer accepts, attribution of the signature to a person who proved control of an address, intent shown by an explicit act, and a record bound to the exact content signed. It is not legal advice. Whether an electronic signature is valid for a given document, in a given jurisdiction, is a question for your counsel.

Sealed PDFs

Countersign.Seal.seal/3 seals a PDF so it proves by itself that it was not altered: one PAdES signature (ETSI.CAdES.detached) per key, each in its own incremental update after the untouched original, Ed25519 first and then SLH-DSA (FIPS 205), a post-quantum signature whose security rests on hash functions alone. Countersign.Seal.verify/1 checks every signature and says whether the last one covers the whole file. Pass the certificates you seal with as :trusted: anyone can make a self-signed certificate under your name, so a seal proves the file unaltered only when its certificate is yours.

{:ok, {:ed25519, ed}} = Countersign.Seal.Cert.from_pem(ed_cert_pem, ed_key_pem)
{:ok, {{:slh_dsa, _}, slh}} = Countersign.Seal.Cert.from_pem(slh_cert_pem, slh_key_pem)

{:ok, sealed} = Countersign.Seal.seal(pdf, %{ed25519: ed, slh_dsa: slh})
{:ok, [%{alg: :ed25519}, %{alg: {:slh_dsa, :slh_dsa_sha2_192s}, covers_whole_file: true}]} =
  Countersign.Seal.verify(sealed, trusted: [elem(ed, 0), elem(slh, 0)])

mix countersign.gen.seal_keys --out <dir> writes a self-signed certificate and a PKCS #8 key for each algorithm into a directory outside the project; keep the keys in your secret store, never in the repository or priv/. Keys are only ever passed in: the seal reads no configuration and no environment.

Security

Report vulnerabilities privately; see SECURITY.md.

Contributing

See CONTRIBUTING.md and the Code of Conduct.

License

Apache License 2.0; see LICENSE and NOTICE.