Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(whatsapp_business): add inbound triggers, rename to Meta's product name
trohitgd6f59bb60448
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex d6e436b9..2badee38 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -325,13 +325,13 @@"scan_text": "Scan with WhatsApp mobile app"}},- "whatsapp_cloud": {- "name": "WhatsApp Business (Meta)",+ "whatsapp_business": {+ "name": "WhatsApp Business","category": "social","category_label": "Social Media","color": "theme.categoryWhatsapp","kind": "apiKey",- "icon_ref": "/api/schemas/credentials/whatsapp_cloud/icon",+ "icon_ref": "/api/schemas/credentials/whatsapp_business/icon","_description": "Meta's official WhatsApp Business Platform (Cloud API). Distinct from the 'whatsapp' provider, which pairs a personal account over an unofficial bridge.","fields": [{@@ -344,7 +344,7 @@"help": "A permanent System User token from Meta Business Settings. Needs whatsapp_business_messaging and whatsapp_business_management."},{- "key": "whatsapp_cloud_waba_id",+ "key": "whatsapp_business_waba_id","label": "WhatsApp Business Account ID","type": "text","secret": false,@@ -353,7 +353,7 @@"help": "Found in Meta App Dashboard > WhatsApp > API Setup. The token cannot be validated without it."},{- "key": "whatsapp_cloud_phone_number_id",+ "key": "whatsapp_business_phone_number_id","label": "Phone Number ID","type": "text","secret": false,@@ -362,7 +362,7 @@"help": "The business number messages are sent FROM. Not the display number - the numeric ID beside it in API Setup."},{- "key": "whatsapp_cloud_app_secret",+ "key": "whatsapp_business_app_secret","label": "App Secret (for webhooks)","type": "password","secret": true,@@ -371,7 +371,7 @@"help": "Meta App Dashboard > App Settings > Basic. Used to verify the X-Hub-Signature-256 on inbound webhooks; leave blank if you only send."},{- "key": "whatsapp_cloud_verify_token",+ "key": "whatsapp_business_verify_token","label": "Webhook Verify Token","type": "password","secret": true,diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.jsonindex 5cddbb1e..ccff0f68 100644--- a/server/config/node_allowlist.json+++ b/server/config/node_allowlist.json@@ -32,7 +32,9 @@"telegramSend","telegramReceive",- "whatsappCloudSend",+ "whatsappBusinessSend",+ "whatsappBusinessReceive",+ "whatsappBusinessStatus","airplaneModeControl","appLauncher",diff --git a/server/constants.py b/server/constants.pyindex c8713c2b..f249e09f 100644--- a/server/constants.py+++ b/server/constants.py@@ -354,6 +354,8 @@ EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset(["webhookTrigger","whatsappReceive",+ "whatsappBusinessReceive",+ "whatsappBusinessStatus","twitterReceive","workflowTrigger","chatTrigger",@@ -395,6 +397,12 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset(# Event-driven triggers"webhookTrigger","whatsappReceive",+ # Omitting a trigger here is a silent failure, not an error:+ # find_trigger_nodes filters on this set, so deploy simply ignores+ # the node -- no listener, no warning. It is why stripeReceive is+ # canvas-only today.+ "whatsappBusinessReceive",+ "whatsappBusinessStatus","workflowTrigger","chatTrigger","taskTrigger",diff --git a/server/nodes/groups.py b/server/nodes/groups.pyindex 178ef0a8..457c28b9 100644--- a/server/nodes/groups.py+++ b/server/nodes/groups.py@@ -55,7 +55,7 @@ register_group(key="whatsapp", metadata={"label": "WhatsApp", "icon": "💬", "c# failure modes -- merging them into one palette section makes it impossible# to tell which node you are dragging.register_group(- key="whatsapp_cloud",+ key="whatsapp_business",metadata={"label": "WhatsApp Business", "icon": "💼", "color": "#128C7E", "visibility": "normal"},)register_group(key="email", metadata={"label": "Email", "icon": "✉️", "color": "#8be9fd", "visibility": "dev"})diff --git a/server/nodes/whatsapp_business/__init__.py b/server/nodes/whatsapp_business/__init__.pynew file mode 100644index 00000000..d5e0b2d0--- /dev/null+++ b/server/nodes/whatsapp_business/__init__.py@@ -0,0 +1,50 @@+"""Official Meta WhatsApp Business Platform (Cloud API) plugin.++Distinct from ``nodes/whatsapp/``, which drives a *personal* account through+an unofficial Go bridge and QR pairing. Both ship; they share no node types,+no credential id, no WebSocket keys and no palette group, because the auth+models, capabilities and failure modes have nothing in common.++Importing the node modules is what registers them --+``BaseNode.__init_subclass__`` does the work, so this file stays pure wiring.+"""++from __future__ import annotations++from services.deployment.canary_registry import register_canary_trigger_type+from services.events import register_webhook_source+from services.node_output_schemas import register_output_schema++from ._credentials import WhatsAppBusinessCredential+from ._events import MESSAGE_RECEIVED_TYPE, STATUS_UPDATED_TYPE+from ._source import get_webhook_source+from .whatsapp_business_receive import (+ WhatsAppBusinessReceiveNode,+ WhatsAppBusinessReceiveOutput,+ WhatsAppBusinessStatusNode,+ WhatsAppBusinessStatusOutput,+)+from .whatsapp_business_send import WhatsAppBusinessSendNode, WhatsAppBusinessSendOutput++# Claims POST/GET /webhook/whatsapp-business. Takes an instance, not the class.+# Without this the path falls through to the generic legacy handler, which+# would fire every deployed webhookTrigger instead of these nodes.+register_webhook_source(get_webhook_source())++# Opt both triggers into the Temporal listener path. The second argument must+# equal the ``type`` on the envelope the source emits -- it becomes the+# EventType Search Attribute the Visibility query matches on, and a mismatch+# is silent: the listener runs forever and never receives a signal.+register_canary_trigger_type(WhatsAppBusinessReceiveNode.type, MESSAGE_RECEIVED_TYPE)+register_canary_trigger_type(WhatsAppBusinessStatusNode.type, STATUS_UPDATED_TYPE)++register_output_schema(WhatsAppBusinessSendNode.type, WhatsAppBusinessSendOutput)+register_output_schema(WhatsAppBusinessReceiveNode.type, WhatsAppBusinessReceiveOutput)+register_output_schema(WhatsAppBusinessStatusNode.type, WhatsAppBusinessStatusOutput)++__all__ = [+ "WhatsAppBusinessCredential",+ "WhatsAppBusinessReceiveNode",+ "WhatsAppBusinessSendNode",+ "WhatsAppBusinessStatusNode",+]diff --git a/server/nodes/whatsapp_cloud/_base.py b/server/nodes/whatsapp_business/_base.pysimilarity index 97%rename from server/nodes/whatsapp_cloud/_base.pyrename to server/nodes/whatsapp_business/_base.pyindex 5c2488b5..3fab6cb6 100644--- a/server/nodes/whatsapp_cloud/_base.py+++ b/server/nodes/whatsapp_business/_base.py@@ -28,7 +28,7 @@ GRAPH_BASE_URL = "https://graph.facebook.com"# v23.0), so do not infer the current version from any single sample page.GRAPH_API_VERSION = "v25.0"-CREDENTIAL_ID = "whatsapp_cloud"+CREDENTIAL_ID = "whatsapp_business"# --------------------------------------------------------------------------@@ -222,12 +222,11 @@ async def resolve_phone_number_id(ctx: NodeContext) -> str:"""from services.plugin.deps import get_auth_service- stored = await get_auth_service().get_api_key("whatsapp_cloud_phone_number_id")+ stored = await get_auth_service().get_api_key("whatsapp_business_phone_number_id")if not stored:raise NodeUserError("No WhatsApp business phone number is configured. Add the Phone "- "Number ID to the WhatsApp Business (Meta) credential, or set it "- "on this node."+ "Number ID to the WhatsApp Business credential.")return str(stored).strip()diff --git a/server/nodes/whatsapp_cloud/_credentials.py b/server/nodes/whatsapp_business/_credentials.pysimilarity index 90%rename from server/nodes/whatsapp_cloud/_credentials.pyrename to server/nodes/whatsapp_business/_credentials.pyindex b27fe7c6..f6cb17c5 100644--- a/server/nodes/whatsapp_cloud/_credentials.py+++ b/server/nodes/whatsapp_business/_credentials.py@@ -4,7 +4,7 @@ Distinct from the ``whatsapp`` credential in ``nodes/whatsapp/``, which pairsa *personal* account over an unofficial Go bridge. Same product name, whollydifferent auth model, so they are separate ids and separate catalogue entries.-The brand icon must live beside this file as ``whatsapp_cloud.svg`` --+The brand icon must live beside this file as ``whatsapp_business.svg`` --``Credential.get_icon_path`` resolves ``<cls.id>.svg`` co-located with theclass, and nothing else is consulted."""@@ -16,7 +16,7 @@ import httpxfrom services.plugin.credential import ApiKeyCredential, ProbeResult-class WhatsAppCloudCredential(ApiKeyCredential):+class WhatsAppBusinessCredential(ApiKeyCredential):"""Graph API bearer token plus the fields the webhook and API need.``apiKey`` is deliberately **not** required at the catalogue level. The@@ -26,21 +26,21 @@ class WhatsAppCloudCredential(ApiKeyCredential):token."""- id = "whatsapp_cloud"- display_name = "WhatsApp Business (Meta)"+ id = "whatsapp_business"+ display_name = "WhatsApp Business"category = "Social"key_name = "Authorization"key_location = "bearer"extra_fields = (# HMAC key for X-Hub-Signature-256. This is the Meta *App Secret*,# not a per-webhook secret -- Meta issues no per-endpoint secret.- "whatsapp_cloud_app_secret",+ "whatsapp_business_app_secret",# Echoed back during the GET subscription handshake.- "whatsapp_cloud_verify_token",+ "whatsapp_business_verify_token",# Needed to list phone numbers and message templates.- "whatsapp_cloud_waba_id",+ "whatsapp_business_waba_id",# The business phone number messages are sent FROM.- "whatsapp_cloud_phone_number_id",+ "whatsapp_business_phone_number_id",)docs_url = "https://developers.facebook.com/documentation/business-messaging/whatsapp/get-started"@@ -56,7 +56,7 @@ class WhatsAppCloudCredential(ApiKeyCredential):from services.plugin.deps import get_auth_serviceauth = get_auth_service()- waba_id = await auth.get_api_key("whatsapp_cloud_waba_id")+ waba_id = await auth.get_api_key("whatsapp_business_waba_id")if not waba_id:return ProbeResult(valid=False,@@ -115,4 +115,4 @@ class WhatsAppCloudCredential(ApiKeyCredential):)-__all__ = ["WhatsAppCloudCredential"]+__all__ = ["WhatsAppBusinessCredential"]diff --git a/server/nodes/whatsapp_business/_events.py b/server/nodes/whatsapp_business/_events.pynew file mode 100644index 00000000..2cce8bb8--- /dev/null+++ b/server/nodes/whatsapp_business/_events.py@@ -0,0 +1,94 @@+"""CloudEvents factories and the dispatch wrapper for the Cloud API plugin.++Two things here are load-bearing and easy to get wrong.++**The base class does not reach deployed listeners.** ``WebhookSource.handle``+only calls ``event_waiter.dispatch``, which serves the canvas Run path.+Deployed triggers are Temporal ``TriggerListenerWorkflow`` executions reached+by ``services.events.dispatch.emit``. A source that does not call ``emit``+works perfectly when you press Run and does nothing at all once deployed.++**The type strings must match the canary registration exactly.** ``emit``+runs a Visibility query for ``EventType='<type>'``, and the listener carries+whatever ``register_canary_trigger_type`` recorded. A mismatch is silent: the+listener sits Running forever and no signal ever arrives.++Message and status events carry distinct types on purpose. Per-node filters+are not applied on the deployed push path, so the CloudEvents type is the+only discriminator that actually works there.+"""++from __future__ import annotations++from typing import Any, Dict, Mapping, Optional++from services.events.envelope import WorkflowEvent+++_SOURCE = "opencompany://nodes/whatsapp_business"++# Inner CloudEvents types. These exact strings are what+# ``register_canary_trigger_type`` records for each node.+MESSAGE_RECEIVED_TYPE = "com.opencompany.whatsapp_business.message.received"+STATUS_UPDATED_TYPE = "com.opencompany.whatsapp_business.status.updated"++# Outer WS wire keys. Distinct from the unofficial plugin's whatsapp_* keys,+# which are already claimed and would raise on registration.+_MESSAGE_WIRE_KEY = "whatsapp_business_message_received"+_STATUS_WIRE_KEY = "whatsapp_business_status_updated"+++def message_received(data: Mapping[str, Any], *, event_id: str) -> WorkflowEvent:+ """An inbound WhatsApp message.++ ``event_id`` is the ``wamid``, which Meta guarantees unique per message.+ The listener dedups on it, and Meta retries undelivered webhooks for up+ to seven days, so a stable id is what stops a replay re-running a+ workflow.+ """+ return WorkflowEvent(+ source=_SOURCE,+ type=MESSAGE_RECEIVED_TYPE,+ subject=str(data.get("from") or "") or None,+ data=dict(data),+ id=event_id,+ )+++def status_updated(data: Mapping[str, Any], *, event_id: str) -> WorkflowEvent:+ """A delivery-status callback for a message we sent.++ ``event_id`` must be ``<wamid>:<status>``, never the bare wamid. The same+ message legitimately reports sent -> delivered -> read, so deduping on+ the id alone would collapse the whole lifecycle into one event and drop+ two of the three.+ """+ return WorkflowEvent(+ source=_SOURCE,+ type=STATUS_UPDATED_TYPE,+ subject=str(data.get("status") or "") or None,+ data=dict(data),+ id=event_id,+ )+++async def emit_message_received(data: Mapping[str, Any], *, event_id: str) -> None:+ from services.events.dispatch import emit++ await emit(message_received(data, event_id=event_id), wire_routing_key=_MESSAGE_WIRE_KEY)+++async def emit_status_updated(data: Mapping[str, Any], *, event_id: str) -> None:+ from services.events.dispatch import emit++ await emit(status_updated(data, event_id=event_id), wire_routing_key=_STATUS_WIRE_KEY)+++__all__ = [+ "MESSAGE_RECEIVED_TYPE",+ "STATUS_UPDATED_TYPE",+ "emit_message_received",+ "emit_status_updated",+ "message_received",+ "status_updated",+]diff --git a/server/nodes/whatsapp_business/_source.py b/server/nodes/whatsapp_business/_source.pynew file mode 100644index 00000000..293fff2e--- /dev/null+++ b/server/nodes/whatsapp_business/_source.py@@ -0,0 +1,330 @@+"""Signed-webhook receiver for Meta's WhatsApp Cloud API.++Meta's delivery shape drives most of the design here:++* One POST can carry several ``entry[]``, each with several ``changes[]``,+ each ``value`` holding several ``messages[]`` and/or ``statuses[]``. Reading+ only ``entry[0].changes[0]`` is the documented common integration bug, so+ this fans out across all three levels.+* Ownership is verified with a ``GET`` that must echo ``hub.challenge`` as+ bare ``text/plain`` -- not the router's JSON body, hence ``handle_get``.+* Signatures are HMAC-SHA256 over the raw body under the Meta **App Secret**,+ in the same header and prefix GitHub uses.+"""++from __future__ import annotations++import hmac+from typing import Any, Dict, List, Optional, Tuple++from fastapi import Request, Response+from fastapi.responses import PlainTextResponse++from core.logging import get_logger+from services.events import WebhookSource, WorkflowEvent+from services.events.verifiers import HmacVerifier++from ._credentials import WhatsAppBusinessCredential+from ._events import (+ MESSAGE_RECEIVED_TYPE,+ emit_message_received,+ emit_status_updated,+ message_received,+ status_updated,+)++logger = get_logger(__name__)+++class MetaHubVerifier(HmacVerifier):+ """Meta signs exactly as GitHub does: ``X-Hub-Signature-256: sha256=<hex>``.++ Subclassed rather than reusing GitHubVerifier so the secret's identity is+ named at the call site: this is the **App Secret** from the Meta app+ dashboard, not a per-webhook secret. Meta issues no per-endpoint secret,+ which is a real difference from Stripe and easy to assume otherwise.++ Known risk: Meta's *Messenger* docs state the signature is computed over+ an escaped-unicode rendering of the payload rather than the raw bytes.+ That claim appears nowhere in the WhatsApp docs, and raw bytes verify+ correctly in practice, so raw bytes it is. If verification ever fails+ intermittently and the failures correlate with emoji or non-Latin names,+ this is the first thing to check -- hence the diagnostic in ``handle``.+ """++ header_name = "X-Hub-Signature-256"+ signature_prefix = "sha256="+++def _media_block(message: Dict[str, Any], msg_type: str) -> Optional[Dict[str, Any]]:+ """Normalise whichever media sub-object this message carries.++ Deliberately carries the ``id`` and no bytes. Downloading here would put+ the payload into the node result, which is persisted, broadcast and+ replayed into LLM context -- the whatsappBusinessMedia node downloads on+ demand instead.+ """+ payload = message.get(msg_type)+ if not isinstance(payload, dict):+ return None+ if msg_type not in {"image", "video", "audio", "document", "sticker"}:+ return None+ return {+ "kind": msg_type,+ "id": payload.get("id"),+ "mime_type": payload.get("mime_type"),+ "sha256": payload.get("sha256"),+ "filename": payload.get("filename"),+ "caption": payload.get("caption"),+ "voice": payload.get("voice"),+ "animated": payload.get("animated"),+ }+++def _text_of(message: Dict[str, Any], msg_type: str) -> str:+ """The human-readable body, whatever shape it arrived in.++ Buttons and interactive replies are the user speaking as much as a text+ message is, so a downstream agent should not have to branch on type just+ to read what someone said.+ """+ if msg_type == "text":+ return str((message.get("text") or {}).get("body") or "")+ if msg_type == "button":+ return str((message.get("button") or {}).get("text") or "")+ if msg_type == "interactive":+ interactive = message.get("interactive") or {}+ reply = interactive.get("button_reply") or interactive.get("list_reply") or {}+ return str(reply.get("title") or "")+ if msg_type in {"image", "video", "document"}:+ return str((message.get(msg_type) or {}).get("caption") or "")+ return ""+++def _interactive_reply(message: Dict[str, Any]) -> Optional[Dict[str, Any]]:+ interactive = message.get("interactive")+ if not isinstance(interactive, dict):+ button = message.get("button")+ if isinstance(button, dict):+ # A template quick-reply tap. `payload` is the developer-defined+ # id; `text` is the visible label.+ return {"kind": "button", "id": button.get("payload"), "title": button.get("text")}+ return None+ reply = interactive.get("button_reply") or interactive.get("list_reply") or {}+ return {+ "kind": interactive.get("type"),+ "id": reply.get("id"),+ "title": reply.get("title"),+ "description": reply.get("description"),+ }+++def shape_message(+ message: Dict[str, Any], metadata: Dict[str, Any], contacts: List[Dict[str, Any]]+) -> Dict[str, Any]:+ """Flatten one inbound message into the trigger's output.++ Kept flat because the deployed path uses ``event["data"]`` verbatim as the+ trigger output, and ``{{trigger.field}}`` resolves against its top level.+ A non-dict here is coerced to ``{}`` upstream, which would silently empty+ the trigger.+ """+ msg_type = str(message.get("type") or "")+ profile = (contacts[0].get("profile") if contacts else None) or {}+ return {+ "message_id": message.get("id"),+ "from": message.get("from"),+ "wa_id": (contacts[0].get("wa_id") if contacts else None),+ "profile_name": profile.get("name"),+ "timestamp": message.get("timestamp"),+ "type": msg_type,+ "text": _text_of(message, msg_type),+ "phone_number_id": metadata.get("phone_number_id"),+ "display_phone_number": metadata.get("display_phone_number"),+ "media": _media_block(message, msg_type),+ "interactive_reply": _interactive_reply(message),+ "reply_to_message_id": (message.get("context") or {}).get("id"),+ "location": message.get("location"),+ "contacts": message.get("contacts"),+ "reaction": message.get("reaction"),+ "errors": message.get("errors"),+ }+++def shape_status(status: Dict[str, Any], metadata: Dict[str, Any]) -> Dict[str, Any]:+ conversation = status.get("conversation") or {}+ pricing = status.get("pricing") or {}+ errors = status.get("errors") or []+ first_error = errors[0] if errors else {}+ return {+ "message_id": status.get("id"),+ "status": status.get("status"),+ "recipient_id": status.get("recipient_id"),+ "timestamp": status.get("timestamp"),+ "phone_number_id": metadata.get("phone_number_id"),+ "conversation_id": conversation.get("id"),+ # The programmatic read on when the 24-hour customer service window+ # closes, so a workflow can act before a send starts failing with 131047.+ "conversation_expires_at": conversation.get("expiration_timestamp"),+ "conversation_category": (conversation.get("origin") or {}).get("type"),+ "billable": pricing.get("billable"),+ # Open string on purpose: both CBP (deprecated) and PMP appear live,+ # and pricing.type exists only in the newer shape.+ "pricing_model": pricing.get("pricing_model"),+ "pricing_category": pricing.get("category"),+ "error_code": first_error.get("code"),+ "error_title": first_error.get("title"),+ "error_detail": (first_error.get("error_data") or {}).get("details"),+ # Our own correlation value, echoed back verbatim by Meta. More+ # reliable than matching on the wamid alone.+ "biz_opaque_callback_data": status.get("biz_opaque_callback_data"),+ }+++def iter_events(payload: Dict[str, Any]) -> List[Tuple[str, Dict[str, Any], str]]:+ """Flatten a webhook body into ``(kind, data, event_id)`` triples.++ Walks all three nesting levels. Status ids are composite+ (``<wamid>:<status>``) because one message reports sent, delivered and+ read under the same wamid and the listener dedups by id.+ """+ out: List[Tuple[str, Dict[str, Any], str]] = []+ for entry in payload.get("entry") or []:+ for change in (entry or {}).get("changes") or []:+ value = (change or {}).get("value") or {}+ metadata = value.get("metadata") or {}+ contacts = value.get("contacts") or []++ for message in value.get("messages") or []:+ message_id = message.get("id")+ if not message_id:+ # Without a stable id the listener drops it anyway, and a+ # minted one would defeat replay dedup.+ logger.warning("whatsapp cloud: inbound message without an id, skipping")+ continue+ out.append(("message", shape_message(message, metadata, contacts), str(message_id)))++ for status in value.get("statuses") or []:+ status_id = status.get("id")+ state = status.get("status")+ if not status_id or not state:+ logger.warning("whatsapp cloud: status without id/status, skipping")+ continue+ out.append(("status", shape_status(status, metadata), f"{status_id}:{state}"))++ for error in value.get("errors") or []:+ # Account/app-level errors are not a trigger firing -- there is+ # no message and no workflow to run -- but they are the only+ # signal for things like a token going bad, so they are logged.+ logger.warning(+ "whatsapp cloud account-level error",+ code=error.get("code"),+ title=error.get("title"),+ detail=(error.get("error_data") or {}).get("details"),+ )+ return out+++class WhatsAppBusinessWebhookSource(WebhookSource):+ type = "whatsapp_business.webhook"+ path = "whatsapp-business"+ verifier = MetaHubVerifier+ secret_field = "whatsapp_business_app_secret"+ credential = WhatsAppBusinessCredential++ async def handle_get(self, request: Request) -> Optional[Response]:+ """Answer Meta's subscription handshake.++ Meta sends ``hub.mode=subscribe``, ``hub.verify_token`` and+ ``hub.challenge``, and requires the bare challenge echoed back. Its+ docs describe the challenge as a string on the WhatsApp page and an+ int on the Graph page, so it is echoed verbatim -- which satisfies+ both readings.+ """+ params = request.query_params+ challenge = params.get("hub.challenge")+ supplied = params.get("hub.verify_token")+ if challenge is None or supplied is None:+ # Not a handshake; let the normal POST path deal with it.+ return None++ expected = None+ try:+ secrets = await self.credential.resolve()+ expected = secrets.get("whatsapp_business_verify_token")+ except PermissionError:+ expected = None++ if not expected:+ logger.warning("whatsapp cloud: handshake attempted with no verify token stored")+ return PlainTextResponse("verify token not configured", status_code=403)++ if not hmac.compare_digest(str(expected), str(supplied)):+ logger.warning("whatsapp cloud: handshake rejected, verify token mismatch")+ return PlainTextResponse("verification failed", status_code=403)++ logger.info("whatsapp cloud: webhook subscription verified")+ return PlainTextResponse(str(challenge))++ async def shape(self, request: Request, body: bytes, payload: dict) -> WorkflowEvent:+ """Shaping happens here, not in the node's ``shape_output``.++ ``shape_output`` runs only on the canvas Run path. When deployed the+ trigger output is ``event["data"]`` verbatim, so shaping there would+ make Run and deploy disagree about the output shape.++ A single return value cannot express a batch, so every event is+ emitted directly and the last is returned for the caller's logging.+ """+ events = iter_events(payload)+ if not events:+ return WorkflowEvent(source="opencompany://nodes/whatsapp_business", type=MESSAGE_RECEIVED_TYPE, data={})++ last: Optional[WorkflowEvent] = None+ for kind, data, event_id in events:+ if kind == "message":+ await emit_message_received(data, event_id=event_id)+ last = message_received(data, event_id=event_id)+ else:+ await emit_status_updated(data, event_id=event_id)+ last = status_updated(data, event_id=event_id)+ return last # type: ignore[return-value]++ async def handle(self, request: Request) -> WorkflowEvent:+ try:+ return await super().handle(request)+ except Exception:+ # Non-ASCII in the body is the fingerprint of the escaped-unicode+ # signature question documented on MetaHubVerifier. Recording it+ # here turns "signatures fail sometimes" into a one-line answer.+ try:+ raw = await request.body()+ if any(byte > 127 for byte in raw):+ logger.warning(+ "whatsapp cloud: webhook failed on a payload containing "+ "non-ASCII bytes -- if this correlates with emoji or "+ "non-Latin names, check the escaped-unicode signature note"+ )+ except Exception: # pragma: no cover - diagnostics must never mask+ pass+ raise+++_source: Optional[WhatsAppBusinessWebhookSource] = None+++def get_webhook_source() -> WhatsAppBusinessWebhookSource:+ global _source+ if _source is None:+ _source = WhatsAppBusinessWebhookSource()+ return _source+++__all__ = [+ "MetaHubVerifier",+ "WhatsAppBusinessWebhookSource",+ "get_webhook_source",+ "iter_events",+ "shape_message",+ "shape_status",+]diff --git a/server/nodes/whatsapp_cloud/icon.svg b/server/nodes/whatsapp_business/icon.svgsimilarity index 100%rename from server/nodes/whatsapp_cloud/icon.svgrename to server/nodes/whatsapp_business/icon.svgdiff --git a/server/nodes/whatsapp_cloud/icon_whatsappCloudSend.svg b/server/nodes/whatsapp_business/icon_whatsappBusinessSend.svgsimilarity index 100%rename from server/nodes/whatsapp_cloud/icon_whatsappCloudSend.svgrename to server/nodes/whatsapp_business/icon_whatsappBusinessSend.svgdiff --git a/server/nodes/whatsapp_cloud/meta.json b/server/nodes/whatsapp_business/meta.jsonsimilarity index 100%rename from server/nodes/whatsapp_cloud/meta.jsonrename to server/nodes/whatsapp_business/meta.jsondiff --git a/server/nodes/whatsapp_cloud/whatsapp_cloud.svg b/server/nodes/whatsapp_business/whatsapp_business.svgsimilarity index 100%rename from server/nodes/whatsapp_cloud/whatsapp_cloud.svgrename to server/nodes/whatsapp_business/whatsapp_business.svgdiff --git a/server/nodes/whatsapp_business/whatsapp_business_receive.py b/server/nodes/whatsapp_business/whatsapp_business_receive.pynew file mode 100644index 00000000..9b247d26--- /dev/null+++ b/server/nodes/whatsapp_business/whatsapp_business_receive.py@@ -0,0 +1,153 @@+"""Inbound triggers for the WhatsApp Cloud API.++Two nodes rather than one with a mode switch. Per-node filters are not+applied on the deployed push path -- only the CloudEvents type is -- so a+``trigger_on: messages | statuses`` parameter would work when you press Run+and silently fire on everything once deployed. Separate node types get+separate type strings, which is the discriminator that actually works.+"""++from __future__ import annotations++from typing import Dict, List, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.events import BaseTriggerParams, WebhookTriggerNode, WorkflowEvent++from ._credentials import WhatsAppBusinessCredential+from ._source import WhatsAppBusinessWebhookSource++_OUTPUT_HANDLE = (+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},+)+++class WhatsAppBusinessMediaRef(BaseModel):+ """The media *id* Meta sends, never the bytes.++ Downloading during the trigger would put the payload into the node+ result, which is persisted, broadcast and replayed into LLM context.+ whatsappBusinessMedia resolves this on demand instead.+ """++ kind: Optional[str] = None+ id: Optional[str] = None+ mime_type: Optional[str] = None+ sha256: Optional[str] = None+ filename: Optional[str] = None+ caption: Optional[str] = None+ voice: Optional[bool] = None+ animated: Optional[bool] = None++ model_config = ConfigDict(extra="allow")+++class WhatsAppBusinessInteractiveReply(BaseModel):+ kind: Optional[str] = None+ id: Optional[str] = None+ title: Optional[str] = None+ description: Optional[str] = None++ model_config = ConfigDict(extra="allow")+++class WhatsAppBusinessReceiveOutput(BaseModel):+ message_id: Optional[str] = None+ # ``from`` is a Python keyword, so the field is declared by alias. Meta's+ # payload uses the bare name and the trigger output is consumed as+ # {{node.from}}, so renaming it would break the obvious template.+ from_: Optional[str] = Field(default=None, alias="from")+ wa_id: Optional[str] = None+ profile_name: Optional[str] = None+ timestamp: Optional[str] = None+ type: Optional[str] = None+ text: Optional[str] = None+ phone_number_id: Optional[str] = None+ display_phone_number: Optional[str] = None+ media: Optional[WhatsAppBusinessMediaRef] = None+ interactive_reply: Optional[WhatsAppBusinessInteractiveReply] = None+ reply_to_message_id: Optional[str] = None+ location: Optional[dict] = None+ contacts: Optional[List[dict]] = None+ reaction: Optional[dict] = None+ errors: Optional[List[dict]] = None++ model_config = ConfigDict(extra="allow", populate_by_name=True)+++class WhatsAppBusinessStatusOutput(BaseModel):+ message_id: Optional[str] = None+ status: Optional[str] = None+ recipient_id: Optional[str] = None+ timestamp: Optional[str] = None+ phone_number_id: Optional[str] = None+ conversation_id: Optional[str] = None+ conversation_expires_at: Optional[str] = None+ conversation_category: Optional[str] = None+ billable: Optional[bool] = None+ pricing_model: Optional[str] = None+ pricing_category: Optional[str] = None+ error_code: Optional[int] = None+ error_title: Optional[str] = None+ error_detail: Optional[str] = None+ biz_opaque_callback_data: Optional[str] = None++ model_config = ConfigDict(extra="allow")+++class WhatsAppBusinessReceiveNode(WebhookTriggerNode):+ type = "whatsappBusinessReceive"+ display_name = "WhatsApp Business Receive"+ subtitle = "Inbound message"+ group = ("whatsapp_business", "trigger")+ description = "Trigger when a WhatsApp user messages your business number"+ component_kind = "trigger"+ handles = _OUTPUT_HANDLE+ credentials = (WhatsAppBusinessCredential,)+ webhook_source = WhatsAppBusinessWebhookSource+ event_type_prefix = "com.opencompany.whatsapp_business.message."+ Params = BaseTriggerParams+ Output = WhatsAppBusinessReceiveOutput++ async def _check_precondition(self) -> Optional[str]:+ """Fail fast on the canvas instead of waiting out the 24h timeout."""+ try:+ secrets = await WhatsAppBusinessCredential.resolve()+ except PermissionError:+ return (+ "WhatsApp Business is not connected. Add the credential in "+ "Credentials first."+ )+ if not secrets.get("whatsapp_business_app_secret"):+ return (+ "Add the Meta App Secret to the WhatsApp Business credential -- "+ "inbound webhooks cannot be verified without it."+ )+ return None+++class WhatsAppBusinessStatusNode(WebhookTriggerNode):+ type = "whatsappBusinessStatus"+ display_name = "WhatsApp Business Status"+ subtitle = "Delivery status"+ group = ("whatsapp_business", "trigger")+ description = "Trigger on sent / delivered / read / failed callbacks for messages you sent"+ component_kind = "trigger"+ handles = _OUTPUT_HANDLE+ credentials = (WhatsAppBusinessCredential,)+ webhook_source = WhatsAppBusinessWebhookSource+ event_type_prefix = "com.opencompany.whatsapp_business.status."+ Params = BaseTriggerParams+ Output = WhatsAppBusinessStatusOutput++ async def _check_precondition(self) -> Optional[str]:+ return await WhatsAppBusinessReceiveNode._check_precondition(self) # type: ignore[arg-type]+++__all__ = [+ "WhatsAppBusinessReceiveNode",+ "WhatsAppBusinessReceiveOutput",+ "WhatsAppBusinessStatusNode",+ "WhatsAppBusinessStatusOutput",+]diff --git a/server/nodes/whatsapp_cloud/whatsapp_cloud_send.py b/server/nodes/whatsapp_business/whatsapp_business_send.pysimilarity index 85%rename from server/nodes/whatsapp_cloud/whatsapp_cloud_send.pyrename to server/nodes/whatsapp_business/whatsapp_business_send.pyindex 66a42e83..601307f0 100644--- a/server/nodes/whatsapp_cloud/whatsapp_cloud_send.py+++ b/server/nodes/whatsapp_business/whatsapp_business_send.py@@ -1,4 +1,4 @@-"""whatsappCloudSend — send a message via Meta's WhatsApp Cloud API."""+"""whatsappBusinessSend — send a message via Meta's WhatsApp Cloud API."""from __future__ import annotations@@ -9,7 +9,7 @@ from pydantic import BaseModel, ConfigDict, Fieldfrom services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueuefrom ._base import graph_post, normalize_recipient, resolve_phone_number_id-from ._credentials import WhatsAppCloudCredential+from ._credentials import WhatsAppBusinessCredential# Meta's documented ceiling for a text body. Longer bodies are rejected# outright rather than truncated: silently dropping the tail of an outbound@@ -17,7 +17,7 @@ from ._credentials import WhatsAppCloudCredential_MAX_TEXT_BODY = 4096-class WhatsAppCloudSendParams(BaseModel):+class WhatsAppBusinessSendParams(BaseModel):"""Operator configuration, persisted on the node."""to: str = Field(@@ -60,7 +60,7 @@ class WhatsAppCloudSendParams(BaseModel):model_config = ConfigDict(extra="ignore")-class WhatsAppCloudSendOutput(BaseModel):+class WhatsAppBusinessSendOutput(BaseModel):message_id: Optional[str] = Noneto: Optional[str] = Nonewa_id: Optional[str] = None@@ -72,14 +72,14 @@ class WhatsAppCloudSendOutput(BaseModel):model_config = ConfigDict(extra="allow")-class WhatsAppCloudSendNode(ActionNode):- type = "whatsappCloudSend"- display_name = "WhatsApp Send (Business API)"+class WhatsAppBusinessSendNode(ActionNode):+ type = "whatsappBusinessSend"+ display_name = "WhatsApp Business Send"subtitle = "Cloud API"- group = ("whatsapp_cloud", "tool")+ group = ("whatsapp_business", "tool")description = "Send a WhatsApp message through Meta's official Cloud API"component_kind = "square"- tool_name = "whatsapp_cloud_send"+ tool_name = "whatsapp_business_send"tool_description = ("Send a WhatsApp text message to a phone number using the official ""WhatsApp Business Cloud API. Only works if the recipient messaged the "@@ -90,7 +90,7 @@ class WhatsAppCloudSendNode(ActionNode):{"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},{"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},)- credentials = (WhatsAppCloudCredential,)+ credentials = (WhatsAppBusinessCredential,)annotations = {"destructive": False, "readonly": False, "open_world": True}task_queue = TaskQueue.MESSAGINGusable_as_tool = True@@ -100,15 +100,15 @@ class WhatsAppCloudSendNode(ActionNode):# silently inert (BaseNode.execute_as_tool short-circuits before reading# them), so declaring them would advertise a protection that does not# exist. Fields the model must not control are kept out of Params instead.- Params = WhatsAppCloudSendParams- Output = WhatsAppCloudSendOutput+ Params = WhatsAppBusinessSendParams+ Output = WhatsAppBusinessSendOutput- @Operation("send_text", cost={"service": "whatsapp_cloud", "action": "send_text", "count": 1})+ @Operation("send_text", cost={"service": "whatsapp_business", "action": "send_text", "count": 1})async def send_text(self,ctx: NodeContext,- params: WhatsAppCloudSendParams,- ) -> WhatsAppCloudSendOutput:+ params: WhatsAppBusinessSendParams,+ ) -> WhatsAppBusinessSendOutput:recipient = normalize_recipient(params.to)body = params.text or ""if not body.strip():@@ -145,7 +145,7 @@ class WhatsAppCloudSendNode(ActionNode):contacts: List[Dict[str, Any]] = result.get("contacts") or []first = messages[0] if messages else {}- return WhatsAppCloudSendOutput(+ return WhatsAppBusinessSendOutput(message_id=first.get("id"),message_status=first.get("message_status"),to=recipient,@@ -155,7 +155,7 @@ class WhatsAppCloudSendNode(ActionNode):__all__ = [- "WhatsAppCloudSendNode",- "WhatsAppCloudSendOutput",- "WhatsAppCloudSendParams",+ "WhatsAppBusinessSendNode",+ "WhatsAppBusinessSendOutput",+ "WhatsAppBusinessSendParams",]diff --git a/server/nodes/whatsapp_cloud/__init__.py b/server/nodes/whatsapp_cloud/__init__.pydeleted file mode 100644index ee1fc668..00000000--- a/server/nodes/whatsapp_cloud/__init__.py+++ /dev/null@@ -1,24 +0,0 @@-"""Official Meta WhatsApp Business Platform (Cloud API) plugin.--Distinct from ``nodes/whatsapp/``, which drives a *personal* account through-an unofficial Go bridge and QR pairing. Both ship; they share no node types,-no credential id, no WebSocket keys and no palette group, because the auth-models, capabilities and failure modes have nothing in common.--Importing the node modules is what registers them ---``BaseNode.__init_subclass__`` does the work, so this file stays pure wiring.-"""--from __future__ import annotations--from services.node_output_schemas import register_output_schema--from ._credentials import WhatsAppCloudCredential-from .whatsapp_cloud_send import WhatsAppCloudSendNode, WhatsAppCloudSendOutput--register_output_schema(WhatsAppCloudSendNode.type, WhatsAppCloudSendOutput)--__all__ = [- "WhatsAppCloudCredential",- "WhatsAppCloudSendNode",-]diff --git a/server/tests/nodes/test_whatsapp_business.py b/server/tests/nodes/test_whatsapp_business.pynew file mode 100644index 00000000..07885c48--- /dev/null+++ b/server/tests/nodes/test_whatsapp_business.py@@ -0,0 +1,568 @@+"""Contract for the official Meta WhatsApp Cloud API plugin.++The security-relevant test here is ``TestModelCannotChooseTheSendingNumber``.+On a dual-purpose ActionNode the split-schema machinery does not apply --+``BaseNode.execute_as_tool`` merges ``{**node_params, **tool_args}`` for+anything that is not a ToolNode -- so the only way to keep a field away from+the model is to keep it out of Params entirely. This asserts that holds.+"""++from __future__ import annotations++import asyncio+from types import SimpleNamespace+from unittest.mock import AsyncMock, patch++import pytest++from nodes.whatsapp_business._base import classify_error, normalize_recipient+from nodes.whatsapp_business.whatsapp_business_send import (+ WhatsAppBusinessSendNode,+ WhatsAppBusinessSendParams,+)+from services.plugin import NodeUserError+++pytestmark = pytest.mark.unit+++def _run(coro):+ return asyncio.new_event_loop().run_until_complete(coro)+++def _ctx(**raw):+ return SimpleNamespace(+ node_id="wac-1",+ node_type="whatsappBusinessSend",+ workflow_id="wf-1",+ session_id="default",+ user_id="owner",+ workspace_dir=None,+ outputs={},+ nodes=[],+ edges=[],+ raw=dict(raw),+ )+++class TestParamsShape:+ def test_phone_number_id_is_not_a_parameter(self):+ """It selects the business identity a message is sent FROM.++ Declaring it would make it model-settable on this node kind, so it is+ credential-sourced instead. If someone adds it back, this fails.+ """+ assert "phone_number_id" not in WhatsAppBusinessSendParams.model_fields++ def test_tool_schema_never_exposes_the_sending_number(self):+ schema = WhatsAppBusinessSendParams.model_json_schema()+ assert "phone_number_id" not in schema.get("properties", {})++ def test_tool_facing_schema_is_flat(self):+ """LLM function-calling rejects $ref; the contract test enforces this+ repo-wide, asserted here too so the reason is local."""+ import json++ schema = WhatsAppBusinessSendParams.model_json_schema()+ assert "$defs" not in schema+ assert "$ref" not in json.dumps(schema)+++class TestModelCannotChooseTheSendingNumber:+ def test_tool_args_cannot_override_the_credential_number(self):+ """Drive the real tool path, not the schema.++ A prompt injection in an inbound WhatsApp message is the realistic+ source of hostile tool arguments, and sending as another tenant's+ number is the worst outcome available here.+ """+ node = WhatsAppBusinessSendNode()+ captured = {}++ async def _fake_post(ctx, path, body=None, **kwargs):+ captured["path"] = path+ captured["body"] = body+ return {+ "messages": [{"id": "wamid.TEST"}],+ "contacts": [{"wa_id": "14155551234"}],+ }++ with (+ patch("nodes.whatsapp_business.whatsapp_business_send.graph_post", new=_fake_post),+ patch(+ "services.plugin.deps.get_auth_service",+ return_value=SimpleNamespace(get_api_key=AsyncMock(return_value="OPERATOR_NUMBER")),+ ),+ ):+ result = _run(+ node.execute_as_tool(+ {"to": "+14155551234", "text": "hi", "phone_number_id": "ATTACKER_NUMBER"},+ {},+ _ctx(),+ )+ )++ assert "ATTACKER_NUMBER" not in captured["path"]+ assert captured["path"].startswith("OPERATOR_NUMBER/")+ assert result.get("phone_number_id") == "OPERATOR_NUMBER"++ def test_missing_credential_number_is_a_clear_error(self):+ node = WhatsAppBusinessSendNode()++ with patch(+ "services.plugin.deps.get_auth_service",+ return_value=SimpleNamespace(get_api_key=AsyncMock(return_value=None)),+ ):+ envelope = _run(+ node.execute("wac-1", {"to": "+14155551234", "text": "hi"}, _ctx())+ )++ assert envelope["success"] is False+ assert envelope["error_type"] == "NodeUserError"+ assert "phone number" in envelope["error"].lower()+++class TestSendText:+ def _send(self, params, *, number="PN1"):+ node = WhatsAppBusinessSendNode()+ captured = {}++ async def _fake_post(ctx, path, body=None, **kwargs):+ captured["path"] = path+ captured["body"] = body+ return {"messages": [{"id": "wamid.X"}], "contacts": [{"wa_id": "1"}]}++ with (+ patch("nodes.whatsapp_business.whatsapp_business_send.graph_post", new=_fake_post),+ patch(+ "services.plugin.deps.get_auth_service",+ return_value=SimpleNamespace(get_api_key=AsyncMock(return_value=number)),+ ),+ ):+ _run(node.execute("wac-1", params, _ctx()))+ return captured++ def test_builds_the_documented_text_envelope(self):+ captured = self._send({"to": "+1 (415) 555-1234", "text": "hello", "format_markdown": False})+ assert captured["body"] == {+ "messaging_product": "whatsapp",+ "recipient_type": "individual",+ # Punctuation a user would paste from a contacts app is stripped;+ # Meta rejects it as error 131009 otherwise.+ "to": "+14155551234",+ "type": "text",+ "text": {"preview_url": False, "body": "hello"},+ }++ def test_reply_threads_via_context(self):+ captured = self._send(+ {"to": "+14155551234", "text": "hi", "reply_to_message_id": "wamid.PARENT", "format_markdown": False}+ )+ assert captured["body"]["context"] == {"message_id": "wamid.PARENT"}++ def test_no_context_key_when_not_replying(self):+ captured = self._send({"to": "+14155551234", "text": "hi", "format_markdown": False})+ assert "context" not in captured["body"]++ def test_markdown_is_converted_by_default(self):+ captured = self._send({"to": "+14155551234", "text": "**bold**"})+ assert captured["body"]["text"]["body"] == "*bold*"++ def test_oversize_body_is_refused_not_truncated(self):+ """Silently dropping the tail of a business message is worse than+ failing."""+ node = WhatsAppBusinessSendNode()+ with patch(+ "services.plugin.deps.get_auth_service",+ return_value=SimpleNamespace(get_api_key=AsyncMock(return_value="PN1")),+ ):+ envelope = _run(+ node.execute(+ "wac-1",+ {"to": "+14155551234", "text": "a" * 5000, "format_markdown": False},+ _ctx(),+ )+ )+ assert envelope["success"] is False+ assert "4096" in envelope["error"]++ def test_empty_body_is_refused(self):+ node = WhatsAppBusinessSendNode()+ with patch(+ "services.plugin.deps.get_auth_service",+ return_value=SimpleNamespace(get_api_key=AsyncMock(return_value="PN1")),+ ):+ envelope = _run(node.execute("wac-1", {"to": "+14155551234", "text": " "}, _ctx()))+ assert envelope["success"] is False+++class TestRecipientNormalization:+ @pytest.mark.parametrize(+ "raw,expected",+ [+ ("+1 (415) 555-1234", "+14155551234"),+ ("14155551234", "14155551234"),+ ("+44 20 7946 0958", "+442079460958"),+ ],+ )+ def test_punctuation_is_stripped(self, raw, expected):+ assert normalize_recipient(raw) == expected++ @pytest.mark.parametrize("raw", ["", " ", "+", "not-a-number"])+ def test_unusable_input_is_refused(self, raw):+ with pytest.raises(NodeUserError):+ normalize_recipient(raw)+++class TestErrorClassification:+ @pytest.mark.parametrize(+ "code,category,retryable",+ [+ (190, "auth", True),+ (0, "auth", True),+ (10, "permission", False),+ (200, "permission", False),+ (130429, "throttle", True),+ (131056, "throttle", True),+ (131057, "transient", True),+ (131047, "window_closed", False),+ (131050, "policy", False),+ (132000, "template", False),+ (133015, "account", False),+ ],+ )+ def test_codes_land_in_the_right_class(self, code, category, retryable):+ assert classify_error(code) == (category, retryable)++ def test_throttles_are_not_node_user_errors(self):+ """NodeUserError is non-retryable in the shared policy, so raising one+ for a throttle would defeat the backoff Meta asks for."""+ from nodes.whatsapp_business._base import raise_for_graph_error++ with pytest.raises(RuntimeError) as exc:+ raise_for_graph_error(+ {"error": {"code": 130429, "message": "Rate limit hit"}}, 429+ )+ assert not isinstance(exc.value, NodeUserError)++ def test_window_closed_points_at_the_template_node(self):+ from nodes.whatsapp_business._base import raise_for_graph_error++ with pytest.raises(NodeUserError) as exc:+ raise_for_graph_error({"error": {"code": 131047, "message": "Re-engagement"}}, 400)+ assert "Template" in str(exc.value)++ def test_auth_failure_carries_credential_annotations(self):+ """The annotated PermissionError is what produces the reconnect chip."""+ from nodes.whatsapp_business._base import raise_for_graph_error++ with pytest.raises(PermissionError) as exc:+ raise_for_graph_error({"error": {"code": 190, "message": "expired"}}, 401)+ assert exc.value.provider == "whatsapp_business"+ assert exc.value.auth == "api_key"+++class TestGraphVersionPin:+ def test_version_is_pinned_not_derived(self):+ """An expired Graph version does not error -- Meta silently falls+ through to the next oldest, so the pin must be explicit."""+ from nodes.whatsapp_business._base import GRAPH_API_VERSION++ assert GRAPH_API_VERSION.startswith("v")+ assert GRAPH_API_VERSION[1:].replace(".", "").isdigit()+++# ==========================================================================+# Trigger — the deployed path+# ==========================================================================+#+# Every failure covered here is invisible on the canvas Run path. That is the+# whole reason they are asserted: pressing Run exercises event_waiter, while+# deploy goes through dispatch.emit -> Temporal Visibility -> a listener whose+# EventType Search Attribute has to match the envelope exactly.+++class TestTriggerIsDeployable:+ def test_trigger_types_are_registered_for_deployment(self):+ """find_trigger_nodes filters on this set. Omission means deploy+ silently ignores the node -- no listener, no error."""+ from constants import WORKFLOW_TRIGGER_TYPES++ assert "whatsappBusinessReceive" in WORKFLOW_TRIGGER_TYPES+ assert "whatsappBusinessStatus" in WORKFLOW_TRIGGER_TYPES++ def test_canary_types_match_the_emitted_envelope(self):+ """A mismatch here is the silent killer: the Visibility query asks for+ one string, the listener advertises another, and no signal arrives."""+ from nodes.whatsapp_business._events import MESSAGE_RECEIVED_TYPE, STATUS_UPDATED_TYPE+ from services.deployment.canary_registry import cloudevent_type_for++ assert cloudevent_type_for("whatsappBusinessReceive") == MESSAGE_RECEIVED_TYPE+ assert cloudevent_type_for("whatsappBusinessStatus") == STATUS_UPDATED_TYPE++ def test_emitted_types_match_the_node_prefixes(self):+ from nodes.whatsapp_business._events import MESSAGE_RECEIVED_TYPE, STATUS_UPDATED_TYPE+ from nodes.whatsapp_business.whatsapp_business_receive import (+ WhatsAppBusinessReceiveNode,+ WhatsAppBusinessStatusNode,+ )++ assert MESSAGE_RECEIVED_TYPE.startswith(WhatsAppBusinessReceiveNode.event_type_prefix)+ assert STATUS_UPDATED_TYPE.startswith(WhatsAppBusinessStatusNode.event_type_prefix)++ def test_webhook_path_is_claimed(self):+ from services.events import WEBHOOK_SOURCES++ assert "whatsapp-business" in WEBHOOK_SOURCES++ def test_triggers_have_no_input_handles(self):+ from nodes.whatsapp_business.whatsapp_business_receive import (+ WhatsAppBusinessReceiveNode,+ WhatsAppBusinessStatusNode,+ )++ for node in (WhatsAppBusinessReceiveNode, WhatsAppBusinessStatusNode):+ assert not [h for h in node.handles if h["kind"] == "input"]+++def _webhook_body(*, messages=None, statuses=None, entries=1):+ """Build a Meta webhook payload with a controllable nesting shape."""+ value = {+ "messaging_product": "whatsapp",+ "metadata": {"display_phone_number": "15550783881", "phone_number_id": "PN1"},+ }+ if messages is not None:+ value["contacts"] = [{"profile": {"name": "Sheena"}, "wa_id": "16505551234"}]+ value["messages"] = messages+ if statuses is not None:+ value["statuses"] = statuses+ return {+ "object": "whatsapp_business_account",+ "entry": [{"id": "WABA1", "changes": [{"value": value, "field": "messages"}]} for _ in range(entries)],+ }+++def _text_message(mid: str):+ return {+ "from": "16505551234",+ "id": mid,+ "timestamp": "1749416383",+ "type": "text",+ "text": {"body": "Does it come in another color?"},+ }+++class TestThreeLevelFanOut:+ """Reading only entry[0].changes[0] is the documented common bug."""++ def test_every_entry_and_message_produces_an_event(self):+ from nodes.whatsapp_business._source import iter_events++ body = _webhook_body(messages=[_text_message("wamid.A"), _text_message("wamid.B")], entries=2)+ events = iter_events(body)++ assert len(events) == 4+ assert {event_id for _, _, event_id in events} == {"wamid.A", "wamid.B"}++ def test_messages_and_statuses_in_one_payload_both_surface(self):+ from nodes.whatsapp_business._source import iter_events++ body = _webhook_body(+ messages=[_text_message("wamid.A")],+ statuses=[{"id": "wamid.OUT", "status": "delivered", "recipient_id": "165"}],+ )+ kinds = [kind for kind, _, _ in iter_events(body)]+ assert kinds == ["message", "status"]++ def test_message_without_an_id_is_dropped(self):+ """A minted id would defeat replay dedup across Meta's 7-day retries."""+ from nodes.whatsapp_business._source import iter_events++ body = _webhook_body(messages=[{"from": "165", "type": "text", "text": {"body": "x"}}])+ assert iter_events(body) == []++ def test_empty_payload_yields_nothing(self):+ from nodes.whatsapp_business._source import iter_events++ assert iter_events({"entry": []}) == []+++class TestStatusDedupKey:+ def test_status_ids_are_composite_not_bare_wamids(self):+ """The same wamid reports sent -> delivered -> read. Deduping on the+ wamid alone would collapse the lifecycle into one event and the+ listener would drop two of the three."""+ from nodes.whatsapp_business._source import iter_events++ body = _webhook_body(+ statuses=[+ {"id": "wamid.OUT", "status": "sent", "recipient_id": "165"},+ {"id": "wamid.OUT", "status": "delivered", "recipient_id": "165"},+ {"id": "wamid.OUT", "status": "read", "recipient_id": "165"},+ ]+ )+ ids = [event_id for _, _, event_id in iter_events(body)]+ assert ids == ["wamid.OUT:sent", "wamid.OUT:delivered", "wamid.OUT:read"]+ assert len(set(ids)) == 3+++class TestMessageShaping:+ def test_output_is_flat_for_template_resolution(self):+ """Deployed, event["data"] IS the trigger output and {{trigger.field}}+ resolves against its top level."""+ from nodes.whatsapp_business._source import iter_events++ (_, data, _), = iter_events(_webhook_body(messages=[_text_message("wamid.A")]))+ assert data["message_id"] == "wamid.A"+ assert data["from"] == "16505551234"+ assert data["text"] == "Does it come in another color?"+ assert data["profile_name"] == "Sheena"+ assert data["phone_number_id"] == "PN1"++ def test_media_carries_an_id_and_never_bytes(self):+ from nodes.whatsapp_business._source import iter_events++ message = {+ "from": "165",+ "id": "wamid.IMG",+ "type": "image",+ "image": {"id": "MEDIA123", "mime_type": "image/jpeg", "sha256": "abc", "caption": "look"},+ }+ (_, data, _), = iter_events(_webhook_body(messages=[message]))+ assert data["media"]["id"] == "MEDIA123"+ assert data["text"] == "look"+ serialized = str(data)+ assert "base64" not in serialized and "data:" not in serialized++ def test_interactive_reply_reads_as_text(self):+ """A button tap is the user speaking; downstream should not have to+ branch on message type to read it."""+ from nodes.whatsapp_business._source import iter_events++ message = {+ "from": "165",+ "id": "wamid.INT",+ "type": "interactive",+ "interactive": {"type": "button_reply", "button_reply": {"id": "cancel", "title": "Cancel"}},+ }+ (_, data, _), = iter_events(_webhook_body(messages=[message]))+ assert data["text"] == "Cancel"+ assert data["interactive_reply"]["id"] == "cancel"++ def test_status_exposes_the_window_expiry(self):+ from nodes.whatsapp_business._source import iter_events++ status = {+ "id": "wamid.OUT",+ "status": "sent",+ "recipient_id": "165",+ "conversation": {"id": "c1", "expiration_timestamp": "1750116480", "origin": {"type": "marketing"}},+ "pricing": {"billable": True, "pricing_model": "PMP", "category": "marketing"},+ }+ (_, data, _), = iter_events(_webhook_body(statuses=[status]))+ assert data["conversation_expires_at"] == "1750116480"+ assert data["pricing_model"] == "PMP"+++class TestSubscriptionHandshake:+ def _request(self, **params):+ return SimpleNamespace(method="GET", headers={}, query_params=params)++ def _source(self, verify_token):+ from nodes.whatsapp_business._source import WhatsAppBusinessWebhookSource++ class _Cred:+ @classmethod+ async def resolve(cls):+ if verify_token is None:+ raise PermissionError+ return {"whatsapp_business_verify_token": verify_token}++ source = WhatsAppBusinessWebhookSource()+ source.credential = _Cred+ return source++ def test_correct_token_echoes_the_bare_challenge(self):+ """Meta rejects a JSON envelope here -- it wants the raw value."""+ source = self._source("s3cret")+ resp = _run(source.handle_get(self._request(**{"hub.mode": "subscribe", "hub.verify_token": "s3cret", "hub.challenge": "1158201444"})))+ assert resp.status_code == 200+ assert resp.body == b"1158201444"+ assert resp.media_type == "text/plain"++ def test_wrong_token_is_refused(self):+ source = self._source("s3cret")+ resp = _run(source.handle_get(self._request(**{"hub.verify_token": "guess", "hub.challenge": "123"})))+ assert resp.status_code == 403++ def test_unconfigured_token_refuses_rather_than_accepting(self):+ source = self._source(None)+ resp = _run(source.handle_get(self._request(**{"hub.verify_token": "anything", "hub.challenge": "123"})))+ assert resp.status_code == 403++ def test_non_handshake_get_falls_through(self):+ source = self._source("s3cret")+ assert _run(source.handle_get(self._request())) is None+++class TestSourceReachesDeployedListeners:+ """The single highest-value test in this file.++ WebhookSource.handle only calls event_waiter.dispatch, which serves the+ canvas Run path. Deployed triggers are Temporal listeners reached solely+ by services.events.dispatch.emit. A source that never calls emit works+ perfectly when you press Run and does nothing once deployed -- with no+ error anywhere.+ """++ def test_shape_emits_one_event_per_message(self):+ from nodes.whatsapp_business._source import WhatsAppBusinessWebhookSource++ source = WhatsAppBusinessWebhookSource()+ body = _webhook_body(messages=[_text_message("wamid.A"), _text_message("wamid.B")])++ with patch("services.events.dispatch.emit", new=AsyncMock()) as emit:+ _run(source.shape(SimpleNamespace(), b"{}", body))++ assert emit.await_count == 2+ emitted = [call.args[0] for call in emit.await_args_list]+ assert {ev.id for ev in emitted} == {"wamid.A", "wamid.B"}+ assert {ev.type for ev in emitted} == {"com.opencompany.whatsapp_business.message.received"}++ def test_statuses_emit_under_their_own_type(self):+ """Distinct types are the only discriminator that works deployed."""+ from nodes.whatsapp_business._source import WhatsAppBusinessWebhookSource++ source = WhatsAppBusinessWebhookSource()+ body = _webhook_body(statuses=[{"id": "wamid.OUT", "status": "failed", "recipient_id": "165"}])++ with patch("services.events.dispatch.emit", new=AsyncMock()) as emit:+ _run(source.shape(SimpleNamespace(), b"{}", body))++ assert emit.await_count == 1+ event = emit.await_args_list[0].args[0]+ assert event.type == "com.opencompany.whatsapp_business.status.updated"+ assert event.id == "wamid.OUT:failed"++ def test_emitted_data_is_a_flat_dict(self):+ """A non-dict is coerced to {} upstream, silently emptying the trigger."""+ from nodes.whatsapp_business._source import WhatsAppBusinessWebhookSource++ source = WhatsAppBusinessWebhookSource()+ with patch("services.events.dispatch.emit", new=AsyncMock()) as emit:+ _run(source.shape(SimpleNamespace(), b"{}", _webhook_body(messages=[_text_message("wamid.A")])))++ data = emit.await_args_list[0].args[0].data+ assert isinstance(data, dict)+ assert data["message_id"] == "wamid.A"++ def test_envelope_carries_no_workflow_id(self):+ """Setting it would scope delivery to one deployment; webhook events+ are meant to reach every deployment carrying the trigger."""+ from nodes.whatsapp_business._source import WhatsAppBusinessWebhookSource++ source = WhatsAppBusinessWebhookSource()+ with patch("services.events.dispatch.emit", new=AsyncMock()) as emit:+ _run(source.shape(SimpleNamespace(), b"{}", _webhook_body(messages=[_text_message("wamid.A")])))++ assert emit.await_args_list[0].args[0].workflow_id is Nonediff --git a/server/tests/nodes/test_whatsapp_cloud.py b/server/tests/nodes/test_whatsapp_cloud.pydeleted file mode 100644index d79e2bf6..00000000--- a/server/tests/nodes/test_whatsapp_cloud.py+++ /dev/null@@ -1,272 +0,0 @@-"""Contract for the official Meta WhatsApp Cloud API plugin.--The security-relevant test here is ``TestModelCannotChooseTheSendingNumber``.-On a dual-purpose ActionNode the split-schema machinery does not apply ---``BaseNode.execute_as_tool`` merges ``{**node_params, **tool_args}`` for-anything that is not a ToolNode -- so the only way to keep a field away from-the model is to keep it out of Params entirely. This asserts that holds.-"""--from __future__ import annotations--import asyncio-from types import SimpleNamespace-from unittest.mock import AsyncMock, patch--import pytest--from nodes.whatsapp_cloud._base import classify_error, normalize_recipient-from nodes.whatsapp_cloud.whatsapp_cloud_send import (- WhatsAppCloudSendNode,- WhatsAppCloudSendParams,-)-from services.plugin import NodeUserError---pytestmark = pytest.mark.unit---def _run(coro):- return asyncio.new_event_loop().run_until_complete(coro)---def _ctx(**raw):- return SimpleNamespace(- node_id="wac-1",- node_type="whatsappCloudSend",- workflow_id="wf-1",- session_id="default",- user_id="owner",- workspace_dir=None,- outputs={},- nodes=[],- edges=[],- raw=dict(raw),- )---class TestParamsShape:- def test_phone_number_id_is_not_a_parameter(self):- """It selects the business identity a message is sent FROM.-- Declaring it would make it model-settable on this node kind, so it is- credential-sourced instead. If someone adds it back, this fails.- """- assert "phone_number_id" not in WhatsAppCloudSendParams.model_fields-- def test_tool_schema_never_exposes_the_sending_number(self):- schema = WhatsAppCloudSendParams.model_json_schema()- assert "phone_number_id" not in schema.get("properties", {})-- def test_tool_facing_schema_is_flat(self):- """LLM function-calling rejects $ref; the contract test enforces this- repo-wide, asserted here too so the reason is local."""- import json-- schema = WhatsAppCloudSendParams.model_json_schema()- assert "$defs" not in schema- assert "$ref" not in json.dumps(schema)---class TestModelCannotChooseTheSendingNumber:- def test_tool_args_cannot_override_the_credential_number(self):- """Drive the real tool path, not the schema.-- A prompt injection in an inbound WhatsApp message is the realistic- source of hostile tool arguments, and sending as another tenant's- number is the worst outcome available here.- """- node = WhatsAppCloudSendNode()- captured = {}-- async def _fake_post(ctx, path, body=None, **kwargs):- captured["path"] = path- captured["body"] = body- return {- "messages": [{"id": "wamid.TEST"}],- "contacts": [{"wa_id": "14155551234"}],- }-- with (- patch("nodes.whatsapp_cloud.whatsapp_cloud_send.graph_post", new=_fake_post),- patch(- "services.plugin.deps.get_auth_service",- return_value=SimpleNamespace(get_api_key=AsyncMock(return_value="OPERATOR_NUMBER")),- ),- ):- result = _run(- node.execute_as_tool(- {"to": "+14155551234", "text": "hi", "phone_number_id": "ATTACKER_NUMBER"},- {},- _ctx(),- )- )-- assert "ATTACKER_NUMBER" not in captured["path"]- assert captured["path"].startswith("OPERATOR_NUMBER/")- assert result.get("phone_number_id") == "OPERATOR_NUMBER"-- def test_missing_credential_number_is_a_clear_error(self):- node = WhatsAppCloudSendNode()-- with patch(- "services.plugin.deps.get_auth_service",- return_value=SimpleNamespace(get_api_key=AsyncMock(return_value=None)),- ):- envelope = _run(- node.execute("wac-1", {"to": "+14155551234", "text": "hi"}, _ctx())- )-- assert envelope["success"] is False- assert envelope["error_type"] == "NodeUserError"- assert "phone number" in envelope["error"].lower()---class TestSendText:- def _send(self, params, *, number="PN1"):- node = WhatsAppCloudSendNode()- captured = {}-- async def _fake_post(ctx, path, body=None, **kwargs):- captured["path"] = path- captured["body"] = body- return {"messages": [{"id": "wamid.X"}], "contacts": [{"wa_id": "1"}]}-- with (- patch("nodes.whatsapp_cloud.whatsapp_cloud_send.graph_post", new=_fake_post),- patch(- "services.plugin.deps.get_auth_service",- return_value=SimpleNamespace(get_api_key=AsyncMock(return_value=number)),- ),- ):- _run(node.execute("wac-1", params, _ctx()))- return captured-- def test_builds_the_documented_text_envelope(self):- captured = self._send({"to": "+1 (415) 555-1234", "text": "hello", "format_markdown": False})- assert captured["body"] == {- "messaging_product": "whatsapp",- "recipient_type": "individual",- # Punctuation a user would paste from a contacts app is stripped;- # Meta rejects it as error 131009 otherwise.- "to": "+14155551234",- "type": "text",- "text": {"preview_url": False, "body": "hello"},- }-- def test_reply_threads_via_context(self):- captured = self._send(- {"to": "+14155551234", "text": "hi", "reply_to_message_id": "wamid.PARENT", "format_markdown": False}- )- assert captured["body"]["context"] == {"message_id": "wamid.PARENT"}-- def test_no_context_key_when_not_replying(self):- captured = self._send({"to": "+14155551234", "text": "hi", "format_markdown": False})- assert "context" not in captured["body"]-- def test_markdown_is_converted_by_default(self):- captured = self._send({"to": "+14155551234", "text": "**bold**"})- assert captured["body"]["text"]["body"] == "*bold*"-- def test_oversize_body_is_refused_not_truncated(self):- """Silently dropping the tail of a business message is worse than- failing."""- node = WhatsAppCloudSendNode()- with patch(- "services.plugin.deps.get_auth_service",- return_value=SimpleNamespace(get_api_key=AsyncMock(return_value="PN1")),- ):- envelope = _run(- node.execute(- "wac-1",- {"to": "+14155551234", "text": "a" * 5000, "format_markdown": False},- _ctx(),- )- )- assert envelope["success"] is False- assert "4096" in envelope["error"]-- def test_empty_body_is_refused(self):- node = WhatsAppCloudSendNode()- with patch(- "services.plugin.deps.get_auth_service",- return_value=SimpleNamespace(get_api_key=AsyncMock(return_value="PN1")),- ):- envelope = _run(node.execute("wac-1", {"to": "+14155551234", "text": " "}, _ctx()))- assert envelope["success"] is False---class TestRecipientNormalization:- @pytest.mark.parametrize(- "raw,expected",- [- ("+1 (415) 555-1234", "+14155551234"),- ("14155551234", "14155551234"),- ("+44 20 7946 0958", "+442079460958"),- ],- )- def test_punctuation_is_stripped(self, raw, expected):- assert normalize_recipient(raw) == expected-- @pytest.mark.parametrize("raw", ["", " ", "+", "not-a-number"])- def test_unusable_input_is_refused(self, raw):- with pytest.raises(NodeUserError):- normalize_recipient(raw)---class TestErrorClassification:- @pytest.mark.parametrize(- "code,category,retryable",- [- (190, "auth", True),- (0, "auth", True),- (10, "permission", False),- (200, "permission", False),- (130429, "throttle", True),- (131056, "throttle", True),- (131057, "transient", True),- (131047, "window_closed", False),- (131050, "policy", False),- (132000, "template", False),- (133015, "account", False),- ],- )- def test_codes_land_in_the_right_class(self, code, category, retryable):- assert classify_error(code) == (category, retryable)-- def test_throttles_are_not_node_user_errors(self):- """NodeUserError is non-retryable in the shared policy, so raising one- for a throttle would defeat the backoff Meta asks for."""- from nodes.whatsapp_cloud._base import raise_for_graph_error-- with pytest.raises(RuntimeError) as exc:- raise_for_graph_error(- {"error": {"code": 130429, "message": "Rate limit hit"}}, 429- )- assert not isinstance(exc.value, NodeUserError)-- def test_window_closed_points_at_the_template_node(self):- from nodes.whatsapp_cloud._base import raise_for_graph_error-- with pytest.raises(NodeUserError) as exc:- raise_for_graph_error({"error": {"code": 131047, "message": "Re-engagement"}}, 400)- assert "Template" in str(exc.value)-- def test_auth_failure_carries_credential_annotations(self):- """The annotated PermissionError is what produces the reconnect chip."""- from nodes.whatsapp_cloud._base import raise_for_graph_error-- with pytest.raises(PermissionError) as exc:- raise_for_graph_error({"error": {"code": 190, "message": "expired"}}, 401)- assert exc.value.provider == "whatsapp_cloud"- assert exc.value.auth == "api_key"---class TestGraphVersionPin:- def test_version_is_pinned_not_derived(self):- """An expired Graph version does not error -- Meta silently falls- through to the next oldest, so the pin must be explicit."""- from nodes.whatsapp_cloud._base import GRAPH_API_VERSION-- assert GRAPH_API_VERSION.startswith("v")- assert GRAPH_API_VERSION[1:].replace(".", "").isdigit()