ForcePilot/backend/package/yuxi/channel/extensions/rocketchat/webhook.py

68 lines
1.8 KiB
Python
Raw Normal View History

from __future__ import annotations
import hashlib
import hmac
import json
import logging
logger = logging.getLogger(__name__)
def verify_rocketchat_webhook_signature(
payload: bytes,
signature_header: str,
secret: str,
) -> bool:
if not signature_header or not secret:
return False
expected = hmac.new(
secret.encode("utf-8"),
payload,
hashlib.sha256,
).hexdigest()
computed = signature_header.replace("sha256=", "")
return hmac.compare_digest(computed, expected)
def parse_rocketchat_incoming_webhook(body: dict) -> dict | None:
channel = body.get("channel", body.get("channel_id", ""))
text = body.get("text", body.get("payload", {}).get("text", ""))
username = body.get("username", body.get("user_name", ""))
if not channel or not text:
return None
return {
"channel": channel,
"text": text,
"username": username,
"icon_emoji": body.get("icon_emoji", ""),
"attachments": body.get("attachments", []),
"raw": body,
}
async def handle_rocketchat_webhook(
request_body: bytes,
headers: dict,
webhook_secret: str = "",
) -> dict | None:
try:
body = json.loads(request_body.decode("utf-8"))
except (json.JSONDecodeError, UnicodeDecodeError):
body = {}
signature = headers.get("X-RocketChat-Signature", "")
if webhook_secret and not verify_rocketchat_webhook_signature(request_body, signature, webhook_secret):
logger.warning("Rocket.Chat webhook signature verification failed")
return None
parsed = parse_rocketchat_incoming_webhook(body)
if not parsed:
return None
logger.info(
"Rocket.Chat webhook received from %s in channel %s",
parsed.get("username", "unknown"),
parsed.get("channel", "unknown"),
)
return parsed