betyebo 0.1.0__tar.gz

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.
betyebo-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 REDX Contributors
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.
betyebo-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,168 @@
1
+ Metadata-Version: 2.4
2
+ Name: betyebo
3
+ Version: 0.1.0
4
+ Summary: Unified webhook verification, parsing, and testing for Python
5
+ Author: REDX Contributors
6
+ License: MIT
7
+ Keywords: webhooks,stripe,github,shopify,fastapi,security
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Software Development :: Libraries
14
+ Classifier: Typing :: Typed
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest>=7.4; extra == "dev"
20
+ Dynamic: license-file
21
+
22
+ # Betyebo
23
+
24
+ Webhooks sound simple: get a POST, do the thing.
25
+
26
+ Then real life happens. Every provider signs stuff differently, wants different headers, and fails in its own special way.
27
+
28
+ Betyebo gives you one small Python interface for the annoying parts: check the signature safely, parse the payload, and get back a clean event object you can actually work with.
29
+
30
+ ## What it’s good for
31
+
32
+ - **Checking signatures properly** (using the raw request body, not JSON you rebuilt yourself).
33
+ - **Not learning every provider’s quirks** — same basic API across providers.
34
+ - **Getting a clean event** (`type`, `id`, `data`, `raw`, etc.) instead of digging through raw payloads everywhere.
35
+ - **Testing without pain** — it can sign test payloads for you, so you don’t have to hand-roll HMAC code in tests.
36
+
37
+ Supported right now: **Stripe**, **GitHub**, **Shopify**, **Slack**, plus a **GenericHMAC** adapter for simple HMAC-signed webhooks.
38
+
39
+ ## Install (local/dev)
40
+
41
+ ```bash
42
+ pip install -e .
43
+ ```
44
+
45
+ ## Quick start
46
+
47
+ ```python
48
+ from betyebo import WebhookSDK, Stripe, GitHub
49
+
50
+ sdk = WebhookSDK()
51
+ sdk.register(Stripe(secret="whsec_..."))
52
+ sdk.register(GitHub(secret="github_secret"))
53
+
54
+ # Important: pass the raw request body bytes.
55
+ event = sdk.verify_and_parse(
56
+ provider="stripe",
57
+ payload=raw_body_bytes,
58
+ headers=request_headers,
59
+ )
60
+
61
+ print(event.provider) # "stripe"
62
+ print(event.type) # e.g. "invoice.paid"
63
+ print(event.id) # provider event id (when available)
64
+ print(event.data) # the useful payload/object
65
+ ```
66
+
67
+ ## FastAPI example
68
+
69
+ ```python
70
+ from fastapi import FastAPI, HTTPException, Request
71
+ from betyebo import WebhookSDK, Stripe, InvalidSignature, ExpiredTimestamp
72
+
73
+ app = FastAPI()
74
+ sdk = WebhookSDK()
75
+ sdk.register(Stripe(secret="whsec_..."))
76
+
77
+ @app.post("/webhooks/stripe")
78
+ async def stripe_webhook(request: Request):
79
+ body = await request.body() # raw bytes, don't JSON-parse first
80
+
81
+ try:
82
+ event = sdk.verify_and_parse("stripe", body, request.headers)
83
+ except (InvalidSignature, ExpiredTimestamp) as e:
84
+ raise HTTPException(status_code=400, detail=str(e))
85
+
86
+ if event.type == "invoice.paid":
87
+ # handle it
88
+ pass
89
+
90
+ return {"ok": True}
91
+ ```
92
+
93
+ ## The event object
94
+
95
+ `WebhookEvent` gives you:
96
+
97
+ - `id` – provider event/delivery ID (when present)
98
+ - `type` – normalized event type (e.g. `invoice.paid`, `pull_request.opened`, `orders/create`)
99
+ - `provider` – `stripe`, `github`, or `shopify`
100
+ - `occurred_at` – timestamp when the provider gives one
101
+ - `data` – the main object/payload
102
+ - `raw` – the original parsed JSON payload
103
+ - `headers` – the request headers you passed in
104
+
105
+ ## Secret rotation
106
+
107
+ If you’re rotating secrets, you can accept both for a while:
108
+
109
+ ```python
110
+ stripe = Stripe(secret="whsec_new")
111
+ stripe.add_secret("whsec_old")
112
+ sdk.register(stripe)
113
+ ```
114
+
115
+ ## Testing without pain
116
+
117
+ You can generate valid headers for tests:
118
+
119
+ ```python
120
+ payload = {
121
+ "id": "evt_1",
122
+ "type": "invoice.paid",
123
+ "created": 1710000000,
124
+ "data": {"object": {"id": "in_1"}},
125
+ }
126
+
127
+ headers = sdk.test.sign("stripe", payload, timestamp=1710000000)
128
+ event = sdk.verify_and_parse("stripe", b'{"id":"evt_1","type":"invoice.paid","created":1710000000,"data":{"object":{"id":"in_1"}}}', headers)
129
+ ```
130
+
131
+
132
+ ## Idempotency helper
133
+
134
+ Webhooks get delivered more than once. Signature checks prove *who* sent it, not *whether you've already handled it*.
135
+
136
+ `python
137
+ from betyebo import InMemoryIdempotencyStore
138
+
139
+ store = InMemoryIdempotencyStore()
140
+
141
+ # One call: verify + parse + dedupe
142
+ event, is_new = sdk.process("stripe", body, request.headers, store=store)
143
+ if not is_new:
144
+ return {"ok": True} # already handled
145
+ `
146
+
147
+ For scripts/local workers there's also JSONFileIdempotencyStore("seen.json"). For production, use Redis or your database.
148
+
149
+ ## Generic HMAC provider
150
+
151
+ For services that use a simple HMAC(secret, raw_body) header:
152
+
153
+ `python
154
+ from betyebo import GenericHMAC
155
+
156
+ sdk.register(GenericHMAC(
157
+ secret="s3cr3t",
158
+ name="acme",
159
+ signature_header="X-Acme-Signature",
160
+ prefix="sha256=",
161
+ ))
162
+ `
163
+
164
+ ## A few honest notes
165
+
166
+ - **Use the raw body.** If you parse and re-dump JSON before verifying, signatures will often fail.
167
+ - **“Valid signature” doesn’t mean “first time seeing this”.** Webhooks can be delivered twice. Use `event.id` (or the dedupe helper) so you don’t handle the same thing twice.
168
+ - This is an MVP. It covers the common cases well, but it’s not trying to support every webhook platform on day one.
@@ -0,0 +1,147 @@
1
+ # Betyebo
2
+
3
+ Webhooks sound simple: get a POST, do the thing.
4
+
5
+ Then real life happens. Every provider signs stuff differently, wants different headers, and fails in its own special way.
6
+
7
+ Betyebo gives you one small Python interface for the annoying parts: check the signature safely, parse the payload, and get back a clean event object you can actually work with.
8
+
9
+ ## What it’s good for
10
+
11
+ - **Checking signatures properly** (using the raw request body, not JSON you rebuilt yourself).
12
+ - **Not learning every provider’s quirks** — same basic API across providers.
13
+ - **Getting a clean event** (`type`, `id`, `data`, `raw`, etc.) instead of digging through raw payloads everywhere.
14
+ - **Testing without pain** — it can sign test payloads for you, so you don’t have to hand-roll HMAC code in tests.
15
+
16
+ Supported right now: **Stripe**, **GitHub**, **Shopify**, **Slack**, plus a **GenericHMAC** adapter for simple HMAC-signed webhooks.
17
+
18
+ ## Install (local/dev)
19
+
20
+ ```bash
21
+ pip install -e .
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```python
27
+ from betyebo import WebhookSDK, Stripe, GitHub
28
+
29
+ sdk = WebhookSDK()
30
+ sdk.register(Stripe(secret="whsec_..."))
31
+ sdk.register(GitHub(secret="github_secret"))
32
+
33
+ # Important: pass the raw request body bytes.
34
+ event = sdk.verify_and_parse(
35
+ provider="stripe",
36
+ payload=raw_body_bytes,
37
+ headers=request_headers,
38
+ )
39
+
40
+ print(event.provider) # "stripe"
41
+ print(event.type) # e.g. "invoice.paid"
42
+ print(event.id) # provider event id (when available)
43
+ print(event.data) # the useful payload/object
44
+ ```
45
+
46
+ ## FastAPI example
47
+
48
+ ```python
49
+ from fastapi import FastAPI, HTTPException, Request
50
+ from betyebo import WebhookSDK, Stripe, InvalidSignature, ExpiredTimestamp
51
+
52
+ app = FastAPI()
53
+ sdk = WebhookSDK()
54
+ sdk.register(Stripe(secret="whsec_..."))
55
+
56
+ @app.post("/webhooks/stripe")
57
+ async def stripe_webhook(request: Request):
58
+ body = await request.body() # raw bytes, don't JSON-parse first
59
+
60
+ try:
61
+ event = sdk.verify_and_parse("stripe", body, request.headers)
62
+ except (InvalidSignature, ExpiredTimestamp) as e:
63
+ raise HTTPException(status_code=400, detail=str(e))
64
+
65
+ if event.type == "invoice.paid":
66
+ # handle it
67
+ pass
68
+
69
+ return {"ok": True}
70
+ ```
71
+
72
+ ## The event object
73
+
74
+ `WebhookEvent` gives you:
75
+
76
+ - `id` – provider event/delivery ID (when present)
77
+ - `type` – normalized event type (e.g. `invoice.paid`, `pull_request.opened`, `orders/create`)
78
+ - `provider` – `stripe`, `github`, or `shopify`
79
+ - `occurred_at` – timestamp when the provider gives one
80
+ - `data` – the main object/payload
81
+ - `raw` – the original parsed JSON payload
82
+ - `headers` – the request headers you passed in
83
+
84
+ ## Secret rotation
85
+
86
+ If you’re rotating secrets, you can accept both for a while:
87
+
88
+ ```python
89
+ stripe = Stripe(secret="whsec_new")
90
+ stripe.add_secret("whsec_old")
91
+ sdk.register(stripe)
92
+ ```
93
+
94
+ ## Testing without pain
95
+
96
+ You can generate valid headers for tests:
97
+
98
+ ```python
99
+ payload = {
100
+ "id": "evt_1",
101
+ "type": "invoice.paid",
102
+ "created": 1710000000,
103
+ "data": {"object": {"id": "in_1"}},
104
+ }
105
+
106
+ headers = sdk.test.sign("stripe", payload, timestamp=1710000000)
107
+ event = sdk.verify_and_parse("stripe", b'{"id":"evt_1","type":"invoice.paid","created":1710000000,"data":{"object":{"id":"in_1"}}}', headers)
108
+ ```
109
+
110
+
111
+ ## Idempotency helper
112
+
113
+ Webhooks get delivered more than once. Signature checks prove *who* sent it, not *whether you've already handled it*.
114
+
115
+ `python
116
+ from betyebo import InMemoryIdempotencyStore
117
+
118
+ store = InMemoryIdempotencyStore()
119
+
120
+ # One call: verify + parse + dedupe
121
+ event, is_new = sdk.process("stripe", body, request.headers, store=store)
122
+ if not is_new:
123
+ return {"ok": True} # already handled
124
+ `
125
+
126
+ For scripts/local workers there's also JSONFileIdempotencyStore("seen.json"). For production, use Redis or your database.
127
+
128
+ ## Generic HMAC provider
129
+
130
+ For services that use a simple HMAC(secret, raw_body) header:
131
+
132
+ `python
133
+ from betyebo import GenericHMAC
134
+
135
+ sdk.register(GenericHMAC(
136
+ secret="s3cr3t",
137
+ name="acme",
138
+ signature_header="X-Acme-Signature",
139
+ prefix="sha256=",
140
+ ))
141
+ `
142
+
143
+ ## A few honest notes
144
+
145
+ - **Use the raw body.** If you parse and re-dump JSON before verifying, signatures will often fail.
146
+ - **“Valid signature” doesn’t mean “first time seeing this”.** Webhooks can be delivered twice. Use `event.id` (or the dedupe helper) so you don’t handle the same thing twice.
147
+ - This is an MVP. It covers the common cases well, but it’s not trying to support every webhook platform on day one.
@@ -0,0 +1,42 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "betyebo"
7
+ version = "0.1.0"
8
+ description = "Unified webhook verification, parsing, and testing for Python"
9
+ readme = "README.md"
10
+ requires-python = ">=3.9"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "REDX Contributors" }]
13
+ dependencies = []
14
+ keywords = ["webhooks", "stripe", "github", "shopify", "fastapi", "security"]
15
+ classifiers = [
16
+ "Development Status :: 3 - Alpha",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Topic :: Software Development :: Libraries",
22
+ "Typing :: Typed",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ dev = ["pytest>=7.4"]
27
+
28
+ [tool.setuptools]
29
+ package-dir = {"" = "src"}
30
+ include-package-data = true
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+ include = ["betyebo*"]
35
+
36
+ [tool.setuptools.package-data]
37
+ betyebo = ["py.typed"]
38
+
39
+ [tool.pytest.ini_options]
40
+ testpaths = ["tests"]
41
+ pythonpath = ["src"]
42
+ addopts = "-ra"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,37 @@
1
+ from .errors import (
2
+ ExpiredTimestamp,
3
+ InvalidSignature,
4
+ MalformedPayload,
5
+ MissingHeader,
6
+ UnknownProvider,
7
+ WebhookError,
8
+ )
9
+ from .idempotency import IdempotencyStore, InMemoryIdempotencyStore, JSONFileIdempotencyStore
10
+ from .models import WebhookEvent
11
+ from .registry import WebhookSDK
12
+ from .providers.generic import GenericHMAC
13
+ from .providers.github import GitHub
14
+ from .providers.shopify import Shopify
15
+ from .providers.slack import Slack
16
+ from .providers.stripe import Stripe
17
+
18
+ __all__ = [
19
+ "WebhookSDK",
20
+ "WebhookEvent",
21
+ "WebhookError",
22
+ "InvalidSignature",
23
+ "ExpiredTimestamp",
24
+ "UnknownProvider",
25
+ "MalformedPayload",
26
+ "MissingHeader",
27
+ "Stripe",
28
+ "GitHub",
29
+ "Shopify",
30
+ "Slack",
31
+ "GenericHMAC",
32
+ "IdempotencyStore",
33
+ "InMemoryIdempotencyStore",
34
+ "JSONFileIdempotencyStore",
35
+ ]
36
+
37
+ __version__ = "0.1.0"
@@ -0,0 +1,31 @@
1
+ """Exceptions for webhook verification and parsing."""
2
+
3
+
4
+ class WebhookError(Exception):
5
+ """Base error for the webhook SDK."""
6
+
7
+
8
+ class InvalidSignature(WebhookError):
9
+ """Raised when a signature is missing or does not match."""
10
+
11
+
12
+ class ExpiredTimestamp(WebhookError):
13
+ """Raised when a webhook timestamp is outside the allowed tolerance."""
14
+
15
+
16
+ class UnknownProvider(WebhookError):
17
+ """Raised when no provider is registered for the given name."""
18
+
19
+
20
+ class MalformedPayload(WebhookError):
21
+ """Raised when a payload cannot be parsed or is missing required fields."""
22
+
23
+
24
+ class MissingHeader(WebhookError):
25
+ """Raised when a required header is missing."""
26
+
27
+ def __init__(self, header: str, provider: str | None = None):
28
+ self.header = header
29
+ self.provider = provider
30
+ where = f" for provider '{provider}'" if provider else ""
31
+ super().__init__(f"Missing required header '{header}'{where}")
@@ -0,0 +1,107 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ from pathlib import Path
5
+ from threading import Lock
6
+ from typing import Protocol
7
+
8
+
9
+ class IdempotencyStore(Protocol):
10
+ """Minimal interface for deduping webhook events."""
11
+
12
+ def check_and_mark(self, key: str) -> bool:
13
+ """Return True if this key was not seen before (and mark it as seen)."""
14
+ ...
15
+
16
+
17
+ class InMemoryIdempotencyStore:
18
+ """Simple in-memory dedupe store.
19
+
20
+ Good for tests/single-process apps. Use Redis/DB in production.
21
+ """
22
+
23
+ def __init__(self) -> None:
24
+ self._seen: set[str] = set()
25
+ self._lock = Lock()
26
+
27
+ def seen(self, key: str) -> bool:
28
+ with self._lock:
29
+ return key in self._seen
30
+
31
+ def mark(self, key: str) -> None:
32
+ with self._lock:
33
+ self._seen.add(key)
34
+
35
+ def check_and_mark(self, key: str) -> bool:
36
+ with self._lock:
37
+ if key in self._seen:
38
+ return False
39
+ self._seen.add(key)
40
+ return True
41
+
42
+ def clear(self) -> None:
43
+ with self._lock:
44
+ self._seen.clear()
45
+
46
+ def __len__(self) -> int:
47
+ with self._lock:
48
+ return len(self._seen)
49
+
50
+
51
+ class JSONFileIdempotencyStore:
52
+ """Tiny file-backed dedupe store.
53
+
54
+ Handy for scripts and local workers. For concurrent production workloads,
55
+ use Redis or a database instead.
56
+ """
57
+
58
+ def __init__(self, path: str | Path):
59
+ self.path = Path(path)
60
+ self._lock = Lock()
61
+ self._seen: set[str] = set()
62
+ self._load()
63
+
64
+ def _load(self) -> None:
65
+ if not self.path.exists():
66
+ return
67
+ try:
68
+ data = json.loads(self.path.read_text(encoding="utf-8"))
69
+ if isinstance(data, list):
70
+ self._seen = {str(x) for x in data}
71
+ except Exception:
72
+ # Corrupt/partial file: start fresh rather than crashing.
73
+ self._seen = set()
74
+
75
+ def _flush(self) -> None:
76
+ self.path.parent.mkdir(parents=True, exist_ok=True)
77
+ tmp = self.path.with_suffix(self.path.suffix + ".tmp")
78
+ tmp.write_text(json.dumps(sorted(self._seen)), encoding="utf-8")
79
+ tmp.replace(self.path)
80
+
81
+ def seen(self, key: str) -> bool:
82
+ with self._lock:
83
+ return key in self._seen
84
+
85
+ def mark(self, key: str) -> None:
86
+ with self._lock:
87
+ if key in self._seen:
88
+ return
89
+ self._seen.add(key)
90
+ self._flush()
91
+
92
+ def check_and_mark(self, key: str) -> bool:
93
+ with self._lock:
94
+ if key in self._seen:
95
+ return False
96
+ self._seen.add(key)
97
+ self._flush()
98
+ return True
99
+
100
+ def clear(self) -> None:
101
+ with self._lock:
102
+ self._seen.clear()
103
+ self._flush()
104
+
105
+ def __len__(self) -> int:
106
+ with self._lock:
107
+ return len(self._seen)
@@ -0,0 +1,36 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass, field
4
+ from datetime import datetime
5
+ from typing import Any, Mapping
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class WebhookEvent:
10
+ """Normalized webhook event."""
11
+
12
+ id: str | None
13
+ type: str
14
+ provider: str
15
+ occurred_at: datetime | None
16
+ data: Any
17
+ raw: Mapping[str, Any]
18
+ headers: Mapping[str, str] = field(default_factory=dict)
19
+
20
+ @property
21
+ def dedupe_key(self) -> str | None:
22
+ """Stable key for idempotency when the provider supplies an event ID."""
23
+ if not self.id:
24
+ return None
25
+ return f"{self.provider}:{self.id}"
26
+
27
+ def to_dict(self) -> dict[str, Any]:
28
+ return {
29
+ "id": self.id,
30
+ "type": self.type,
31
+ "provider": self.provider,
32
+ "occurred_at": self.occurred_at.isoformat() if self.occurred_at else None,
33
+ "data": self.data,
34
+ "raw": dict(self.raw),
35
+ "dedupe_key": self.dedupe_key,
36
+ }
@@ -0,0 +1,8 @@
1
+ from .base import Provider
2
+ from .generic import GenericHMAC
3
+ from .github import GitHub
4
+ from .shopify import Shopify
5
+ from .slack import Slack
6
+ from .stripe import Stripe
7
+
8
+ __all__ = ["Provider", "Stripe", "GitHub", "Shopify", "Slack", "GenericHMAC"]
@@ -0,0 +1,89 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ from abc import ABC, abstractmethod
7
+ from typing import Any, Mapping
8
+
9
+ from ..errors import MalformedPayload, MissingHeader
10
+ from ..models import WebhookEvent
11
+
12
+
13
+ def _get_header(headers: Mapping[str, str], name: str) -> str | None:
14
+ # HTTP headers are case-insensitive; support common dict types.
15
+ lower = name.lower()
16
+ for k, v in headers.items():
17
+ if k.lower() == lower:
18
+ return v
19
+ return None
20
+
21
+
22
+ def require_header(headers: Mapping[str, str], name: str, provider: str) -> str:
23
+ value = _get_header(headers, name)
24
+ if value is None or value == "":
25
+ raise MissingHeader(name, provider)
26
+ return value
27
+
28
+
29
+ def parse_json_payload(payload: bytes | str) -> Mapping[str, Any]:
30
+ if isinstance(payload, bytes):
31
+ try:
32
+ text = payload.decode("utf-8")
33
+ except UnicodeDecodeError as e:
34
+ raise MalformedPayload("Payload is not valid UTF-8") from e
35
+ else:
36
+ text = payload
37
+ try:
38
+ data = json.loads(text)
39
+ except json.JSONDecodeError as e:
40
+ raise MalformedPayload("Payload is not valid JSON") from e
41
+ if not isinstance(data, dict):
42
+ raise MalformedPayload("Payload must be a JSON object")
43
+ return data
44
+
45
+
46
+ def secure_compare(a: str | bytes, b: str | bytes) -> bool:
47
+ a_bytes = a.encode("utf-8") if isinstance(a, str) else a
48
+ b_bytes = b.encode("utf-8") if isinstance(b, str) else b
49
+ return hmac.compare_digest(a_bytes, b_bytes)
50
+
51
+
52
+ def hmac_sha256_hex(secret: str | bytes, message: bytes) -> str:
53
+ key = secret.encode("utf-8") if isinstance(secret, str) else secret
54
+ return hmac.new(key, message, hashlib.sha256).hexdigest()
55
+
56
+
57
+ class Provider(ABC):
58
+ """Base webhook provider adapter."""
59
+
60
+ name: str
61
+
62
+ def __init__(self, secret: str, *, tolerance_seconds: int = 300):
63
+ if not secret:
64
+ raise ValueError("secret must not be empty")
65
+ self.secrets = [secret]
66
+ self.tolerance_seconds = tolerance_seconds
67
+
68
+ def add_secret(self, secret: str) -> None:
69
+ """Add an active secret (supports rotation)."""
70
+ if not secret:
71
+ raise ValueError("secret must not be empty")
72
+ if secret not in self.secrets:
73
+ self.secrets.append(secret)
74
+
75
+ @abstractmethod
76
+ def verify(self, payload: bytes, headers: Mapping[str, str]) -> None:
77
+ """Raise InvalidSignature/ExpiredTimestamp if the payload is not authentic."""
78
+
79
+ @abstractmethod
80
+ def parse(self, payload: bytes, headers: Mapping[str, str]) -> WebhookEvent:
81
+ """Parse an already-verified payload into a normalized event."""
82
+
83
+ @abstractmethod
84
+ def sign(self, payload: bytes, *, secret: str | None = None, **kwargs: Any) -> dict[str, str]:
85
+ """Return headers that would sign this payload (for tests/local replay)."""
86
+
87
+ def verify_and_parse(self, payload: bytes, headers: Mapping[str, str]) -> WebhookEvent:
88
+ self.verify(payload, headers)
89
+ return self.parse(payload, headers)