Skip to content

Self-improving AI Employees for everyone

fix(discord): let Discord's signed interactions through when login is on

trohitg2f9a2aa8ed67
diff --git a/CLAUDE.md b/CLAUDE.md
index 1dd652cf..bf4ecffb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -20,7 +20,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Theme System](./docs-internal/theme_system.md)** | Three themes — the base `light` and `dark` plus one stylized skin, `atomic` (the design handoff's nine other skins were removed on 2026-10-12) — driven by `<html data-theme>` + per-theme CSS files in `client/src/themes/`. Home, the editor and the sign-in screen all show the chosen theme, and one theme button ([components/ui/ThemeButton.tsx](./client/src/components/ui/ThemeButton.tsx)) in the Home header, the editor's toolbar and the sign-in screen steps Light → Dark → Atomic (`cycleTheme`; every theme name comes from `THEME_LABEL` in `ThemeContext.tsx`). Token taxonomy (surface / fg / border / accent / typography / motion) in **hex + `color-mix()`**; `@theme inline` bridge maps `--color-X: var(--X)` (no `hsl()` wrapper); per-theme files own the colour hex, base.css owns the shared `--tint-*` alpha scale; action role tokens (incl. `-ink` readable text), **per-theme `--code-*` syntax tokens** (tier 6 — the code editor, console/output JSON viewers, and chat code blocks paint in each theme's own palette: keyword→trigger, string→success, number→agent, function→model, on an adaptive dark/light code surface; replaced the global dracula `--prism-*` block + dead `getPrismTokenCSS`; the `OutputPanel` JSON viewer reads the same vars), the `--pulse-keyframe` animation system + `.opencompany-*` helpers in `animations.css`, per-component decoration hooks (`.canvas-host`, `.toolbar`, `.sq-node`, …; Atomic's panel edges, starburst canvas and node styling), **canvas-node visual contract via `--node-color` CSS custom property** (no inline `background` / `border` on node components — base.css + per-theme CSS owns visuals; `NodeStyle` helper type at [types/NodeTypes.ts](./client/src/types/NodeTypes.ts) makes the inline custom-prop typecheck-clean), **`--node-pulse-color` separate from `--node-color`** so executing-node glow uses each theme's highest-contrast accent regardless of plugin accent, **`data-page-hidden` animation pause** (set by `app/usePageActivitySync.ts`, mounted in `App.tsx` above the sign-in gate so it covers every screen, while the page is hidden per the Page Visibility API, never merely because the window lost focus; base.css declares `html[data-page-hidden] *, *::before, *::after { animation-play-state: paused !important }` to prevent compositor stall on tab return), **per-theme icon glyphs** (Atomic's 29 inline SVG glyphs in [themedGlyphs.ts](./client/src/assets/icons/themedGlyphs.ts), read by theme-aware [NodeIcon.tsx](./client/src/assets/icons/NodeIcon.tsx)), **per-theme canvas-grid + custom cursors** via `--canvas-grid` / `--cursor-default` slots, **parameter panel migrated to Tailwind tokens** (no `useAppTheme()` reads; section headers carry the display-typography triplet; raw `<Button>` swapped to `<ActionButton intent>`), scrollbars from the global token rules plus Atomic's own, 9-event WebAudio sound system (3 packs — parchment, terminal, vibraphone — via `--sound-pack` token + `useSound()` hook + global hover delegate + sonner toast monkey-patch + `withSound()` HOC + `Sounds.unlock()` gesture-unlock for AudioContext autoplay-policy compliance), `@media (prefers-reduced-motion: reduce)` accessibility, 30 ms throttle on `type` / `hover`, migration recipe, anti-patterns. Read this before adding a new theme, migrating a component to the new contract, or adding a canvas-node component. |
| **[Design System Bundle](./docs-internal/design-system/IMPLEMENTATION.md)** | Canonical, vendored design-system reference (extracted from this repo; see its `IMPLEMENTATION.md` for the contract). Tokens are **hex + `color-mix()`** (`tokens/{colors,typography,spacing,motion,fonts,base}.css`) — the format the live codebase standardizes on. Includes 34 reference components (`components/`, inline-style reference only — recreate in Tailwind/shadcn idioms), full-app UI kit (`ui_kits/opencompany/index.html`), theme docs (`guidelines/THEMES.md`), **the merged handoff brief (`HANDOFF.md` — glow-ladder traps, step-edge contract, toolbar layout traps, canvas-layer asymmetries, plus the recorded product amendments)**, and **the panel×theme fidelity target (`reference-mockup/Panel Theme Matrix.dc.html` — 17 panels × 3 themes, open in a browser)**. `reference/themes/` no longer vendors CSS snapshots — it points at the authoritative [client/src/themes/](./client/src/themes/). Copy token values verbatim; do not re-derive by eye. Pairs with [Theme System](./docs-internal/theme_system.md). |
| **[Schema Source of Truth RFC](./docs-internal/ARCHIVE/schema_source_of_truth_rfc.md)** | *Archived — shipped.* Backend is SSOT for node schemas, visual metadata, handlers, palette metadata, icons; `VITE_NODESPEC_BACKEND` defaults on and the frontend node definitions are gone. Plugin pattern: one `BaseNode` subclass in `server/nodes/<group>/<plugin>/__init__.py`. Wire format: `asset:<key>` / `<lib>:<brand>` / URL / emoji. Endpoint: `/api/schemas/nodes/{type}/spec.json`. Current reference: [Plugin System](./docs-internal/plugin_system.md). |
-| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern; `request()` supports `json` / `data` / `files` — the last for multipart uploads, threaded through the auth-retry rebuild). `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use); live count via `len(services.plugin.credential.CREDENTIAL_REGISTRY)` — do not hand-maintain a number here. `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live plugin count via `len(services.node_registry.NODE_METADATA)`; a bare `__init__.py` glob overcounts by also matching group packages); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — generic registries (live list via `grep -rn '^def register_' server/services server/core`; the plugin-facing ones are `ws_handler_registry.{register_ws_handlers,register_router,register_option_loader,register_oauth_callback_path}`, `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`, `edge_walker.{register_agent_context_builder,register_master_skill_expander}`, `register_webhook_source`, `register_canary_trigger_type`, `register_poll_coroutine_factory`, `register_social_send_handler`, `register_shutdown_hook`, `register_service_factory`, `register_log_source_tag`, `register_conversation_listener`) so rich plugins like telegram own their entire surface area without core-services edits. |
+| **[Plugin System (Wave 11)](./docs-internal/plugin_system.md)** | Class-based plugin-first architecture. `BaseNode` / `ActionNode` / `TriggerNode` / `ToolNode` + `@Operation` decorator. Pydantic `Params`/`Output`. Declarative `Routing` DSL + `Connection` facade (Nango pattern; `request()` supports `json` / `data` / `files` — the last for multipart uploads, threaded through the auth-retry rebuild). `Credential` subclasses live in each node folder's `_credentials.py` (or inline for single-use); live count via `len(services.plugin.credential.CREDENTIAL_REGISTRY)` — do not hand-maintain a number here. `TaskQueue` constants route to Temporal worker pools. Plugins live across 9 queues (live plugin count via `len(services.node_registry.NODE_METADATA)`; a bare `__init__.py` glob overcounts by also matching group packages); handler bodies fully inlined (`services/handlers/` shrank 12.8K → 1.1K LOC across 16 → 4 files; only cross-cutting orchestration remains: `tools.py` AI-tool dispatch + agent delegation, `triggers.py` generic trigger-node handler, `todo.py` writeTodos shim — `google_auth.py` was retired into `nodes/google/_auth_helper.py`). **Wave 11.H added "self-contained plugin folders"** — generic registries (live list via `grep -rn '^def register_' server/services server/core`; the plugin-facing ones are `ws_handler_registry.{register_ws_handlers,register_router,register_option_loader,register_oauth_callback_path,register_public_ingress_path}` (the last for a route a provider calls without a session cookie, which must authenticate each request itself), `event_waiter.{register_filter_builder,register_trigger_precheck}`, `status_broadcaster.register_service_refresh`, `node_output_schemas.register_output_schema`, `edge_walker.{register_agent_context_builder,register_master_skill_expander}`, `register_webhook_source`, `register_canary_trigger_type`, `register_poll_coroutine_factory`, `register_social_send_handler`, `register_shutdown_hook`, `register_service_factory`, `register_log_source_tag`, `register_conversation_listener`) so rich plugins like telegram own their entire surface area without core-services edits. |
| **[Nodes Cookbook](./server/nodes/README.md)** | 5-minute recipe + folder map + shared helpers (`_base.py` / `_inline.py` per domain) + shared credentials + **canonical folder-per-plugin shape (telegram is the reference implementation)** + contract invariants + common pitfalls. Lives next to the plugin files. |
| **[Node Creation Guide](./docs-internal/node_creation.md)** | Canonical plugin recipe — one self-contained folder per plugin under `server/nodes/<group>/<plugin>/`, rooted at `__init__.py`. Multi-file split (`_service.py` / `_handlers.py` / etc.) when the plugin owns long-lived state. Zero frontend edits, zero core-services edits. Auto-registers via `BaseNode.__init_subclass__` + the generic `register_*` hooks (see the Plugin System row). Covers tool nodes, dual-purpose nodes (workflow + AI tool), and specialized agents as variations of the same recipe. |
| **[Agent Architecture](./docs-internal/agent_architecture.md)** | How AI Agent and Chat Agent discover skills/tools, inject them into LLM prompts, and execute through the provider-neutral `run_native_agent_loop` |
diff --git a/docs-internal/discord_service.md b/docs-internal/discord_service.md
index fd5a50d4..74f07484 100644
--- a/docs-internal/discord_service.md
+++ b/docs-internal/discord_service.md
@@ -183,6 +183,12 @@ public key is stored → PING answers PONG → anything else defers (type 5, or
type 6 for a component so the existing message is edited) and fans out in a
background task whose reference is held, since the loop keeps only a weak one.
+Discord calls the endpoint without a session cookie, so the plugin registers
+`/api/discord/interactions` with `register_public_ingress_path`, and
+`AuthMiddleware` lets it (and the per-account paths below it) through with
+login on. The signature check above is what authenticates each request;
+`/api/discord/callback` stays behind the login.
+
Per-account paths exist so the server never trial-verifies against every stored
public key, which would be both a timing oracle and an availability multiplier.
diff --git a/docs-internal/plugin_system.md b/docs-internal/plugin_system.md
index 4b065b30..14a2af32 100644
--- a/docs-internal/plugin_system.md
+++ b/docs-internal/plugin_system.md
@@ -642,6 +642,7 @@ skips them. The two non-underscore `.py` files are the plugin classes
| FastAPI HTTP router (OAuth callbacks, webhook receivers, etc.) | `services.ws_handler_registry` | `register_router(router, name='<plugin>')` — Wave 11.I; declare a `_router.py` exposing an `APIRouter` and call from `__init__.py`. Discovered at startup via `services.ws_handler_registry.get_routers()`. |
| `loadOptionsMethod` async loader for a dynamic dropdown (`json_schema_extra={"loadOptionsMethod": "..."}`). A loader that lists one user's things reads the caller from `current_load_options_principal()`, never a `user_id` in its params (the client writes those) | `services.ws_handler_registry` | `register_option_loader(method_name, fn)` |
| OAuth callback path (`/api/<provider>/callback`) so `services.oauth_utils.get_redirect_uri` never cross-imports `nodes/<plugin>/_oauth.py` | `services.ws_handler_registry` | `register_oauth_callback_path(provider, path)` |
+| A route a provider calls without a session cookie (Discord's signed interactions). `AuthMiddleware` lets the path and everything below it through, so the route must authenticate each request itself and fail closed | `services.ws_handler_registry` | `register_public_ingress_path(path, name='<plugin>')` |
| Trigger event-filter builder | `services.event_waiter` | `register_filter_builder(node_type, fn)` |
| Trigger pre-execution check (e.g. "bot not connected") | `services.event_waiter` | `register_trigger_precheck(node_type, fn)` |
| Service-status refresh (runs once, in a background task at startup; not on each WebSocket connect) | `services.status_broadcaster` | `register_service_refresh(callback)` |
diff --git a/server/middleware/auth.py b/server/middleware/auth.py
index 575af3ec..d63f625b 100644
--- a/server/middleware/auth.py
+++ b/server/middleware/auth.py
@@ -7,6 +7,7 @@ from starlette.middleware.base import BaseHTTPMiddleware
from core.auth_cookies import get_session_token
from core.container import container
+from services.ws_handler_registry import is_public_ingress_path
logger = logging.getLogger(__name__)
@@ -94,4 +95,6 @@ class AuthMiddleware(BaseHTTPMiddleware):
if path.startswith(prefix):
return True
- return False
+ # Plugin routes that authenticate each request themselves
+ # (services.ws_handler_registry.register_public_ingress_path).
+ return is_public_ingress_path(path)
diff --git a/server/nodes/README.md b/server/nodes/README.md
index 1e91ef66..dc1d95bc 100644
--- a/server/nodes/README.md
+++ b/server/nodes/README.md
@@ -456,7 +456,7 @@ These seven are the core self-contained-folder set; newer concerns have
their own generic `register_*` entrypoints in the same spirit —
`services.events.register_webhook_source`,
`services.ws_handler_registry.register_option_loader` /
-`register_oauth_callback_path`,
+`register_oauth_callback_path` / `register_public_ingress_path`,
`services.deployment.canary_registry.register_canary_trigger_type`,
`services.deployment.poll_registry.register_poll_coroutine_factory`,
`services.plugin.edge_walker.register_master_skill_expander`, and
diff --git a/server/nodes/discord/__init__.py b/server/nodes/discord/__init__.py
index bcc29da4..d668b1f3 100644
--- a/server/nodes/discord/__init__.py
+++ b/server/nodes/discord/__init__.py
@@ -20,6 +20,7 @@ from services.status_broadcaster import register_service_refresh
from services.ws_handler_registry import (
register_oauth_callback_path,
register_option_loader,
+ register_public_ingress_path,
register_router,
register_ws_handlers,
)
@@ -43,6 +44,9 @@ register_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")
+# Discord calls the interactions endpoint without a session cookie; the route
+# verifies Ed25519 over the raw body and fails closed without a public key.
+register_public_ingress_path("/api/discord/interactions", name="discord")
register_option_loader("discordAccounts", load_accounts)
register_option_loader("discordGuilds", load_guilds)
diff --git a/server/services/ws_handler_registry.py b/server/services/ws_handler_registry.py
index a0517616..5f4a137c 100644
--- a/server/services/ws_handler_registry.py
+++ b/server/services/ws_handler_registry.py
@@ -1,6 +1,6 @@
"""Plugin self-registration registries.
-Four sibling concerns share this file because they're the same pattern
+Five sibling concerns share this file because they're the same pattern
(idempotent dict + collision check) for the same audience (plugin
``__init__.py`` modules wiring themselves into the framework):
@@ -26,9 +26,15 @@ Four sibling concerns share this file because they're the same pattern
path)`` so :func:`services.oauth_utils.get_redirect_uri` can derive
the full redirect URI at runtime without a cross-folder import.
+5. **Public ingress paths** — ``register_public_ingress_path(path,
+ name="<plugin>")`` for a plugin route that a provider calls without a
+ session cookie and that authenticates each request itself (Discord's
+ signed interactions). Read by ``middleware.auth.AuthMiddleware``.
+
No hardcoded plugin names anywhere in the central router or main.py.
-Adding a new plugin's WS / HTTP / option-loader / oauth-callback
-surface is one registration call inside that plugin's package.
+Adding a new plugin's WS / HTTP / option-loader / oauth-callback /
+public-ingress surface is one registration call inside that plugin's
+package.
"""
from __future__ import annotations
@@ -87,6 +93,7 @@ _WS_REGISTRY: IdempotentRegistry[str, WSHandler] = IdempotentRegistry("ws_handle
_ROUTER_REGISTRY: IdempotentRegistry[str, APIRouter] = IdempotentRegistry("router")
_OPTION_LOADER_REGISTRY: IdempotentRegistry[str, LoadOptionsFn] = IdempotentRegistry("option_loader")
_OAUTH_CALLBACK_PATHS: IdempotentRegistry[str, str] = IdempotentRegistry("oauth_callback_path")
+_PUBLIC_INGRESS_PATHS: IdempotentRegistry[str, str] = IdempotentRegistry("public_ingress_path")
# ---- WebSocket handlers --------------------------------------------------
@@ -237,3 +244,22 @@ def get_oauth_callback_path(provider: str) -> str:
def list_registered_oauth_providers() -> List[str]:
"""For diagnostics / startup logging."""
return sorted(_OAUTH_CALLBACK_PATHS.keys())
+
+
+# ---- Public ingress paths -----------------------------------------------
+
+
+def register_public_ingress_path(path: str, *, name: str) -> None:
+ """Publish a route a provider calls without a session cookie.
+
+ The route itself must authenticate every request (a signature over
+ the raw body, failing closed), because the auth middleware lets the
+ path and everything below it through. Same idempotency contract as
+ the other registries, keyed by ``name``.
+ """
+ _PUBLIC_INGRESS_PATHS.register(name, path.rstrip("/"))
+
+
+def is_public_ingress_path(path: str) -> bool:
+ """Whether ``path`` is a registered public ingress path or below one."""
+ return any(path == public or path.startswith(public + "/") for public in _PUBLIC_INGRESS_PATHS.values())
diff --git a/server/tests/auth/test_auth_middleware.py b/server/tests/auth/test_auth_middleware.py
index 7c7dee78..b4b7c462 100644
--- a/server/tests/auth/test_auth_middleware.py
+++ b/server/tests/auth/test_auth_middleware.py
@@ -138,6 +138,36 @@ class TestGating:
assert response.status_code == 200
+class TestPublicIngressPaths:
+ """Plugin routes a provider calls without a session cookie, published with
+ ``register_public_ingress_path``. Each route authenticates the request
+ itself; Discord's interactions endpoint verifies Ed25519 over the body."""
+
+ def test_discord_interactions_are_public_and_its_callback_is_not(self):
+ import nodes.discord # noqa: F401 -- registers its public ingress path
+
+ middleware = AuthMiddleware(app=FastAPI())
+ assert middleware._is_public_path("/api/discord/interactions")
+ assert middleware._is_public_path("/api/discord/interactions/account-1")
+ assert not middleware._is_public_path("/api/discord/interactionsX")
+ assert not middleware._is_public_path("/api/discord/callback")
+
+ async def test_a_post_without_a_cookie_reaches_the_route(self, user_auth, settings, overridden_container):
+ import nodes.discord # noqa: F401 -- registers its public ingress path
+
+ overridden_container(settings=settings, user_auth=user_auth)
+ app = FastAPI()
+ app.add_middleware(AuthMiddleware)
+
+ @app.post("/api/discord/interactions")
+ async def interactions(): # pragma: no cover - exercised via HTTP
+ return {"reached": True}
+
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://test") as http:
+ response = await http.post("/api/discord/interactions")
+ assert response.status_code == 200
+
+
class TestPublicSurfaceInvariant:
"""Every mounted router must sit under a gated prefix, or be explicitly
public. Without this, the GET-exclusion rule turns any new non-`/api`