webhookd-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,24 @@
1
+ """webhookd-sdk — the official Python client for NimbusNexus Webhooks.
2
+
3
+ - :func:`verify` — verify an incoming webhook's HMAC signature (for subscribers).
4
+ - :class:`Client` — publish events to webhookd (for producers).
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from webhookd_sdk.client import Client, Event
10
+ from webhookd_sdk.errors import WebhookdAPIError, WebhookdError
11
+ from webhookd_sdk.signature import DEFAULT_TOLERANCE_SECONDS, sign, verify
12
+
13
+ __version__ = "0.1.0"
14
+
15
+ __all__ = [
16
+ "Client",
17
+ "Event",
18
+ "WebhookdAPIError",
19
+ "WebhookdError",
20
+ "DEFAULT_TOLERANCE_SECONDS",
21
+ "sign",
22
+ "verify",
23
+ "__version__",
24
+ ]
webhookd_sdk/client.py ADDED
@@ -0,0 +1,147 @@
1
+ """Typed publish client for the webhookd API."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from dataclasses import dataclass
7
+ from typing import Any
8
+
9
+ import httpx
10
+
11
+ from webhookd_sdk.errors import WebhookdAPIError, WebhookdError
12
+
13
+ _RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
14
+
15
+
16
+ @dataclass
17
+ class Event:
18
+ """The published event, as returned by ``POST /v1/events`` (webhookd's ``EventOut``)."""
19
+
20
+ id: str
21
+ event_uid: str
22
+ event_type: str
23
+ application: str
24
+ environment: str
25
+ deliveries_created: int
26
+ source: str | None = None
27
+
28
+ @classmethod
29
+ def _from_json(cls, d: dict[str, Any]) -> Event:
30
+ return cls(
31
+ id=d["id"],
32
+ event_uid=d["event_uid"],
33
+ event_type=d["event_type"],
34
+ application=d.get("application", "default"),
35
+ environment=d.get("environment", "prod"),
36
+ deliveries_created=d.get("deliveries_created", 0),
37
+ source=d.get("source"),
38
+ )
39
+
40
+
41
+ class Client:
42
+ """Publish events to webhookd.
43
+
44
+ Authenticate with a per-tenant API key (``whsk_…``) or a service token::
45
+
46
+ with Client("https://webhooks.example.com", api_key="whsk_…") as wh:
47
+ event = wh.publish("order.created", {"id": 123}, idempotency_key="order-123")
48
+
49
+ Transient failures (connection errors, 429, 5xx) are retried with exponential backoff; a 429
50
+ honours its ``Retry-After`` header. Other 4xx raise :class:`WebhookdAPIError` carrying the
51
+ server's ``{error: {code, message}}`` envelope.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ base_url: str,
57
+ api_key: str,
58
+ *,
59
+ timeout: float = 10.0,
60
+ max_retries: int = 2,
61
+ transport: httpx.BaseTransport | None = None,
62
+ ):
63
+ self._base = base_url.rstrip("/")
64
+ self._key = api_key
65
+ self._max_retries = max_retries
66
+ self._client = httpx.Client(timeout=timeout, transport=transport)
67
+
68
+ def publish(
69
+ self,
70
+ event_type: str,
71
+ payload: dict[str, Any],
72
+ *,
73
+ environment: str = "prod",
74
+ application: str = "default",
75
+ source: str | None = None,
76
+ idempotency_key: str | None = None,
77
+ ) -> Event:
78
+ """Publish one event. ``idempotency_key`` makes the publish safe to retry (a replay returns
79
+ the original event without re-fanning-out)."""
80
+ body: dict[str, Any] = {
81
+ "event_type": event_type,
82
+ "payload": payload,
83
+ "environment": environment,
84
+ "application": application,
85
+ }
86
+ if source is not None:
87
+ body["source"] = source
88
+ headers = {"Authorization": f"Bearer {self._key}"}
89
+ if idempotency_key is not None:
90
+ headers["Idempotency-Key"] = idempotency_key
91
+ resp = self._post("/v1/events", body, headers)
92
+ return Event._from_json(resp.json())
93
+
94
+ def close(self) -> None:
95
+ self._client.close()
96
+
97
+ def __enter__(self) -> Client:
98
+ return self
99
+
100
+ def __exit__(self, *_exc: object) -> None:
101
+ self.close()
102
+
103
+ # -- internals -------------------------------------------------------------
104
+ def _post(
105
+ self, path: str, json_body: dict[str, Any], headers: dict[str, str]
106
+ ) -> httpx.Response:
107
+ url = f"{self._base}{path}"
108
+ last_exc: Exception | None = None
109
+ for attempt in range(self._max_retries + 1):
110
+ try:
111
+ resp = self._client.post(url, json=json_body, headers=headers)
112
+ except httpx.HTTPError as exc:
113
+ last_exc = exc
114
+ if attempt < self._max_retries:
115
+ time.sleep(_backoff(attempt))
116
+ continue
117
+ raise WebhookdError(f"request failed: {exc}") from exc
118
+
119
+ if resp.status_code in _RETRY_STATUSES and attempt < self._max_retries:
120
+ time.sleep(_retry_after(resp) or _backoff(attempt))
121
+ continue
122
+ if resp.status_code >= 400:
123
+ raise _api_error(resp)
124
+ return resp
125
+ raise WebhookdError(f"request failed after retries: {last_exc}")
126
+
127
+
128
+ def _backoff(attempt: int) -> float:
129
+ return min(2.0, 0.2 * (2**attempt))
130
+
131
+
132
+ def _retry_after(resp: httpx.Response) -> float | None:
133
+ raw = resp.headers.get("Retry-After")
134
+ if raw and raw.isdigit():
135
+ return float(raw)
136
+ return None
137
+
138
+
139
+ def _api_error(resp: httpx.Response) -> WebhookdAPIError:
140
+ code, message = "error", resp.text
141
+ try:
142
+ err = resp.json().get("error") or {}
143
+ code = err.get("code", code)
144
+ message = err.get("message", message)
145
+ except Exception: # noqa: BLE001 - a non-JSON error body falls back to the raw text
146
+ pass
147
+ return WebhookdAPIError(resp.status_code, code, message)
webhookd_sdk/errors.py ADDED
@@ -0,0 +1,21 @@
1
+ """SDK exceptions."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class WebhookdError(Exception):
7
+ """Base class for all webhookd SDK errors (network failures, etc.)."""
8
+
9
+
10
+ class WebhookdAPIError(WebhookdError):
11
+ """A non-2xx response from the webhookd API.
12
+
13
+ Carries the M5a error envelope: a stable machine ``code`` (e.g. ``"rate_limited"``,
14
+ ``"not_found"``, ``"validation_error"``) and a human ``message``, plus the HTTP ``status_code``.
15
+ """
16
+
17
+ def __init__(self, status_code: int, code: str, message: str):
18
+ self.status_code = status_code
19
+ self.code = code
20
+ self.message = message
21
+ super().__init__(f"[{status_code} {code}] {message}")
@@ -0,0 +1,81 @@
1
+ """Verify webhookd webhook signatures.
2
+
3
+ webhookd signs every delivery as ``HMAC_SHA256(secret, f"{timestamp}.".encode() + raw_body)`` (its
4
+ default timestamped mode) and sends:
5
+
6
+ - ``X-Webhook-Signature: sha256=<hex>``
7
+ - ``X-Webhook-Timestamp: <unix-seconds>``
8
+
9
+ A subscriber MUST verify the signature to prove the request genuinely came from webhookd and was not
10
+ tampered with in transit. ``verify`` does it correctly: it rebuilds the signed bytes, enforces the
11
+ replay window against the timestamp, and compares in constant time. This mirrors
12
+ ``delivery_core.webhook_outbox.{sign,verify}`` byte-for-byte.
13
+
14
+ from webhookd_sdk import verify
15
+
16
+ if not verify(secret, request.body, request.headers["X-Webhook-Signature"],
17
+ timestamp=request.headers["X-Webhook-Timestamp"]):
18
+ return 400 # reject — forged, tampered, or replayed
19
+
20
+ Pass the EXACT bytes you received as ``raw_body`` — do not re-serialize the JSON, or the signature
21
+ won't match (webhookd signs the bytes on the wire).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import hashlib
27
+ import hmac
28
+ import time
29
+
30
+ _PREFIX = "sha256="
31
+ DEFAULT_TOLERANCE_SECONDS = 300
32
+
33
+
34
+ def _as_bytes(value: str | bytes) -> bytes:
35
+ return value if isinstance(value, bytes) else value.encode("utf-8")
36
+
37
+
38
+ def _signed_bytes(raw_body: bytes, timestamp: int | None) -> bytes:
39
+ if timestamp is None:
40
+ return raw_body
41
+ return f"{timestamp}.".encode("ascii") + raw_body
42
+
43
+
44
+ def sign(secret: str | bytes, raw_body: str | bytes, timestamp: int | None = None) -> str:
45
+ """The ``sha256=<hex>`` signature webhookd would send for ``raw_body`` (+ optional timestamp).
46
+
47
+ Mainly useful for tests; subscribers call :func:`verify`.
48
+ """
49
+ digest = hmac.new(
50
+ _as_bytes(secret), _signed_bytes(_as_bytes(raw_body), timestamp), hashlib.sha256
51
+ ).hexdigest()
52
+ return f"{_PREFIX}{digest}"
53
+
54
+
55
+ def verify(
56
+ secret: str | bytes,
57
+ raw_body: str | bytes,
58
+ signature: str,
59
+ *,
60
+ timestamp: int | str | None = None,
61
+ tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS,
62
+ now: int | None = None,
63
+ ) -> bool:
64
+ """Return ``True`` iff ``signature`` is a valid webhookd signature for ``raw_body``.
65
+
66
+ :param secret: the endpoint's signing secret (shown once at endpoint creation).
67
+ :param raw_body: the exact request body bytes received (do not re-serialize).
68
+ :param signature: the ``X-Webhook-Signature`` header (``sha256=…``; the prefix is optional).
69
+ :param timestamp: the ``X-Webhook-Timestamp`` header. When given, the signature is rejected if
70
+ it is older/newer than ``tolerance_seconds`` (replay protection) — always pass it.
71
+ :param tolerance_seconds: replay window; webhookd's default is 300s.
72
+ :param now: override the current unix time (for tests).
73
+ """
74
+ ts = int(timestamp) if timestamp is not None else None
75
+ if ts is not None:
76
+ current = int(time.time()) if now is None else now
77
+ if abs(current - ts) > tolerance_seconds:
78
+ return False
79
+ expected = sign(secret, raw_body, ts)
80
+ candidate = signature if signature.startswith(_PREFIX) else f"{_PREFIX}{signature}"
81
+ return hmac.compare_digest(expected, candidate)
@@ -0,0 +1,82 @@
1
+ Metadata-Version: 2.4
2
+ Name: webhookd-sdk
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for NimbusNexus Webhooks — publish events + verify webhook signatures.
5
+ Project-URL: Homepage, https://github.com/NimbusNexus/Webhooks-sdks/tree/develop/python#readme
6
+ Project-URL: Repository, https://github.com/NimbusNexus/Webhooks-sdks
7
+ Project-URL: Issues, https://github.com/NimbusNexus/Webhooks-sdks/issues
8
+ Author: NimbusNexus
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: hmac,nimbusnexus,sdk,signature,verify,webhook,webhooks
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Software Development :: Libraries
21
+ Requires-Python: >=3.11
22
+ Requires-Dist: httpx>=0.27
23
+ Provides-Extra: dev
24
+ Requires-Dist: mypy; extra == 'dev'
25
+ Requires-Dist: pytest; extra == 'dev'
26
+ Requires-Dist: ruff; extra == 'dev'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # webhookd-sdk (Python)
30
+
31
+ Official Python SDK for **NimbusNexus Webhooks** — publish events, and verify the webhooks you receive.
32
+
33
+ ```sh
34
+ pip install webhookd-sdk
35
+ ```
36
+
37
+ ## Verify an incoming webhook (subscribers)
38
+
39
+ When webhookd delivers a webhook it signs the body with your endpoint's signing secret. **Always
40
+ verify the signature** before trusting the payload — it proves the request really came from webhookd
41
+ and wasn't tampered with or replayed.
42
+
43
+ ```python
44
+ from webhookd_sdk import verify
45
+
46
+ # In your webhook handler — pass the RAW request body bytes (do not re-serialize the JSON):
47
+ ok = verify(
48
+ secret=ENDPOINT_SIGNING_SECRET,
49
+ raw_body=request.body,
50
+ signature=request.headers["X-Webhook-Signature"],
51
+ timestamp=request.headers["X-Webhook-Timestamp"],
52
+ )
53
+ if not ok:
54
+ return Response(status_code=400) # forged, tampered, or outside the 300s replay window
55
+ ```
56
+
57
+ ## Publish an event (producers)
58
+
59
+ ```python
60
+ from webhookd_sdk import Client, WebhookdAPIError
61
+
62
+ with Client("https://webhooks.example.com", api_key="whsk_…") as wh:
63
+ try:
64
+ event = wh.publish(
65
+ "order.created",
66
+ {"order_id": "ord_123", "total": 4200},
67
+ idempotency_key="order-123", # makes the publish safe to retry
68
+ )
69
+ print(event.event_uid, event.deliveries_created)
70
+ except WebhookdAPIError as e:
71
+ print(e.status_code, e.code, e.message) # the stable {error:{code,message}} envelope
72
+ ```
73
+
74
+ Transient failures (connection errors, `429`, `5xx`) are retried with backoff (a `429` honours
75
+ `Retry-After`); other `4xx` raise `WebhookdAPIError`.
76
+
77
+ ## Develop
78
+
79
+ ```sh
80
+ pip install -e '.[dev]'
81
+ pytest && ruff check . && mypy webhookd_sdk
82
+ ```
@@ -0,0 +1,8 @@
1
+ webhookd_sdk/__init__.py,sha256=6zonAUSFHB-fpqFWVsPPKY_W1lQezzc10rhsBGkUFIo,638
2
+ webhookd_sdk/client.py,sha256=AEMbGwO9H1IWZQwyZ09hzHwj27IrxNUfLeSYGsqLDws,4748
3
+ webhookd_sdk/errors.py,sha256=D64IwB9CsJwHKb4JhZkGmeDhnJzS9g0Bpkdy8-BITfE,680
4
+ webhookd_sdk/signature.py,sha256=Nb9iSDIAj7mQzUAsTJNyNGZsVZ9U7wSmkQwOHR0wVYA,3171
5
+ webhookd_sdk-0.1.0.dist-info/METADATA,sha256=B1oMecC_6qERBfncZXViqcKTB6Xk03ec2v2KNVcyuIU,2863
6
+ webhookd_sdk-0.1.0.dist-info/WHEEL,sha256=mffPy8wBnZQn2VnJUU5jE99KsxaSfiyMHV9Yt0aLVxs,87
7
+ webhookd_sdk-0.1.0.dist-info/licenses/LICENSE,sha256=hS9BbOZ6ifcDCGFnmJkTf-4i6DChPPi358uOIfLD4dE,1068
8
+ webhookd_sdk-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.30.1
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NimbusNexus
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.