"""签名 Webhook 的 HMAC 与时间窗校验。""" from __future__ import annotations import hashlib import hmac import time DEFAULT_TOLERANCE_SECONDS = 300 def build_webhook_signature(secret: str, timestamp: str, raw_body: bytes) -> str: content = timestamp.encode("utf-8") + b"." + raw_body digest = hmac.new(secret.encode("utf-8"), content, hashlib.sha256).hexdigest() return f"sha256={digest}" def verify_webhook_signature( *, secret: str, timestamp: str, raw_body: bytes, signature: str, tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS, now_seconds: int | None = None, ) -> bool: return verify_webhook_signature_at( secret=secret, timestamp=timestamp, raw_body=raw_body, signature=signature, tolerance_seconds=tolerance_seconds, now_seconds=now_seconds, ) def verify_webhook_signature_at( *, secret: str, timestamp: str, raw_body: bytes, signature: str, tolerance_seconds: int = DEFAULT_TOLERANCE_SECONDS, now_seconds: int | None = None, ) -> bool: secret = secret.strip() timestamp = timestamp.strip() signature = signature.strip() if not secret or not timestamp or not signature: return False try: timestamp_seconds = int(timestamp) except ValueError: return False if timestamp_seconds <= 0: return False tolerance = max(1, int(tolerance_seconds)) current = int(now_seconds if now_seconds is not None else time.time()) if abs(current - timestamp_seconds) > tolerance: return False expected = build_webhook_signature(secret, timestamp, raw_body) return hmac.compare_digest(expected, signature) def webhook_tolerance_seconds() -> int: import os try: value = int(os.getenv("PLATFORM_FULFILLMENT_WEBHOOK_TOLERANCE_SECONDS", "300")) except ValueError: return DEFAULT_TOLERANCE_SECONDS return value if value > 0 else DEFAULT_TOLERANCE_SECONDS