Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(whatsapp_cloud): add the official Meta Cloud API plugin with whatsappCloudSend
trohitgd5c5d49870f7
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex 4dfe072c..d6e436b9 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -325,6 +325,63 @@"scan_text": "Scan with WhatsApp mobile app"}},+ "whatsapp_cloud": {+ "name": "WhatsApp Business (Meta)",+ "category": "social",+ "category_label": "Social Media",+ "color": "theme.categoryWhatsapp",+ "kind": "apiKey",+ "icon_ref": "/api/schemas/credentials/whatsapp_cloud/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": [+ {+ "key": "apiKey",+ "label": "System User Access Token",+ "type": "password",+ "secret": true,+ "placeholder": "EAAG...",+ "required": true,+ "help": "A permanent System User token from Meta Business Settings. Needs whatsapp_business_messaging and whatsapp_business_management."+ },+ {+ "key": "whatsapp_cloud_waba_id",+ "label": "WhatsApp Business Account ID",+ "type": "text",+ "secret": false,+ "placeholder": "102290129340398",+ "required": true,+ "help": "Found in Meta App Dashboard > WhatsApp > API Setup. The token cannot be validated without it."+ },+ {+ "key": "whatsapp_cloud_phone_number_id",+ "label": "Phone Number ID",+ "type": "text",+ "secret": false,+ "placeholder": "106540352242922",+ "required": true,+ "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",+ "label": "App Secret (for webhooks)",+ "type": "password",+ "secret": true,+ "placeholder": "Only needed to receive messages",+ "required": false,+ "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",+ "label": "Webhook Verify Token",+ "type": "password",+ "secret": true,+ "placeholder": "Any string you choose",+ "required": false,+ "help": "A string you invent, then paste into Meta's webhook configuration. Echoed back during the subscription handshake."+ }+ ],+ "instructions": "Create a Meta app with the WhatsApp use case, then copy the Phone Number ID and WhatsApp Business Account ID from API Setup. Generate a permanent token under Business Settings > System users. The App Secret and Verify Token are only needed if you also want to receive messages."+ },"twitter": {"name": "Twitter/X","category": "social",diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.jsonindex 9d2327ca..5cddbb1e 100644--- a/server/config/node_allowlist.json+++ b/server/config/node_allowlist.json@@ -32,6 +32,8 @@"telegramSend","telegramReceive",+ "whatsappCloudSend",+"airplaneModeControl","appLauncher","appList",diff --git a/server/nodes/groups.py b/server/nodes/groups.pyindex 5f3ad309..178ef0a8 100644--- a/server/nodes/groups.py+++ b/server/nodes/groups.py@@ -49,6 +49,15 @@ register_group(key="microsoft", metadata={"label": "Microsoft Graph", "icon": "lregister_group(key="scheduler", metadata={"label": "Schedulers", "icon": "π ", "color": "#ff79c6", "visibility": "dev"})register_group(key="proxy", metadata={"label": "Proxy", "icon": "π‘", "color": "#bd93f9", "visibility": "dev"})register_group(key="whatsapp", metadata={"label": "WhatsApp", "icon": "π¬", "color": "#25D366", "visibility": "dev"})+# Separate from "whatsapp" above deliberately. That group is the unofficial+# personal-account bridge; this is Meta's sanctioned Business Platform. Same+# product name, different auth model, different capabilities and different+# failure modes -- merging them into one palette section makes it impossible+# to tell which node you are dragging.+register_group(+ key="whatsapp_cloud",+ metadata={"label": "WhatsApp Business", "icon": "πΌ", "color": "#128C7E", "visibility": "normal"},+)register_group(key="email", metadata={"label": "Email", "icon": "βοΈ", "color": "#8be9fd", "visibility": "dev"})register_group(key="payments", metadata={"label": "Payments", "icon": "asset:stripe", "color": "#635BFF", "visibility": "dev"})register_group(key="deployment", metadata={"label": "Deployment", "icon": "lobehub:Vercel", "color": "#666666", "visibility": "dev"})diff --git a/server/nodes/whatsapp_cloud/__init__.py b/server/nodes/whatsapp_cloud/__init__.pynew file mode 100644index 00000000..ee1fc668--- /dev/null+++ b/server/nodes/whatsapp_cloud/__init__.py@@ -0,0 +1,24 @@+"""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/nodes/whatsapp_cloud/_base.py b/server/nodes/whatsapp_cloud/_base.pynew file mode 100644index 00000000..5c2488b5--- /dev/null+++ b/server/nodes/whatsapp_cloud/_base.py@@ -0,0 +1,258 @@+"""Shared Graph API plumbing for the WhatsApp Cloud API nodes.++One place owns the version pin, the request helpers and the error-code+translation, so the four node files contain message-shaping logic and+nothing else.+"""++from __future__ import annotations++from typing import Any, Dict, Optional, Tuple++from core.logging import get_logger+from services.plugin import NodeContext, NodeUserError++logger = get_logger(__name__)+++GRAPH_BASE_URL = "https://graph.facebook.com"++# Pinned deliberately, never interpolated per call site. Meta guarantees a+# version at least two years from release, and an *expired* version does not+# error -- calls silently fall through to the next oldest usable version, so+# an unpinned integration changes behaviour without any signal.+#+# v25.0 released 2026-02-18. Pin reviewed 2026-08-04.+# Meta's own docs are internally inconsistent here (Get Started shows v23.0,+# the phone-numbers page shows a stale v15.0, the published OpenAPI spec is+# v23.0), so do not infer the current version from any single sample page.+GRAPH_API_VERSION = "v25.0"++CREDENTIAL_ID = "whatsapp_cloud"+++# --------------------------------------------------------------------------+# Error classification+# --------------------------------------------------------------------------+#+# Meta returns a numeric ``code`` inside a Graph error envelope. The split+# that matters is retryable-vs-terminal: NodeUserError is in the shared+# non-retryable list, so classifying a transient throttle as one would fail+# fast instead of backing off, and classifying a permanent rejection as+# retryable burns three attempts and re-bills nothing but time.+#+# Codes verified against+# developers.facebook.com/documentation/business-messaging/whatsapp/support/error-codes++# Token expired / invalidated. Retryable only after the credential refreshes.+_AUTH_CODES = frozenset({0, 190})++# Permission genuinely absent -- retrying cannot help.+_PERMISSION_CODES = frozenset({3, 10})++# Rate limits and throughput ceilings. Meta documents a 4^X second backoff+# for the per-user case.+_THROTTLE_CODES = frozenset({4, 80007, 130429, 131048, 131056, 133008, 133009})++# Server-side or transient; worth another attempt.+_TRANSIENT_CODES = frozenset({131000, 131057, 133004})++# Terminal policy decisions. 131050 is documented "do not retry".+_POLICY_CODES = frozenset({368, 131050, 131064})++# The 24-hour customer service window closed. Actionable, and the remedy is+# a different node, so it gets its own message.+_WINDOW_CLOSED_CODE = 131047+++def _is_permission_code(code: int) -> bool:+ return code in _PERMISSION_CODES or 200 <= code <= 299+++def classify_error(code: int) -> Tuple[str, bool]:+ """Return ``(category, retryable)`` for a Meta error code."""+ if code in _AUTH_CODES:+ return "auth", True+ if _is_permission_code(code):+ return "permission", False+ if code in _THROTTLE_CODES:+ return "throttle", True+ if code in _TRANSIENT_CODES:+ return "transient", True+ if code in _POLICY_CODES:+ return "policy", False+ if code == _WINDOW_CLOSED_CODE:+ return "window_closed", False+ if 132000 <= code <= 132999:+ return "template", False+ if 133000 <= code <= 133999:+ return "account", False+ return "unknown", False+++def _friendly_message(code: int, category: str, detail: str) -> str:+ if category == "window_closed":+ return (+ "This WhatsApp user has not messaged you in the last 24 hours, so "+ "only an approved template message can be delivered. Use the "+ "WhatsApp Cloud Template node instead. "+ f"(Meta error {code}: {detail})"+ )+ if category == "auth":+ return f"WhatsApp access token was rejected. Reconnect the credential. (Meta error {code}: {detail})"+ if category == "permission":+ return (+ "The access token lacks a required permission "+ "(whatsapp_business_messaging / whatsapp_business_management). "+ f"(Meta error {code}: {detail})"+ )+ if category == "template":+ return f"Template rejected by Meta. (error {code}: {detail})"+ return f"WhatsApp API error {code}: {detail}"+++def raise_for_graph_error(payload: Dict[str, Any], status_code: int) -> None:+ """Translate a Graph error envelope into the right exception.++ ``error_data.details`` is the field that actually explains the failure;+ ``message`` is frequently generic. ``fbtrace_id`` is always logged because+ it is the identifier Meta support asks for and it cannot be recovered+ afterwards.+ """+ error = (payload or {}).get("error") or {}+ code = int(error.get("code") or 0)+ detail = (error.get("error_data") or {}).get("details") or error.get("message") or "no detail provided"+ fbtrace_id = error.get("fbtrace_id")+ category, retryable = classify_error(code)++ logger.warning(+ "whatsapp cloud api error",+ code=code,+ subcode=error.get("error_subcode"),+ category=category,+ retryable=retryable,+ status_code=status_code,+ fbtrace_id=fbtrace_id,+ )++ if category == "auth":+ # Annotated PermissionError gets the framework's credential envelope+ # and a reconnect affordance in the UI, which a NodeUserError does not.+ exc = PermissionError(_friendly_message(code, category, detail))+ exc.provider = CREDENTIAL_ID # type: ignore[attr-defined]+ exc.reason = "invalid" # type: ignore[attr-defined]+ exc.auth = "api_key" # type: ignore[attr-defined]+ raise exc++ if retryable:+ # Not a NodeUserError: that type is non-retryable in the shared retry+ # policy, so raising one here would defeat the backoff Meta asks for.+ raise RuntimeError(_friendly_message(code, category, detail))++ raise NodeUserError(_friendly_message(code, category, detail))+++# --------------------------------------------------------------------------+# Request helpers+# --------------------------------------------------------------------------+++async def _request(+ ctx: NodeContext,+ method: str,+ path: str,+ *,+ json: Optional[Dict[str, Any]] = None,+ params: Optional[Dict[str, Any]] = None,+ files: Optional[Any] = None,+ data: Optional[Dict[str, Any]] = None,+) -> Dict[str, Any]:+ """Call the Graph API with the node's credential and translate failures."""+ url = f"{GRAPH_BASE_URL}/{GRAPH_API_VERSION}/{path.lstrip('/')}"+ async with ctx.connection(CREDENTIAL_ID) as conn:+ response = await conn.request(+ method, url, json=json, params=params, files=files, data=data+ )++ try:+ payload = response.json() if response.content else {}+ except ValueError:+ payload = {}++ if response.status_code >= 400:+ raise_for_graph_error(payload, response.status_code)+ return payload+++async def graph_post(+ ctx: NodeContext,+ path: str,+ body: Optional[Dict[str, Any]] = None,+ *,+ files: Optional[Any] = None,+ data: Optional[Dict[str, Any]] = None,+) -> Dict[str, Any]:+ return await _request(ctx, "POST", path, json=body, files=files, data=data)+++async def graph_get(+ ctx: NodeContext, path: str, params: Optional[Dict[str, Any]] = None+) -> Dict[str, Any]:+ return await _request(ctx, "GET", path, params=params)+++async def graph_delete(+ ctx: NodeContext, path: str, params: Optional[Dict[str, Any]] = None+) -> Dict[str, Any]:+ return await _request(ctx, "DELETE", path, params=params)+++async def resolve_phone_number_id(ctx: NodeContext) -> str:+ """The business number to send from β credential-sourced only.++ Deliberately takes no node-level override. This value selects which+ business identity a message is sent *from*, and on a dual-purpose+ ActionNode any declared parameter is reachable by model arguments:+ ``BaseNode.execute_as_tool`` sends ``{**node_params, **tool_args}`` for+ anything that is not a ToolNode, so the model wins. Sourcing it from the+ credential puts it somewhere model arguments cannot reach.++ A per-node override belongs with multi-number support, which needs the+ deployed-trigger filtering that is currently deferred.+ """+ from services.plugin.deps import get_auth_service++ stored = await get_auth_service().get_api_key("whatsapp_cloud_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."+ )+ return str(stored).strip()+++def normalize_recipient(value: str) -> str:+ """Meta wants digits, tolerating a leading '+'.++ Stripping spaces, dashes and parentheses here means a number pasted from+ a contacts app works instead of failing as error 131009.+ """+ cleaned = "".join(ch for ch in (value or "") if ch.isdigit() or ch == "+")+ if not cleaned.lstrip("+"):+ raise NodeUserError(f"'{value}' is not a usable WhatsApp phone number.")+ return cleaned+++__all__ = [+ "CREDENTIAL_ID",+ "GRAPH_API_VERSION",+ "GRAPH_BASE_URL",+ "classify_error",+ "graph_delete",+ "graph_get",+ "graph_post",+ "normalize_recipient",+ "raise_for_graph_error",+ "resolve_phone_number_id",+]diff --git a/server/nodes/whatsapp_cloud/_credentials.py b/server/nodes/whatsapp_cloud/_credentials.pynew file mode 100644index 00000000..b27fe7c6--- /dev/null+++ b/server/nodes/whatsapp_cloud/_credentials.py@@ -0,0 +1,118 @@+"""Credential for Meta's official WhatsApp Business Platform Cloud API.++Distinct from the ``whatsapp`` credential in ``nodes/whatsapp/``, which pairs+a *personal* account over an unofficial Go bridge. Same product name, wholly+different auth model, so they are separate ids and separate catalogue entries.++The brand icon must live beside this file as ``whatsapp_cloud.svg`` --+``Credential.get_icon_path`` resolves ``<cls.id>.svg`` co-located with the+class, and nothing else is consulted.+"""++from __future__ import annotations++import httpx++from services.plugin.credential import ApiKeyCredential, ProbeResult+++class WhatsAppCloudCredential(ApiKeyCredential):+ """Graph API bearer token plus the fields the webhook and API need.++ ``apiKey`` is deliberately **not** required at the catalogue level. The+ Connect button gates on required fields only, so marking the token+ required would block the browser sign-up path before it can supply one.+ Runtime resolution still fails loudly when neither path has produced a+ token.+ """++ id = "whatsapp_cloud"+ display_name = "WhatsApp Business (Meta)"+ 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",+ # Echoed back during the GET subscription handshake.+ "whatsapp_cloud_verify_token",+ # Needed to list phone numbers and message templates.+ "whatsapp_cloud_waba_id",+ # The business phone number messages are sent FROM.+ "whatsapp_cloud_phone_number_id",+ )+ docs_url = "https://developers.facebook.com/documentation/business-messaging/whatsapp/get-started"++ @classmethod+ async def _probe(cls, api_key: str) -> ProbeResult:+ """Validate the token without sending a message.++ ``GET /{waba-id}/phone_numbers`` is authenticated, read-only and free,+ and it doubles as the call that discovers which numbers the token can+ actually send from -- so a successful probe also proves the WABA id is+ right, which a bare token check would not.+ """+ from services.plugin.deps import get_auth_service++ auth = get_auth_service()+ waba_id = await auth.get_api_key("whatsapp_cloud_waba_id")+ if not waba_id:+ return ProbeResult(+ valid=False,+ message=(+ "Add your WhatsApp Business Account ID as well -- the token "+ "cannot be checked without it."+ ),+ )++ from ._base import GRAPH_API_VERSION, GRAPH_BASE_URL++ url = f"{GRAPH_BASE_URL}/{GRAPH_API_VERSION}/{waba_id}/phone_numbers"+ async with httpx.AsyncClient(timeout=cls.probe_timeout_seconds) as client:+ response = await client.get(+ url,+ headers={"Authorization": f"Bearer {api_key}"},+ params={"fields": "id,display_phone_number,verified_name,quality_rating"},+ )+ response.raise_for_status()+ return cls._handle_probe_response(response)++ @classmethod+ def _handle_probe_response(cls, response: httpx.Response) -> ProbeResult:+ payload = response.json()+ numbers = payload.get("data") or []+ if not numbers:+ return ProbeResult(+ valid=False,+ message=(+ "The token is accepted but that WhatsApp Business Account has "+ "no phone numbers. Add one in the Meta dashboard first."+ ),+ )++ display = numbers[0].get("display_phone_number") or "?"+ name = numbers[0].get("verified_name")+ label = f"{display} ({name})" if name else display+ suffix = "" if len(numbers) == 1 else f" (+{len(numbers) - 1} more)"+ return ProbeResult(+ valid=True,+ message=f"Connected to {label}{suffix}",+ extra={+ "phone_numbers": [+ {+ "id": entry.get("id"),+ "display_phone_number": entry.get("display_phone_number"),+ "verified_name": entry.get("verified_name"),+ # Surfaced verbatim. Meta's developer docs show these+ # values but never define them, so inventing semantics+ # here would be guessing.+ "quality_rating": entry.get("quality_rating"),+ }+ for entry in numbers+ ]+ },+ )+++__all__ = ["WhatsAppCloudCredential"]diff --git a/server/nodes/whatsapp_cloud/icon.svg b/server/nodes/whatsapp_cloud/icon.svgnew file mode 100644index 00000000..c2df5a87--- /dev/null+++ b/server/nodes/whatsapp_cloud/icon.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#25D366"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>diff --git a/server/nodes/whatsapp_cloud/icon_whatsappCloudSend.svg b/server/nodes/whatsapp_cloud/icon_whatsappCloudSend.svgnew file mode 100644index 00000000..42f8b042--- /dev/null+++ b/server/nodes/whatsapp_cloud/icon_whatsappCloudSend.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#25D366"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg>diff --git a/server/nodes/whatsapp_cloud/meta.json b/server/nodes/whatsapp_cloud/meta.jsonnew file mode 100644index 00000000..550bea1d--- /dev/null+++ b/server/nodes/whatsapp_cloud/meta.json@@ -0,0 +1 @@+{"color": "#128C7E"}diff --git a/server/nodes/whatsapp_cloud/whatsapp_cloud.svg b/server/nodes/whatsapp_cloud/whatsapp_cloud.svgnew file mode 100644index 00000000..c2df5a87--- /dev/null+++ b/server/nodes/whatsapp_cloud/whatsapp_cloud.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#25D366"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>diff --git a/server/nodes/whatsapp_cloud/whatsapp_cloud_send.py b/server/nodes/whatsapp_cloud/whatsapp_cloud_send.pynew file mode 100644index 00000000..66a42e83--- /dev/null+++ b/server/nodes/whatsapp_cloud/whatsapp_cloud_send.py@@ -0,0 +1,161 @@+"""whatsappCloudSend β send a message via Meta's WhatsApp Cloud API."""++from __future__ import annotations++from typing import Any, Dict, List, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.plugin import ActionNode, NodeContext, NodeUserError, Operation, TaskQueue++from ._base import graph_post, normalize_recipient, resolve_phone_number_id+from ._credentials import WhatsAppCloudCredential++# Meta's documented ceiling for a text body. Longer bodies are rejected+# outright rather than truncated: silently dropping the tail of an outbound+# business message is worse than a clear failure.+_MAX_TEXT_BODY = 4096+++class WhatsAppCloudSendParams(BaseModel):+ """Operator configuration, persisted on the node."""++ to: str = Field(+ default="",+ description="Recipient phone number in international format (e.g. +14155551234).",+ )+ text: str = Field(+ default="",+ description="Message body.",+ json_schema_extra={"rows": 4},+ )+ preview_url: bool = Field(+ default=False,+ description="Render a link preview for the first URL in the body.",+ )+ reply_to_message_id: str = Field(+ default="",+ description="Optional message id to reply to, threading the message.",+ )+ format_markdown: bool = Field(+ default=True,+ description="Convert GFM markdown to WhatsApp's *bold* / _italic_ syntax.",+ )++ # There is deliberately NO phone_number_id parameter.+ #+ # It selects which business identity a message is sent *from*, so it is+ # exactly the field a prompt injection in an inbound message would want to+ # set. On a dual-purpose ActionNode there is no way to protect it: the+ # split-schema machinery (ToolInput / server_controlled_fields) is a+ # ToolNode extension, and BaseNode.execute_as_tool sends+ # ``{**node_params, **tool_args}`` for everything else -- model arguments+ # win, and ctx.raw["_raw_parameters"] is that same merged dict, so reading+ # from it protects nothing.+ #+ # The sending number therefore comes only from the credential, where the+ # model cannot reach it. A per-node override belongs with multi-number+ # support, which is deferred (see the plan's 6.4).++ model_config = ConfigDict(extra="ignore")+++class WhatsAppCloudSendOutput(BaseModel):+ message_id: Optional[str] = None+ to: Optional[str] = None+ wa_id: Optional[str] = None+ phone_number_id: Optional[str] = None+ # Meta's reference schema always documents this, but no per-type example+ # includes it, so it is parsed as optional rather than assumed.+ message_status: Optional[str] = None++ model_config = ConfigDict(extra="allow")+++class WhatsAppCloudSendNode(ActionNode):+ type = "whatsappCloudSend"+ display_name = "WhatsApp Send (Business API)"+ subtitle = "Cloud API"+ group = ("whatsapp_cloud", "tool")+ description = "Send a WhatsApp message through Meta's official Cloud API"+ component_kind = "square"+ tool_name = "whatsapp_cloud_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 "+ "business within the last 24 hours; outside that window an approved "+ "template is required instead."+ )+ handles = (+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},+ )+ credentials = (WhatsAppCloudCredential,)+ annotations = {"destructive": False, "readonly": False, "open_world": True}+ task_queue = TaskQueue.MESSAGING+ usable_as_tool = True++ # ToolInput / server_controlled_fields are deliberately NOT declared.+ # They are ToolNode extensions; on a dual-purpose ActionNode they are+ # 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++ @Operation("send_text", cost={"service": "whatsapp_cloud", "action": "send_text", "count": 1})+ async def send_text(+ self,+ ctx: NodeContext,+ params: WhatsAppCloudSendParams,+ ) -> WhatsAppCloudSendOutput:+ recipient = normalize_recipient(params.to)+ body = params.text or ""+ if not body.strip():+ raise NodeUserError("Cannot send an empty WhatsApp message.")++ if params.format_markdown:+ from services.markdown_formatter import to_whatsapp++ body = to_whatsapp(body)++ if len(body) > _MAX_TEXT_BODY:+ raise NodeUserError(+ f"Message body is {len(body)} characters; WhatsApp accepts at most "+ f"{_MAX_TEXT_BODY}. Split it before sending."+ )++ preview_url = params.preview_url+ reply_to = (params.reply_to_message_id or "").strip()+ phone_number_id = await resolve_phone_number_id(ctx)++ payload: Dict[str, Any] = {+ "messaging_product": "whatsapp",+ "recipient_type": "individual",+ "to": recipient,+ "type": "text",+ "text": {"preview_url": preview_url, "body": body},+ }+ if reply_to:+ payload["context"] = {"message_id": reply_to}++ result = await graph_post(ctx, f"{phone_number_id}/messages", payload)++ messages: List[Dict[str, Any]] = result.get("messages") or []+ contacts: List[Dict[str, Any]] = result.get("contacts") or []+ first = messages[0] if messages else {}++ return WhatsAppCloudSendOutput(+ message_id=first.get("id"),+ message_status=first.get("message_status"),+ to=recipient,+ wa_id=(contacts[0].get("wa_id") if contacts else None),+ phone_number_id=phone_number_id,+ )+++__all__ = [+ "WhatsAppCloudSendNode",+ "WhatsAppCloudSendOutput",+ "WhatsAppCloudSendParams",+]diff --git a/server/tests/nodes/test_whatsapp_cloud.py b/server/tests/nodes/test_whatsapp_cloud.pynew file mode 100644index 00000000..d79e2bf6--- /dev/null+++ b/server/tests/nodes/test_whatsapp_cloud.py@@ -0,0 +1,272 @@+"""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()