# Alerts: webhooks, Slack and Discord

> Send what happens to your account to your own systems or your team's channels: the events, the body, the signature and a tested verifier.

Source: https://www.nexus402.dev/docs/developers/alerts/

Email is not the only way we tell you something happened. An alert can go to a URL of yours, signed so you can prove it came from us, or into a Slack or Discord channel. Developers and creators both use them: a developer hears that a balance is running low before calls start returning `402`; a creator hears that an endpoint has started failing before the version is de-listed.

## Three kinds of destination

| Kind | URL | What it carries |
| --- | --- | --- |
| **Signed webhook** | Any public HTTPS URL of yours | A JSON body with the event's exact figures, signed with a secret only you and we hold |
| **Slack** | A Slack incoming-webhook URL, on `hooks.slack.com` | One line saying what happened and a link to the app. **No amounts** |
| **Discord** | A Discord webhook URL, on `discord.com/api/webhooks` | The same line and link. **No amounts** |

Slack and Discord URLs must be on those hosts. A “Slack” URL pointing anywhere else would just be an unsigned webhook, so it is refused.

> **Why chat channels carry no amounts**
>
> A channel is read by a whole team, and often by people outside it. So Slack and Discord get what our emails get: what happened, and a link to see the figures in the app. Exact figures go only to a signed webhook, which only your own system receives.

## Setting one up

1. In the account app, open **Profile**, then **Alerts** (`/account/alerts`).
2. Add a destination: choose the kind, give it a label (1 to 60 characters), paste the URL, and tick the events it should receive. You see only the events for the roles your account holds.
3. **For a signed webhook, copy the signing secret now.** It starts `whsec_` and is shown once, when the destination is created, and never again. If you lose it, delete the destination and add it again.
4. Press **Send a test**. A `test` event is delivered within about fifteen seconds, and the destination then shows whether it arrived.

An account holds at most **ten destinations**, of any mix of kinds. You can change a destination's events at any time. After you save it, the URL is shown only masked: a Slack or Discord webhook URL is itself the credential that lets anyone post to your channel, so we treat it like the signing secret. Deleting a destination wipes its stored URL and secret and cancels anything still waiting to be delivered to it.

### What URL is accepted

- **HTTPS on port 443**, with a certificate a public client trusts. No `http://`, no other port, no user name or password in the URL, no `#fragment`.
- **A public address.** A host that resolves to a private, loopback or link-local address is refused (`refused_address`). This is checked when you save, and again at every delivery, so a name that later starts resolving inward is refused then too.
- **Redirects are never followed.** A `3xx` answer is a failed delivery. Give us the final URL.

## The events

The list is closed: these are every event we send. A new event is added only by a later release, and this page lists it when it is. Each destination receives only the events you ticked for it.

| Type | Audience | When | `data` fields |
| --- | --- | --- | --- |
| `balance.low` | Developer | Your balance fell below your low-balance threshold: a tenth of what your last top-up left it at, the same point as the low-balance email | `balance_micro`, `threshold_micro`, `currency` |
| `key.cap_warning` | Developer | A key passed 80% of its spending cap | `key_name`, `key_last4`, `spent_micro`, `cap_micro`, `currency` |
| `key.cap_reached` | Developer | A key reached its spending cap | `key_name`, `key_last4`, `cap_micro`, `currency` |
| `topup.credited` | Developer | A top-up was credited to your wallet | `amount_micro` (what was credited to your balance), `currency` |
| `endpoint.failing` | Creator | A tool's endpoint started failing | `tool`, `version`, `consecutive_failures` |
| `version.delisted` | Creator | A tool version was de-listed after repeated failures | `tool`, `version`, `consecutive_failures` |
| `withdrawal.paid` | Creator | A withdrawal was paid | `withdrawal_id`, `amount_micro` (before the fee), `fee_micro`, `received_micro`, `currency` |
| `margin.changed` | Creator | Your platform margin is changing | `previous_bps`, `margin_bps`, `effective_from` |
| `streak.at_risk` | Creator | Your reliable streak is at risk today: an endpoint is failing calls | `day`, `current_days` |
| `withdrawal_fee.changed` | Creator | Your withdrawal fee is changing | `old_flat_micro`, `old_bps`, `new_flat_micro`, `new_bps`, `currency`, `effective_at`, `direction`, `reason` |
| `milestone.reached` | Both | You reached a milestone | `award_id`, `milestone`, `name`, `scope`. No amount, even for an earnings milestone |
| `followed.new_tool` | Both | A creator you follow published a new tool | `creator`, `tool`, `version` |
| `followed.new_version` | Both | A creator you follow released a new version | `creator`, `tool`, `version`, `changelog` (at most 200 characters) |
| `followed.retired` | Both | A creator you follow retired a tool version | `creator`, `tool`, `version` |
| `test` | Both | You pressed **Send a test**. Never subscribable | `message` |

