# `Ankusa.SDK.Receiver`
[🔗](https://github.com/jamescarr/ankusa/blob/sdk-elixir-v0.6.0/packages/sdk-elixir/lib/ankusa/sdk/receiver.ex#L1)

A `Plug` that receives `Ankusa.Sink.Http` deliveries and hands each one to
your handler module.

Mount it **before** any body parser (`Plug.Parsers`), so the raw bytes can be
read: the SDK hands the handler exactly what the sink sent. `Ankusa.Sink.Http`
signs every delivery unless it is configured `allow_unsigned: true`, so the
receiver is closed by default: it needs the sink's `:secret` to verify the
Standard Webhooks signature (`Ankusa.SDK.Signature`) and refuses to start
without one, unless you pass `allow_unsigned: true`. Otherwise any host that
can reach this URL could inject hooks.

```elixir
# Bandit, standalone
{Bandit,
 plug: {Ankusa.SDK.Receiver, handler: MyApp.Hooks, secret: System.fetch_env!("ANKUSA_WHSEC")},
 port: 4200}

# Phoenix, in an endpoint
plug Ankusa.SDK.Receiver,
  path: "/deliveries",
  handler: MyApp.Hooks,
  secret: System.fetch_env!("ANKUSA_WHSEC")

plug Plug.Parsers, parsers: [:json], json_decoder: JSON
```

Responses, matching what `Ankusa.Sink.Http` treats as success:

| Situation | Response |
| --- | --- |
| handler returned `:ok` | `202`, empty body |
| handler returned `{:error, reason}` | `503` (the dispatcher retries per `dispatch.retry`) |
| body unreadable | `400`, `{"error":"body unreadable"}` |
| body over `:max_body_bytes` | `413`, `{"error":"body too large"}` |
| signature missing or does not verify | `401`, `{"error":"invalid_signature","code":"..."}` |
| `x-ankusa-id` missing (after the signature passed) | `400`, `{"error":"missing x-ankusa-id"}` |

Anything else the handler does — a different return value, a raise — is not
rescued: Plug turns it into a `500`, which the dispatcher retries exactly
like a `503`.

The request method is not checked. A source's `dispatch` config may use
`POST`, `PUT` or `PATCH`; the hook id, not the method, identifies the
delivery.

## Options

* `:handler` (required) — a module implementing `Ankusa.SDK.Handler`, or
  `{module, arg}`; a bare module means the arg `[]`.
* `:path` (optional) — when set, requests to any other path are passed
  through untouched, so the plug can sit in a shared endpoint.
* `:max_body_bytes` (optional) — default `8_000_000`, the same cap core's
  ingest applies to a raw webhook body.
* `:secret` (required unless `allow_unsigned: true`) — the sink's secret
  (`whsec_` + base64, or any other string used as its own bytes), or a list
  of them during a rotation.
* `:allow_unsigned` (optional) — `true` accepts deliveries with no
  signature when no `:secret` is set. Default `false`. A `:secret` is
  never weakened by it: with one, every delivery must verify.
* `:tolerance_seconds` (optional) — how far `webhook-timestamp` may be from
  now; default `300`. Only meaningful with `:secret`.

---

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