agentboxd 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.
agentboxd/_version.py ADDED
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
agentboxd/_webhooks.py ADDED
@@ -0,0 +1,68 @@
1
+ """Webhook signature verification, byte-for-byte compatible with the Agentboxd server.
2
+
3
+ Signature = hex(HMAC-SHA256(secret, f"{timestamp}.{raw_body}")), sent in ``X-Mailroom-Signature``
4
+ alongside the unix-seconds ``X-Mailroom-Timestamp`` (header names kept from the original API).
5
+ """
6
+
7
+ import hashlib
8
+ import hmac
9
+ import re
10
+ import time
11
+ from typing import Optional, Union
12
+
13
+ __all__ = ["SIGNATURE_HEADER", "TIMESTAMP_HEADER", "compute_signature", "verify_webhook"]
14
+
15
+ SIGNATURE_HEADER = "X-Mailroom-Signature"
16
+ TIMESTAMP_HEADER = "X-Mailroom-Timestamp"
17
+
18
+ _TIMESTAMP_RE = re.compile(r"[0-9]+")
19
+ _SIGNATURE_RE = re.compile(r"[0-9a-fA-F]{64}")
20
+
21
+
22
+ def _to_bytes(value: Union[str, bytes, bytearray, memoryview]) -> bytes:
23
+ if isinstance(value, str):
24
+ return value.encode("utf-8")
25
+ if isinstance(value, (bytes, bytearray, memoryview)):
26
+ return bytes(value)
27
+ raise TypeError(f"expected str or bytes, got {type(value).__name__}")
28
+
29
+
30
+ def compute_signature(
31
+ timestamp: str, body: Union[str, bytes, bytearray, memoryview], secret: Union[str, bytes]
32
+ ) -> str:
33
+ """Return the hex signature the server would send for ``body`` at ``timestamp``."""
34
+ mac = hmac.new(_to_bytes(secret), digestmod=hashlib.sha256)
35
+ mac.update(timestamp.encode("ascii") + b".")
36
+ mac.update(_to_bytes(body))
37
+ return mac.hexdigest()
38
+
39
+
40
+ def verify_webhook(
41
+ signature: Optional[str],
42
+ timestamp: Optional[str],
43
+ body: Union[str, bytes, bytearray, memoryview],
44
+ secret: Union[str, bytes],
45
+ tolerance_seconds: float = 300,
46
+ *,
47
+ now: Optional[float] = None,
48
+ ) -> bool:
49
+ """Verify a webhook delivery. Never raises on malformed input; returns ``False`` instead.
50
+
51
+ Pass the **raw** request body exactly as received (not re-serialized JSON) and the
52
+ ``X-Mailroom-Signature`` / ``X-Mailroom-Timestamp`` header values. Timestamps further than
53
+ ``tolerance_seconds`` from ``now`` (default: current time) are rejected to limit replays;
54
+ pass ``tolerance_seconds=0`` to skip the freshness check.
55
+ """
56
+ try:
57
+ if not isinstance(signature, str) or not isinstance(timestamp, str):
58
+ return False
59
+ if not _TIMESTAMP_RE.fullmatch(timestamp) or not _SIGNATURE_RE.fullmatch(signature):
60
+ return False
61
+ if tolerance_seconds > 0:
62
+ current = time.time() if now is None else now
63
+ if abs(current - int(timestamp)) > tolerance_seconds:
64
+ return False
65
+ expected = compute_signature(timestamp, body, secret)
66
+ return hmac.compare_digest(expected, signature.lower())
67
+ except (TypeError, ValueError, UnicodeError):
68
+ return False