- **Money is integer micro-USD in a JSON string**, always: `"1000000"` is one dollar. Never parse it as a float. See [money is a string](https://www.nexus402.dev/docs/developers/money-format/). `currency` is `"USD"`.
- **Counts and basis points are JSON numbers**: `consecutive_failures`, `previous_bps` and `margin_bps` (1,000 basis points is 10%). `effective_from` and `created_at` are RFC 3339 times in UTC.
- A key is named by its `key_name` and the last four characters of the key, `key_last4`. No event carries a key, a token, a request or response body, a prompt, or anything belonging to another account.

## The webhook body

Each delivery is one `POST` with `Content-Type: application/json` and one event: its `id`, its `type`, when it happened (`created_at`) and its `data`. The examples are indented here; what we send is compact, and the signature covers those exact bytes.

**An event body — Developer: balance.low**

```
{
  "id": "evt_3f9c0e0f6a1b4c3d9e8f7a6b5c4d3e2f",
  "type": "balance.low",
  "created_at": "2026-11-17T12:00:00Z",
  "data": {
    "balance_micro": "412000",
    "threshold_micro": "500000",
    "currency": "USD"
  }
}
```

**An event body — Creator: withdrawal.paid**

```
{
  "id": "evt_0a1b2c3d4e5f60718293a4b5c6d7e8f9",
  "type": "withdrawal.paid",
  "created_at": "2026-11-17T12:00:00Z",
  "data": {
    "withdrawal_id": "wd_...",
    "amount_micro": "25000000",
    "fee_micro": "250000",
    "received_micro": "24750000",
    "currency": "USD"
  }
}
```

In `withdrawal.paid`, `received_micro` is what reached you: `amount_micro` minus `fee_micro`, the withdrawal fee. See [payouts](https://www.nexus402.dev/docs/creators/payouts/).

A Slack destination receives `{"text": "<what happened>. Open Nexus402: <link>"}` and a Discord one `{"content": "..."}` with the same words, for example: *Your balance fell below your low-balance threshold. Open Nexus402:* followed by a link to your wallet in the account app. Neither is signed, because Slack and Discord authenticate the URL itself.

## The signature

Every webhook delivery carries three headers:

**Webhook headers**

```text
X-Nexus-Event-Id:          evt_...           (the body's id)
X-Nexus-Webhook-Timestamp: <unix seconds>    (when this delivery was signed)
X-Nexus-Webhook-Signature: v1=<lowercase hex HMAC-SHA256>
```

The signature is an HMAC-SHA256, keyed with your **whole signing secret as UTF-8 text**, `whsec_` prefix included — copy it as shown and decode nothing. It is computed over the timestamp, one full stop, and the raw body:

**The signed string**

```text
<X-Nexus-Webhook-Timestamp>.<raw body bytes, exactly as received>
```

- **Verify the raw bytes, before you parse the JSON.** Parsing and re-serialising changes the bytes, and the signature will not match.
- **Compare in constant time**: `crypto.timingSafeEqual`, `hmac.compare_digest`, `subtle.ConstantTimeCompare`. An ordinary `==` returns sooner the earlier it finds a difference, which leaks the expected value to anyone who can time your answers.
- **Refuse everything if your secret is missing.** Anyone can sign with an empty secret. These verifiers answer `bad_secret`, before reading the delivery, unless the secret starts with `whsec_` and has something after it. That means your setup needs fixing, not the delivery.
- **Check the `v1=` prefix.** It names the scheme, so a later one can be added beside it without being mistaken for this one.

### Replay protection: 300 seconds either side

Refuse a delivery whose timestamp is more than **300 seconds** from your clock, in **both** directions. Without a lower bound a captured delivery can be replayed at you forever; without an upper one a future-dated one is valid forever. The timestamp is inside the signed string, so it cannot be changed without breaking the signature. Keep your server's clock synchronised; five minutes is room for ordinary drift, not for a clock that is wrong.

A retry is signed afresh, with a new timestamp, so a delivery we retry an hour later still verifies.

## A complete verifier

One function per language that takes your secret, the raw body and the two header values, and returns whether the delivery is ours and recent, or the reason it is not. Standard library only in each.

> **Machine-checked against our real signer**
>
> Our test suite signs real event bodies with the same function our delivery job signs with, and requires each of these verifiers to accept the genuine signature, including at exactly 300 seconds either side, and to refuse a changed body, a changed timestamp, the wrong secret, a timestamp 301 seconds old or 301 seconds ahead, and a signature without its `v1=` prefix. That runs on every change, so the code below cannot drift from what we send.

**examples/webhooks — Node.js**

```
// A Nexus402 alert-webhook verifier for Node.js. NO DEPENDENCIES.
//
// Copy this file. It is not a package to import, so it can never version-skew
// against the platform. `examples/webhooks/webhooks_test.go` signs real bodies
// with the platform's own signer (`internal/alerts.Sign`) and refuses to pass
// unless this code accepts the genuine signature and refuses every tampered
// one, so what you copy is what our tests run.
//
// Every delivery carries three headers:
//   X-Nexus-Event-Id           the event id, also the body's `id`
//   X-Nexus-Webhook-Timestamp  Unix seconds when the delivery was signed
//   X-Nexus-Webhook-Signature  v1=<lowercase hex HMAC-SHA256>
//
// The signed string is `<timestamp>.<raw body>`, and the HMAC key is your
// whole signing secret as UTF-8, `whsec_` prefix included.

import { createHmac, timingSafeEqual } from "node:crypto";

/**
 * How far either side of your clock a timestamp may be: 300 seconds.
 * Narrower rejects honest deliveries on ordinary clock skew; wider accepts
 * older replays of a captured delivery.
 */
export const TOLERANCE_SECONDS = 300;

const SIGNATURE_PREFIX = "v1=";
// Every signing secret starts with this.
const SECRET_PREFIX = "whsec_";

/**
 * Verify one delivery. Call it with the RAW body bytes, before any JSON
 * parse: re-serialising changes the bytes and the signature will not match.
 *
 * @param {object} input
 * @param {string} input.secret           your destination's signing secret, `whsec_...`
 * @param {Buffer|Uint8Array} input.rawBody the request body exactly as received
 * @param {string|undefined} input.timestamp the X-Nexus-Webhook-Timestamp header
 * @param {string|undefined} input.signature the X-Nexus-Webhook-Signature header
 * @param {number} [input.nowUnixSeconds]  defaults to your clock
 * @returns {{ ok: boolean, reason: string }}
 */
export function verifyWebhook({ secret, rawBody, timestamp, signature, nowUnixSeconds = Math.floor(Date.now() / 1000) }) {
  // First: anyone can sign with an empty secret, so a missing one must
  // refuse every delivery. This is a mistake in YOUR setup, not in the
  // delivery: check that your signing secret is set.
  if (typeof secret !== "string" || !secret.startsWith(SECRET_PREFIX) || secret.length === SECRET_PREFIX.length) {
    return { ok: false, reason: "bad_secret" };
  }
  // Digits only: a sign, a space or an exponent is not a timestamp we sent.
  if (typeof timestamp !== "string" || !/^[0-9]{1,15}$/.test(timestamp)) {
    return { ok: false, reason: "bad_timestamp" };
  }
  // Both directions: without an upper bound a future-dated delivery is valid
  // forever; without a lower one a captured delivery replays forever.
  if (Math.abs(nowUnixSeconds - Number(timestamp)) > TOLERANCE_SECONDS) {
    return { ok: false, reason: "timestamp_out_of_tolerance" };
  }
  if (typeof signature !== "string" || !signature.startsWith(SIGNATURE_PREFIX)) {
    return { ok: false, reason: "bad_signature_format" };
  }
  const expected = createHmac("sha256", Buffer.from(secret, "utf8"))
    .update(`${timestamp}.`, "utf8")
    .update(rawBody)
    .digest("hex");
  const presented = Buffer.from(signature.slice(SIGNATURE_PREFIX.length), "utf8");
  // timingSafeEqual throws on a length mismatch. The length of a SHA-256 hex
  // digest is public (64), so checking it first leaks nothing secret.
  const want = Buffer.from(expected, "utf8");
  if (presented.length !== want.length || !timingSafeEqual(presented, want)) {
    return { ok: false, reason: "signature_mismatch" };
  }
  return { ok: true, reason: "" };
}

// Using it, with node:http. Read the body as bytes, verify, THEN parse:
//
//   const chunks = [];
//   for await (const chunk of req) chunks.push(chunk);
//   const rawBody = Buffer.concat(chunks);
//   const verdict = verifyWebhook({
//     secret: process.env.NEXUS_WEBHOOK_SECRET,
//     rawBody,
//     timestamp: req.headers["x-nexus-webhook-timestamp"],
//     signature: req.headers["x-nexus-webhook-signature"],
//   });
//   if (!verdict.ok) { res.writeHead(400).end(); return; }
//   const event = JSON.parse(rawBody.toString("utf8"));
//   // Delivery is at least once: drop an event.id you have already handled.
//   res.writeHead(204).end();
```

**examples/webhooks — Python**

```
"""A Nexus402 alert-webhook verifier for Python. STANDARD LIBRARY ONLY.

Copy this file. `examples/webhooks/webhooks_test.go` signs real bodies with
the platform's own signer (`internal/alerts.Sign`) and refuses to pass unless
this code accepts the genuine signature and refuses every tampered one, so
what you copy is what our tests run.

Every delivery carries three headers:
  X-Nexus-Event-Id           the event id, also the body's `id`
  X-Nexus-Webhook-Timestamp  Unix seconds when the delivery was signed
  X-Nexus-Webhook-Signature  v1=<lowercase hex HMAC-SHA256>

The signed string is `<timestamp>.<raw body>`, and the HMAC key is your whole
signing secret as UTF-8, `whsec_` prefix included.
"""

from __future__ import annotations

import hashlib
import hmac
import re
import time

# How far either side of your clock a timestamp may be: 300 seconds. Narrower
# rejects honest deliveries on ordinary clock skew; wider accepts older
# replays of a captured delivery.
TOLERANCE_SECONDS = 300

_SIGNATURE_PREFIX = "v1="
# Every signing secret starts with this.
_SECRET_PREFIX = "whsec_"
# ASCII digits only. `str.isdigit` would accept other scripts' digits, and a
# sign, a space or an exponent is not a timestamp we sent.
_TIMESTAMP = re.compile(r"[0-9]{1,15}")


def verify_webhook(
    secret: str | None,
    raw_body: bytes,
    timestamp: str | None,
    signature: str | None,
    now: int | None = None,
) -> tuple[bool, str]:
    """Verify one delivery; returns (ok, reason).

    Call it with the RAW body bytes, before any JSON parse: re-serialising
    changes the bytes and the signature will not match.
    """
    # First: anyone can sign with an empty secret, so a missing one must
    # refuse every delivery. This is a mistake in YOUR setup, not in the
    # delivery: check that your signing secret is set.
    if not secret or not secret.startswith(_SECRET_PREFIX) or secret == _SECRET_PREFIX:
        return False, "bad_secret"
    if now is None:
        now = int(time.time())
    if timestamp is None or _TIMESTAMP.fullmatch(timestamp) is None:
        return False, "bad_timestamp"
    # Both directions: without an upper bound a future-dated delivery is
    # valid forever; without a lower one a captured delivery replays forever.
    if abs(now - int(timestamp)) > TOLERANCE_SECONDS:
        return False, "timestamp_out_of_tolerance"
    if signature is None or not signature.startswith(_SIGNATURE_PREFIX):
        return False, "bad_signature_format"
    expected = hmac.new(
        secret.encode("utf-8"),
        timestamp.encode("ascii") + b"." + raw_body,
        hashlib.sha256,
    ).hexdigest()
    presented = signature[len(_SIGNATURE_PREFIX):]
    # Bytes, not str: compare_digest refuses a str holding non-ASCII text.
    if not hmac.compare_digest(expected.encode("ascii"), presented.encode("utf-8")):
        return False, "signature_mismatch"
    return True, ""


# Using it, with any framework that gives you the body as bytes. Verify,
# THEN parse:
#
#   ok, reason = verify_webhook(
#       os.environ["NEXUS_WEBHOOK_SECRET"],
#       request.body,  # bytes, exactly as received
#       request.headers.get("X-Nexus-Webhook-Timestamp"),
#       request.headers.get("X-Nexus-Webhook-Signature"),
#   )
#   if not ok:
#       return 400
#   event = json.loads(request.body)
#   # Delivery is at least once: drop an event["id"] you have already handled.
#   return 204
```

**examples/webhooks — Go**

```
// Package webhook verifies Nexus402 alert webhooks. STANDARD LIBRARY ONLY.
//
// Copy this file into your own package. `examples/webhooks/webhooks_test.go`
// signs real bodies with the platform's own signer (`internal/alerts.Sign`)
// and refuses to pass unless this code accepts the genuine signature and
// refuses every tampered one, so what you copy is what our tests run.
//
// Every delivery carries three headers:
//
//	X-Nexus-Event-Id           the event id, also the body's `id`
//	X-Nexus-Webhook-Timestamp  Unix seconds when the delivery was signed
//	X-Nexus-Webhook-Signature  v1=<lowercase hex HMAC-SHA256>
//
// The signed string is `<timestamp>.<raw body>`, and the HMAC key is your
// whole signing secret as UTF-8, `whsec_` prefix included.
//
// Using it in a handler. Read the body as bytes, verify, THEN parse:
//
//	raw, err := io.ReadAll(io.LimitReader(r.Body, 64<<10))
//	if err != nil { http.Error(w, "", http.StatusBadRequest); return }
//	if err := webhook.Verify(secret, raw,
//		r.Header.Get("X-Nexus-Webhook-Timestamp"),
//		r.Header.Get("X-Nexus-Webhook-Signature"), time.Now()); err != nil {
//		http.Error(w, "", http.StatusBadRequest)
//		return
//	}
//	// json.Unmarshal(raw, &event). Delivery is at least once:
//	// drop an event.ID you have already handled.
//	w.WriteHeader(http.StatusNoContent)
package webhook

import (
	"crypto/hmac"
	"crypto/sha256"
	"crypto/subtle"
	"encoding/hex"
	"errors"
	"strconv"
	"strings"
	"time"
)

// ToleranceSeconds is how far either side of your clock a timestamp may be.
// Narrower rejects honest deliveries on ordinary clock skew; wider accepts
// older replays of a captured delivery.
const ToleranceSeconds = 300

const signaturePrefix = "v1="

// Every signing secret starts with this.
const secretPrefix = "whsec_"

// The reasons a delivery is refused. Each error's text is the same reason
// code the Node and Python verifiers return.
var (
	// ErrBadSecret is a mistake in YOUR setup, not in the delivery: check
	// that your signing secret is set.
	ErrBadSecret          = errors.New("bad_secret")
	ErrBadTimestamp       = errors.New("bad_timestamp")
	ErrOutOfTolerance     = errors.New("timestamp_out_of_tolerance")
	ErrBadSignatureFormat = errors.New("bad_signature_format")
	ErrSignatureMismatch  = errors.New("signature_mismatch")
)

// Verify checks one delivery against the destination's signing secret. Pass
// the RAW body bytes, before any JSON parse: re-serialising changes the bytes
// and the signature will not match. A nil error means the delivery is ours
// and recent.
func Verify(secret string, rawBody []byte, timestamp, signature string, now time.Time) error {
	// First: anyone can sign with an empty secret, so a missing one must
	// refuse every delivery.
	if rest, ok := strings.CutPrefix(secret, secretPrefix); !ok || rest == "" {
		return ErrBadSecret
	}
	// Digits only: strconv.ParseInt alone would accept a leading sign.
	if timestamp == "" || len(timestamp) > 15 || strings.Trim(timestamp, "0123456789") != "" {
		return ErrBadTimestamp
	}
	seconds, err := strconv.ParseInt(timestamp, 10, 64)
	if err != nil {
		return ErrBadTimestamp
	}
	// Both directions: without an upper bound a future-dated delivery is
	// valid forever; without a lower one a captured delivery replays forever.
	if skew := now.Unix() - seconds; skew > ToleranceSeconds || skew < -ToleranceSeconds {
		return ErrOutOfTolerance
	}
	presented, ok := strings.CutPrefix(signature, signaturePrefix)
	if !ok {
		return ErrBadSignatureFormat
	}
	mac := hmac.New(sha256.New, []byte(secret))
	mac.Write([]byte(timestamp + "."))
	mac.Write(rawBody)
	expected := hex.EncodeToString(mac.Sum(nil))
	if subtle.ConstantTimeCompare([]byte(expected), []byte(presented)) != 1 {
		return ErrSignatureMismatch
	}
	return nil
}
```

## Delivery, retries and duplicates

- **Answer `2xx` within 10 seconds.** Any `2xx` is success, and the body of your answer is ignored (we read at most 4 KiB of it). Anything else — another status, a redirect, a timeout, a refused connection, a failed TLS handshake — is a failed attempt. If you have slow work to do, answer first and do it afterwards.
- **Failed attempts are retried with backoff for 24 hours.** After that the event counts as failed for that destination.
- **Delivery is at least once.** A delivery that reached you but whose answer we never saw is sent again, so you can receive the same event twice. Remember the event `id` (also in `X-Nexus-Event-Id`) and drop one you have already handled.
- **Do not depend on order.** A retried event can arrive after a newer one. Use `created_at` if order matters to you.
- An alert reports something that has already happened. It never holds up a call, a top-up or a payout, and a failed delivery never undoes one.

### When a destination is paused

After **20 consecutive failed events** — each one already retried for 24 hours — we pause the destination. It stops receiving, we email the account, and the app shows it as paused. Fix whatever is wrong, then press **Resume** on the destination: that clears the pause and its count of failed events. A paused destination cannot send a test until it is resumed. One delivered event resets the count to zero, so only an unbroken run of failures pauses a destination.

The app shows each destination's last success, last failure and its reason, and the status code where there was one:

| Reason | What happened |
| --- | --- |
| `http_status` | Your URL answered with a status that is not `2xx`, a redirect included. The status code is shown beside it |
| `timeout` | No answer within 10 seconds |
| `connect` | The connection could not be made |
| `tls` | The TLS handshake failed, usually a certificate a public client does not trust |
| `refused_address` | The host resolved to a private, loopback or link-local address, so we did not connect |
| `invalid_url` | The stored URL no longer passes the rules above |
| `unsealed` | We could not read the destination's stored URL or secret. This one is ours, not yours; if it persists, delete the destination and add it again |

## What we do to keep this safe

- **Your secrets are encrypted at rest**: the signing secret and the Slack and Discord URLs. They are never written to a log, and our own operators see only a destination's host, never its URL.
- **Every delivery goes through the same guard as calls to creators' endpoints**: the address is resolved and checked on every connection, so a name cannot be pointed at our internal network after you save it.
- **Deliveries come from our background worker**, never from the gateway that serves paid calls, so a slow or failing webhook never slows a tool call.
