# `Countersign.Requests`
[🔗](https://github.com/mkreyman/countersign/blob/v0.1.0/lib/countersign/requests.ex#L1)

The signing-request lifecycle.

This release carries the path a signer walks: `send/3` creates requests,
`open/2` resolves a link token, `request_code/2` and `verify_code/3` prove
control of the address, `consent/3` records the electronic-records
consent and `sign/3` records the signature through the host's
`c:Countersign.Signable.record_signature/4`. The sender's side: `resend/3`
mints a new link, `revoke/4` withdraws one, `supersede/4` retires the
requests a changed or filled subject left behind, and `get_by_token/2`,
`list/3` and `count/2` read them. Decline, reminders and expiry follow in
later releases.

Every function takes a `Countersign.Config` first and reads nothing else.

# `meta`

```elixir
@type meta() :: %{
  optional(:ip_address) =&gt; String.t(),
  optional(:user_agent) =&gt; String.t()
}
```

The signer's HTTP request facts: `:ip_address` and `:user_agent`.

# `recipient`

```elixir
@type recipient() :: %{
  :role =&gt; String.t(),
  :signer_name =&gt; String.t(),
  :delivery_channel =&gt; String.t() | :email | :sms,
  :to_address =&gt; String.t(),
  optional(:signer_relationship) =&gt; String.t() | nil,
  optional(:signer_ref) =&gt; String.t() | nil
}
```

One recipient of a send: the `role` they sign, their name, and where the
link goes (`delivery_channel` `"email"` or `"sms"`, and `to_address`).

# `subject_ref`

```elixir
@type subject_ref() :: %{
  :scope_id =&gt; Ecto.UUID.t() | nil,
  :subject_type =&gt; String.t(),
  :subject_id =&gt; String.t(),
  optional(:sent_by_ref) =&gt; String.t() | nil
}
```

Which subject a send is for, and who sent it.

# `code_attempts_left`

```elixir
@spec code_attempts_left(Countersign.Config.t(), Countersign.Request.t()) ::
  non_neg_integer()
```

The guesses left on the request's newest unexpired, unconsumed code, `0`
when it has none.

# `consent`

```elixir
@spec consent(Countersign.Config.t(), Countersign.Request.t(), meta()) ::
  {:ok, Countersign.Request.t()} | {:error, term()}
```

Records that the signer accepted the configured electronic-records
disclosure (`Countersign.Config` `:disclosure`): `consented_at`,
`consent_version` and `consent_sha256`.

The request row is locked `FOR UPDATE` and re-checked, so a request
signed or superseded since the caller loaded it is refused. It must be
live and its code verified within the last
30 minutes. Answers
`{:error, :no_disclosure}` when the config carries none, and
`{:error, :not_verified}` before a code was verified or once the
verification is older than that.

A verification belongs to the row, not to a caller: the host must bind it
to the signer's session (the demo keeps the verified request id in the
session) so that only the browser that entered the code can consent and
sign.

# `copy_subject`

```elixir
@spec copy_subject(Countersign.Config.t(), Countersign.Request.t()) ::
  {:ok, Countersign.Signable.subject()} | {:error, :unusable | :not_found}
```

The subject of a signed request still inside its copy window
(`Countersign.Request.copyable?/2`), as it stands now, for the signer's
copy. Answers `{:error, :unusable}` outside the window.

# `count`

```elixir
@spec count(Countersign.Config.t(), subject_ref()) :: non_neg_integer()
```

How many requests one subject has, for paging `list/3`.

# `decline`

```elixir
@spec decline(
  Countersign.Config.t(),
  Countersign.Request.t(),
  :declined | :paper_requested,
  map()
) ::
  {:ok, Countersign.Request.t()} | {:error, term()}
```

Ends the request without a signature: `kind` `:declined` (the signer
refuses) or `:paper_requested` (the signer wants to sign on paper).

`meta[:token]` is the token in the URL the page was opened on. The same
checks as `sign/3` hold: in one transaction the request row is locked
`FOR UPDATE` and re-checked (live, its code verified within
`verification_seconds/0`), the token must hash to its `token_hash` (else
`{:error, :unusable}`), and the scope must be switched on (else
`{:error, :disabled}`, the request stays pending). The row is then marked
`declined` with `declined_at`, `decline_kind` and the optional
`meta[:reason]` (at most 1000 characters, else
`{:error, :reason_too_long}`), and its token is dropped. Audits and
notifies `:decline`.

