51 行
1.7 KiB
Python
51 行
1.7 KiB
Python
"""Webhook and SSE payload helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import hashlib
|
|
import hmac
|
|
import json
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime, timezone
|
|
from typing import Any
|
|
from uuid import uuid4
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class WebhookEvent:
|
|
event_type: str
|
|
data: dict[str, Any] = field(default_factory=dict)
|
|
event_id: str = field(default_factory=lambda: f"wh_{uuid4().hex}")
|
|
created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
|
|
|
|
def to_dict(self) -> dict[str, Any]:
|
|
return {
|
|
"event_id": self.event_id,
|
|
"event_type": self.event_type,
|
|
"data": self.data,
|
|
"created_at": self.created_at,
|
|
}
|
|
|
|
def canonical_payload(self) -> str:
|
|
return json.dumps(self.to_dict(), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
|
|
|
|
|
def sign_event(event: WebhookEvent, secret: str) -> str:
|
|
key = str(secret or "").encode("utf-8")
|
|
if not key:
|
|
raise ValueError("webhook secret is required")
|
|
return hmac.new(key, event.canonical_payload().encode("utf-8"), hashlib.sha256).hexdigest()
|
|
|
|
|
|
def verify_signature(event: WebhookEvent, secret: str, signature: str) -> bool:
|
|
expected = sign_event(event, secret)
|
|
return hmac.compare_digest(expected, str(signature or ""))
|
|
|
|
|
|
def to_sse(event: WebhookEvent) -> str:
|
|
payload = json.dumps(event.to_dict(), ensure_ascii=False, sort_keys=True)
|
|
return f"id: {event.event_id}\nevent: {event.event_type}\ndata: {payload}\n\n"
|
|
|
|
|
|
def event_from_bus(event_type: str, payload: dict[str, Any]) -> WebhookEvent:
|
|
return WebhookEvent(event_type=event_type, data=dict(payload))
|