Webhooks
Last updated: 6 December 2026 · Webhook payload version 1
A webhook means that when an event happens, hadronbox sends a POST request to your HTTPS address, so you do not have to poll for the state all the time. You add endpoints in the panel on the Webhooks page: you choose the address and the events you subscribe to, and the signing key (whsec_…) is shown once, when it is created. Managing webhook endpoints (adding, deleting, rotating the key) needs a session and cannot be done with an API key.
Events
An endpoint receives only the events it is subscribed to.
With "Send test" in the panel, a webhook.test event is sent; it is not an event you can subscribe to and is produced only for this purpose.
Request format
Every delivery comes with these headers:
Payload examples
The body of every payload starts with the fields id, version, type, at (ISO 8601, UTC) and organizationId. Only names and IDs are included; environment variables, secrets and host information are not.
{
"id": "evt_9f3a1c",
"version": 1,
"type": "machine.paused",
"at": "2026-11-20T18:46:03.000Z",
"organizationId": "org_7b2d",
"machine": "ubuntu-dev",
"machineId": "sbx_a1b2c3d4",
"reason": "idle",
"idleMinutes": 30
}
- The
machine.created,machine.resumedandmachine.deletedpayloads have noreasonandidleMinutes. - The
reasonvalue in amachine.pausedpayload can beuser,idle,max_runtime,suspended,abuse,credit_exhaustedorbudget.idleMinutesis present only whenreasonisidle. - A
snapshot.createdpayload also carries thesnapshot(name) andsnapshotIdfields;machineandmachineIdpoint to the source machine.
quota.warning
A quota.warning payload carries only numbers; it does not include the organization name, an email address or a user ID.
{
"id": "evt_4d8e02",
"version": 1,
"type": "quota.warning",
"at": "2026-11-25T09:15:00.000Z",
"organizationId": "org_7b2d",
"limitKey": "machines",
"used": 4,
"limit": 5,
"percent": 80,
"state": "warning",
"occurredAt": "2026-11-25T09:15:00.000Z"
}
limitKey:machines,snapshotsormembers.state:warning(80% of the limit and above) orexceeded(100% and above).percentis rounded down.occurredAtis the same moment asat: the evaluation in which the threshold was crossed. The warning arrives at most 15 minutes after the change and is sent once for every threshold crossing.
port.exposed
A port.exposed payload carries only IDs; it does not include the preview address, a preview token or a user ID.
{
"id": "evt_5a1b7c",
"version": 1,
"type": "port.exposed",
"at": "2026-11-28T10:20:00.000Z",
"organizationId": "org_7b2d",
"machineId": "sbx_a1b2c3d4",
"portId": "prt_9c8d7e",
"port": 3000,
"access": "private"
}
port: the port number inside the machine.access:privateorpublic.
terminal.session.started
A terminal.session.started payload carries only IDs; it does not include a ticket, a stream permit, an IP address, browser information or a user ID.
{
"id": "evt_2e6f90",
"version": 1,
"type": "terminal.session.started",
"at": "2026-11-28T10:25:00.000Z",
"organizationId": "org_7b2d",
"machineId": "sbx_a1b2c3d4",
"sessionId": "trm_3f2a1b0c",
"clientKind": "web"
}
clientKind: the client that opened the session (web,cliorsdk).
machine.tools.ready and machine.tools.failed
It arrives once when the install of the tools you chose when creating the machine, or added later, is finished. If all of them were installed, machine.tools.ready arrives; if at least one could not be installed even after the last attempt, machine.tools.failed arrives. When you add a new tool or retry a failed one, a new event arrives when the install is finished. When you start a machine you stopped, the tools are installed again; when the install is finished, an event arrives again with a new id. The same id is always the same event.
{
"id": "evt_5c1d7a20-4b3e-5f10-a2c4-9e8d7c6b5a41",
"version": 1,
"type": "machine.tools.failed",
"at": "2026-11-29T10:04:12.000Z",
"organizationId": "org_7b2d",
"machine": "ai-box",
"machineId": "sbx_a1b2c3d4",
"ready": [{ "id": "node", "version": "26.13.1" }],
"failed": [{ "id": "codex", "errorCode": "NETWORK" }]
}
ready: the tools that were installed and their fixed versions in the catalogue. In amachine.tools.readypayload,failedis empty.errorCode:NETWORK,CHECKSUM,DISK_FULL,TIMEOUT,VERIFY_FAILED,DEPENDENCY,INTERNAL,KERNEL_UNSUPPORTED(Docker: the machine's kernel is too old),DAEMON_FAILED(Docker: the service did not start),UNSUPPORTED_IMAGEorUNKNOWN.
credit.low, credit.exhausted and credit.restored
They arrive at the balance thresholds; they are produced while balance metering is on. Balance enforcement is still off: today these events do not pause machines. For every level, at most one arrives in 24 hours. The payload carries only amounts; the amounts are in kuruş and arrive as strings so that there is no number overflow.
{
"id": "evt_2f9c4a10-7d3b-4e21-b5a8-1c0d9e8f7a63",
"version": 1,
"type": "credit.exhausted",
"at": "2026-11-29T10:04:12.000Z",
"organizationId": "org_7b2d",
"balanceKurus": "0",
"cycleBaseKurus": "50000",
"occurredAt": "2026-11-29T10:04:12.000Z"
}
credit.low: the balance fell to 20% ofcycleBaseKurusor below.credit.exhausted: the balance fell to zero or below. When enforcement is turned on, running machines are paused withmachine.paused(reason:credit_exhausted); today no pausing is done.credit.restored: the balance rose above zero again. Paused machines do not resume on their own; you resume them from the panel or the API.
budget.warning and budget.exceeded
Sent at the thresholds of a spend budget, independently of balance enforcement. At most once per budget and level per month (with a 24-hour cooldown). Amounts are kurus as strings; machineId is null for the organization budget.
{
"id": "evt_5a1e2b44-0c7d-4f1a-9b6e-3d2c1b0a9f88",
"version": 1,
"type": "budget.exceeded",
"at": "2026-12-05T10:04:12.000Z",
"organizationId": "org_7b2d",
"budgetId": "bdg_4c1f",
"scope": "organization",
"machineId": null,
"limitKurus": "20000",
"spentKurus": "20130",
"percent": 100,
"action": "pause",
"periodStart": "2026-11-30T21:00:00.000Z",
"occurredAt": "2026-12-05T10:04:12.000Z"
}
budget.warning: this month’s spend reached the budget’s warning threshold.budget.exceeded: spend reached the limit. Whenactionispause, running machines in scope are paused withmachine.paused(reason:budget) and do not resume on their own.
schedule.run.completed and schedule.run.failed
The payload carries only ids, the status and numbers; it never contains the command, the output, a secret, a trigger body or a user id. The last 4 KB of the output is available in the panel and through GET /v1/schedules/{id}/runs.
{
"id": "evt_6c0d41",
"version": 1,
"type": "schedule.run.failed",
"at": "2026-12-05T00:03:10.000Z",
"organizationId": "org_7b2d",
"scheduleId": "sch_0123456789abcdef0123456789abcdef",
"machineId": "sbx_a1b2c3d4",
"runId": "run_8e2f10",
"trigger": "cron",
"status": "failed",
"exitCode": 2,
"durationMs": 10000,
"errorCode": "EXIT_NONZERO",
"consecutiveFailures": 3,
"autoDisabled": true,
"startedAt": "2026-12-05T00:03:00.000Z",
"finishedAt": "2026-12-05T00:03:10.000Z"
}
trigger:cron,urlormanual.status:succeeded,failedortimed_out; no event is sent for skipped (skipped) runs.consecutiveFailures: the number of failures in a row after this run. At 3 the job is disabled andautoDisabledistrue; to enable it again sendenabled: truewithPATCH /v1/schedules/{id}.errorCode:EXIT_NONZEROwhen the command ended with an error code,TIMEOUTwhen the time limit was exceeded; the related error code such asBUDGET_EXCEEDEDorCREDIT_INSUFFICIENTwhen the machine could not be resumed.nullon a successful run.
agent.run.completed and agent.run.failed
Sent when an agent run ends. A cancelled run sends no event. The payload carries no task text, output or secret value; read the output and the change summary with GET /v1/agent-runs/{id}.
{
"id": "evt_9c3b7e10-52a4-4d2e-8f1b-6a0d4c2e7b13",
"version": 1,
"type": "agent.run.completed",
"at": "2026-12-06T10:42:07.000Z",
"organizationId": "org_7b2d",
"runId": "run_0f8e6c1a2b3c4d5e8f90123456789abc",
"machineId": "sbx_ar_3f2a9c1d4e5b6a7c8d9e0f12",
"status": "succeeded",
"agent": "claude-code",
"repoUrl": "https://github.com/acme/web",
"branch": "main",
"exitCode": 0,
"changedFiles": 3,
"failureReason": null,
"startedAt": "2026-12-06T10:31:44.000Z",
"finishedAt": "2026-12-06T10:42:07.000Z",
"occurredAt": "2026-12-06T10:42:07.000Z"
}
agent.run.completed:statusissucceeded.agent.run.failed:statusisfailedortimed_out;failureReasongives the cause (for exampleclone_failed,agent_failed).machineIdisnullwhen the machine was never created.
Signature verification
Always verify with the signature that a request came from hadronbox and was not changed on the way. The signature header looks like this:
X-Hadronbox-Signature: t=1763664363,v1=727a49f805c1eb55f8289dfa908bde1cb0faf4977061720aeaf18ee9d8c02492
The algorithm:
- Split the header by commas; take
t(the unix time in seconds, the time of the delivery attempt) and one or morev1values. - Build the signed text: the
tvalue, a dot and the raw request body (<t>.<raw body>). Do not parse the body and serialize it again; use it as it came, byte for byte. - Using the whole signing key (the
whsec_…string, UTF-8) as the key, compute HMAC-SHA256 and convert it to lowercase hexadecimal text. - Compare it with one of the
v1values in constant time (timingSafeEqual,compare_digest). Do not use a plain==. - If the difference between
tand the current time is greater than 300 seconds, reject the request. This check only prevents replaying a request older than 300 seconds. - After the signature is verified, parse the body and remove duplicates with the
idin the body; if there is noid, reject the request. The headers (includingX-Hadronbox-Event-Id) are not signed: someone who resends a delivery captured within the 300-second window with the same body and signature but a different header can get around a duplicate check that relies on a header.
Every attempt is signed again with its own time: on a retry the body is the same, while t and the signature are new. If you rotate the signing key in the panel, the old key stops working at once.
Node.js example
Node.js 20 or later; it needs no dependencies. Save the file as verify-webhook.mjs. verifyWebhook only verifies the signature; handleWebhook also parses the body and removes duplicates with the id in the signed body. You call both from your own server with the raw body; the file also runs from the command line (see the test vector section below).
import { createHmac, timingSafeEqual } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
const TOLERANCE_SECONDS = 300;
/**
* X-Hadronbox-Signature: t=<unix seconds>,v1=<HMAC-SHA256(secret, `${t}.${raw body}`) hexadecimal>
* rawBody: the body of the request, byte for byte (a Buffer or a string).
* Returns: 'valid' | 'malformed' | 'expired' | 'mismatch'
*/
export function verifyWebhook(secret, signatureHeader, rawBody, nowMs = Date.now()) {
if (typeof signatureHeader !== 'string' || signatureHeader.length === 0 || signatureHeader.length > 1024) {
return 'malformed';
}
let timestamp;
const candidates = [];
for (const part of signatureHeader.split(',')) {
const eq = part.indexOf('=');
if (eq <= 0) return 'malformed';
const key = part.slice(0, eq).trim();
const value = part.slice(eq + 1).trim();
if (key === 't') {
if (!/^\d{1,12}$/.test(value)) return 'malformed';
timestamp = Number(value);
} else if (key === 'v1') {
candidates.push(value);
}
}
if (timestamp === undefined || candidates.length === 0) return 'malformed';
if (Math.abs(Math.floor(nowMs / 1000) - timestamp) > TOLERANCE_SECONDS) return 'expired';
// Key: the whsec_… string itself (UTF-8). Signed text: "<t>.<raw body>".
const expected = createHmac('sha256', Buffer.from(secret, 'utf8'))
.update(`${timestamp}.`)
.update(rawBody)
.digest('hex');
const expectedBytes = Buffer.from(expected, 'utf8');
const match = candidates.some((candidate) => {
const candidateBytes = Buffer.from(candidate, 'utf8');
return candidateBytes.length === expectedBytes.length && timingSafeEqual(candidateBytes, expectedBytes);
});
return match ? 'valid' : 'mismatch';
}
/**
* Handles a delivery from start to end: verifies the signature, parses the body and removes duplicates with the `id`
* of the signed body. The `X-Hadronbox-Event-Id` header is NOT signed: someone who resends a delivery captured within
* the 300-second window with a different header gets around a header check, but not a check on the `id` in the body.
* seenEventIds: a store with `has` and `add` (a Set in the example; use a persistent store in production).
* Returns: { status, result, event? }; result: 'ok' | 'duplicate' | 'invalid_body' | the result of verifyWebhook
*/
export function handleWebhook(secret, signatureHeader, rawBody, seenEventIds, nowMs = Date.now()) {
const result = verifyWebhook(secret, signatureHeader, rawBody, nowMs);
if (result !== 'valid') return { status: 401, result };
let event;
try {
event = JSON.parse(typeof rawBody === 'string' ? rawBody : Buffer.from(rawBody).toString('utf8'));
} catch {
return { status: 400, result: 'invalid_body' };
}
// Without an `id` in the body we cannot identify the event: reject (do not fall back to the header, it is not signed).
if (event === null || typeof event !== 'object' || typeof event.id !== 'string' || event.id === '') {
return { status: 400, result: 'invalid_body' };
}
if (seenEventIds.has(event.id)) return { status: 200, result: 'duplicate' }; // A redelivery: do not process it, return 2xx.
seenEventIds.add(event.id);
return { status: 200, result: 'ok', event };
}
// Command line: HADRONBOX_WEBHOOK_SECRET=whsec_… node verify-webhook.mjs [--now <unix seconds>] "<signature header>" < body.json
// Prints the result; the exit code is 0 only for 'valid'.
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
const args = process.argv.slice(2);
const nowIndex = args.indexOf('--now');
const nowMs = nowIndex === -1 ? Date.now() : Number(args.splice(nowIndex, 2)[1]) * 1000;
const secret = process.env.HADRONBOX_WEBHOOK_SECRET;
if (!secret || args.length !== 1) {
console.error('Usage: HADRONBOX_WEBHOOK_SECRET=whsec_… node verify-webhook.mjs [--now <unix seconds>] "<signature header>" < body.json');
process.exit(2);
}
const result = verifyWebhook(secret, args[0], readFileSync(0), nowMs);
console.log(result);
process.exit(result === 'valid' ? 0 : 1);
}
Using it with Express: do not parse the body with express.json(); the signature is over the raw body, so use express.raw.
import express from 'express';
import { handleWebhook } from './verify-webhook.mjs';
const app = express();
const seenEventIds = new Set(); // In memory for the example; use a persistent store in production.
app.post('/hadronbox/webhook', express.raw({ type: 'application/json', limit: '1mb' }), (req, res) => {
// Duplicates are detected with the `id` in the signed body; the X-Hadronbox-Event-Id header is not signed.
const { status, result, event } = handleWebhook(
process.env.HADRONBOX_WEBHOOK_SECRET,
req.get('X-Hadronbox-Signature'),
req.body,
seenEventIds,
);
if (event) console.log(`${event.type} (${event.id})`); // Ignore unknown fields and event types.
res.status(status).send(result); // Answer fast (10-second limit), queue the heavy work.
});
app.listen(3000);
Python example
Python 3.8 or later; the standard library only. Save the file as verify_webhook.py; provide the HADRONBOX_WEBHOOK_SECRET environment variable and run python3 verify_webhook.py to start a receiver on port 3000. The verify_webhook and handle_delivery functions take the raw body as bytes; handle_delivery removes duplicates with the id in the signed body. The receiver rejects a request whose Content-Length header is missing or invalid with 400, and a body larger than 1 MiB with 413 without reading it.
import hashlib
import hmac
import json
import os
import re
import time
from http.server import BaseHTTPRequestHandler, HTTPServer
TOLERANCE_SECONDS = 300
def verify_webhook(secret, signature_header, raw_body, now=None):
"""X-Hadronbox-Signature: t=<unix seconds>,v1=<HMAC-SHA256(secret, "<t>.<raw body>") hexadecimal>
raw_body: bytes. Returns: 'valid' | 'malformed' | 'expired' | 'mismatch'
"""
if not isinstance(signature_header, str) or not signature_header or len(signature_header) > 1024:
return "malformed"
timestamp = None
candidates = []
for part in signature_header.split(","):
key, sep, value = part.partition("=")
key, value = key.strip(), value.strip()
if not sep or not key:
return "malformed"
if key == "t":
if not re.fullmatch(r"[0-9]{1,12}", value):
return "malformed"
timestamp = int(value)
elif key == "v1":
candidates.append(value)
if timestamp is None or not candidates:
return "malformed"
current = int(time.time() if now is None else now)
if abs(current - timestamp) > TOLERANCE_SECONDS:
return "expired"
# Key: the whsec_… string itself (UTF-8). Signed text: "<t>.<raw body>".
signed = f"{timestamp}.".encode("utf-8") + raw_body
expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
if any(hmac.compare_digest(c.encode("utf-8"), expected.encode("utf-8")) for c in candidates):
return "valid"
return "mismatch"
def handle_delivery(secret, signature_header, raw_body, seen_event_ids, now=None):
"""Handles a delivery from start to end: verifies the signature, parses the body, removes duplicates with the ``id`` of the signed body.
The X-Hadronbox-Event-Id header is NOT signed: someone who resends a delivery captured within the 300-second window
with a different header gets around a header check, but not a check on the ``id`` in the body.
seen_event_ids: a store that supports ``in`` and ``add`` (a set in the example; use a persistent store in production).
Returns: (status code, result, event); result: 'ok' | 'duplicate' | 'invalid_body' | the result of verify_webhook
"""
result = verify_webhook(secret, signature_header, raw_body, now)
if result != "valid":
return 401, result, None
try:
event = json.loads(raw_body.decode("utf-8"))
except ValueError:
return 400, "invalid_body", None
# Without an id in the body we cannot identify the event: reject (do not fall back to the header, it is not signed).
event_id = event.get("id") if isinstance(event, dict) else None
if not isinstance(event_id, str) or not event_id:
return 400, "invalid_body", None
if event_id in seen_event_ids:
return 200, "duplicate", None # The same event was delivered again: do not process it, return 2xx.
seen_event_ids.add(event_id)
return 200, "ok", event
SECRET = os.environ.get("HADRONBOX_WEBHOOK_SECRET", "")
MAX_BODY_BYTES = 1024 * 1024 # Webhook payloads are small; reject a larger body without reading it.
seen_event_ids = set() # In memory for the example; use a persistent store in production.
class Receiver(BaseHTTPRequestHandler):
def do_POST(self):
length_header = self.headers.get("Content-Length", "").strip()
if not re.fullmatch(r"[0-9]{1,12}", length_header):
return self._reply(400, "invalid content-length") # A missing, negative or non-numeric value.
length = int(length_header)
if length > MAX_BODY_BYTES:
return self._reply(413, "body too large")
# The signature is computed over the RAW body: verify it before parsing the JSON.
raw_body = self.rfile.read(length)
status, result, event = handle_delivery(
SECRET, self.headers.get("X-Hadronbox-Signature", ""), raw_body, seen_event_ids
)
if event is not None:
print(event.get("type"), event["id"]) # Ignore unknown fields and event types.
return self._reply(status, result) # Answer fast (10-second limit), queue the heavy work.
def _reply(self, status, text):
body = text.encode("utf-8")
self.send_response(status)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
if not SECRET:
raise SystemExit("HADRONBOX_WEBHOOK_SECRET is not set")
HTTPServer(("", int(os.environ.get("PORT", "3000"))), Receiver).serve_forever()
Test vector
Test your own implementation with these values. Give the t value as now (the current time); otherwise it returns expired because of the timeout.
With the Node.js example (--now makes the current time t):
First set the HADRONBOX_WEBHOOK_SECRET environment variable to the signing key in the table above (for example with export); the commands read the value from it.
printf '%s' '{"id":"evt_1","type":"machine.paused"}' \
| node verify-webhook.mjs --now 1763664363 \
't=1763664363,v1=727a49f805c1eb55f8289dfa908bde1cb0faf4977061720aeaf18ee9d8c02492'
The output must be valid. For Python, the call verify_webhook(secret, header, body_bytes, now=1763664363) must return "valid". You can produce the same value in the shell (the hexadecimal text at the end of the output is the expected signature):
printf '%s' '1763664363.{"id":"evt_1","type":"machine.paused"}' \
| openssl dgst -sha256 -hmac "$HADRONBOX_WEBHOOK_SECRET"
If a single byte in the body changes (including a trailing space) or the key is different, verification returns mismatch. The examples return the result valid, malformed, expired or mismatch.
Response, retries and being disabled
- Your address must answer with
2xxwithin 10 seconds. Redirects (3xx) are not followed and count as failures; the response body is not stored. - A failed delivery is tried 4 times in total: the first attempt, then after 10 seconds, 60 seconds and 300 seconds. Answer fast and put heavy work in a queue.
- You can receive the same event more than once (a retry or a redelivery). After the signature is verified, remove the duplicate with the
idin the body (theX-Hadronbox-Event-Idheader carries the same value but is not signed) and make your processing idempotent. - If 15 deliveries in a row fail, the endpoint is disabled automatically; you can enable it again from the panel.
- The target address must be a public HTTPS address. Private and local network addresses (for example
10.0.0.0/8,127.0.0.1) are blocked. - Delivery records are kept for 30 days.
Redelivery
You can send an event you missed again in the panel on the Webhooks page, with "Resend" in the "Deliveries" list of the endpoint (owner and admin). A redelivery:
- Sends the same payload of the event again; the
idin the body (andX-Hadronbox-Event-Id) is the same as the original event's, andX-Hadronbox-Delivery-Idis new. Every attempt is signed with a newt, so your signature verification does not change. - Uses the same retry rules (4 attempts) and counts toward the consecutive failure counter.
- Cannot be done for events older than 30 days, test deliveries, deliveries that are still pending, disabled endpoints and events the endpoint no longer subscribes to.
- At most 10 redeliveries per minute can be made per endpoint.
Versioning
The body of every payload has the field "version": 1 and every delivery has the header X-Hadronbox-Webhook-Version: 1. The payload version is independent of the HTTP API version.
- Changes that are not breaking are published in the same version and written to the changelog: a new event type, a new field in a payload, a new value in fields such as
reason. That is why your receiver must ignore unknown fields, event types andreasonvalues. - A breaking change (removing an event or a field, changing a field type or the signature format) comes with a new payload version. A deprecation is announced at least 6 months in advance; the schema is not changed silently.