# `deliver_code`

```elixir
@spec deliver_code(Countersign.Config.t(), Countersign.Request.t(), Ecto.UUID.t()) ::
  :ok | {:error, term()}
```

Delivers the code `code_id` of `request` (a `Countersign.Workers.Code`
job's work): decrypts it and hands it to
`c:Countersign.Delivery.deliver_code/2`. A code consumed or past its
expiry, or a request the signer may no longer open, sends nothing and
answers `:ok`, and so does a scope switched off since the code was asked
for (`c:Countersign.Host.enabled?/1`): the code lives 10 minutes, so it is
dropped rather than held. A permanent failure fails a pending request
(`fail/3`).

# `deliver_link`

```elixir
@spec deliver_link(
  Countersign.Config.t(),
  Countersign.Request.t(),
  Countersign.Delivery.link_kind()
) ::
  Countersign.Delivery.result() | {:error, :no_token}
```

Delivers the request's link through `c:Countersign.Delivery.deliver_link/3`.
The delivery job of a later release calls this; a host may call it
directly after `send/3`.

`{:error, {:permanent, reason}}` from the delivery marks a still-pending
request `failed` with `failed_reason`, clears its token, audits and
notifies `:fail`, and is answered as is; the role is then free for a new
`send/3`. `{:error, :retry}` changes nothing.

# `fail`

```elixir
@spec fail(Countersign.Config.t(), Countersign.Request.t(), term()) :: :ok
```

Ends a still-pending request as `failed` with `reason` (written to
`failed_reason`), clears its token, and reports `:fail` to
`c:Countersign.Host.audit/3` and `c:Countersign.Host.notify/2`. A request
that is no longer pending is left as it is and not reported twice. A
permanent delivery failure calls it, and so does a delivery job out of
attempts (`Countersign.Workers.Delivery`).

# `get_by_token`

```elixir
@spec get_by_token(Countersign.Config.t(), String.t()) ::
  Countersign.Request.t() | nil
```

The request a link token names, read without side effects; `nil` for a
malformed or unknown token, or one a resend replaced.

# `landing`

```elixir
@spec landing(Countersign.Config.t(), String.t()) ::
  {:ok, Countersign.Request.t()}
  | {:error, :not_found | {:unusable, Countersign.Request.t()}}
```

Resolves a link token for the page a signer lands on: `{:ok, request}`
for a live request (stamping `opened_at` on the first open, as `open/2`)
and for a signed request still inside its copy window
(`Countersign.Request.copyable?/2`), so a signer whose session ended can
come back for the copy. Otherwise as `open/2`: `{:error, :not_found}` for
a malformed or unknown token, `{:error, {:unusable, request}}` for any
other known request.

# `link_url`

```elixir
@spec link_url(Countersign.Config.t(), Countersign.Request.t()) ::
  {:ok, String.t()} | :error
```

The signing link for `request`, rebuilt from its encrypted last token:
`base_url`, then `sign_path` (`Countersign.Config`, default `"/sign"`),
then the token.

# `list`

```elixir
@spec list(Countersign.Config.t(), subject_ref(), keyword()) :: [
  Countersign.Request.t()
]
```

The requests of one subject, newest first. Options `:limit` (default 20,
at most 100) and `:offset` (default 0).

# `notify_superseded`

```elixir
@spec notify_superseded(Countersign.Config.t(), [Countersign.Request.t()]) :: :ok
```

Reports `:supersede` to `c:Countersign.Host.notify/2` for each request
`supersede/4` moved. Call it after the transaction that called
`supersede/4` commits.

# `open`

```elixir
@spec open(Countersign.Config.t(), String.t()) ::
  {:ok, Countersign.Request.t()}
  | {:error, :not_found | {:unusable, Countersign.Request.t()}}
```

Resolves a link token to its request and stamps `opened_at` on the first
open.

Answers `{:error, :not_found}` for a malformed or unknown token and
`{:error, {:unusable, request}}` for a request that is not pending or is
past its expiry, so the page can name the sender without showing more.

# `request_code`

```elixir
@spec request_code(Countersign.Config.t(), Countersign.Request.t()) ::
  :ok | {:error, term()}
```

Issues a new six-digit code for a request the signer may open
(`landing/2`: live, or signed and still copyable) and sends it to the
request's own address and channel.

Refuses with `{:error, :disabled}` while `c:Countersign.Host.enabled?/1`
answers false for the scope, with `{:error, {:unreachable, reason}}` when
`c:Countersign.Delivery.reachable/1` says the address can no longer be
reached (a number that opted out), and with `{:error, :rate_limited}` past
3 codes per request per 10 minutes,
10 per request per day, or the host's
`c:Countersign.Host.codes_per_day/1` per scope (all through
`c:Countersign.Host.check_rate/3`).

With a `:code_worker` in the config the code's delivery job is inserted
in the transaction that wrote the code, and `:ok` means it is queued.
Without one the code is delivered here: `:ok`, `{:error, :retry}`, or a
permanent failure, which also fails a pending request (`fail/3`).

# `resend`

```elixir
@spec resend(Countersign.Config.t(), Ecto.UUID.t(), keyword()) ::
  {:ok, Countersign.Request.t()} | {:error, term()}
```

Sends a pending, failed or expired request again under a new link.

In one transaction: the host's subject lock, then the request row locked
`FOR UPDATE`. A request no longer pending, failed or expired answers
`{:error, :not_resendable}`; one already sent `:max_sends` times (default
5, the first send included) answers `{:error, :resend_limit}`.
The subject is fetched (`{:error, :not_found}` or `{:error, :not_signable}`);
when its content hash no longer equals the request's, the request is marked
`superseded` (that commits, with its `:supersede` audit and notice) and the
answer is `{:error, :superseded}`. Otherwise a new token replaces the old,
which stops resolving, and the request turns `pending` with a new
`expires_at`, `send_count` one higher and `last_sent_at` now, audited as
`:resend`. Refused `{:error, :disabled}` while the host has signing off.

## Options

  * `:max_sends` - the send limit, default 5.
  * `:before_resend` - `(subject, Request.t() -> :ok | {:error, reason})`,
    run after the checks above and before the update, with the locked row:
    the host re-checks there what may have changed while a failed or
    expired request sat (another channel opened, the line signed).
  * `:after_resend` - `(Request.t() -> :ok | {:error, reason})`, run after
    the update in the same transaction, for the delivery job.

# `review`

```elixir
@spec review(Countersign.Config.t(), Countersign.Request.t()) ::
  {:ok, Countersign.Signable.subject()}
  | {:error, :changed | :unusable | :not_found}
```

The subject a live request's signer is about to read, checked against the
request: under the host's subject lock and the request row locked
`FOR UPDATE`, the subject must still be found, signable and hash to the
request's `content_sha256`. Otherwise the request is superseded (audited
and notified `:supersede`) and the answer is `{:error, :changed}`. A
request no longer live answers `{:error, :unusable}`.

