Webhooks
Webhooks provide best-effort HTTP POST notifications for selected recorded events. Delivery is not transactional or guaranteed real-time and may be delayed, retried, duplicated, or lost; consumers must verify signatures, process idempotently, and reconcile authoritative state.
Note: Configuration requires an authenticated admin session. Five user-lifecycle names are emitted; three additional names are configuration-only. Signed best-effort delivery is not an authoritative change feed.
Creating a Webhook
Navigate to the Admin Panel and select Webhooks from the sidebar. Click Create Webhook and fill in the following fields:
- Name — A descriptive label for this webhook (e.g., “Production CRM sync”)
- URL — The public HTTP or HTTPS endpoint that will receive POST requests; use HTTPS for transport confidentiality
- Events — Select stored event names; only the entries marked as wired below are currently emitted
- Secret — A server-generated HMAC secret returned once in the successful create response; callers cannot supply or rotate it through the current admin API
You can also create webhooks programmatically via the /api/admin/webhooksAPI endpoint.
POST /api/admin/webhooks
Content-Type: application/json
Cookie: auth_token=<admin-session-cookie>
{
"name": "Production CRM sync",
"url": "https://your-app.com/webhooks/uniauth",
"events": ["user.created", "user.updated", "user.deleted"]
}Event Types
Five event names below have runtime producers. The three marked configured-only can be stored but are not currently emitted.
| Event | Description |
|---|---|
user.created | New user registered |
user.login | User logged in |
user.logout | User logged out |
user.updated | Profile updated |
user.deleted | Account deleted |
user.password_changed | Configured-only name; no runtime producer is wired |
oauth.client_created | Configured-only name; no runtime producer is wired |
oauth.consent_granted | Configured-only name; no runtime producer is wired |
Payload Format
Each runtime delivery sends a JSON object via HTTP POST with exactly three outer fields:
{
"event": "user.created",
"timestamp": "2026-02-26T14:30:00.000Z",
"data": {
"userId": "550e8400-e29b-41d4-a716-446655440000",
"email": "jane@example.com"
}
}The data object is producer-defined. Currently wired events use user.* names. The configured-only values above have no runtime producer, so oauth.* payloads are not emitted.
Signature Verification
Every webhook request includes an X-UniAuth-Signature header containing an HMAC-SHA256 signature over the exact raw request bytes. Verify those bytes before parsing. A valid value authenticates possession of the shared secret; it does not prevent replay or replace idempotency.
The signature is computed as an HMAC-SHA256 hash of the raw request body using your webhook secret, prefixed with sha256=. The header value format is:
sha256=HMAC-SHA256(webhook_secret, request_body)When verifying, strip the sha256= prefix before comparing the hex digest, or compare the full prefixed string.
Node.js
import crypto from "crypto";
import express from "express";
const app = express();
function verifyWebhookSignature(rawBody, signatureHeader, secret) {
if (!Buffer.isBuffer(rawBody) || typeof signatureHeader !== "string" || !secret) {
return false;
}
const expected = Buffer.from("sha256=" + crypto
.createHmac("sha256", secret)
.update(rawBody)
.digest("hex"), "utf8");
const received = Buffer.from(signatureHeader, "utf8");
return received.length === expected.length
&& crypto.timingSafeEqual(received, expected);
}
// Register this raw parser before any JSON body parser for this route.
app.post("/webhooks/uniauth", express.raw({ type: "application/json" }), (req, res) => {
const signature = req.headers["x-uniauth-signature"];
const rawBody = req.body;
if (!verifyWebhookSignature(rawBody, signature, process.env.WEBHOOK_SECRET)) {
return res.status(401).send("Invalid signature");
}
let event;
try {
event = JSON.parse(rawBody.toString("utf8"));
} catch {
return res.status(400).send("Invalid JSON");
}
console.log("Received event:", event.event);
// Process the event asynchronously
processEvent(event).catch(console.error);
// Respond immediately with 200
res.status(200).send("OK");
});Python
import hmac
import hashlib
def verify_webhook_signature(body: bytes, signature_header: str, secret: str) -> bool:
expected = "sha256=" + hmac.new(
secret.encode("utf-8"),
body,
hashlib.sha256
).hexdigest()
return hmac.compare_digest(signature_header, expected)
# In your Flask/FastAPI handler:
@app.post("/webhooks/uniauth")
async def handle_webhook(request: Request):
body = await request.body()
signature = request.headers.get("X-UniAuth-Signature", "")
if not verify_webhook_signature(body, signature, WEBHOOK_SECRET):
raise HTTPException(status_code=401, detail="Invalid signature")
event = await request.json()
print(f"Received event: {event['event']}")
# Process asynchronously
background_tasks.add_task(process_event, event)
return {"status": "ok"}Retry Policy
A non-2xx response or transport failure can enter this bounded schedule, for at most three total attempts:
- Attempt 1 — Immediate
- Attempt 2 — Eligible after 1 minute
- Attempt 3 — Eligible after 5 minutes
- No attempt 4 — No automatic 30-minute attempt is scheduled
After three total attempts, a delivery remains failed. Recent history exposes status and attempt metadata only: no failure reason, payload, response body, dead-letter queue, replay receipt, ordering guarantee, or delivery SLO is provided. Manual retry queues eligible rows; it does not prove recipient processing. The runtime is in lib/webhooks.ts.
Testing Webhooks
The admin action sends a synthetic, unledgered connectivity request. It is not a delivery or SLO receipt. Click Send Test Event. The endpoint HTTP status is returned; that status does not prove downstream processing.
You can also trigger test events via the API:
POST /api/admin/webhooks/:id/test
Content-Type: application/json
Cookie: auth_token=<admin-session-cookie>
{}For local development, use a tunneling service like ngrok or localtunnel to expose your local server to the internet so UniAuth can reach your endpoint.
Delivery Logs
Recent history retains bounded delivery metadata only. Navigate to Admin Panel → Webhooks → [Your Webhook] → Deliveries to view:
- Event name and record timestamp
- Status: pending, success, or failed
- Attempt count
- HTTP response status, when recorded
- Last-attempt and next-retry timestamps, when recorded
- No payload, response body, raw error, duration, or dead-letter record
Retry queues an eligible failed row when you click Retry on its history entry; it does not prove that the selected row was sent or processed.
Best Practices
- Respond quickly — Return a 2xx response within the 10-second transport timeout and process the event asynchronously after acknowledging receipt.
- Always verify signatures — Never process a webhook without verifying the
X-UniAuth-Signatureheader over the exact raw bytes before parsing. This authenticates shared-secret possession; it does not prevent replay or replace idempotency. - Handle idempotency — Runtime retries reuse the same X-UniAuth-Delivery value for the recorded delivery; the JSON envelope itself has no event or delivery ID. Deduplicate on that header, handle missing identifiers defensively, and reconcile authoritative state. Unledgered test requests omit the delivery header.
- Use HTTPS — Use HTTPS for transport confidentiality. The current validator may also admit public HTTP endpoints, which are not confidential.
- Monitor delivery health — Check the admin panel regularly for failed deliveries. Persistent failures may indicate an endpoint issue.
- Protect the generated secret — The HMAC secret is shown once at creation. The current admin surface has no secret rotation or dual-secret grace period; changing it requires a coordinated replacement webhook.
Payload data boundary
The outer envelope contains event, timestamp, and data only. The data object is producer-defined; no per-event schema is promised. Runtime requests carry X-UniAuth-Event and a stable per-delivery X-UniAuth-Delivery header, while configured-only names emit nothing.
Delivery Details
- Timeout: Each transport attempt has a 10-second timeout. A timeout is recorded as failed and can be eligible for the bounded retry schedule above; delivery is not guaranteed.
- Ordering: There is no guaranteed ordering between events. If a user registers and logs in within the same second, you may receive
user.loginbeforeuser.created. Timestamps do not establish a total order; reconcile authoritative state instead. - Parallelism: Initial attempts for matching subscriptions start concurrently. Retry workers process bounded batches and may also run concurrently; no simultaneity or ordering guarantee is provided.
More Verification Examples
Go
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"io"
"net/http"
)
func verifyWebhook(body []byte, signatureHeader, secret string) bool {
mac := hmac.New(sha256.New, []byte(secret))
mac.Write(body)
expected := "sha256=" + hex.EncodeToString(mac.Sum(nil))
return hmac.Equal([]byte(signatureHeader), []byte(expected))
}
func webhookHandler(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, "Bad request", http.StatusBadRequest)
return
}
defer r.Body.Close()
signature := r.Header.Get("X-UniAuth-Signature")
if !verifyWebhook(body, signature, "your-webhook-secret") {
http.Error(w, "Invalid signature", http.StatusUnauthorized)
return
}
// Process the event asynchronously
go processEvent(body)
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}Ruby
require 'openssl'
require 'json'
# Sinatra example
post '/webhooks/uniauth' do
request.body.rewind
body = request.body.read
signature = request.env['HTTP_X_UNIAUTH_SIGNATURE'].to_s
expected = "sha256=" + OpenSSL::HMAC.hexdigest(
'sha256',
ENV['WEBHOOK_SECRET'],
body
)
unless signature.bytesize == expected.bytesize &&
Rack::Utils.secure_compare(signature, expected)
halt 401, 'Invalid signature'
end
event = JSON.parse(body)
puts "Received event: #{event['event']}"
# Process asynchronously
Thread.new { process_event(event) }
status 200
'OK'
end