Cabinhub News API v1.0.0

Docs / Webhooks

Webhooks

We POST one signed item.published event per configured endpoint. Here is the envelope, the retry contract, the SSRF rules, and a verification snippet in Python and JavaScript.

Delivery response lookup

503 · Service unavailable

The dispatcher retries 5xx responses within the attempt budget. Defaults are three total attempts, with backoff starting at 30 seconds and ±25% jitter. After the last attempt the event is dead-lettered.

2xx · Acknowledged

The dispatcher marks the delivery complete. Store the delivery ID with your processed event to handle a duplicate safely.

408 / 425 / 429 · Temporary rejection

The dispatcher retries with backoff within the configured attempt budget. Use the stable delivery ID to correlate attempts.

Other 4xx · Rejected

The dispatcher dead-letters the delivery immediately. Correct the receiver and ask an operator to replay the affected delivery.

Connection failure or timeout

The attempt is retryable. Check the receiver’s TLS, connectivity and response latency, then use the delivery ID to find the next attempt.

Verify raw bytes, then parse

v1 = HMAC-SHA256(secret, "<t>." + raw_body_bytes). Recompute it before any JSON parse or framework body middleware, compare in constant time, and reject a timestamp more than 300 seconds from your clock.

Signature verification

Two implementations, both checked against a signature produced by the product code. The fixture below is rebuilt and re-verified on every build of this site.

Fixture secret
whsec_test_cross_language
Timestamp t
1793825760
Header
t=1793825760,v1=ee458438dc51d59c5ba5f31dda86c5cc6cf8849b7cd06017ed5f31fbef6a3912
Recomputed
v1=ee458438dc51d59c... matches the fixture

Fixture: clients/typescript/test/fixtures/webhook_signature.json, produced by backend/app/webhooks.py::sign + build_body and consumed by both client suites.

Verification, Python

Source: docs/WEBHOOKS.md §5.

Framework-agnostic: pass the raw request body and the header value.

Python
import hashlib
import hmac
import time

TOLERANCE_SECONDS = 300