# `revoke`

```elixir
@spec revoke(Countersign.Config.t(), Ecto.UUID.t(), String.t(), keyword()) ::
  {:ok, Countersign.Request.t()}
  | {:error, :invalid_reason | :not_pending | :not_found}
```

Withdraws a pending request: `revoked`, `revoked_at`, `revoked_by_ref`
(option `:revoked_by_ref`) and `revoke_reason`, with its token cleared and
a `:revoke` audit. The reason is trimmed and must be 3 to 1000 characters
(`{:error, :invalid_reason}`); a request in any other status answers
`{:error, :not_pending}`, and an unknown id `{:error, :not_found}`. Only a
row still pending moves, so a revoke racing a signature or a resend never
turns a finished row back.

# `send`

```elixir
@spec send(Countersign.Config.t(), subject_ref(), [recipient()], keyword()) ::
  {:ok, [Countersign.Request.t()]} | {:error, term()}
```

Creates one pending request per recipient for one subject, in one
transaction that first takes the host's subject lock
(`c:Countersign.Host.lock_subject/4`).

Refuses with `{:error, :disabled}` when the host has signing off for the
scope, `{:error, :not_found}` or `{:error, :not_signable}` for the subject,
`{:error, {:request_open, role}}` when the role already has a pending
request (the `signing_requests_one_pending_per_role_index`), and
`{:error, %Ecto.Changeset{}}` for an invalid recipient. Nothing is
inserted unless every recipient is.

