# Hooks and webhooks

> Signed hooks that decide sign-ups and scopes before the server acts, and events delivered at least once after it does.

From `docs/server.md` in tensile-tools/tensile-auth at commit `e66760d` (v0.4.1-7-ge66760d). The HTML page is https://auth.tensile.tools/docs/server/webhooks.

Both are signed with [Standard Webhooks](https://www.standardwebhooks.com/): HMAC-SHA256 over the ID, the timestamp, and the body, in the `webhook-id`, `webhook-timestamp`, and `webhook-signature` headers, with one signature for each live secret. `tensile-auth-server keys webhook-secret` prints the secrets for the app's Standard Webhooks library. Both URLs must use `https://`, except on loopback, and `dev` refuses them.

## Hooks

With `hooks.url` set, the server asks the app before it acts, and waits up to 2 seconds for a signed answer:

- **`sign_up`**, before it creates an account. The app answers `{"allow": true}`, optionally with its own `"user_id"`, or `{"allow": false}`.
- **`session_scopes`**, when a session starts. The app answers the session's scopes, in place of `sessions.default_scopes`.

The answer must be 200, signed with a live webhook secret, carry the request's own `webhook-id`, and have a timestamp within 5 minutes. Hooks fail closed: a timeout, an error, or an unsigned answer refuses the sign-up with 503 `unavailable`, and gives a session no scopes. A `user_id` must match `^[A-Za-z0-9._:@-]{1,128}$` and name no user the server already knows.

## Webhooks

With `webhooks.url` set, the server delivers events after their change commits: `user.created`, `user.erased`, `email.verified`, `email.changed`, `agent.created`, `agent.revoked`, and `session.revoked`.

- **At least once.** The server reads events from the sealed audit log in order and moves its cursor only after the app answers 2xx within 10 seconds. The app deduplicates by `webhook-id`, which stays the same on every retry, and upserts on `user.created`.
- **From when you turn them on.** The first delivery starts at the end of the audit log, so no past events are sent.
- **Retries.** A failed delivery is retried with backoff from 1 second to 1 hour, and every later event waits behind it. After 15 minutes of failures, the admin API raises a `high` `webhook_late` alert until a delivery succeeds. After 72 hours, the server skips the event, records `server.webhook_skipped`, and raises `webhook_skipped`; reconcile the app's records from the audit log.
- **One replica delivers at a time**, so adding replicas never sends an event twice at once.