def verify(secret: str, header: str, body: bytes, now: float | None = None) -> bool:
    """True only for a fresh, correctly signed delivery."""
    parts = dict(
        piece.split("=", 1) for piece in (header or "").split(",") if "=" in piece
    )
    timestamp, signature = parts.get("t", ""), parts.get("v1", "")
    if not timestamp.isdigit() or not signature:
        return False
    if abs(int(time.time() if now is None else now) - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(
        secret.encode("utf-8"),
        timestamp.encode("ascii") + b"." + body,
        hashlib.sha256,
    ).hexdigest()
    return hmac.compare_digest(expected, signature.lower())

FastAPI/Starlette note: await request.body() gives the raw bytes. Do not use a parsed model and re-serialise it before verifying — key order, spacing and ensure_ascii would no longer match.

Verification, JavaScript

Source: docs/WEBHOOKS.md §6.

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

const TOLERANCE_SECONDS = 300;

export function verifySignature(secret, header, rawBody, now = Math.floor(Date.now() / 1000)) {
  const parts = new Map();
  for (const piece of String(header || "").split(",")) {
    const at = piece.indexOf("=");
    if (at > 0) parts.set(piece.slice(0, at).trim(), piece.slice(at + 1).trim());
  }
  const timestamp = parts.get("t");
  const signature = parts.get("v1");
  if (!timestamp || !/^\d+$/.test(timestamp) || !signature) return false;
  if (Math.abs(now - Number(timestamp)) > TOLERANCE_SECONDS) return false;

  const expected = createHmac("sha256", secret)
    .update(`${timestamp}.`)
    .update(rawBody)              // raw bytes, before any JSON.parse
    .digest("hex");
  const a = Buffer.from(expected, "utf8");
  const b = Buffer.from(signature.toLowerCase(), "utf8");
  return a.length === b.length && timingSafeEqual(a, b);
}

Express note: mount express.raw({ type: "application/json" }) on the webhook route so req.body is the untouched Buffer. With express.json() the body is already parsed and the signature will not match.

Browser note: if you must verify in a browser, the same scheme works with WebCrypto (crypto.subtle.importKey → HMAC/SHA-256 → sign), but a browser is the wrong trust boundary — verify on your server.

Envelope, retries and dead-lettering

What you receive

One event type today: item.published. It is sent once per (item, endpoint) pair. Withheld items are never enqueued, and an item that is missing or not clean at enqueue time is counted and skipped, never raised.

Text
POST <your endpoint>
Content-Type: application/json
User-Agent: CabinhubNews-Webhooks/1.0
X-Cabinhub-Signature: t=1762378800,v1=2d9b6c270b15515472723ff247b8e8f113a87ad14e69cf187040847d51e34b81
X-Cabinhub-Delivery-Id: whk_9c8c3ee2af7324d8b995f6c898ba2f0b
X-Cabinhub-Attempt: 1

{"delivered_at":"2026-11-04T21:40:00Z","event":"item.published","id":"...","item":{...},"locale":"en"}

1.0 Headers

HeaderMeaning
X-Cabinhub-Signaturet=<unix seconds>,v1=<hex HMAC>. See §2
X-Cabinhub-Delivery-IdIdempotency key for this event to this subscription. Identical on every retry and after an operator requeue; different for a different endpoint. Deduplicate on this
X-Cabinhub-Attempt1-based attempt number: 1 on the first POST, 2 on the first retry, and so on. Informational

The body is compact JSON (separators=(",", ":")) with sorted keys, UTF-8, ensure_ascii=False. Those properties are part of the contract: they are what lets you reproduce the signed bytes exactly (§3).

1.1 Envelope

FieldTypeMeaning
eventstringitem.published today. Branch on it; treat an unknown event as ignorable, not an error
idstringThe item id. Deduplicate on this
localestringThe item's locale (en or zh-Hans), mirrored at the top level for filtering
delivered_atstringRFC3339 UTC, second resolution, the time of this attempt. A retry carries a new delivered_at
itemobjectThe item payload frozen at enqueue time — the same object the API stores

1.2 The item object

item is the stored API item: the exact Item.to_api() document described in docs/API.md §11. Two read-time additions are not present, because the event is serialised from the stored row, not from an HTTP response:

A later edit to the stored item never changes an event already queued: the payload is copied into the outbox at enqueue time.

1.3 A complete event

This body was produced by webhooks.build_body() from a real stored item:

JSON
{
  "delivered_at": "2026-11-04T21:40:00Z",
  "event": "item.published",
  "id": "11111111-1111-5111-9111-111111111111",
  "item": {
    "assets": {
      "title_image_aspect": "16:9",
      "title_image_prompt": "Federal Reserve building, editorial style"
    },
    "body": "The Federal Reserve kept its target range for the federal funds rate unchanged on Wednesday, saying that core inflation had cooled to 2.4 percent while the labour market remained firm. Policymakers repeated that further adjustments would depend on incoming data rather than a preset path.",
    "bullets": ["Bullet one", "Bullet two"],
    "category": "central_banks",
    "claims": [
      {
        "confidence": 0.92,
        "source_span": "left the target range unchanged",
        "text": "The committee left its target range unchanged."
      }
    ],
    "compliance": {
      "policy_version": "2026-11-04.2",
      "reason_codes": ["CLEAN"],
      "risk_score": 0.0,
      "status": "clean"
    },
    "entities": {"countries": ["US"], "instruments": ["USD"], "organizations": ["Federal Reserve"]},
    "id": "11111111-1111-5111-9111-111111111111",
    "importance": 0.94,
    "locale": "en",
    "market_data": {"as_of": "2026-11-03T18:00:00Z", "change_pct": -0.21, "price": 104.12, "symbol": "DXY"},
    "published_at": "2026-11-03T18:00:00Z",
    "schema_version": 1,
    "source": {
      "canonical_url": "https://www.federalreserve.gov/newsevents/pressreleases/monetary20261103a.htm",
      "name": "Federal Reserve — Monetary Policy",
      "retrieved_at": "2026-11-03T18:03:00Z",
      "url": "https://www.federalreserve.gov/newsevents/pressreleases/monetary20261103a.htm"
    },
    "summary": "Officials left the target range unchanged and repeated that further moves depend on incoming data, not a preset path.",
    "title": "Fed holds policy rate as core inflation cools to 2.4%",
    "updated_at": "2026-11-03T18:07:00Z"
  },
  "locale": "en"
}

(Shown pretty-printed for reading. The bytes on the wire are compact, one line, sorted keys.)

Signature header

The only signature is X-Cabinhub-Signature, version v1:

Text
X-Cabinhub-Signature: t=<unix seconds>,v1=<hex>
Text
signed_payload = str(t) + "." + body_bytes
v1             = hmac_sha256_hex(secret, signed_payload)

The secret is the value of NEWS_WEBHOOK_SECRET on our side and the shared secret we gave you. It is never sent in a header or a body.

Verification rules a correct client implements, all enforced by our reference verifier:

  1. Parse t and v1 out of the header; a missing or non-numeric t, or a missing v1, is invalid — do not continue to compare.
  2. Reject when abs(now - t) > 300 seconds. This is the replay window in both directions: a captured event cannot be replayed later, and a badly skewed clock cannot be used to replay it earlier.
  3. Recompute the HMAC over the raw bytes you received, before any JSON parsing, re-serialisation or framework body middleware rewrites them.
  4. Compare with a constant-time function (hmac.compare_digest, crypto.timingSafeEqual).
  5. Only then parse JSON and act on it.

Tolerance is exactly 300 seconds (SIGNATURE_TOLERANCE_SECONDS). Header order and whitespace are not significant: v1=…, t=… verifies (measured).

Response contract, retries and dead-lettering

Your endpoint must answer any 2xx to acknowledge. The dispatcher treats the response as follows:

Your statusOutcome
2xxdelivered; the row is finished and never sent again
408, 425, 429retried with backoff
5xxretried with backoff
any other 4xx (e.g. 400, 401, 403, 404, 410)dead-lettered immediately — retrying a rejected request only repeats the rejection
timeout (default 10 s), DNS/TLS/connect errorretried with backoff

Retry budget and schedule, from NEWS_WEBHOOK_MAX_ATTEMPTS (default 3, clamped to 1..10), NEWS_WEBHOOK_BACKOFF (base delay, default 30 s, doubling per attempt) and NEWS_WEBHOOK_JITTER (default 0.25 = ±25 %):

AttemptSent at (defaults)If it fails again
1at enqueueretry after 30 s ± 25 % (22.5 – 37.5 s)
2~30 sretry after 60 s ± 25 % (45 – 75 s)
3~90 sdead — no further attempt

The delay before attempt n+1 is backoff * 2**(n-1) multiplied by a per-event factor inside 1 ± jitter. The jitter is deterministic per (event, attempt), so a retry is reproducible in a support investigation, while a batch of events that failed together (a customer deploy, a network blip) spreads out instead of retrying in lockstep. Set NEWS_WEBHOOK_JITTER=0 to get the exact column above.

The attempt counter and the next-attempt time live in the outbox row, so a dispatcher restart continues the existing backoff instead of resetting it. The worker never sleeps on a customer's behalf; a retry is simply not due until its stored time.

Dead-lettering, not loss. After the last attempt the row becomes status = 'dead' with attempts and last_error (HTTP 500: ..., ConnectError: ...). It is never deleted and never silently dropped. It is queryable three ways:

Shell
# 1. the operator CLI (one JSON line, no network, exit 0)
python -m app.workers.webhook_worker --list-dead --limit 50 --db /path/news.db
# 2. one scoped requeue, then it is delivered again with its ORIGINAL Delivery-Id
python -m app.workers.webhook_worker --requeue-dead --db /path/news.db
# 3. SQL
sqlite3 /path/news.db "select item_id, endpoint, attempts, last_error \
  from webhook_outbox where status='dead' order by updated_at desc limit 20;"

webhooks.dead_letters() and webhooks.requeue_dead(item_id=..., endpoint=...) are the Python surface behind those commands. A requeue resets the attempt budget, so fix the endpoint first or the row will simply die again after the same number of attempts.

Delivery is at-least-once. A retried event keeps the same id, the same frozen item and the same X-Cabinhub-Delivery-Id; only delivered_at, X-Cabinhub-Attempt and the signature timestamp change. Deduplicate on X-Cabinhub-Delivery-Id (§3.1).

Ordering is per subscription. For one endpoint, events are delivered in submission order: an event that is waiting out a backoff is never overtaken by a later one, so you will not see item 2 before item 1 of the same subscription. Different subscriptions are independent — a stalled endpoint never delays another customer. The cost of that guarantee is deliberate head-of-line blocking on one subscription, bounded by the attempt cap: the head either delivers or dead-letters, and the stream continues.

One slow endpoint cannot stall the worker. Every POST carries a hard request timeout (NEWS_WEBHOOK_TIMEOUT, default 10 s). After NEWS_WEBHOOK_ENDPOINT_FAILURE_LIMIT (default 2) consecutive transport failures (timeout / DNS / TLS / connect) to the same endpoint, the rest of that endpoint's rows are left untouched for this pass — no attempt is burned and no backoff is inflated — and the pass continues with the other endpoints. A 4xx or 5xx answer is a live endpoint and never trips this; only silence does.

Endpoint refusals are dead letters too. If an endpoint fails the SSRF guard at delivery time — configuration changed, a hostname now resolves to a private address — the row dies with endpoint refused: <reason>. That is our configuration problem, not yours; tell your account contact.

Configuration behaviour:

Endpoint requirements (SSRF policy)

Endpoints come only from the server's own environment (NEWS_WEBHOOK_ENDPOINTS), never from a request body. Each candidate URL is checked before use and again before every delivery:

If you need a private-network receiver, talk to your account contact before integration; there is no customer-facing override. With NEWS_WEBHOOK_ALLOW_PRIVATE=1 (local testing only) http:// is additionally accepted for a loopback/private target, because a test receiver on 127.0.0.1 has no certificate; http:// to a public host stays refused in every mode.

How the snippets were verified

A signature was produced by the product code itself, not by either snippet:

Python
body = webhooks.build_body(item, delivered_at="2026-11-04T21:40:00Z")
header = webhooks.sign(secret, 1762378800, body)
# t=1762378800,v1=2d9b6c270b15515472723ff247b8e8f113a87ad14e69cf187040847d51e34b81
webhooks.verify_signature(header, body, secret, now=1762378800)  # True

Both published snippets were then executed against that exact body and header:

CheckPython snippetJavaScript snippet
correct signature, now = tTruetrue
body with one appended byteFalsefalse
now = t + 301Falsefalse

The reverse direction was checked too: an HMAC computed independently (plain hmac.new(secret, "1762378800." + body, sha256)) was accepted by webhooks.verify_signature, and a wrong secret was rejected. A header with the fields in the other order and inner spaces (v1=..., t=...) was also accepted.

Dispatcher behaviour, executed on a temporary database (fake transport, real app.webhooks functions):

ScenarioResult
endpoint answers 500, then 200 on the next passrow pending after 1 attempt with last_error: HTTP 500: ...; delivered after attempt 2; the two attempts were signed t=1000 and t=2000 (a fresh signature per attempt)
endpoint answers 410dead after 1 attempt
endpoint answers 503 three times (default max attempts 3)dead after 3 attempts, last_error: HTTP 503: ...
NEWS_WEBHOOK_BACKOFF=30, endpoint keeps failingnext_attempt_at was +30 s after attempt 1 and +60 s after attempt 2
no NEWS_WEBHOOK_ENDPOINTSone pass prints status: "disabled", endpoints: 0, exit 0, zero network calls
endpoint set, no NEWS_WEBHOOK_SECRETone pass prints status: "config_error", exit 2, rows left pending
NEWS_WEBHOOK_ENDPOINTS=http://127.0.0.1:9/hookrejected at load: scheme 'http' refused; only https is allowed

8.1 Real end-to-end run (2026-11-08, this worktree)

A live 127.0.0.1 HTTP receiver, verifying the HMAC with its own implementation, driven through the SHIPPED CLI (python -m app.workers.webhook_worker --once) as a subprocess — not through a fake transport:

PassReceiver answeredWorkerRow afterwards
1500rc=1, retried=1pending, attempts=1, backoff 12.0 s, last_error='HTTP 500'
2 (immediately)—rc=0, due=0unchanged: the backoff window is honoured, 0 new POSTs
3 (after 12 s)200rc=0, delivered=1delivered, attempts=2
4 (fresh item)400rc=0, dead=1dead, attempts=1, last_error='HTTP 400'

Both POSTs in passes 1 and 3 carried signature_ok=True at the receiver, a timestamp inside the 300 s window, the same X-Cabinhub-Delivery-Id (a whk_… value, stable across the two attempts) and X-Cabinhub-Attempt 1 then 2. The receiver's own record of the second attempt was +27.8 s after the first, i.e. the 12 s backoff plus the two worker process starts — the retry really did happen on the wall clock, not inside one process. --list-dead then printed the dead row with its last_error: "HTTP 400".

8.2 Mutation arms (the tests can fail)

Each arm below was applied to app/webhooks.py and the named test went RED (10/10), with a control run GREEN before and after:

PatchTest that caught it
timestamp window removedtest_signature_rejects_tampered_body_wrong_secret_and_stale_timestamp
jitter disabledtest_backoff_is_exponential_jittered_and_bounded
per-subscription ordering removedtest_same_subscription_is_delivered_in_submission_order
endpoint breaker removedtest_endpoint_that_never_answers_is_skipped_after_the_failure_limit
delivery id randomised per attempttest_delivery_id_is_stable_across_retries_and_distinct_per_endpoint
attempt header pinned to 1test_delivery_id_is_stable_across_retries_and_distinct_per_endpoint
outbound timeout droppedtest_outbound_post_carries_the_configured_timeout
5xx treated as permanenttest_retry_then_dead_letter_after_three_attempts
dead letters unreadabletest_dead_letter_is_queryable_and_requeue_resets_the_budget
requeue does not reset attemptstest_dead_letter_is_queryable_and_requeue_resets_the_budget