The link token is not returned; it is kept encrypted on the row, and
`link_url/2` rebuilds the link for delivery.

## Options

  * `:before_insert` - `(subject -> :ok | {:error, reason})`, run in the
    transaction after the lock and the fetch, before any insert: the
    host's own existence checks (another channel's open request, a line
    signed elsewhere) belong here, so they and the insert serialise on the
    subject lock. An error rolls back and is answered as is.
  * `:after_insert` - `([Request.t()] -> :ok | {:error, reason})`, run in
    the same transaction after the inserts and their audits: the host
    enqueues its delivery jobs here, so a request and its job commit
    together.

# `sign`

```elixir
@spec sign(
  Countersign.Config.t(),
  Countersign.Request.t(),
  Countersign.Signable.input() | map()
) ::
  {:ok, Countersign.Request.t()} | {:error, term()}
```

Signs the request.

In one transaction: the host's subject lock first, then the request row
locked `FOR UPDATE` and re-checked (live, verified within
`verification_seconds/0`, consented), the subject
fetched and its content hash compared with the hash the request was sent
against, then `c:Countersign.Signable.record_signature/4`, and finally the
request marked `signed` with the returned `signature_ref`.

`input` carries `:token`, the token in the URL the signing page was opened
on: the locked row's `token_hash` must be its hash, so a page opened on a
link that a resend has since replaced signs nothing (`{:error, :unusable}`).
While the scope is switched off (`c:Countersign.Host.enabled?/1`) nothing
is signed, the request stays pending, and the answer is
`{:error, :disabled}`.

A changed subject (by hash, `{:error, :changed}` from the host, or a
subject no longer found or signable) marks the request `superseded`,
audits and notifies `:supersede`, and answers `{:error, :changed}`; a
role whose line is already signed (`{:error, :already_signed}` from the
host) supersedes it the same way and answers `{:error, :already_signed}`.
Any other host error rolls back.

# `supersede`

```elixir
@spec supersede(
  Countersign.Config.t(),
  subject_ref(),
  String.t(),
  :all | :stale | {:filled, [String.t()], Ecto.UUID.t() | nil}
) :: {:ok, [Countersign.Request.t()]}
```

Marks `superseded` the pending requests of one subject that a change left
behind, in one statement, each with a `:supersede` audit. Answers the
requests it moved; notify them with `notify_superseded/2` once the
caller's transaction has committed, so a rollback never leaves a notice
for a supersede that did not happen.

`content_hash` is the subject's hash now. `mode`:

  * `:all` - every pending request (the subject was withdrawn or
    redrafted);
  * `:stale` - those whose `content_sha256` differs from `content_hash`;
  * `{:filled, roles, except_id}` - the stale ones, and every pending
    request for one of `roles` (a line just filled, with any role that
    excludes it), except the request `except_id` (nil for none) whose own
    signature filled it.

Call it inside the transaction that changed the subject, after the
host's subject lock, so a send racing the change sees one or the other.

# `verification_seconds`

```elixir
@spec verification_seconds() :: pos_integer()
```

How long a verified code lets a signer consent and sign, in seconds.

# `verify_code`

```elixir
@spec verify_code(Countersign.Config.t(), Countersign.Request.t(), String.t()) ::
  {:ok, Countersign.Request.t()}
  | {:error, :invalid_code | :too_many_attempts | :unusable}
```

Checks `code` against the request's newest unexpired, unconsumed code.

The attempt is spent by a conditional UPDATE before Bcrypt runs, so a
retried POST never earns an extra guess. On a match the code is consumed
and `verified_at` is stamped. A signed request inside its copy window
verifies too, for the copy, and keeps its `verified_at`, the time the
signer proved the address before signing. Answers `{:ok, request}`,
`{:error, :invalid_code}` or `{:error, :too_many_attempts}`.

# `with_address`

```elixir
@spec with_address(Countersign.Config.t(), Countersign.Request.t()) ::
  Countersign.Request.t()
```

The request with its virtual `address` field set to the decrypted address.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
