Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(discord): interactions endpoint, slash-command trigger and OAuth2
trohitga10becc90864
diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex 16e2678b..aca0acbe 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -407,6 +407,31 @@"placeholder": "e.g. 1234567890123456789","required": false,"help": "General Information > Application ID. Used to label this bot when several are connected."+ },+ {+ "key": "discord_public_key",+ "label": "Public Key (optional)",+ "type": "text",+ "secret": false,+ "placeholder": "64-character hex string",+ "required": false,+ "help": "General Information > Public Key. Required only for slash commands. Set the Interactions Endpoint URL to <your-server>/api/discord/interactions. Note that doing so stops interactions arriving over the gateway."+ },+ {+ "key": "discord_client_id",+ "label": "OAuth2 Client ID (optional)",+ "type": "text",+ "secret": false,+ "required": false,+ "help": "Only needed to authorise individual users. Separate from the bot token."+ },+ {+ "key": "discord_client_secret",+ "label": "OAuth2 Client Secret (optional)",+ "type": "password",+ "secret": true,+ "required": false,+ "help": "OAuth2 > General > Client Secret. Add <your-server>/api/discord/callback as a redirect URI."}],"instructions": "Create an application in the Discord Developer Portal, add a Bot to it, and copy the token. Enable the Message Content intent under Bot > Privileged Gateway Intents, or inbound message text arrives empty. Invite the bot to a server with the bot scope before using it."diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.jsonindex 1e9fc079..3b74d98d 100644--- a/server/config/node_allowlist.json+++ b/server/config/node_allowlist.json@@ -37,6 +37,7 @@"discordSend","discordAction","discordReceive",+ "discordInteraction","whatsappBusinessSend","whatsappBusinessReceive",diff --git a/server/constants.py b/server/constants.pyindex 98f04133..978f8dc2 100644--- a/server/constants.py+++ b/server/constants.py@@ -357,6 +357,7 @@ EVENT_TRIGGER_TYPES: FrozenSet[str] = frozenset("whatsappBusinessReceive","whatsappBusinessStatus","discordReceive",+ "discordInteraction","twitterReceive","workflowTrigger","chatTrigger",@@ -405,6 +406,7 @@ WORKFLOW_TRIGGER_TYPES: FrozenSet[str] = frozenset("whatsappBusinessReceive","whatsappBusinessStatus","discordReceive",+ "discordInteraction","workflowTrigger","chatTrigger","taskTrigger",diff --git a/server/nodes/discord/__init__.py b/server/nodes/discord/__init__.pyindex b2f5df2b..79b3ed29 100644--- a/server/nodes/discord/__init__.py+++ b/server/nodes/discord/__init__.py@@ -17,22 +17,33 @@ from services.node_output_schemas import register_output_schemafrom services.plugin.shutdown_hooks import register_shutdown_hookfrom services.plugin.social_provider_registry import register_social_send_handlerfrom services.status_broadcaster import register_service_refresh-from services.ws_handler_registry import register_option_loader, register_ws_handlers+from services.ws_handler_registry import (+ register_oauth_callback_path,+ register_option_loader,+ register_router,+ register_ws_handlers,+)from ._credentials import DiscordBotCredential-from ._events import MESSAGE_RECEIVED_TYPE-from ._filters import build_discord_filter+from ._events import INTERACTION_CREATED_TYPE, MESSAGE_RECEIVED_TYPE+from ._filters import build_discord_filter, build_interaction_filterfrom ._gateway import stop_all_gatewaysfrom ._handlers import WS_HANDLERSfrom ._option_loaders import load_accounts, load_channels, load_guildsfrom ._refresh import precheck_discord_trigger, refresh_discord_status+from ._router import router as discord_routerfrom ._social import social_send_adapterfrom .discord_action import DiscordActionNode, DiscordActionOutput+from .discord_interaction import DiscordInteractionNode, DiscordInteractionOutputfrom .discord_receive import DiscordReceiveNode, DiscordReceiveOutputfrom .discord_send import DiscordSendNode, DiscordSendOutputregister_ws_handlers(WS_HANDLERS)+# POST /api/discord/interactions[/{account_id}] and GET /api/discord/callback.+register_router(discord_router, name="discord")+register_oauth_callback_path("discord", "/api/discord/callback")+register_option_loader("discordAccounts", load_accounts)register_option_loader("discordGuilds", load_guilds)register_option_loader("discordChannels", load_channels)@@ -40,8 +51,10 @@ register_option_loader("discordChannels", load_channels)register_output_schema(DiscordSendNode.type, DiscordSendOutput)register_output_schema(DiscordActionNode.type, DiscordActionOutput)register_output_schema(DiscordReceiveNode.type, DiscordReceiveOutput)+register_output_schema(DiscordInteractionNode.type, DiscordInteractionOutput)register_filter_builder(DiscordReceiveNode.type, build_discord_filter)+register_filter_builder(DiscordInteractionNode.type, build_interaction_filter)register_trigger_precheck(DiscordReceiveNode.type, precheck_discord_trigger)register_service_refresh(refresh_discord_status)@@ -49,7 +62,11 @@ register_service_refresh(refresh_discord_status)# Visibility query matches on, so it must equal the type the envelope in# _events.py carries. A mismatch is silent: the listener starts and never# receives a signal.+#+# Two registrations because the registry maps one node type to one event+# type; a single trigger could not subscribe to both.register_canary_trigger_type(DiscordReceiveNode.type, MESSAGE_RECEIVED_TYPE)+register_canary_trigger_type(DiscordInteractionNode.type, INTERACTION_CREATED_TYPE)# Sessions left open count against the account's concurrent-session limit# until Discord times them out, which across dev restarts looks like a second@@ -59,6 +76,7 @@ register_shutdown_hook("discord_gateway", stop_all_gateways)__all__ = ["DiscordActionNode","DiscordBotCredential",+ "DiscordInteractionNode","DiscordReceiveNode","DiscordSendNode","WS_HANDLERS",diff --git a/server/nodes/discord/_credentials.py b/server/nodes/discord/_credentials.pyindex a16b818f..685b0cb8 100644--- a/server/nodes/discord/_credentials.py+++ b/server/nodes/discord/_credentials.py@@ -6,7 +6,7 @@ from typing import Any, Dictimport httpx-from services.plugin.credential import ApiKeyCredential, ProbeResult+from services.plugin.credential import ApiKeyCredential, OAuth2Credential, ProbeResultfrom ._accounts import APPLICATION_ID_KEY, LABEL_KEY, PUBLIC_KEY_KEY@@ -91,4 +91,27 @@ class DiscordBotCredential(ApiKeyCredential):)-__all__ = ["DiscordBotCredential"]+class DiscordUserCredential(OAuth2Credential):+ """Tokens for a user who authorised the app, distinct from the bot.++ A separate credential id so connecting a user never overwrites the bot+ token, and so a node can state which identity it acts as. Requests carry+ ``Bearer`` here, unlike the bot's ``Bot`` scheme.+ """++ id = "discord_oauth"+ display_name = "Discord (User)"+ category = "Social"+ authorization_url = "https://discord.com/oauth2/authorize"+ token_url = "https://discord.com/api/oauth2/token"+ client_id_api_key = "discord_client_id"+ client_secret_api_key = "discord_client_secret"+ # Deliberately narrow: nothing here needs email, and asking for it widens+ # both the consent screen and the damage a leaked token can do.+ scopes = ("identify", "guilds")+ docs_url = "https://discord.com/developers/docs/topics/oauth2"+ # The bot's mark; there is no separate user-flow artwork.+ icon = "/api/schemas/credentials/discord/icon"+++__all__ = ["DiscordBotCredential", "DiscordUserCredential"]diff --git a/server/nodes/discord/_events.py b/server/nodes/discord/_events.pyindex 40420107..5bd7abbc 100644--- a/server/nodes/discord/_events.py+++ b/server/nodes/discord/_events.py@@ -24,6 +24,7 @@ CONNECTION_CLOSED_TYPE = "com.opencompany.discord.connection.closed"# Shared across plugins; the frontend routes on envelope.source.STATUS_WIRE_KEY = "plugin_connection_status"MESSAGE_WIRE_KEY = "discord_message_received"+INTERACTION_WIRE_KEY = "discord_interaction_created"def discord_message_received(event_data: Mapping[str, Any]) -> WorkflowEvent:@@ -38,6 +39,22 @@ def discord_message_received(event_data: Mapping[str, Any]) -> WorkflowEvent:)+def discord_interaction_created(event_data: Mapping[str, Any]) -> WorkflowEvent:+ """Envelope for one slash command or component click.++ A separate type from messages, not a flag on one: a canary trigger+ registers exactly one CloudEvents type, because that string becomes the+ Search Attribute its listener is found by. One type per trigger node is+ the only shape the routing supports.+ """+ return WorkflowEvent(+ source=SOURCE,+ type=INTERACTION_CREATED_TYPE,+ subject=str(event_data.get("interaction_id") or ""),+ data=dict(event_data),+ )++def discord_connection_status(*,connected: bool,@@ -79,6 +96,12 @@ async def dispatch_discord_message_received(event_data: Mapping[str, Any]) -> Noawait emit(discord_message_received(event_data), wire_routing_key=MESSAGE_WIRE_KEY)+async def dispatch_discord_interaction_created(event_data: Mapping[str, Any]) -> None:+ from services.events.dispatch import emit++ await emit(discord_interaction_created(event_data), wire_routing_key=INTERACTION_WIRE_KEY)++__all__ = ["CONNECTION_CLOSED_TYPE","CONNECTION_OPENED_TYPE",@@ -87,6 +110,8 @@ __all__ = ["SOURCE","broadcast_discord_status","discord_connection_status",+ "discord_interaction_created","discord_message_received",+ "dispatch_discord_interaction_created","dispatch_discord_message_received",]diff --git a/server/nodes/discord/_filters.py b/server/nodes/discord/_filters.pyindex ee9faed1..8ad943f7 100644--- a/server/nodes/discord/_filters.py+++ b/server/nodes/discord/_filters.py@@ -60,4 +60,35 @@ def build_discord_filter(params: Dict[str, Any]) -> Callable[[Dict[str, Any]], breturn matches-__all__ = ["build_discord_filter"]+_INTERACTION_KINDS = {"command": 2, "component": 3, "modal": 5}+++def build_interaction_filter(params: Dict[str, Any]) -> Callable[[Dict[str, Any]], bool]:+ """Predicate for discordInteraction, over _interactions.shape_interaction."""+ params = params or {}++ account_id = (params.get("account_id") or "").strip()+ kind = params.get("interaction_kind") or "all"+ command_name = (params.get("command_name") or "").strip().lstrip("/")+ custom_id = (params.get("custom_id") or "").strip()+ guild_id = (params.get("guild_id") or "").strip()++ expected_type = _INTERACTION_KINDS.get(kind)++ def matches(event: Dict[str, Any]) -> bool:+ if account_id and event.get("account_id") != account_id:+ return False+ if expected_type is not None and event.get("interaction_type") != expected_type:+ return False+ if command_name and event.get("command_name") != command_name:+ return False+ if custom_id and event.get("custom_id") != custom_id:+ return False+ if guild_id and event.get("guild_id") != guild_id:+ return False+ return True++ return matches+++__all__ = ["build_discord_filter", "build_interaction_filter"]diff --git a/server/nodes/discord/_handlers.py b/server/nodes/discord/_handlers.pyindex 0cf5d89b..6c4e415d 100644--- a/server/nodes/discord/_handlers.py+++ b/server/nodes/discord/_handlers.py@@ -11,9 +11,11 @@ from typing import Any, Awaitable, Callable, Dictfrom fastapi import WebSocketfrom core.logging import get_logger+from services.events.oauth_lifecycle import make_oauth_lifecycle_handlersfrom services.plugin.ws import ws_responsefrom ._accounts import DEFAULT_ACCOUNT, list_accounts+from ._oauth import build_oauthlogger = get_logger(__name__)@@ -90,12 +92,27 @@ async def handle_discord_accounts(data: Dict[str, Any], websocket: WebSocket) ->return {"success": True, "accounts": snapshot["accounts"]}+def _user_info_to_subject(info: Dict[str, Any]) -> str:+ username = info.get("username") or ""+ return f"@{username}" if username else "Unknown"+++# discord_oauth_login / discord_oauth_status / discord_logout. Without these+# the callback route exists but nothing can start the flow.+_OAUTH_HANDLERS = make_oauth_lifecycle_handlers(+ provider="discord",+ oauth_factory=build_oauth,+ user_info_to_subject=_user_info_to_subject,+)++WS_HANDLERS: Dict[str, Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]] = {"discord_connect": handle_discord_connect,"discord_disconnect": handle_discord_disconnect,"discord_reconnect": handle_discord_reconnect,"discord_status": handle_discord_status,"discord_accounts": handle_discord_accounts,+ **_OAUTH_HANDLERS,}diff --git a/server/nodes/discord/_interactions.py b/server/nodes/discord/_interactions.pynew file mode 100644index 00000000..9a6bf540--- /dev/null+++ b/server/nodes/discord/_interactions.py@@ -0,0 +1,130 @@+"""Interaction shaping and the response-token store.++Discord's interaction token is a 15-minute bearer credential that can post+messages as the app. A trigger's output is persisted three ways, broadcast+twice, retained in the status cache and replayed into LLM context on every+turn, so the token itself never leaves this module. The trigger emits an+opaque ``interaction_ref`` and discordAction trades it back here.++Refs do not survive a restart. That is deliberate rather than a gap: a+workflow that outlived a restart mid-interaction has already blown the+15-minute window, so persisting the token would only widen its exposure+without making anything work.+"""++from __future__ import annotations++import secrets+import time+from typing import Any, Dict, Optional, Tuple++from core.logging import get_logger++logger = get_logger(__name__)++# Discord interaction types.+PING = 1+APPLICATION_COMMAND = 2+MESSAGE_COMPONENT = 3+APPLICATION_COMMAND_AUTOCOMPLETE = 4+MODAL_SUBMIT = 5++# Interaction callback types.+PONG = 1+CHANNEL_MESSAGE_WITH_SOURCE = 4+DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE = 5+DEFERRED_UPDATE_MESSAGE = 6++# Discord invalidates the token at 15 minutes; expiring slightly earlier means+# a ref never resolves to a token that is already dead.+TOKEN_TTL_SECONDS = 14 * 60++_TOKENS: Dict[str, Tuple[str, str, float]] = {}+++def store_token(application_id: str, token: str) -> str:+ """Stash a response token and return an opaque handle for it."""+ _expire()+ ref = secrets.token_urlsafe(16)+ _TOKENS[ref] = (application_id, token, time.monotonic() + TOKEN_TTL_SECONDS)+ return ref+++def resolve_token(ref: str) -> Optional[Tuple[str, str]]:+ """Return ``(application_id, token)`` for a ref, or None if unknown."""+ _expire()+ entry = _TOKENS.get(ref)+ if entry is None:+ return None+ application_id, token, _ = entry+ return application_id, token+++def _expire(now: Optional[float] = None) -> None:+ moment = now if now is not None else time.monotonic()+ for ref in [r for r, (_, _, expiry) in _TOKENS.items() if expiry <= moment]:+ _TOKENS.pop(ref, None)+++def deferred_response_type(interaction_type: int) -> int:+ """How to acknowledge within the three-second deadline.++ A component click defers with UPDATE_MESSAGE so the existing message is+ edited; deferring it as a new message would post an empty one.+ """+ return (+ DEFERRED_UPDATE_MESSAGE+ if interaction_type == MESSAGE_COMPONENT+ else DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE+ )+++def shape_interaction(payload: Dict[str, Any], *, account_id: str) -> Dict[str, Any]:+ """Flatten an interaction into the trigger's output shape.++ Snowflakes are stringified for the same reason as in _dispatch: ids past+ 2^53 lose precision the moment anything treats them as numbers.+ """+ data = payload.get("data") or {}+ member = payload.get("member") or {}+ user = member.get("user") or payload.get("user") or {}++ options = {+ option.get("name"): option.get("value")+ for option in (data.get("options") or [])+ if isinstance(option, dict) and option.get("name")+ }++ return {+ "account_id": account_id,+ "interaction_id": str(payload.get("id") or ""),+ "interaction_type": payload.get("type"),+ "application_id": str(payload.get("application_id") or ""),+ "command_name": data.get("name"),+ "custom_id": data.get("custom_id"),+ "component_type": data.get("component_type"),+ "options": options,+ "channel_id": str(payload.get("channel_id") or "") or None,+ "guild_id": str(payload.get("guild_id") or "") or None,+ "user_id": str(user.get("id") or "") or None,+ "user_name": user.get("username"),+ # The token itself is never emitted. discordAction resolves this.+ "interaction_ref": store_token(+ str(payload.get("application_id") or ""), str(payload.get("token") or "")+ ),+ }+++__all__ = [+ "APPLICATION_COMMAND",+ "DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE",+ "DEFERRED_UPDATE_MESSAGE",+ "MESSAGE_COMPONENT",+ "PING",+ "PONG",+ "TOKEN_TTL_SECONDS",+ "deferred_response_type",+ "resolve_token",+ "shape_interaction",+ "store_token",+]diff --git a/server/nodes/discord/_oauth.py b/server/nodes/discord/_oauth.pynew file mode 100644index 00000000..8e7fe42b--- /dev/null+++ b/server/nodes/discord/_oauth.py@@ -0,0 +1,85 @@+"""Discord OAuth2 client for user-context authorisation.++Subclasses the shared PKCE base, which owns the state store, code-verifier+generation, code exchange, refresh and revocation. Only the endpoints, the+scope set and the user-info translation are Discord-specific.++Distinct from the bot token: that authenticates the *app*, this authorises a+*user*. They are stored under different credential ids so connecting one+never overwrites the other.++Scopes are the minimum that identifies the user. ``email`` is deliberately+not requested -- nothing here needs it, and asking widens the consent screen+and the blast radius of a leaked token for no gain.+"""++from __future__ import annotations++from typing import Any, ClassVar, Dict, List, Optional++import httpx++from core.logging import get_logger+from services.plugin.oauth import OAuth2PKCEClient++logger = get_logger(__name__)++USER_INFO_URL = "https://discord.com/api/v10/users/@me"++CLIENT_ID_KEY = "discord_client_id"+CLIENT_SECRET_KEY = "discord_client_secret"+++class DiscordOAuth(OAuth2PKCEClient):+ provider: ClassVar[str] = "discord"+ authorization_endpoint: ClassVar[str] = "https://discord.com/oauth2/authorize"+ token_endpoint: ClassVar[str] = "https://discord.com/api/oauth2/token"+ revocation_endpoint: ClassVar[str] = "https://discord.com/api/oauth2/token/revoke"++ DEFAULT_SCOPES: ClassVar[List[str]] = ["identify", "guilds"]++ async def fetch_user_info(self, access_token: str) -> Dict[str, Any]:+ """Translate Discord's user object into the unified shape.++ Bearer here, not Bot: this token represents a user, and the bot+ prefix would be rejected.+ """+ async with httpx.AsyncClient(timeout=10.0) as client:+ response = await client.get(+ USER_INFO_URL,+ headers={+ "Authorization": f"Bearer {access_token}",+ "User-Agent": "DiscordBot (https://github.com/trohitg/opencompany, 1.0)",+ },+ )+ response.raise_for_status()+ user = response.json()++ username = user.get("username") or ""+ return {+ "id": str(user.get("id") or ""),+ "username": username,+ "name": user.get("global_name") or username,+ "email": user.get("email") or "",+ }+++async def build_oauth(+ *,+ redirect_uri: Optional[str] = None,+ **_kwargs: Any,+) -> DiscordOAuth:+ """Build a client from stored application credentials."""+ from services.plugin.deps import get_auth_service++ auth_service = get_auth_service()+ client_id = await auth_service.get_api_key(CLIENT_ID_KEY) or ""+ client_secret = await auth_service.get_api_key(CLIENT_SECRET_KEY) or ""+ return DiscordOAuth(+ client_id=client_id,+ client_secret=client_secret or None,+ redirect_uri=redirect_uri or "",+ )+++__all__ = ["CLIENT_ID_KEY", "CLIENT_SECRET_KEY", "DiscordOAuth", "build_oauth"]diff --git a/server/nodes/discord/_router.py b/server/nodes/discord/_router.pynew file mode 100644index 00000000..7db92faf--- /dev/null+++ b/server/nodes/discord/_router.py@@ -0,0 +1,141 @@+"""HTTP surface: the interactions endpoint and the OAuth2 callback.++A plugin-owned router rather than a ``WebhookSource``, for three reasons the+generic intake cannot express:++* Discord's endpoint-validation probe deliberately sends bad signatures and+ requires **401**. ``WebhookSource.handle`` raises 400 on verifier failure,+ and a 400 makes Discord refuse to save the endpoint URL at all.+* The initial response is due within three seconds. ``WebhookSource.handle``+ awaits shaping, ``emit`` (a Temporal Visibility query plus a Signal per+ consumer) and dispatch before the router writes a byte. That is not a+ latency budget a plugin controls. This ACKs first and fans out after.+* The reply body is part of the protocol -- PING must be answered with+ ``{"type": 1}`` -- while the generic route returns a fixed envelope.++Interaction delivery is mutually exclusive with the gateway: setting an+endpoint URL stops INTERACTION_CREATE arriving over the socket. The account's+public key is what identifies which app is calling, so each app points at its+own path rather than the server trial-verifying against every stored key,+which would be both a timing oracle and an availability multiplier.+"""++from __future__ import annotations++import asyncio+from typing import Any, Dict++from fastapi import Request, Response+from fastapi.responses import JSONResponse++from core.logging import get_logger+from services.events.oauth_lifecycle import make_oauth_callback_router++from . import _interactions+from ._accounts import DEFAULT_ACCOUNT, PUBLIC_KEY_KEY, storage_scope+from ._oauth import build_oauth+from ._verifier import DiscordEd25519Verifier++logger = get_logger(__name__)+++def _user_info_to_email(info: Dict[str, Any]) -> str:+ # /users/@me returns a username; email would need the email scope, which+ # is deliberately not requested.+ return info.get("email") or info.get("username") or "Unknown"+++# One router, built by the OAuth factory and then extended, rather than a+# fresh APIRouter with the factory's router included into it. On an APIRouter+# (unlike an app) include_router leaves a pathless placeholder instead of+# flattening the child's routes: the callback never mounts, and the pathless+# entry reads as an ungated route to the public-surface invariant.+#+# The factory sets prefix="/api/discord", so paths added below are relative+# to it.+router = make_oauth_callback_router(+ provider="discord",+ oauth_factory=build_oauth,+ user_info_to_email=_user_info_to_email,+ color_hex="#5865F2",+)++# Strong references to in-flight fan-out tasks. The event loop only holds a+# weak reference, so without this a task can be garbage-collected mid-await+# and the interaction silently never reaches the workflow.+_PENDING: set[asyncio.Task] = set()+++async def _public_key(account_id: str) -> str:+ from services.plugin.deps import get_auth_service++ return await get_auth_service().get_api_key(PUBLIC_KEY_KEY, storage_scope(account_id)) or ""+++async def _handle_interaction(request: Request, account_id: str) -> Response:+ # The signature covers the exact bytes Discord sent. Re-serialising the+ # parsed JSON would change key order or separators and break verification+ # for authentic requests, so the body is read raw and parsed afterwards.+ body = await request.body()++ public_key = await _public_key(account_id)+ if not public_key:+ # Fail closed. Without a key nothing can be authenticated, and+ # accepting anyway would let anyone trigger workflows.+ return JSONResponse(+ {"error": "Discord public key is not configured for this account."},+ status_code=503,+ headers={"Retry-After": "5"},+ )++ try:+ DiscordEd25519Verifier.verify(dict(request.headers), body, public_key)+ except ValueError as exc:+ # 401, not 400: Discord's endpoint-validation probe sends a bad+ # signature on purpose and refuses to save the URL unless it gets a+ # 401 back.+ logger.debug("discord interaction signature rejected", error=str(exc))+ return JSONResponse({"error": "invalid request signature"}, status_code=401)++ try:+ payload: Dict[str, Any] = await request.json()+ except Exception:+ return JSONResponse({"error": "malformed interaction payload"}, status_code=400)++ interaction_type = payload.get("type")++ if interaction_type == _interactions.PING:+ return JSONResponse({"type": _interactions.PONG})++ # Acknowledge inside the three-second window, then do the work. The+ # workflow finishes the interaction later through discordAction.+ event = _interactions.shape_interaction(payload, account_id=account_id)+ task = asyncio.create_task(_emit(event))+ _PENDING.add(task)+ task.add_done_callback(_PENDING.discard)++ return JSONResponse({"type": _interactions.deferred_response_type(interaction_type)})+++async def _emit(event: Dict[str, Any]) -> None:+ from ._events import dispatch_discord_interaction_created++ try:+ await dispatch_discord_interaction_created(event)+ except Exception as exc:+ # The HTTP reply already went out; losing the fan-out must not+ # surface as an unhandled task exception.+ logger.warning("discord interaction dispatch failed", error=str(exc))++[email protected]("/interactions")+async def interactions_default(request: Request) -> Response:+ return await _handle_interaction(request, DEFAULT_ACCOUNT)++[email protected]("/interactions/{account_id}")+async def interactions_for_account(request: Request, account_id: str) -> Response:+ return await _handle_interaction(request, account_id)+++__all__ = ["router"]diff --git a/server/nodes/discord/_verifier.py b/server/nodes/discord/_verifier.pynew file mode 100644index 00000000..b1ba36dd--- /dev/null+++ b/server/nodes/discord/_verifier.py@@ -0,0 +1,53 @@+"""Discord interaction signature verifier.++Headers: ``X-Signature-Ed25519`` (hex) and ``X-Signature-Timestamp``.+Signed payload: ``timestamp + raw_body``.+Reference: https://discord.com/developers/docs/interactions/receiving-and-responding++The first asymmetric verifier in the tree -- the four shipped ones are all+HMAC. The "secret" here is the application's Ed25519 *public* key, which is+not secret at all; it rides the same ``secret_field`` plumbing because what+that plumbing does is fetch one stored string.++Verification runs over the raw request body, never a re-serialised JSON dict:+any difference in key order or separators changes the bytes and the signature+stops matching for authentic requests.+"""++from __future__ import annotations++from typing import Mapping++from services.events.verifiers.base import WebhookVerifier+++class DiscordEd25519Verifier(WebhookVerifier):+ @classmethod+ def verify(cls, headers: Mapping[str, str], body: bytes, secret: str) -> None:+ # Imported here rather than at module scope so importing the plugin+ # never depends on the crypto backend loading.+ from cryptography.exceptions import InvalidSignature+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey++ signature = cls._header(headers, "x-signature-ed25519")+ timestamp = cls._header(headers, "x-signature-timestamp")+ if not signature or not timestamp:+ raise ValueError("X-Signature-Ed25519 or X-Signature-Timestamp header missing")++ try:+ public_key = Ed25519PublicKey.from_public_bytes(bytes.fromhex(secret))+ except ValueError as exc:+ raise ValueError(f"Discord public key is not valid hex: {exc}") from exc++ try:+ signature_bytes = bytes.fromhex(signature)+ except ValueError as exc:+ raise ValueError("X-Signature-Ed25519 is not valid hex") from exc++ try:+ public_key.verify(signature_bytes, timestamp.encode() + body)+ except InvalidSignature as exc:+ raise ValueError("Discord signature mismatch") from exc+++__all__ = ["DiscordEd25519Verifier"]diff --git a/server/nodes/discord/discord_action.py b/server/nodes/discord/discord_action.pyindex 3574af2d..5034150b 100644--- a/server/nodes/discord/discord_action.py+++ b/server/nodes/discord/discord_action.py@@ -41,6 +41,7 @@ class DiscordActionParams(BaseModel):"add_reaction","pin_message","download_attachments",+ "interaction_respond","execute_webhook","custom",] = Field(default="list_channels", description="What to do.")@@ -111,6 +112,17 @@ class DiscordActionParams(BaseModel):json_schema_extra=_show(operation=["download_attachments"]),)+ interaction_ref: str = Field(+ default="",+ description="The interaction_ref from a discordInteraction trigger.",+ json_schema_extra=_show(operation=["interaction_respond"]),+ )+ interaction_message: str = Field(+ default="",+ description="Message to send as the interaction response.",+ json_schema_extra={"rows": 3, **_show(operation=["interaction_respond"])},+ )+webhook_url: str = Field(default="",description="Discord webhook URL. Posts without a bot token.",@@ -318,6 +330,53 @@ class DiscordActionNode(AccountScopedNode):return DiscordActionOutput(files=files, count=len(files))+ @Operation("interaction_respond", cost={"service": "discord", "action": "interaction", "count": 1})+ async def interaction_respond(+ self, ctx: NodeContext, params: DiscordActionParams+ ) -> DiscordActionOutput:+ """Finish an interaction the trigger deferred.++ The router already acknowledged within Discord's three-second window,+ so this edits that deferred response rather than creating one. The+ token is resolved from the opaque ref here; it never travels through+ node output.+ """+ from ._interactions import resolve_token++ ref = _require(params.interaction_ref, "interaction reference")+ message = _require(params.interaction_message, "message")++ resolved = resolve_token(ref)+ if resolved is None:+ raise NodeUserError(+ "That interaction reference is unknown or has expired. Discord "+ "interaction tokens last 15 minutes, and references do not survive "+ "a server restart."+ )+ application_id, token = resolved++ # Webhook-style route: the token authenticates it, so no bot token is+ # attached and this deliberately bypasses the account path.+ import httpx++ url = (+ f"{_base.API_BASE_URL}/{_base.API_VERSION}/webhooks/"+ f"{application_id}/{token}/messages/@original"+ )+ async with httpx.AsyncClient(timeout=_base.REQUEST_TIMEOUT_SECONDS) as client:+ response = await client.patch(+ url,+ json={"content": message},+ headers={"User-Agent": _base.USER_AGENT},+ )+ if response.status_code >= 400:+ # Never echo the URL: it embeds the interaction token.+ raise NodeUserError(+ f"Discord rejected the interaction response with HTTP "+ f"{response.status_code}. The 15-minute window may have closed."+ )+ return DiscordActionOutput(result=response.json() if response.content else {"sent": True})+# ---- escape hatches -------------------------------------------------@Operation("execute_webhook", cost={"service": "discord", "action": "execute_webhook", "count": 1})diff --git a/server/nodes/discord/discord_interaction.py b/server/nodes/discord/discord_interaction.pynew file mode 100644index 00000000..5e12239f--- /dev/null+++ b/server/nodes/discord/discord_interaction.py@@ -0,0 +1,114 @@+"""discordInteraction — fire a workflow on a slash command or component click.++A second trigger node rather than a mode on discordReceive. A canary trigger+registers exactly one CloudEvents type, because that string becomes the+EventType Search Attribute its listener is discovered by, so one node cannot+subscribe to both. The payloads also share almost nothing: merging them would+mean a union output schema and weaker {{trigger.field}} resolution. This is+the same split, for the same reasons, as whatsappBusinessReceive vs+whatsappBusinessStatus.++Interactions arrive over HTTP, not the gateway. Setting an interactions+endpoint URL for an application stops INTERACTION_CREATE being delivered over+the socket, so the two paths are mutually exclusive per app.+"""++from __future__ import annotations++from typing import Any, Callable, Dict, Literal, Optional++from pydantic import BaseModel, ConfigDict, Field++from services.plugin import NodeContext, Operation, TaskQueue, TriggerNode++from ._credentials import DiscordBotCredential+from ._events import INTERACTION_CREATED_TYPE+++class DiscordInteractionParams(BaseModel):+ account_id: str = Field(+ default="",+ description="Which Discord app to accept interactions for.",+ json_schema_extra={"loadOptionsMethod": "discordAccounts"},+ )+ interaction_kind: Literal["all", "command", "component", "modal"] = Field(+ default="all",+ description="Which kind of interaction fires this trigger.",+ )+ command_name: str = Field(+ default="",+ description="Only fire for this slash command.",+ json_schema_extra={"displayOptions": {"show": {"interaction_kind": ["all", "command"]}}},+ )+ custom_id: str = Field(+ default="",+ description="Only fire for a component or modal with this custom_id.",+ json_schema_extra={"displayOptions": {"show": {"interaction_kind": ["all", "component", "modal"]}}},+ )+ guild_id: str = Field(+ default="",+ description="Only fire for interactions in this server.",+ )++ model_config = ConfigDict(extra="ignore")+++class DiscordInteractionOutput(BaseModel):+ account_id: Optional[str] = None+ interaction_id: Optional[str] = None+ interaction_type: Optional[int] = None+ application_id: Optional[str] = None+ command_name: Optional[str] = None+ custom_id: Optional[str] = None+ component_type: Optional[int] = None+ options: Dict[str, Any] = Field(default_factory=dict)+ channel_id: Optional[str] = None+ guild_id: Optional[str] = None+ user_id: Optional[str] = None+ user_name: Optional[str] = None+ # An opaque handle, never the token. Pass it to+ # discordAction[interaction_respond] to answer within the 15-minute+ # window. The token itself is a bearer credential and node output is+ # persisted, broadcast and replayed into LLM context.+ interaction_ref: Optional[str] = None++ model_config = ConfigDict(extra="allow")+++class DiscordInteractionNode(TriggerNode):+ type = "discordInteraction"+ display_name = "Discord Interaction"+ subtitle = "Slash Command"+ group = ("discord", "trigger")+ description = "Trigger a workflow when a Discord slash command or component is used"+ component_kind = "trigger"+ handles = (+ {"name": "output-main", "kind": "output", "position": "right", "label": "Output", "role": "main"},+ )+ credentials = (DiscordBotCredential,)+ task_queue = TaskQueue.TRIGGERS_EVENT+ mode = "event"+ event_type = "discord_interaction_created"++ Params = DiscordInteractionParams+ Output = DiscordInteractionOutput++ def build_filter(self, params: BaseModel) -> Callable[[Dict[str, Any]], bool]:+ from ._filters import build_interaction_filter++ return build_interaction_filter(params.model_dump())++ @Operation("wait")+ async def wait(+ self, ctx: NodeContext, params: DiscordInteractionParams+ ) -> DiscordInteractionOutput:+ """Never called; interactions resolve through the event waiter."""+ raise NotImplementedError("discordInteraction resolves through the event waiter")+++__all__ = [+ "INTERACTION_CREATED_TYPE",+ "DiscordInteractionNode",+ "DiscordInteractionOutput",+ "DiscordInteractionParams",+]diff --git a/server/tests/nodes/test_discord.py b/server/tests/nodes/test_discord.pyindex d00438b5..248af025 100644--- a/server/tests/nodes/test_discord.py+++ b/server/tests/nodes/test_discord.py@@ -655,3 +655,297 @@ class TestGatewayLifecycle:result = _run(DiscordReceiveNode().execute("d1", {}, _ctx()))assert result["success"] is Falseassert "not connected" in result["error"].lower()+++def _keypair():+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey++ private = Ed25519PrivateKey.generate()+ from cryptography.hazmat.primitives import serialization++ public_hex = private.public_key().public_bytes(+ encoding=serialization.Encoding.Raw,+ format=serialization.PublicFormat.Raw,+ ).hex()+ return private, public_hex+++class TestEd25519Verifier:+ """The first asymmetric verifier here; the four shipped ones are HMAC."""++ def test_valid_signature_passes(self):+ from nodes.discord._verifier import DiscordEd25519Verifier++ private, public_hex = _keypair()+ body = b'{"type":1}'+ timestamp = "1700000000"+ signature = private.sign(timestamp.encode() + body).hex()++ DiscordEd25519Verifier.verify(+ {"X-Signature-Ed25519": signature, "X-Signature-Timestamp": timestamp},+ body,+ public_hex,+ )++ def test_tampered_body_is_rejected(self):+ from nodes.discord._verifier import DiscordEd25519Verifier++ private, public_hex = _keypair()+ timestamp = "1700000000"+ signature = private.sign(timestamp.encode() + b'{"type":1}').hex()++ with pytest.raises(ValueError):+ DiscordEd25519Verifier.verify(+ {"X-Signature-Ed25519": signature, "X-Signature-Timestamp": timestamp},+ b'{"type":2}',+ public_hex,+ )++ def test_timestamp_is_part_of_the_signed_payload(self):+ """Signing the body alone would let a captured request be replayed+ under a different timestamp."""+ from nodes.discord._verifier import DiscordEd25519Verifier++ private, public_hex = _keypair()+ body = b'{"type":1}'+ signature = private.sign(b"1700000000" + body).hex()++ with pytest.raises(ValueError):+ DiscordEd25519Verifier.verify(+ {"X-Signature-Ed25519": signature, "X-Signature-Timestamp": "1700009999"},+ body,+ public_hex,+ )++ @pytest.mark.parametrize(+ "headers",+ [+ {},+ {"X-Signature-Ed25519": "aa"},+ {"X-Signature-Timestamp": "1700000000"},+ ],+ )+ def test_missing_headers_are_rejected(self, headers):+ from nodes.discord._verifier import DiscordEd25519Verifier++ _, public_hex = _keypair()+ with pytest.raises(ValueError):+ DiscordEd25519Verifier.verify(headers, b"{}", public_hex)++ def test_non_hex_inputs_are_rejected_not_crashed(self):+ from nodes.discord._verifier import DiscordEd25519Verifier++ _, public_hex = _keypair()+ with pytest.raises(ValueError):+ DiscordEd25519Verifier.verify(+ {"X-Signature-Ed25519": "zzzz", "X-Signature-Timestamp": "1"},+ b"{}",+ public_hex,+ )+++class TestInteractionTokenNeverLeaves:+ """The token is a 15-minute bearer credential and trigger output is+ persisted, broadcast and replayed into LLM context."""++ def test_shaped_interaction_carries_a_ref_not_the_token(self):+ from nodes.discord._interactions import resolve_token, shape_interaction++ payload = {+ "id": "111",+ "type": 2,+ "application_id": "999",+ "token": "SUPER_SECRET_TOKEN",+ "data": {"name": "ping", "options": [{"name": "who", "value": "world"}]},+ "member": {"user": {"id": "222", "username": "bob"}},+ }+ event = shape_interaction(payload, account_id="default")++ assert "SUPER_SECRET_TOKEN" not in str(event)+ assert event["interaction_ref"]+ assert event["command_name"] == "ping"+ assert event["options"] == {"who": "world"}+ # The ref is what trades back for the token, server-side only.+ assert resolve_token(event["interaction_ref"]) == ("999", "SUPER_SECRET_TOKEN")++ def test_unknown_ref_resolves_to_nothing(self):+ from nodes.discord._interactions import resolve_token++ assert resolve_token("not-a-real-ref") is None++ def test_component_click_defers_as_an_update(self):+ """Deferring a component as a new message posts an empty one."""+ from nodes.discord._interactions import (+ APPLICATION_COMMAND,+ DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE,+ DEFERRED_UPDATE_MESSAGE,+ MESSAGE_COMPONENT,+ deferred_response_type,+ )++ assert deferred_response_type(MESSAGE_COMPONENT) == DEFERRED_UPDATE_MESSAGE+ assert deferred_response_type(APPLICATION_COMMAND) == DEFERRED_CHANNEL_MESSAGE_WITH_SOURCE+++class TestInteractionsEndpoint:+ """Protocol requirements Discord enforces on the endpoint itself."""++ def _app(self):+ from fastapi import FastAPI++ from nodes.discord._router import router++ app = FastAPI()+ app.include_router(router)+ return app++ def _client(self):+ from fastapi.testclient import TestClient++ return TestClient(self._app())++ def _post(self, body: bytes, headers: dict, public_key: str):+ auth = SimpleNamespace(get_api_key=AsyncMock(return_value=public_key))+ with patch("services.plugin.deps.get_auth_service", return_value=auth):+ return self._client().post(+ "/api/discord/interactions", content=body, headers=headers+ )++ def test_ping_is_answered_with_pong(self):+ private, public_hex = _keypair()+ body = b'{"type":1}'+ ts = "1700000000"+ sig = private.sign(ts.encode() + body).hex()++ response = self._post(+ body,+ {"X-Signature-Ed25519": sig, "X-Signature-Timestamp": ts, "Content-Type": "application/json"},+ public_hex,+ )++ assert response.status_code == 200+ assert response.json() == {"type": 1}++ def test_bad_signature_is_401_not_400(self):+ """Discord's endpoint-validation probe sends a deliberately invalid+ signature and refuses to save the URL unless it gets a 401."""+ _, public_hex = _keypair()+ other_private, _ = _keypair()+ body = b'{"type":1}'+ ts = "1700000000"+ sig = other_private.sign(ts.encode() + body).hex()++ response = self._post(+ body,+ {"X-Signature-Ed25519": sig, "X-Signature-Timestamp": ts, "Content-Type": "application/json"},+ public_hex,+ )++ assert response.status_code == 401++ def test_missing_public_key_fails_closed(self):+ """Accepting unverified requests would let anyone trigger workflows."""+ response = self._post(+ b'{"type":1}',+ {"X-Signature-Ed25519": "aa", "X-Signature-Timestamp": "1", "Content-Type": "application/json"},+ "",+ )++ assert response.status_code == 503+ assert response.headers.get("Retry-After") == "5"++ def test_command_is_deferred_within_the_deadline(self):+ """A workflow cannot run in three seconds, so the endpoint must ACK+ and fan out afterwards."""+ private, public_hex = _keypair()+ body = b'{"type":2,"id":"1","application_id":"9","token":"t","data":{"name":"ping"}}'+ ts = "1700000000"+ sig = private.sign(ts.encode() + body).hex()++ with patch("nodes.discord._events.dispatch_discord_interaction_created", new=AsyncMock()):+ response = self._post(+ body,+ {"X-Signature-Ed25519": sig, "X-Signature-Timestamp": ts, "Content-Type": "application/json"},+ public_hex,+ )++ assert response.status_code == 200+ assert response.json() == {"type": 5}+++class TestRouterMounting:+ """Both surfaces must actually mount.++ Building a fresh APIRouter and include_router()-ing the OAuth factory's+ router into it looks right and is not: on an APIRouter, unlike an app,+ include_router leaves a pathless placeholder rather than flattening the+ child's routes. The callback silently did not exist, and the pathless+ entry read as an ungated route to the public-surface invariant.+ """++ def _paths(self):+ from nodes.discord._router import router++ return {getattr(route, "path", None) for route in router.routes}++ def test_all_routes_mount(self):+ assert {+ "/api/discord/callback",+ "/api/discord/interactions",+ "/api/discord/interactions/{account_id}",+ } <= self._paths()++ def test_no_pathless_route_entries(self):+ assert all(path for path in self._paths())++ def test_every_route_is_under_the_gated_api_prefix(self):+ """AuthMiddleware gates on the prefix; anything outside it would be+ served unauthenticated."""+ assert all(path.startswith("/api/discord/") for path in self._paths())+++class TestInteractionTriggerIsDeployable:+ def test_registered_for_deployment(self):+ from constants import EVENT_TRIGGER_TYPES, POLLING_TRIGGER_TYPES, WORKFLOW_TRIGGER_TYPES++ from nodes.discord.discord_interaction import DiscordInteractionNode++ assert DiscordInteractionNode.type in EVENT_TRIGGER_TYPES+ assert DiscordInteractionNode.type in WORKFLOW_TRIGGER_TYPES+ assert DiscordInteractionNode.type not in POLLING_TRIGGER_TYPES++ def test_canary_type_matches_the_emitted_envelope(self):+ from services.deployment.canary_registry import cloudevent_type_for++ from nodes.discord._events import INTERACTION_CREATED_TYPE, discord_interaction_created+ from nodes.discord.discord_interaction import DiscordInteractionNode++ assert cloudevent_type_for(DiscordInteractionNode.type) == INTERACTION_CREATED_TYPE+ assert discord_interaction_created({"interaction_id": "1"}).type == INTERACTION_CREATED_TYPE++ def test_message_and_interaction_use_distinct_types(self):+ """One node maps to one CloudEvents type, so a shared type would make+ each trigger fire on the other's events."""+ from nodes.discord._events import INTERACTION_CREATED_TYPE, MESSAGE_RECEIVED_TYPE++ assert INTERACTION_CREATED_TYPE != MESSAGE_RECEIVED_TYPE++ @pytest.mark.parametrize(+ "params, event, expected",+ [+ ({}, {"interaction_type": 2, "command_name": "ping"}, True),+ ({"interaction_kind": "command"}, {"interaction_type": 3}, False),+ ({"interaction_kind": "component"}, {"interaction_type": 3}, True),+ ({"command_name": "ping"}, {"command_name": "ping"}, True),+ ({"command_name": "/ping"}, {"command_name": "ping"}, True),+ ({"command_name": "other"}, {"command_name": "ping"}, False),+ ({"custom_id": "btn"}, {"custom_id": "btn"}, True),+ ({"guild_id": "g1"}, {"guild_id": "g2"}, False),+ ],+ )+ def test_filter_matrix(self, params, event, expected):+ from nodes.discord._filters import build_interaction_filter++ base = {"account_id": "default"}+ base.update(event)+ assert build_interaction_filter(params)(base) is expecteddiff --git a/server/tests/test_plugin_self_containment.py b/server/tests/test_plugin_self_containment.pyindex df7c2b06..528d439f 100644--- a/server/tests/test_plugin_self_containment.py+++ b/server/tests/test_plugin_self_containment.py@@ -95,6 +95,7 @@ _PLUGINS_WITH_HANDLERS = (# from its package ``__init__.py``._PLUGINS_WITH_ROUTERS = ("android",+ "discord","google","microsoft","twitter",