# Webhooks

mails.fit POSTs JSON to your HTTPS endpoint when something finishes, so you do not have to poll.

## Events

| Event | When | Subscribe with |
|---|---|---|
| `list.completed` | A list finished | `webhook_url` on upload, the account webhook (Dashboard → API keys), or a REST hook |
| `verify.completed` | A `/v1/verify` request finished | REST hook (`verify` scope) |
| `monitor.changed` | A blacklist monitor found a listing or delisting | Account webhook or REST hook |
| `list.monitor_changed` | A monitored list changed on re-verification | Account webhook or REST hook |

REST hooks are for Zapier, Make and your own code: `POST /v1/hooks` with `{"target_url": "https://...", "event": "list.completed"}`, and `DELETE /v1/hooks/{id}` to stop. A target that answers `410 Gone` is unsubscribed. At most 25 per account.

```bash
curl https://api.mails.fit/v1/hooks \
  -H "Authorization: Bearer $MAILSFIT_KEY" \
  -H "Content-Type: application/json" \
  -d '{"target_url": "https://example.com/hooks/mailsfit", "event": "list.completed"}'
```

## Delivery

- Targets must be public `https` URLs. Redirects are not followed.
- Any 2xx acknowledges. Otherwise we retry 3 times (after 2 s, 10 s and 60 s).
- `verify.completed` carries the same fields as the [verify response](/docs/verify#response-fields) plus `event`.

## Signatures

Every delivery has three headers:

- `X-Mailsfit-Event`: the event name
- `X-Mailsfit-Timestamp`: unix seconds
- `X-Mailsfit-Signature`: `sha256=` + hex HMAC-SHA256 of `"{timestamp}.{raw body}"`, keyed with your signing secret (`whsec_...`, shown under Dashboard → API keys)

Verify it on the **raw** body before parsing, compare in constant time, and reject timestamps older than 5 minutes to stop replays.

```javascript
import crypto from "node:crypto";

// Express: app.post("/hooks/mailsfit", express.raw({ type: "*/*" }), handler)
function verifyMailsfit(rawBody, headers, secret) {
  const ts = headers["x-mailsfit-timestamp"];
  const sig = headers["x-mailsfit-signature"] ?? "";
  if (Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
  const expected = "sha256=" + crypto.createHmac("sha256", secret).update(`${ts}.`).update(rawBody).digest("hex");
  return sig.length === expected.length && crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(expected));
}
```

```python
import hashlib, hmac, time

def verify_mailsfit(raw_body: bytes, headers, secret: str) -> bool:
    ts = headers.get("X-Mailsfit-Timestamp", "")
    sig = headers.get("X-Mailsfit-Signature", "")
    if not ts.isdigit() or abs(time.time() - int(ts)) > 300:
        return False
    mac = hmac.new(secret.encode(), f"{ts}.".encode() + raw_body, hashlib.sha256)
    return hmac.compare_digest(sig, "sha256=" + mac.hexdigest())
```

```go
func verifyMailsfit(rawBody []byte, h http.Header, secret string) bool {
	ts := h.Get("X-Mailsfit-Timestamp")
	sec, err := strconv.ParseInt(ts, 10, 64)
	if err != nil || math.Abs(float64(time.Now().Unix()-sec)) > 300 {
		return false
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(ts + "."))
	mac.Write(rawBody)
	expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
	return hmac.Equal([]byte(h.Get("X-Mailsfit-Signature")), []byte(expected))
}
```

```php
function verify_mailsfit(string $rawBody, string $ts, string $sig, string $secret): bool {
    if (!ctype_digit($ts) || abs(time() - (int) $ts) > 300) {
        return false;
    }
    $expected = "sha256=" . hash_hmac("sha256", $ts . "." . $rawBody, $secret);
    return hash_equals($expected, $sig);
}

// $ok = verify_mailsfit(file_get_contents("php://input"),
//     $_SERVER["HTTP_X_MAILSFIT_TIMESTAMP"] ?? "", $_SERVER["HTTP_X_MAILSFIT_SIGNATURE"] ?? "", $secret);
```

```rust
use hmac::{Hmac, Mac};
use sha2::Sha256;

fn verify_mailsfit(raw_body: &[u8], ts: &str, sig: &str, secret: &str, now: u64) -> bool {
    let Ok(sent) = ts.parse::<u64>() else { return false };
    if now.abs_diff(sent) > 300 {
        return false;
    }
    let Some(hex_sig) = sig.strip_prefix("sha256=") else { return false };
    let Ok(sig_bytes) = hex::decode(hex_sig) else { return false };
    let mut mac = Hmac::<Sha256>::new_from_slice(secret.as_bytes()).expect("any key length");
    mac.update(ts.as_bytes());
    mac.update(b".");
    mac.update(raw_body);
    mac.verify_slice(&sig_bytes).is_ok() // constant time
}
```

```bash
# Check a captured delivery by hand
printf '%s.%s' "$TS" "$(cat body.json)" | openssl dgst -sha256 -hmac "$WHSEC" | sed 's/^.* /sha256=/'
```
