standardwebhooks 1.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.
|
File without changes
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
import hashlib
|
|
3
|
+
import hmac
|
|
4
|
+
import json
|
|
5
|
+
import typing as t
|
|
6
|
+
from datetime import datetime, timedelta, timezone
|
|
7
|
+
from math import floor
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def hmac_data(key: bytes, data: bytes) -> bytes:
|
|
11
|
+
return hmac.new(key, data, hashlib.sha256).digest()
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class WebhookVerificationError(Exception):
|
|
15
|
+
pass
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class EmptyWebhookSecretError(Exception):
|
|
19
|
+
pass
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Webhook:
|
|
23
|
+
_SECRET_PREFIX: str = "whsec_"
|
|
24
|
+
_whsecret: bytes
|
|
25
|
+
|
|
26
|
+
def __init__(self, whsecret: t.Union[str, bytes]):
|
|
27
|
+
if isinstance(whsecret, str):
|
|
28
|
+
if whsecret.startswith(self._SECRET_PREFIX):
|
|
29
|
+
whsecret = whsecret[len(self._SECRET_PREFIX) :]
|
|
30
|
+
# add padding in case whsecret is unpadded base64 (b64decode skips extra padding)
|
|
31
|
+
whsecret = base64.b64decode(whsecret + "==")
|
|
32
|
+
|
|
33
|
+
if not whsecret:
|
|
34
|
+
raise EmptyWebhookSecretError("webhook secret may not be empty")
|
|
35
|
+
|
|
36
|
+
if isinstance(whsecret, bytes):
|
|
37
|
+
self._whsecret = whsecret
|
|
38
|
+
else:
|
|
39
|
+
raise RuntimeError("Invalid webhook secret")
|
|
40
|
+
|
|
41
|
+
def verify(
|
|
42
|
+
self,
|
|
43
|
+
data: t.Union[bytes, str],
|
|
44
|
+
headers: t.Dict[str, str],
|
|
45
|
+
*,
|
|
46
|
+
json_parse: bool = True,
|
|
47
|
+
) -> t.Any:
|
|
48
|
+
"""
|
|
49
|
+
Verify the given webhook headers against the body bytes (data).
|
|
50
|
+
|
|
51
|
+
Args:
|
|
52
|
+
json_parse (bool): Whether to deserialize the data to (default: True)
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
After successful verification: if json_parse is True, returns the
|
|
56
|
+
JSON-parsed input data; if it json_parse False, returns None.
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
WebhookVerificationError if one of the required headers is missing,
|
|
60
|
+
invalid, too old or too new; or no matching signature is found.
|
|
61
|
+
"""
|
|
62
|
+
|
|
63
|
+
data = data if isinstance(data, str) else data.decode()
|
|
64
|
+
headers = {k.lower(): v for (k, v) in headers.items()}
|
|
65
|
+
msg_id = headers.get("webhook-id")
|
|
66
|
+
msg_signature = headers.get("webhook-signature")
|
|
67
|
+
msg_timestamp = headers.get("webhook-timestamp")
|
|
68
|
+
if not (msg_id and msg_timestamp and msg_signature):
|
|
69
|
+
raise WebhookVerificationError("Missing required headers")
|
|
70
|
+
|
|
71
|
+
timestamp = self.__verify_timestamp(msg_timestamp)
|
|
72
|
+
|
|
73
|
+
expected_sig = base64.b64decode(self.sign(msg_id=msg_id, timestamp=timestamp, data=data).split(",")[1])
|
|
74
|
+
passed_sigs = msg_signature.split(" ")
|
|
75
|
+
for versioned_sig in passed_sigs:
|
|
76
|
+
(version, signature) = versioned_sig.split(",")
|
|
77
|
+
if version != "v1":
|
|
78
|
+
continue
|
|
79
|
+
sig_bytes = base64.b64decode(signature)
|
|
80
|
+
if hmac.compare_digest(expected_sig, sig_bytes):
|
|
81
|
+
if json_parse:
|
|
82
|
+
return json.loads(data)
|
|
83
|
+
else:
|
|
84
|
+
return
|
|
85
|
+
|
|
86
|
+
raise WebhookVerificationError("No matching signature found")
|
|
87
|
+
|
|
88
|
+
def sign(self, msg_id: str, timestamp: datetime, data: str) -> str:
|
|
89
|
+
timestamp_str = str(floor(timestamp.replace(tzinfo=timezone.utc).timestamp()))
|
|
90
|
+
to_sign = f"{msg_id}.{timestamp_str}.{data}".encode()
|
|
91
|
+
signature = hmac_data(self._whsecret, to_sign)
|
|
92
|
+
return f"v1,{base64.b64encode(signature).decode('utf-8')}"
|
|
93
|
+
|
|
94
|
+
def __verify_timestamp(self, timestamp_header: str) -> datetime:
|
|
95
|
+
webhook_tolerance = timedelta(minutes=5)
|
|
96
|
+
now = datetime.now(tz=timezone.utc)
|
|
97
|
+
try:
|
|
98
|
+
timestamp = datetime.fromtimestamp(float(timestamp_header), tz=timezone.utc)
|
|
99
|
+
except Exception:
|
|
100
|
+
raise WebhookVerificationError("Invalid Signature Headers")
|
|
101
|
+
|
|
102
|
+
if timestamp < (now - webhook_tolerance):
|
|
103
|
+
raise WebhookVerificationError("Message timestamp too old")
|
|
104
|
+
if timestamp > (now + webhook_tolerance):
|
|
105
|
+
raise WebhookVerificationError("Message timestamp too new")
|
|
106
|
+
return timestamp
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: standardwebhooks
|
|
3
|
+
Version: 1.1.0
|
|
4
|
+
Summary: Standard Webhooks
|
|
5
|
+
Author: Standard Webhooks Team
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: webhooks
|
|
8
|
+
Classifier: Intended Audience :: Developers
|
|
9
|
+
Classifier: Intended Audience :: Information Technology
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
21
|
+
Classifier: Topic :: Software Development
|
|
22
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
23
|
+
Classifier: Topic :: Software Development :: Libraries :: Application Frameworks
|
|
24
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
Python library for Standard Webhooks
|
|
30
|
+
|
|
31
|
+
# Example
|
|
32
|
+
|
|
33
|
+
Verifying a webhook payload:
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from standardwebhooks.webhooks import Webhook
|
|
37
|
+
|
|
38
|
+
wh = Webhook(base64_secret)
|
|
39
|
+
wh.verify(webhook_payload, webhook_headers)
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
# Development
|
|
43
|
+
|
|
44
|
+
## Requirements
|
|
45
|
+
|
|
46
|
+
- python 3
|
|
47
|
+
|
|
48
|
+
## Installing dependencies
|
|
49
|
+
|
|
50
|
+
```sh
|
|
51
|
+
python -m venv .venv
|
|
52
|
+
pip install -r requirements.txt && pip install -r requirements-dev.txt
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Contributing
|
|
56
|
+
|
|
57
|
+
Before opening a PR be sure to format your code!
|
|
58
|
+
|
|
59
|
+
```sh
|
|
60
|
+
./scripts/format.sh
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Running Tests
|
|
64
|
+
|
|
65
|
+
Simply run:
|
|
66
|
+
|
|
67
|
+
```sh
|
|
68
|
+
pytest
|
|
69
|
+
```
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
standardwebhooks/__init__.py,sha256=cI5RgwFSHNdHT7x3w4FikERf7C2-jkQ4lbs9NzAoicg,141
|
|
2
|
+
standardwebhooks/exceptions.py,sha256=Q8UmKDpmuOv_C_eWFQyQStjNK4Y5urtyZVqrFb7rrzQ,94
|
|
3
|
+
standardwebhooks/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
4
|
+
standardwebhooks/webhooks.py,sha256=twE2k0cyUIWuoEvhiipvRBrkCmnckg_Zs_KbElwVoP8,3830
|
|
5
|
+
standardwebhooks-1.1.0.dist-info/METADATA,sha256=u3nSj4FhylvJC_cYEVlgY6BO_BHdjflte_CQ4sjr7CE,1689
|
|
6
|
+
standardwebhooks-1.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
7
|
+
standardwebhooks-1.1.0.dist-info/RECORD,,
|