feat: add interaction interop webhook helpers
这个提交存在于:
父节点
069b5f58a3
当前提交
30c8610a02
共有 4 个文件被更改,包括 222 次插入 和 3 次删除
|
|
@ -1 +1,74 @@
|
|||
"""Interaction menu and user action helpers placeholder."""
|
||||
"""Interaction menu and user action helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
VALID_ACTIONS = {
|
||||
"open_workbench",
|
||||
"quick_profile",
|
||||
"create_workflow",
|
||||
"generate_node",
|
||||
"retry_task",
|
||||
"open_logs",
|
||||
"open_settings",
|
||||
}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class InteractionAction:
|
||||
action_id: str
|
||||
label: str
|
||||
action_type: str
|
||||
payload: dict[str, Any] = field(default_factory=dict)
|
||||
requires_permission: str = "read"
|
||||
enabled: bool = True
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"action_id": self.action_id,
|
||||
"label": self.label,
|
||||
"action_type": self.action_type,
|
||||
"payload": self.payload,
|
||||
"requires_permission": self.requires_permission,
|
||||
"enabled": self.enabled,
|
||||
}
|
||||
|
||||
|
||||
def build_default_actions(*, api_base: str = "") -> list[InteractionAction]:
|
||||
return [
|
||||
InteractionAction("open_workbench", "Workbench", "open_workbench", {"url": f"{api_base}/web"}),
|
||||
InteractionAction("quick_profile", "Quick profile", "quick_profile", requires_permission="write"),
|
||||
InteractionAction("open_logs", "Logs", "open_logs", {"view": "logs"}),
|
||||
InteractionAction("open_settings", "Settings", "open_settings", {"view": "settings"}, "config"),
|
||||
]
|
||||
|
||||
|
||||
def normalize_action(payload: dict[str, Any]) -> InteractionAction:
|
||||
action_type = str(payload.get("action_type") or payload.get("type") or "").strip()
|
||||
if action_type not in VALID_ACTIONS:
|
||||
raise ValueError("unsupported interaction action")
|
||||
action_id = str(payload.get("action_id") or action_type).strip()
|
||||
label = str(payload.get("label") or action_type).strip()
|
||||
return InteractionAction(
|
||||
action_id=action_id,
|
||||
label=label,
|
||||
action_type=action_type,
|
||||
payload=dict(payload.get("payload") or {}),
|
||||
requires_permission=str(payload.get("requires_permission") or "read"),
|
||||
enabled=bool(payload.get("enabled", True)),
|
||||
)
|
||||
|
||||
|
||||
def filter_actions_for_permissions(
|
||||
actions: list[InteractionAction],
|
||||
permissions: set[str] | frozenset[str],
|
||||
) -> list[InteractionAction]:
|
||||
allowed = set(permissions)
|
||||
return [
|
||||
action
|
||||
for action in actions
|
||||
if action.enabled and (action.requires_permission == "read" or action.requires_permission in allowed)
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1 +1,60 @@
|
|||
"""External plugin interoperability placeholder."""
|
||||
"""External plugin interoperability helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Any
|
||||
|
||||
|
||||
PRIVATE_COMPANION = "astrbot_plugin_private_companion"
|
||||
ALLOWED_PLUGINS = {PRIVATE_COMPANION}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class PluginRequest:
|
||||
plugin_name: str
|
||||
action: str
|
||||
payload: dict[str, Any] = field(default_factory=dict)
|
||||
request_id: str | None = None
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"plugin_name": self.plugin_name,
|
||||
"action": self.action,
|
||||
"payload": self.payload,
|
||||
"request_id": self.request_id,
|
||||
}
|
||||
|
||||
|
||||
def normalize_plugin_request(payload: dict[str, Any]) -> PluginRequest:
|
||||
plugin_name = str(payload.get("plugin_name") or payload.get("request_source") or "").strip()
|
||||
action = str(payload.get("action") or "").strip()
|
||||
if not plugin_name:
|
||||
raise ValueError("plugin_name is required")
|
||||
if not action:
|
||||
raise ValueError("action is required")
|
||||
return PluginRequest(
|
||||
plugin_name=plugin_name,
|
||||
action=action,
|
||||
payload=dict(payload.get("payload") or {}),
|
||||
request_id=payload.get("request_id"),
|
||||
)
|
||||
|
||||
|
||||
def is_allowed_plugin(plugin_name: str, allowed_plugins: set[str] | list[str] | tuple[str, ...] | None = None) -> bool:
|
||||
allowed = set(allowed_plugins or ALLOWED_PLUGINS)
|
||||
return str(plugin_name or "").strip() in allowed
|
||||
|
||||
|
||||
def daily_outfit_request(payload: dict[str, Any]) -> PluginRequest:
|
||||
request = normalize_plugin_request(
|
||||
{
|
||||
"plugin_name": payload.get("request_source") or PRIVATE_COMPANION,
|
||||
"action": "daily_outfit",
|
||||
"payload": payload,
|
||||
"request_id": payload.get("request_id"),
|
||||
}
|
||||
)
|
||||
if not is_allowed_plugin(request.plugin_name):
|
||||
raise ValueError("plugin is not allowed")
|
||||
return request
|
||||
|
|
|
|||
|
|
@ -1 +1,51 @@
|
|||
"""Webhook dispatch placeholder."""
|
||||
"""Webhook and SSE payload helpers."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class WebhookEvent:
|
||||
event_type: str
|
||||
data: dict[str, Any] = field(default_factory=dict)
|
||||
event_id: str = field(default_factory=lambda: f"wh_{uuid4().hex}")
|
||||
created_at: str = field(default_factory=lambda: datetime.now(timezone.utc).isoformat())
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
return {
|
||||
"event_id": self.event_id,
|
||||
"event_type": self.event_type,
|
||||
"data": self.data,
|
||||
"created_at": self.created_at,
|
||||
}
|
||||
|
||||
def canonical_payload(self) -> str:
|
||||
return json.dumps(self.to_dict(), ensure_ascii=False, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def sign_event(event: WebhookEvent, secret: str) -> str:
|
||||
key = str(secret or "").encode("utf-8")
|
||||
if not key:
|
||||
raise ValueError("webhook secret is required")
|
||||
return hmac.new(key, event.canonical_payload().encode("utf-8"), hashlib.sha256).hexdigest()
|
||||
|
||||
|
||||
def verify_signature(event: WebhookEvent, secret: str, signature: str) -> bool:
|
||||
expected = sign_event(event, secret)
|
||||
return hmac.compare_digest(expected, str(signature or ""))
|
||||
|
||||
|
||||
def to_sse(event: WebhookEvent) -> str:
|
||||
payload = json.dumps(event.to_dict(), ensure_ascii=False, sort_keys=True)
|
||||
return f"id: {event.event_id}\nevent: {event.event_type}\ndata: {payload}\n\n"
|
||||
|
||||
|
||||
def event_from_bus(event_type: str, payload: dict[str, Any]) -> WebhookEvent:
|
||||
return WebhookEvent(event_type=event_type, data=dict(payload))
|
||||
|
|
|
|||
|
|
@ -5,10 +5,13 @@ import unittest
|
|||
|
||||
from core.event_bus import EventBus
|
||||
from core.fsm import node_transition, task_transition, workflow_transition
|
||||
from core.interactions import build_default_actions, filter_actions_for_permissions, normalize_action
|
||||
from core.interop import PRIVATE_COMPANION, daily_outfit_request, is_allowed_plugin, normalize_plugin_request
|
||||
from core.model_router import ModelRoute, route_from_capability_profile, select_model_route
|
||||
from core.prompt_pipeline import PromptPart, compose_prompt, merge_prompt_sections
|
||||
from core.queue_manager import QueueManager
|
||||
from core.secret_service import MASK, env_ref, redact, resolve_env_value
|
||||
from core.webhook import WebhookEvent, sign_event, to_sse, verify_signature
|
||||
|
||||
|
||||
class EventBusTests(unittest.TestCase):
|
||||
|
|
@ -131,5 +134,39 @@ class SecretServiceTests(unittest.TestCase):
|
|||
os.environ.pop("IMAGESTUDIO_TEST_SECRET", None)
|
||||
|
||||
|
||||
class InteractionTests(unittest.TestCase):
|
||||
def test_actions_are_normalized_and_filtered_by_permission(self):
|
||||
action = normalize_action({"type": "open_logs", "label": "Logs"})
|
||||
self.assertEqual(action.action_type, "open_logs")
|
||||
|
||||
actions = build_default_actions(api_base="/api/plugin")
|
||||
filtered = filter_actions_for_permissions(actions, {"write"})
|
||||
self.assertIn("quick_profile", [item.action_id for item in filtered])
|
||||
self.assertNotIn("open_settings", [item.action_id for item in filtered])
|
||||
|
||||
|
||||
class InteropTests(unittest.TestCase):
|
||||
def test_plugin_request_normalization_and_allow_list(self):
|
||||
request = normalize_plugin_request(
|
||||
{"plugin_name": PRIVATE_COMPANION, "action": "daily_outfit", "payload": {"profile_id": "profile_001"}}
|
||||
)
|
||||
|
||||
self.assertTrue(is_allowed_plugin(request.plugin_name))
|
||||
self.assertEqual(request.payload["profile_id"], "profile_001")
|
||||
self.assertEqual(daily_outfit_request({"profile_id": "profile_001"}).plugin_name, PRIVATE_COMPANION)
|
||||
|
||||
|
||||
class WebhookTests(unittest.TestCase):
|
||||
def test_webhook_signature_and_sse_format(self):
|
||||
event = WebhookEvent("task.completed", {"task_id": "task_001"}, event_id="wh_test")
|
||||
signature = sign_event(event, "secret")
|
||||
|
||||
self.assertTrue(verify_signature(event, "secret", signature))
|
||||
self.assertFalse(verify_signature(event, "secret", "bad"))
|
||||
sse = to_sse(event)
|
||||
self.assertIn("event: task.completed", sse)
|
||||
self.assertIn("data:", sse)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用