# 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](CHANGELOG.md).

The [Getting started](guides/getting-started.md) 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

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

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

```sh
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:

```elixir
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

```elixir
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:

```elixir
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`:

```elixir
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 `use`s `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.

```sh
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`).

## Legal basis

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.

```elixir
{: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.

- **Identifiers.** Ed25519 is id-Ed25519 (1.3.101.112) with SHA-512, as
  RFC 8419 requires. SLH-DSA is SLH-DSA-SHA2-192s (2.16.840.1.101.3.4.3.22,
  NIST category 3) by default; `:slh_dsa_variant` picks any of the twelve
  sets (RFC 9814, NIST CSOR sigAlgs 20 to 31), with SHA-512 for the 192 and
  256 sets and SHA-256 for the 128 sets.
- **Who can verify what.** `Countersign.Seal.verify/1` is the verifier of
  record for both signatures. OpenSSL 3.5 or later verifies both
  (`openssl cms -verify`). Today's PDF readers verify neither: poppler's
  `pdfsig` lists both signatures and their byte ranges, but its NSS and
  GnuPG backends verify no Ed25519 CMS (OpenSSL's own included) and no
  SLH-DSA.
- **Requirements.** An OTP linked to OpenSSL 3.5 or later, for SLH-DSA;
  `seal/3` refuses with `{:error, {:unsupported, variant}}` rather than seal
  with Ed25519 alone. CI runs the seal's tests on such an OTP, and they fail,
  not skip, without it. Classic cross-reference tables only: a PDF with a
  cross-reference stream is refused (`{:error, :xref_stream}`), as is an
  encrypted one. No dependency beyond OTP's `:crypto` and `:public_key`.

## Security

Report vulnerabilities privately; see [SECURITY.md](SECURITY.md).

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) and the
[Code of Conduct](https://github.com/mkreyman/countersign/blob/main/CODE_OF_CONDUCT.md).

## License

Apache License 2.0; see [LICENSE](https://github.com/mkreyman/countersign/blob/main/LICENSE) and [NOTICE](https://github.com/mkreyman/countersign/blob/main/NOTICE).
