Skip to content

Self-improving AI Employees for everyone

feat(stripe): Stripe CLI plugin via Wave 12 framework

trohitg268cd2f82024
diff --git a/client/src/assets/icons/stripe.svg b/client/src/assets/icons/stripe.svg
new file mode 100644
index 00000000..19008486
--- /dev/null
+++ b/client/src/assets/icons/stripe.svg
@@ -0,0 +1 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#635BFF"/><path d="M14.4 13.2c0-.9.7-1.3 1.9-1.3 1.7 0 3.9.5 5.6 1.4V8.1c-1.9-.7-3.7-1-5.6-1-4.6 0-7.6 2.4-7.6 6.4 0 6.2 8.6 5.2 8.6 7.9 0 1.1-.9 1.4-2.2 1.4-1.9 0-4.3-.8-6.2-1.8v5.4c2.1.9 4.3 1.3 6.2 1.3 4.7 0 7.9-2.3 7.9-6.4 0-6.7-8.6-5.5-8.6-8.1z" fill="#fff"/></svg>
diff --git a/server/nodes/groups.py b/server/nodes/groups.py
index d12ed374..bd70e069 100644
--- a/server/nodes/groups.py
+++ b/server/nodes/groups.py
@@ -49,6 +49,7 @@ register_group(key="scheduler", metadata={"label": "Schedulers", "icon"
register_group(key="proxy", metadata={"label": "Proxy", "icon": "πŸ›‘", "color": "#bd93f9", "visibility": "dev"})
register_group(key="whatsapp", metadata={"label": "WhatsApp", "icon": "πŸ’¬", "color": "#25D366", "visibility": "dev"})
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="browser", metadata={"label": "Browser", "icon": "🌐", "color": "#ff79c6", "visibility": "dev"})
register_group(key="scraper", metadata={"label": "Scrapers", "icon": "πŸ•Έ", "color": "#ff79c6", "visibility": "dev"})
register_group(key="filesystem", metadata={"label": "Filesystem", "icon": "πŸ“", "color": "#8be9fd", "visibility": "dev"})
diff --git a/server/nodes/stripe/__init__.py b/server/nodes/stripe/__init__.py
new file mode 100644
index 00000000..b4afd27f
--- /dev/null
+++ b/server/nodes/stripe/__init__.py
@@ -0,0 +1,46 @@
+"""Plugins for the 'payments' palette group β€” Stripe.
+
+Self-contained Wave 12 plugin. All boilerplate (lifecycle WS handlers,
+status refresh, signature verification, CLI subprocess) lives in
+``services.events``. This package contributes only the Stripe-specific
+shapes: command builder, secret-capture regex, output reshape, the
+livemode filter, and the credential class.
+"""
+
+from __future__ import annotations
+
+from services.events import make_status_refresh, register_webhook_source
+from services.node_output_schemas import register_output_schema
+from services.status_broadcaster import register_service_refresh
+from services.ws_handler_registry import register_ws_handlers
+
+from ._credentials import StripeCredential
+from ._handlers import WS_HANDLERS
+from ._source import (
+ StripeListenSource,
+ StripeWebhookSource,
+ get_listen_source,
+ get_webhook_source,
+)
+
+from .stripe_action import StripeActionNode, StripeActionOutput
+from .stripe_receive import StripeReceiveNode, StripeReceiveOutput
+
+
+register_ws_handlers(WS_HANDLERS)
+register_webhook_source(get_webhook_source())
+register_service_refresh(make_status_refresh(
+ get_listen_source(), status_key="stripe", broadcast_type="stripe_status",
+))
+register_output_schema("stripeReceive", StripeReceiveOutput)
+register_output_schema("stripeAction", StripeActionOutput)
+
+
+__all__ = [
+ "StripeCredential",
+ "StripeListenSource",
+ "StripeWebhookSource",
+ "WS_HANDLERS",
+ "get_listen_source",
+ "get_webhook_source",
+]
diff --git a/server/nodes/stripe/_credentials.py b/server/nodes/stripe/_credentials.py
new file mode 100644
index 00000000..79c33f1c
--- /dev/null
+++ b/server/nodes/stripe/_credentials.py
@@ -0,0 +1,25 @@
+"""Stripe API key credential.
+
+Used by the two stripe plugins in this folder (stripe_action,
+stripe_receive) and by :class:`StripeService` for the supervised
+``stripe listen`` daemon.
+
+The webhook signing secret (``whsec_…``) is captured automatically from
+the CLI startup banner and stored as the ``stripe_webhook_secret``
+extra field β€” same persistence path as ``telegram_owner_chat_id``.
+"""
+
+from __future__ import annotations
+
+from services.plugin.credential import ApiKeyCredential
+
+
+class StripeCredential(ApiKeyCredential):
+ id = "stripe_api_key"
+ display_name = "Stripe"
+ category = "Payments"
+ icon = "asset:stripe"
+ key_name = "" # Stripe CLI takes the key via --api-key flag, not a header
+ key_location = "header"
+ extra_fields = ("stripe_webhook_secret",)
+ docs_url = "https://stripe.com/docs/cli"
diff --git a/server/nodes/stripe/_handlers.py b/server/nodes/stripe/_handlers.py
new file mode 100644
index 00000000..5676df6a
--- /dev/null
+++ b/server/nodes/stripe/_handlers.py
@@ -0,0 +1,34 @@
+"""Stripe WebSocket handlers β€” built from the framework lifecycle factory.
+
+Only ``stripe_trigger`` (synthetic test events via the CLI) is
+plugin-specific; the other 4 lifecycle handlers come from
+:func:`services.events.make_lifecycle_handlers`.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Dict
+
+from fastapi import WebSocket
+
+from services.events import make_lifecycle_handlers, run_cli_command
+
+from ._credentials import StripeCredential
+from ._source import get_listen_source
+
+
+async def handle_stripe_trigger(data: Dict[str, Any], websocket: WebSocket) -> Dict[str, Any]:
+ """Run ``stripe trigger <event>`` for synthetic test events."""
+ event = data.get("event")
+ if not event:
+ return {"success": False, "error": "event required (e.g. 'charge.succeeded')"}
+ return await run_cli_command(
+ binary="stripe", argv=["trigger", event], credential=StripeCredential,
+ )
+
+
+WS_HANDLERS = make_lifecycle_handlers(
+ prefix="stripe",
+ source=get_listen_source(),
+ extra={"stripe_trigger": handle_stripe_trigger},
+)
diff --git a/server/nodes/stripe/_source.py b/server/nodes/stripe/_source.py
new file mode 100644
index 00000000..e276da39
--- /dev/null
+++ b/server/nodes/stripe/_source.py
@@ -0,0 +1,117 @@
+"""Stripe event source β€” supervised ``stripe listen`` daemon + the
+companion ``WebhookSource`` that receives forwarded events.
+
+Two cooperating sources:
+
+* :class:`StripeListenSource` (DaemonEventSource) keeps the CLI alive,
+ captures the ``whsec_…`` signing secret from its stderr banner.
+* :class:`StripeWebhookSource` (WebhookSource) is the actual event
+ producer β€” verifies the Stripe-Signature header on each forwarded
+ POST and turns the payload into a :class:`WorkflowEvent`.
+
+Module-level singletons (``get_listen_source`` / ``get_webhook_source``)
+plug into the framework registries from ``__init__.py``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import re
+from datetime import datetime, timezone
+from typing import Any, Dict, Optional
+
+from fastapi import Request
+
+from core.logging import get_logger
+from services.events import (
+ DaemonEventSource,
+ StripeVerifier,
+ WebhookSource,
+ WorkflowEvent,
+)
+
+from ._credentials import StripeCredential
+
+logger = get_logger(__name__)
+
+_SECRET_RE = re.compile(r"whsec_[A-Za-z0-9_]+")
+_SECRET_FIELD = "stripe_webhook_secret"
+
+
+class StripeListenSource(DaemonEventSource):
+ """Supervises ``stripe listen`` and persists the captured webhook
+ signing secret. Emits no events itself β€” Stripe events arrive over
+ HTTP via :class:`StripeWebhookSource`."""
+
+ type = "stripe.listen"
+ process_name = "stripe-listen"
+ binary_name = "stripe"
+ workflow_namespace = "_stripe"
+ install_hint = "https://stripe.com/docs/stripe-cli#install"
+ credential = StripeCredential
+
+ def build_command(self, secrets: Dict) -> str:
+ from core.config import Settings
+ port = int(Settings().port)
+ return (
+ f"stripe listen --forward-to http://localhost:{port}/webhook/stripe "
+ f"--print-secret --api-key {secrets['api_key']}"
+ )
+
+ def parse_line(self, stream: str, line: str) -> Optional[WorkflowEvent]:
+ if stream == "stderr" and (m := _SECRET_RE.search(line)):
+ secret = m.group(0)
+ asyncio.create_task(self._persist_secret(secret))
+ return None
+
+ async def _persist_secret(self, secret: str) -> None:
+ try:
+ from core.container import container
+ await container.auth_service().store_api_key(_SECRET_FIELD, secret, models=[])
+ logger.info("[Stripe] webhook signing secret captured and persisted")
+ except Exception as e:
+ logger.warning("[Stripe] persist secret failed: %s", e)
+
+
+class StripeWebhookSource(WebhookSource):
+ """HTTP receiver for Stripe-forwarded events."""
+
+ type = "stripe.webhook"
+ path = "stripe"
+ verifier = StripeVerifier
+ secret_field = _SECRET_FIELD
+ credential = StripeCredential
+
+ async def shape(self, request: Request, body: bytes, payload: dict) -> WorkflowEvent:
+ created = payload.get("created")
+ try:
+ time = datetime.fromtimestamp(int(created), tz=timezone.utc) if created else datetime.now(timezone.utc)
+ except (TypeError, ValueError):
+ time = datetime.now(timezone.utc)
+ account = payload.get("account") or "default"
+ return WorkflowEvent(
+ id=payload.get("id") or "",
+ type=f"stripe.{payload.get('type', 'unknown')}",
+ source=f"stripe://{account}",
+ time=time,
+ data=payload.get("data") or {},
+ subject=payload.get("type"),
+ )
+
+
+_listen: Optional[StripeListenSource] = None
+_webhook: Optional[StripeWebhookSource] = None
+
+
+def get_listen_source() -> StripeListenSource:
+ global _listen
+ if _listen is None:
+ _listen = StripeListenSource()
+ return _listen
+
+
+def get_webhook_source() -> StripeWebhookSource:
+ global _webhook
+ if _webhook is None:
+ _webhook = StripeWebhookSource()
+ return _webhook
diff --git a/server/nodes/stripe/stripe_action.py b/server/nodes/stripe/stripe_action.py
new file mode 100644
index 00000000..cececb05
--- /dev/null
+++ b/server/nodes/stripe/stripe_action.py
@@ -0,0 +1,75 @@
+"""Stripe Action β€” pass-through over the Stripe CLI."""
+
+from __future__ import annotations
+
+import shlex
+from typing import Any, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from services.events import run_cli_command
+from services.plugin import ActionNode, NodeContext, Operation, TaskQueue
+
+from ._credentials import StripeCredential
+
+
+class StripeActionParams(BaseModel):
+ command: str = Field(
+ default="",
+ description=(
+ "Stripe CLI command, exactly as you would type after 'stripe '. "
+ "Examples: 'customers create --email [email protected]', 'charges list --limit 10', "
+ "'trigger charge.succeeded'. Reference: https://stripe.com/docs/cli"
+ ),
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+
+class StripeActionOutput(BaseModel):
+ command: Optional[str] = None
+ success: Optional[bool] = None
+ result: Optional[Any] = None
+ stdout: Optional[str] = None
+ error: Optional[str] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class StripeActionNode(ActionNode):
+ type = "stripeAction"
+ display_name = "Stripe"
+ subtitle = "CLI Command"
+ group = ("payments", "tool")
+ description = "Run any Stripe CLI command (customers, charges, payment_intents, refunds, invoices, trigger, …)"
+ component_kind = "square"
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left",
+ "label": "Input", "role": "main"},
+ {"name": "output-main", "kind": "output", "position": "right",
+ "label": "Output", "role": "main"},
+ )
+ annotations = {"destructive": False, "readonly": False, "open_world": True}
+ credentials = (StripeCredential,)
+ task_queue = TaskQueue.REST_API
+ usable_as_tool = True
+
+ Params = StripeActionParams
+ Output = StripeActionOutput
+
+ @Operation("run", cost={"service": "stripe", "action": "run", "count": 1})
+ async def run(self, ctx: NodeContext, params: StripeActionParams) -> Any:
+ cmd = params.command.strip()
+ if not cmd:
+ raise RuntimeError("command is required (e.g. 'customers create --email [email protected]')")
+ result = await run_cli_command(
+ binary="stripe", argv=shlex.split(cmd), credential=StripeCredential,
+ )
+ if not result["success"]:
+ raise RuntimeError(result.get("error") or "Stripe CLI invocation failed")
+ return {
+ "command": cmd,
+ "success": True,
+ "result": result.get("result"),
+ "stdout": result.get("stdout"),
+ }
diff --git a/server/nodes/stripe/stripe_receive.py b/server/nodes/stripe/stripe_receive.py
new file mode 100644
index 00000000..2340456a
--- /dev/null
+++ b/server/nodes/stripe/stripe_receive.py
@@ -0,0 +1,92 @@
+"""Stripe Receive β€” fires when StripeWebhookSource accepts a verified
+forwarded event."""
+
+from __future__ import annotations
+
+from typing import Callable, Dict, Literal, Optional
+
+from pydantic import BaseModel, ConfigDict, Field
+
+from services.events import BaseTriggerParams, WebhookTriggerNode, WorkflowEvent
+
+from ._credentials import StripeCredential
+from ._source import StripeWebhookSource
+
+
+_PREFIX = "stripe."
+
+
+class StripeReceiveParams(BaseTriggerParams):
+ livemode_filter: Literal["all", "test", "live"] = Field(
+ default="all",
+ description="Filter by livemode flag on the event.",
+ )
+
+
+class StripeReceiveOutput(BaseModel):
+ event_id: Optional[str] = None
+ event_type: Optional[str] = None
+ created: Optional[int] = None
+ livemode: Optional[bool] = None
+ api_version: Optional[str] = None
+ request_id: Optional[str] = None
+ account: Optional[str] = None
+ data: Optional[dict] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class StripeReceiveNode(WebhookTriggerNode):
+ type = "stripeReceive"
+ display_name = "Stripe Receive"
+ subtitle = "Webhook Event"
+ group = ("payments", "trigger")
+ description = "Trigger workflow when Stripe webhook event arrives"
+ component_kind = "trigger"
+ handles = (
+ {"name": "output-main", "kind": "output", "position": "right",
+ "label": "Output", "role": "main"},
+ )
+ credentials = (StripeCredential,)
+ webhook_source = StripeWebhookSource
+ event_type_prefix = _PREFIX
+ Params = StripeReceiveParams
+ Output = StripeReceiveOutput
+
+ def _extra_filter(
+ self, params: StripeReceiveParams,
+ ) -> Optional[Callable[[WorkflowEvent], bool]]:
+ if params.livemode_filter == "all":
+ return None
+ target_live = params.livemode_filter == "live"
+
+ def matches(ev: WorkflowEvent) -> bool:
+ payload = ev.data if isinstance(ev.data, dict) else {}
+ return bool(payload.get("livemode")) is target_live
+
+ return matches
+
+ async def _check_precondition(self) -> Optional[str]:
+ from ._source import get_listen_source
+ if not get_listen_source()._started:
+ return "Stripe daemon not running. Add Stripe API key in Credentials and connect."
+ return None
+
+ def shape_output(self, event: WorkflowEvent) -> Dict:
+ payload = event.data if isinstance(event.data, dict) else {}
+ stripe_type = event.type[len(_PREFIX):] if event.type.startswith(_PREFIX) else event.type
+ request = payload.get("request")
+ request_id = request.get("id") if isinstance(request, dict) else request
+ nested = payload.get("data")
+ return {
+ "event_id": event.id,
+ "event_type": stripe_type,
+ "created": payload.get("created"),
+ "livemode": payload.get("livemode"),
+ "api_version": payload.get("api_version"),
+ "request_id": request_id,
+ "account": payload.get("account") or (
+ event.source.split("://", 1)[1] if "://" in event.source else None
+ ),
+ "data": nested if isinstance(nested, dict) else payload,
+ }
diff --git a/server/nodes/visuals.json b/server/nodes/visuals.json
index b17e07b8..b722aed6 100644
--- a/server/nodes/visuals.json
+++ b/server/nodes/visuals.json
@@ -467,5 +467,13 @@
"icon": "πŸ“",
"color": "#bd93f9",
"skill": "write-todos-skill"
+ },
+ "stripeAction": {
+ "icon": "asset:stripe",
+ "color": "#635BFF"
+ },
+ "stripeReceive": {
+ "icon": "asset:stripe",
+ "color": "#635BFF"
}
}
diff --git a/server/tests/nodes/test_stripe_plugin.py b/server/tests/nodes/test_stripe_plugin.py
new file mode 100644
index 00000000..848eb1b7
--- /dev/null
+++ b/server/tests/nodes/test_stripe_plugin.py
@@ -0,0 +1,285 @@
+"""Contract tests for the Stripe plugin (Wave 12 framework version).
+
+The plugin is now a thin specialisation of ``services.events`` β€”
+``StripeListenSource`` (DaemonEventSource) supervises ``stripe listen``
+and ``StripeWebhookSource`` (WebhookSource) receives forwarded events.
+These tests verify the plugin wiring and the receive-node reshape;
+end-to-end smoke against the real CLI requires the binary on PATH.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import hmac
+import json
+import time
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+pytestmark = pytest.mark.node_contract
+
+
+def _run(coro):
+ return asyncio.new_event_loop().run_until_complete(coro)
+
+
+def _signed(body: bytes, secret: str) -> dict:
+ ts = int(time.time())
+ sig = hmac.new(secret.encode(), f"{ts}.".encode() + body, hashlib.sha256).hexdigest()
+ return {"Stripe-Signature": f"t={ts},v1={sig}"}
+
+
+def _fake_request(body: bytes, headers: dict | None = None):
+ """Return an object with the two attrs WebhookSource.handle uses."""
+
+ class R:
+ pass
+
+ r = R()
+ r.headers = headers or {}
+
+ async def _body():
+ return body
+
+ r.body = _body
+ return r
+
+
+# ============================================================================
+# StripeWebhookSource β€” shape() and end-to-end handle()
+# ============================================================================
+
+
+class TestStripeWebhookShape:
+ SECRET = "whsec_test_xyz"
+
+ def _stub_secret_resolution(self):
+ return patch(
+ "nodes.stripe._source.StripeCredential.resolve",
+ AsyncMock(return_value={"api_key": "sk_test", "stripe_webhook_secret": self.SECRET}),
+ )
+
+ def test_shape_extracts_stripe_fields(self):
+ from nodes.stripe._source import get_webhook_source
+ src = get_webhook_source()
+ payload = {
+ "id": "evt_1",
+ "type": "charge.succeeded",
+ "created": 1700000000,
+ "livemode": False,
+ "account": "acct_test",
+ "data": {"object": {"amount": 1000}},
+ }
+
+ class FakeReq:
+ headers = {}
+
+ async def body(self):
+ return b""
+
+ ev = _run(src.shape(FakeReq(), b"", payload))
+ assert ev.id == "evt_1"
+ assert ev.type == "stripe.charge.succeeded"
+ assert ev.source == "stripe://acct_test"
+ assert ev.data == {"object": {"amount": 1000}}
+
+ def test_handle_dispatches_on_valid_signature(self):
+ from nodes.stripe._source import get_webhook_source
+ src = get_webhook_source()
+ body = json.dumps({"id": "evt_2", "type": "charge.succeeded", "data": {}}).encode()
+ req = _fake_request(body, headers=_signed(body, self.SECRET))
+ with self._stub_secret_resolution(), \
+ patch("services.event_waiter.dispatch") as dispatch:
+ ev = _run(src.handle(req))
+ assert ev.type == "stripe.charge.succeeded"
+ dispatch.assert_called_once()
+ ev_type, dispatched = dispatch.call_args[0]
+ assert ev_type == "stripe.webhook"
+ assert dispatched.id == "evt_2"
+
+ def test_handle_rejects_tampered_signature(self):
+ from fastapi import HTTPException
+ from nodes.stripe._source import get_webhook_source
+ src = get_webhook_source()
+ body = json.dumps({"id": "evt_3", "type": "charge.succeeded"}).encode()
+ req = _fake_request(body, headers=_signed(body, "whsec_other"))
+ with self._stub_secret_resolution():
+ with pytest.raises(HTTPException) as exc:
+ _run(src.handle(req))
+ assert exc.value.status_code == 400
+
+
+# ============================================================================
+# StripeReceiveNode β€” filter + reshape
+# ============================================================================
+
+
+class TestStripeReceiveFilter:
+ def _filter(self, params: dict | None = None):
+ from nodes.stripe.stripe_receive import StripeReceiveNode, StripeReceiveParams
+ node = StripeReceiveNode()
+ return node.build_filter(StripeReceiveParams(**(params or {})))
+
+ def _ev(self, stripe_type: str, livemode: bool = False):
+ from services.events import WorkflowEvent
+ return WorkflowEvent(
+ source="stripe://acct_1",
+ type=f"stripe.{stripe_type}",
+ data={"livemode": livemode},
+ )
+
+ def test_all_matches_anything(self):
+ f = self._filter({"event_type_filter": "all"})
+ assert f(self._ev("charge.succeeded")) is True
+ assert f(self._ev("payment_intent.created")) is True
+
+ def test_exact_match(self):
+ f = self._filter({"event_type_filter": "charge.succeeded"})
+ assert f(self._ev("charge.succeeded")) is True
+ assert f(self._ev("charge.refunded")) is False
+
+ def test_wildcard_prefix(self):
+ f = self._filter({"event_type_filter": "charge.*"})
+ assert f(self._ev("charge.succeeded")) is True
+ assert f(self._ev("charge.refunded")) is True
+ assert f(self._ev("payment_intent.created")) is False
+
+ def test_livemode_filter(self):
+ live = self._filter({"livemode_filter": "live"})
+ test = self._filter({"livemode_filter": "test"})
+ assert live(self._ev("charge.succeeded", livemode=True)) is True
+ assert live(self._ev("charge.succeeded", livemode=False)) is False
+ assert test(self._ev("charge.succeeded", livemode=False)) is True
+ assert test(self._ev("charge.succeeded", livemode=True)) is False
+
+
+class TestStripeReceiveReshape:
+ def test_shape_output_extracts_stripe_fields(self):
+ from nodes.stripe.stripe_receive import StripeReceiveNode
+ from services.events import WorkflowEvent
+ ev = WorkflowEvent(
+ id="evt_1",
+ source="stripe://acct_42",
+ type="stripe.charge.succeeded",
+ data={
+ "request": {"id": "req_99"},
+ "data": {"object": {"amount": 2500}},
+ "livemode": True,
+ "api_version": "2024-04-10",
+ },
+ )
+ out = StripeReceiveNode().shape_output(ev)
+ assert out["event_id"] == "evt_1"
+ assert out["event_type"] == "charge.succeeded"
+ assert out["request_id"] == "req_99"
+ assert out["account"] == "acct_42"
+ assert out["livemode"] is True
+ assert out["data"] == {"object": {"amount": 2500}}
+
+
+# ============================================================================
+# StripeActionNode β€” pass-through over the CLI
+# ============================================================================
+
+
+class TestStripeActionPassthrough:
+ @pytest.fixture
+ def cli_capture(self):
+ captured: list[list[str]] = []
+
+ async def fake_run(*, binary, argv, credential, **kwargs):
+ captured.append(list(argv))
+ return {"success": True, "result": {"id": "x"}, "stdout": "{}"}
+
+ return captured, fake_run
+
+ def test_command_is_shlex_split(self, cli_capture):
+ captured, fake = cli_capture
+ with patch("nodes.stripe.stripe_action.run_cli_command", AsyncMock(side_effect=fake)):
+ from nodes.stripe.stripe_action import StripeActionNode, StripeActionParams
+ node = StripeActionNode()
+ result = _run(node.run(None, StripeActionParams(command="customers create --email [email protected]")))
+ assert result["success"] is True
+ assert captured == [["customers", "create", "--email", "[email protected]"]]
+
+ def test_quoted_args_preserved(self, cli_capture):
+ captured, fake = cli_capture
+ with patch("nodes.stripe.stripe_action.run_cli_command", AsyncMock(side_effect=fake)):
+ from nodes.stripe.stripe_action import StripeActionNode, StripeActionParams
+ node = StripeActionNode()
+ _run(node.run(None, StripeActionParams(command="customers create --name 'Acme Inc'")))
+ assert captured == [["customers", "create", "--name", "Acme Inc"]]
+
+ def test_empty_command_raises(self):
+ from nodes.stripe.stripe_action import StripeActionNode, StripeActionParams
+ node = StripeActionNode()
+ with pytest.raises(RuntimeError, match="command is required"):
+ _run(node.run(None, StripeActionParams(command=" ")))
+
+ def test_cli_failure_raises(self):
+ from nodes.stripe.stripe_action import StripeActionNode, StripeActionParams
+
+ async def fake_fail(*, binary, argv, credential, **kwargs):
+ return {"success": False, "error": "stripe: unknown command 'frobnicate'"}
+
+ with patch("nodes.stripe.stripe_action.run_cli_command", AsyncMock(side_effect=fake_fail)):
+ node = StripeActionNode()
+ with pytest.raises(RuntimeError, match="frobnicate"):
+ _run(node.run(None, StripeActionParams(command="frobnicate")))
+
+
+# ============================================================================
+# Plugin self-registration
+# ============================================================================
+
+
+class TestStripePluginRegistration:
+ def test_ws_handlers_registered(self):
+ import nodes.stripe # noqa: F401
+ from services.ws_handler_registry import get_ws_handlers
+ registered = get_ws_handlers()
+ for name in (
+ "stripe_connect", "stripe_disconnect", "stripe_reconnect",
+ "stripe_status", "stripe_trigger",
+ ):
+ assert name in registered, f"WS handler '{name}' not registered"
+
+ def test_webhook_source_registered(self):
+ import nodes.stripe # noqa: F401
+ from services.events import WEBHOOK_SOURCES
+ assert "stripe" in WEBHOOK_SOURCES
+ assert WEBHOOK_SOURCES["stripe"].type == "stripe.webhook"
+
+ def test_node_classes_registered(self):
+ import nodes.stripe # noqa: F401
+ from services.node_registry import get_node_class
+ assert get_node_class("stripeReceive").__name__ == "StripeReceiveNode"
+ assert get_node_class("stripeAction").__name__ == "StripeActionNode"
+
+ def test_credential_registered(self):
+ import nodes.stripe # noqa: F401
+ from services.plugin.credential import CREDENTIAL_REGISTRY
+ assert "stripe_api_key" in CREDENTIAL_REGISTRY
+
+ def test_output_schemas_registered(self):
+ import nodes.stripe # noqa: F401
+ from services.node_output_schemas import NODE_OUTPUT_SCHEMAS
+ assert "stripeReceive" in NODE_OUTPUT_SCHEMAS
+ assert "stripeAction" in NODE_OUTPUT_SCHEMAS
+
+ def test_action_node_is_ai_tool(self):
+ from nodes.stripe.stripe_action import StripeActionNode
+ assert StripeActionNode.usable_as_tool is True
+
+ def test_receive_node_subscribes_to_stripe_webhook(self):
+ from nodes.stripe.stripe_receive import StripeReceiveNode
+ assert StripeReceiveNode.event_type == "stripe.webhook"
+
+ def test_listen_source_has_correct_namespace(self):
+ from nodes.stripe._source import get_listen_source
+ src = get_listen_source()
+ assert src.process_name == "stripe-listen"
+ assert src.workflow_namespace == "_stripe"
+ assert src.binary_name == "stripe"