Spaces:
Running
Running
Download core/events/intake.py from Aynkhn/WorkPilot-AI: direct link, hf CLI and curl.
- Browser
- Download file 13.3 kB
-
https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/events/intake.py
- Command line
-
hf download hf://spaces/Aynkhn/WorkPilot-AI/core/events/intake.py
-
curl -L -o intake.py https://huggingface.co/spaces/Aynkhn/WorkPilot-AI/resolve/main/core/events/intake.py
13.3 kB
| """Normalize every inbound channel into ``Event`` + a dedupe key, and verify signatures. | |
| Pure functions: no I/O, so they are unit-tested exhaustively. Text that arrives over a | |
| webhook, email or customer channel is always untrusted (``trusted=False``); only an | |
| authenticated operator's chat message is trusted. Signature checks use constant-time | |
| comparison and run over the exact raw request body. | |
| """ | |
| from __future__ import annotations | |
| import base64 | |
| import hashlib | |
| import hmac | |
| import json | |
| import uuid | |
| from dataclasses import dataclass | |
| from datetime import datetime | |
| from typing import Any | |
| from core.agent.state import Event | |
| MAX_DEDUPE_KEY = 300 | |
| WEBHOOK_SOURCES = ("shopify", "whatsapp", "generic") | |
| class SignatureError(Exception): | |
| """The request is not signed with the endpoint's secret (HTTP 401).""" | |
| class PayloadError(Exception): | |
| """The request is signed but its body cannot be normalized (HTTP 400).""" | |
| class NormalizedEvent: | |
| event: Event | |
| dedupe_key: str | |
| def _key(*parts: str) -> str: | |
| key = ":".join(parts) | |
| if len(key) > MAX_DEDUPE_KEY: # keep the namespace, hash the tail | |
| key = f"{parts[0]}:sha256:{hashlib.sha256(key.encode()).hexdigest()}" | |
| return key | |
| def _hmac(secret: str, body: bytes) -> bytes: | |
| return hmac.new(secret.encode(), body, hashlib.sha256).digest() | |
| def _json_object(body: bytes) -> dict[str, Any]: | |
| try: | |
| data = json.loads(body or b"{}") | |
| except ValueError as exc: | |
| raise PayloadError("body is not valid JSON") from exc | |
| if not isinstance(data, dict): | |
| raise PayloadError("body must be a JSON object") | |
| return data | |
| # ------------------------------------------------------------------ signatures | |
| def verify_shopify(secret: str, body: bytes, header: str | None) -> None: | |
| """``X-Shopify-Hmac-Sha256``: base64(HMAC-SHA256(app secret, raw body)).""" | |
| if not header: | |
| raise SignatureError("missing X-Shopify-Hmac-Sha256") | |
| expected = base64.b64encode(_hmac(secret, body)).decode() | |
| if not hmac.compare_digest(expected.encode(), header.strip().encode()): | |
| raise SignatureError("bad Shopify signature") | |
| def verify_meta(secret: str, body: bytes, header: str | None) -> None: | |
| """``X-Hub-Signature-256``: ``sha256=`` + hex(HMAC-SHA256(app secret, raw body)).""" | |
| if not header or not header.startswith("sha256="): | |
| raise SignatureError("missing X-Hub-Signature-256") | |
| expected = "sha256=" + _hmac(secret, body).hex() | |
| if not hmac.compare_digest(expected.encode(), header.strip().lower().encode()): | |
| raise SignatureError("bad Meta signature") | |
| def verify_generic(secret: str, body: bytes, header: str | None) -> None: | |
| """``X-WorkPilot-Signature``: ``sha256=`` + hex(HMAC-SHA256(endpoint secret, raw body)).""" | |
| if not header: | |
| raise SignatureError("missing X-WorkPilot-Signature") | |
| value = header.strip().lower() | |
| value = value.removeprefix("sha256=") | |
| expected = _hmac(secret, body).hex() | |
| if not hmac.compare_digest(expected.encode(), value.encode()): | |
| raise SignatureError("bad signature") | |
| def sign_generic(secret: str, body: bytes) -> str: | |
| """Header value a sender (or a test) uses for ``X-WorkPilot-Signature``.""" | |
| return "sha256=" + _hmac(secret, body).hex() | |
| def meta_handshake(params: dict[str, str], verify_token: str | None) -> str | None: | |
| """Meta's GET subscription check: echo ``hub.challenge`` iff the verify token matches.""" | |
| if not verify_token or params.get("hub.mode") != "subscribe": | |
| return None | |
| given = params.get("hub.verify_token", "") | |
| if not hmac.compare_digest(given.encode(), verify_token.encode()): | |
| return None | |
| challenge = params.get("hub.challenge") | |
| return challenge if challenge else None | |
| def verify_webhook(source: str, secret: str, body: bytes, headers: dict[str, str]) -> None: | |
| """Dispatch on the endpoint's source. ``headers`` keys must be lower-case.""" | |
| if source == "shopify": | |
| verify_shopify(secret, body, headers.get("x-shopify-hmac-sha256")) | |
| elif source == "whatsapp": | |
| verify_meta(secret, body, headers.get("x-hub-signature-256")) | |
| elif source == "generic": | |
| verify_generic(secret, body, headers.get("x-workpilot-signature")) | |
| else: | |
| raise SignatureError(f"unknown webhook source {source!r}") | |
| # ----------------------------------------------------------------- normalizers | |
| def shopify_event_type(topic: str) -> str: | |
| """``orders/create`` -> ``shopify.orders.create``.""" | |
| clean = topic.strip().lower().replace("/", ".") | |
| if not clean or not all(c.isalnum() or c in "._" for c in clean): | |
| raise PayloadError(f"bad Shopify topic {topic!r}") | |
| return f"shopify.{clean}" | |
| def normalize_shopify(body: bytes, headers: dict[str, str]) -> list[NormalizedEvent]: | |
| topic = headers.get("x-shopify-topic") | |
| if not topic: | |
| raise PayloadError("missing X-Shopify-Topic") | |
| data = _json_object(body) | |
| webhook_id = headers.get("x-shopify-webhook-id") or headers.get("x-shopify-event-id") | |
| if not webhook_id: | |
| # Shopify always sends one; fall back to the topic + resource id + body hash. | |
| webhook_id = hashlib.sha256(body).hexdigest() | |
| payload = { | |
| "topic": topic, | |
| "shop_domain": headers.get("x-shopify-shop-domain"), | |
| "data": data, | |
| } | |
| event = Event(type=shopify_event_type(topic), source="shopify", payload=payload) | |
| return [NormalizedEvent(event, _key("shopify", webhook_id))] | |
| def normalize_whatsapp(body: bytes) -> list[NormalizedEvent]: | |
| """WhatsApp Cloud API webhook: one POST may carry several messages and statuses.""" | |
| data = _json_object(body) | |
| out: list[NormalizedEvent] = [] | |
| for entry in data.get("entry") or []: | |
| for change in (entry or {}).get("changes") or []: | |
| value = (change or {}).get("value") or {} | |
| meta = value.get("metadata") or {} | |
| names = { | |
| c.get("wa_id"): (c.get("profile") or {}).get("name") | |
| for c in value.get("contacts") or [] | |
| } | |
| for m in value.get("messages") or []: | |
| mid = m.get("id") | |
| if not mid: | |
| continue | |
| kind = m.get("type", "unknown") | |
| text = None | |
| if kind == "text": | |
| text = (m.get("text") or {}).get("body") | |
| elif kind in ("button", "interactive"): | |
| text = json.dumps(m.get(kind), ensure_ascii=False) | |
| payload = { | |
| "message_id": mid, | |
| "from": m.get("from"), | |
| "contact_name": names.get(m.get("from")), | |
| "phone_number_id": meta.get("phone_number_id"), | |
| "message_type": kind, | |
| "timestamp": m.get("timestamp"), | |
| "raw": m, | |
| } | |
| # Phase 7: reply correlation, quick-reply payloads, voice notes. | |
| context = m.get("context") or {} | |
| if context.get("id"): | |
| payload["reply_to"] = context["id"] | |
| if kind == "button" and (m.get("button") or {}).get("payload"): | |
| payload["button_payload"] = m["button"]["payload"] | |
| if kind in ("audio", "voice"): | |
| media = m.get(kind) or {} | |
| payload["media"] = { | |
| "id": media.get("id"), | |
| "mime_type": media.get("mime_type"), | |
| "voice": bool(media.get("voice", kind == "voice")), | |
| } | |
| payload["needs_transcription"] = True | |
| event = Event( | |
| type="whatsapp.message", source="whatsapp", text=text, payload=payload | |
| ) | |
| out.append(NormalizedEvent(event, _key("whatsapp", mid))) | |
| for st in value.get("statuses") or []: | |
| sid, status = st.get("id"), st.get("status") | |
| if not sid or not status: | |
| continue | |
| event = Event( | |
| type="whatsapp.status", | |
| source="whatsapp", | |
| payload={ | |
| "message_id": sid, | |
| "status": status, | |
| "recipient": st.get("recipient_id"), | |
| "timestamp": st.get("timestamp"), | |
| "phone_number_id": meta.get("phone_number_id"), | |
| # Phase 7: failure reasons and conversation pricing (cost tracking). | |
| "errors": st.get("errors") or [], | |
| "pricing": st.get("pricing") or {}, | |
| }, | |
| ) | |
| out.append(NormalizedEvent(event, _key("whatsapp-status", sid, status))) | |
| return out | |
| def normalize_generic(body: bytes, headers: dict[str, str]) -> list[NormalizedEvent]: | |
| """Generic signed webhook: ``{"type": ..., "text"?: ..., "payload"?: {...}, "id"?: ...}``. | |
| Dedupe on ``X-Idempotency-Key`` / ``X-Event-Id`` / body ``id``, else the body hash. | |
| """ | |
| data = _json_object(body) | |
| etype = data.get("type") | |
| if not isinstance(etype, str) or not etype or len(etype) > 200: | |
| raise PayloadError("generic webhook needs a string 'type'") | |
| text = data.get("text") | |
| if text is not None and not isinstance(text, str): | |
| raise PayloadError("'text' must be a string") | |
| payload = data.get("payload", {}) | |
| if not isinstance(payload, dict): | |
| raise PayloadError("'payload' must be an object") | |
| ident = ( | |
| headers.get("x-idempotency-key") | |
| or headers.get("x-event-id") | |
| or (str(data["id"]) if data.get("id") is not None else None) | |
| or "sha256:" + hashlib.sha256(body).hexdigest() | |
| ) | |
| event = Event(type=etype, source="webhook", text=text, payload=payload) | |
| return [NormalizedEvent(event, _key("webhook", ident))] | |
| def normalize_webhook(source: str, body: bytes, headers: dict[str, str]) -> list[NormalizedEvent]: | |
| if source == "shopify": | |
| return normalize_shopify(body, headers) | |
| if source == "whatsapp": | |
| return normalize_whatsapp(body) | |
| if source == "generic": | |
| return normalize_generic(body, headers) | |
| raise PayloadError(f"unknown webhook source {source!r}") | |
| def normalize_email( | |
| message: dict[str, Any], *, event_type: str = "email.received" | |
| ) -> NormalizedEvent: | |
| """An inbound email as a dict (Phase 7's mail connector produces these).""" | |
| subject = str(message.get("subject") or "") | |
| body = str(message.get("body") or message.get("text") or "") | |
| text = f"{subject}\n\n{body}".strip() if subject else body | |
| ident = ( | |
| message.get("message_id") | |
| or "sha256:" | |
| + hashlib.sha256(json.dumps(message, sort_keys=True, default=str).encode()).hexdigest() | |
| ) | |
| payload = { | |
| k: message.get(k) | |
| for k in ( | |
| "from", | |
| "to", | |
| "cc", | |
| "subject", | |
| "message_id", | |
| "in_reply_to", | |
| "received_at", | |
| # Phase 7 (mail connectors): provider ids for threading and replies. | |
| "thread_id", | |
| "provider_message_id", | |
| "rfc_message_id", | |
| "provider", | |
| ) | |
| if message.get(k) is not None | |
| } | |
| event = Event(type=event_type, source="email", text=text or None, payload=payload) | |
| return NormalizedEvent(event, _key("email", str(ident))) | |
| def normalize_chat(message: str, *, client_message_id: str | None = None) -> NormalizedEvent: | |
| """An authenticated operator's chat message: the only trusted free text.""" | |
| event = Event(type="chat.message", source="chat", text=message, trusted=True) | |
| return NormalizedEvent(event, _key("chat", client_message_id or str(uuid.uuid4()))) | |
| def normalize_cron( | |
| schedule_id: uuid.UUID | str, | |
| fire_time: datetime, | |
| *, | |
| event_type: str = "schedule.tick", | |
| payload: dict[str, Any] | None = None, | |
| schedule_name: str | None = None, | |
| ) -> NormalizedEvent: | |
| """One schedule slot. The dedupe key is (schedule, slot), so a slot fires at most once.""" | |
| slot = fire_time.isoformat() | |
| body = {**(payload or {}), "schedule_id": str(schedule_id), "fire_time": slot} | |
| if schedule_name: | |
| body["schedule_name"] = schedule_name | |
| event = Event(type=event_type, source="cron", payload=body) | |
| return NormalizedEvent(event, _key("schedule", str(schedule_id), slot)) | |
| def normalize_manual( | |
| event_type: str, | |
| *, | |
| source: str = "manual", | |
| text: str | None = None, | |
| payload: dict[str, Any] | None = None, | |
| dedupe_key: str | None = None, | |
| ) -> NormalizedEvent: | |
| """``POST /events`` by a manager. Text is untrusted: it is usually pasted customer content.""" | |
| event = Event(type=event_type, source=source, text=text, payload=payload or {}) | |
| return NormalizedEvent(event, _key("manual", dedupe_key or str(uuid.uuid4()))) | |