Skip to content

JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.

Python

feat:同步pcclaw分支,增加origin校验、过滤非法skill文件名、cleancode修改

xiaoyao4245fd1d9dfb3d
diff --git a/jiuwenclaw/agentserver/agent_ws_server.py b/jiuwenclaw/agentserver/agent_ws_server.py
index bd2cf649df..9c6eabceb4 100644
--- a/jiuwenclaw/agentserver/agent_ws_server.py
+++ b/jiuwenclaw/agentserver/agent_ws_server.py
@@ -4,9 +4,9 @@
from __future__ import annotations
-import logging
import asyncio
import json
+import logging
import math
import os
from pathlib import Path
@@ -34,6 +34,12 @@ from jiuwenclaw.agentserver.permissions.patterns import persist_cli_trusted_dire
from jiuwenclaw.schema.hooks_context import AgentServerChatHookContext
from jiuwenclaw.agentserver.agent_manager import AgentManager, ACP_DEFAULT_CAPABILITIES
from jiuwenclaw.agentserver.permissions.config_rpc import get_permissions_config_req_methods
+from jiuwenclaw.security.ws_origin import (
+ extract_handshake_request,
+ forbidden_origin_response,
+ get_header_value,
+ is_allowed_browser_origin,
+)
logger = logging.getLogger(__name__)
@@ -169,6 +175,7 @@ class AgentWebSocketServer:
self._connection_handler,
self._host,
self._port,
+ process_request=self._process_request,
ping_interval=self._ping_interval,
ping_timeout=self._ping_timeout,
)
@@ -178,6 +185,7 @@ class AgentWebSocketServer:
self._connection_handler,
self._host,
self._port,
+ process_request=self._process_request,
ping_interval=self._ping_interval,
ping_timeout=self._ping_timeout,
)
@@ -185,6 +193,27 @@ class AgentWebSocketServer:
"[AgentWebSocketServer] 已启动: ws://%s:%s", self._host, self._port
)
+ async def _process_request(self, *args: Any) -> Any:
+ """在握手阶段执行 Origin 校验,兼容 legacy/new websockets APIs。"""
+ path, request_headers = extract_handshake_request(args)
+ origin = get_header_value(request_headers, "Origin")
+ allowed = is_allowed_browser_origin(origin)
+ logger.info(
+ "[AgentWebSocketServer] 握手检查 path=%s origin=%s allowed=%s",
+ path,
+ origin,
+ allowed,
+ )
+ if allowed:
+ return None
+
+ logger.warning(
+ "[AgentWebSocketServer] 握手拒绝 path=%s origin=%s reason=origin_not_allowed",
+ path,
+ origin,
+ )
+ return forbidden_origin_response(args)
+
async def stop(self) -> None:
"""停止 WebSocket 服务端."""
if self._server is None:
diff --git a/jiuwenclaw/agentserver/skill_manager.py b/jiuwenclaw/agentserver/skill_manager.py
index 9b3e71cd54..36d473fa37 100644
--- a/jiuwenclaw/agentserver/skill_manager.py
+++ b/jiuwenclaw/agentserver/skill_manager.py
@@ -14,7 +14,7 @@ import tempfile
import uuid
from contextlib import contextmanager
from datetime import datetime, timezone
-from pathlib import Path
+from pathlib import Path, PureWindowsPath
from typing import Any, Awaitable, Callable
from urllib.parse import urlparse
import yaml
@@ -150,6 +150,44 @@ def _skillnet_network_context():
os.environ[key] = value
+def _safe_path_name(value: Any, label: str) -> str:
+ raw = str(value or "").strip()
+ if not raw:
+ raise ValueError(f"invalid {label} name")
+ path_value = Path(raw)
+ invalid_name_checks = (
+ raw in (".", ".."),
+ "/" in raw,
+ "\\" in raw,
+ path_value.is_absolute(),
+ PureWindowsPath(raw).is_absolute(),
+ )
+ if any(invalid_name_checks):
+ raise ValueError(f"invalid {label} name: {raw}")
+ return raw
+
+
+def _safe_child_path(base: Path, name: Any, label: str) -> Path:
+ safe_name = _safe_path_name(name, label)
+ base_resolved = base.resolve()
+ candidate = (base / safe_name).resolve()
+ try:
+ candidate.relative_to(base_resolved)
+ except ValueError as exc:
+ raise ValueError(f"invalid {label} path: {safe_name}") from exc
+ return candidate
+
+
+def _log_rejected_name(operation: str, label: str, value: Any, exc: ValueError) -> None:
+ logger.warning(
+ "rejected invalid %s name: operation=%s value=%r error=%s",
+ label,
+ operation,
+ value,
+ exc,
+ )
+
+
def _safe_rmtree(path: Path) -> bool:
"""安全地删除目录树,处理 Windows 上的 git 文件锁定问题.
"""
@@ -365,6 +403,11 @@ class SkillManager:
name = str(params.get("name") or "").strip()
if not name:
raise ValueError("缺少参数: name")
+ try:
+ name = _safe_path_name(name, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.evolution.status", "skill", name, exc)
+ raise ValueError(str(exc)) from exc
evo_path = self._get_skill_evolution_path(name)
return {
"name": name,
@@ -376,6 +419,11 @@ class SkillManager:
name = str(params.get("name") or "").strip()
if not name:
raise ValueError("缺少参数: name")
+ try:
+ name = _safe_path_name(name, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.evolution.get", "skill", name, exc)
+ raise ValueError(str(exc)) from exc
evo_path = self._get_skill_evolution_path(name)
if evo_path is None or not evo_path.is_file():
@@ -416,6 +464,11 @@ class SkillManager:
name = str(params.get("name") or "").strip()
if not name:
raise ValueError("缺少参数: name")
+ try:
+ name = _safe_path_name(name, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.evolution.save", "skill", name, exc)
+ raise ValueError(str(exc)) from exc
if not self._resolve_local_skill_dir(name):
raise ValueError(f"未找到 skill: {name}")
@@ -499,6 +552,12 @@ class SkillManager:
plugin_name, marketplace_name = spec.rsplit("@", 1)
if not plugin_name or not marketplace_name:
return {"success": False, "detail": "plugin 或 marketplace 名称为空"}
+ try:
+ plugin_name = _safe_path_name(plugin_name, "plugin")
+ marketplace_name = _safe_path_name(marketplace_name, "marketplace")
+ except ValueError as exc:
+ _log_rejected_name("skills.install", "plugin/marketplace", spec, exc)
+ return {"success": False, "detail": str(exc)}
if marketplace_name == "builtin":
return await self.handle_skills_install_builtin({"name": plugin_name})
@@ -517,7 +576,7 @@ class SkillManager:
return {"success": False, "detail": f"marketplace {marketplace_name} 缺少 url"}
# 确保 marketplace 仓库已 clone
- repo_dir = self._marketplace_dir / marketplace_name
+ repo_dir = _safe_child_path(self._marketplace_dir, marketplace_name, "marketplace")
if repo_dir.exists():
await self._git_pull(repo_dir)
else:
@@ -539,7 +598,7 @@ class SkillManager:
return {"success": False, "detail": f"plugin {plugin_name} 缺少 SKILL.md"}
# 复制到本地 skills 目录
- dest = self._skills_dir / plugin_name
+ dest = _safe_child_path(self._skills_dir, plugin_name, "skill")
if dest.exists():
if not force:
return {"success": False, "detail": f"skill {plugin_name} 已存在"}
@@ -571,17 +630,22 @@ class SkillManager:
name = params.get("name", "")
if not name:
return {"success": False, "detail": "缺少参数: name"}
+ try:
+ name = _safe_path_name(name, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.install_builtin", "skill", name, exc)
+ return {"success": False, "detail": str(exc)}
builtin_dir = get_builtin_skills_dir()
if not builtin_dir.exists():
return {"success": False, "detail": "内置技能目录不存在"}
- src = builtin_dir / name
+ src = _safe_child_path(builtin_dir, name, "skill")
if not src.exists() or not src.is_dir():
return {"success": False, "detail": f"未找到内置技能: {name}"}
# 检查是否已经安装
- dest = get_agent_skills_dir() / name
+ dest = _safe_child_path(self._skills_dir, name, "skill")
if dest.exists() and dest.is_dir():
return {"success": False, "detail": f"技能 {name} 已经安装"}
@@ -890,6 +954,11 @@ class SkillManager:
slug = str(params.get("slug", "")).strip()
if not slug:
return {"success": False, "detail": "缺少参数: slug"}
+ try:
+ slug = _safe_path_name(slug, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.clawhub.download", "skill", slug, exc)
+ return {"success": False, "detail": str(exc)}
token = self._get_clawhub_token()
if not token:
@@ -904,7 +973,7 @@ class SkillManager:
force = bool(params.get("force", False))
# 检查 skill 是否已安装
- dest = self._skills_dir / slug
+ dest = _safe_child_path(self._skills_dir, slug, "skill")
if dest.exists() and not force:
return {
"success": False,
@@ -979,7 +1048,7 @@ class SkillManager:
# 复制到 skills 目录
shutil.copytree(skill_dir, dest)
for mirror_root in self._get_mirror_skills_dirs():
- mirror_dest = mirror_root / slug
+ mirror_dest = _safe_child_path(mirror_root, slug, "skill")
if mirror_dest.exists():
if not force:
continue
@@ -1147,8 +1216,13 @@ class SkillManager:
"detail_key": "skills.skillNet.errors.parseSkillFailed",
}
- skill_name = str(meta.get("name", skill_dir.name)).strip() or skill_dir.name
- dest = self._skills_dir / skill_name
+ raw_skill_name = meta.get("name", skill_dir.name)
+ try:
+ skill_name = _safe_path_name(raw_skill_name, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.skillnet.install", "skill", raw_skill_name, exc)
+ return {"ok": False, "detail": str(exc)}
+ dest = _safe_child_path(self._skills_dir, skill_name, "skill")
if dest.exists():
if not force:
return {
@@ -1160,7 +1234,7 @@ class SkillManager:
shutil.copytree(skill_dir, dest)
for mirror_root in self._get_mirror_skills_dirs():
- mirror_dest = mirror_root / skill_name
+ mirror_dest = _safe_child_path(mirror_root, skill_name, "skill")
if mirror_dest.exists():
if not force:
continue
@@ -1201,6 +1275,11 @@ class SkillManager:
name = params.get("name", "")
if not name:
return {"success": False, "detail": "缺少参数: name"}
+ try:
+ name = _safe_path_name(name, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.uninstall", "skill", name, exc)
+ return {"success": False, "detail": str(exc)}
# 使用 _resolve_local_skill_dir 正确解析技能目录(处理 name 与文件夹名称不一致的情况)
dest = self._resolve_local_skill_dir(name)
@@ -1212,7 +1291,7 @@ class SkillManager:
if builtin_dir.exists():
# 检查 builtin 技能目录中是否有该技能
builtin_skill_path = None
- direct_builtin = builtin_dir / name
+ direct_builtin = _safe_child_path(builtin_dir, name, "skill")
if direct_builtin.exists() and direct_builtin.is_dir():
builtin_skill_path = direct_builtin
else:
@@ -1236,7 +1315,7 @@ class SkillManager:
# 处理 mirror 根目录中的技能
for mirror_root in self._get_mirror_skills_dirs():
- mirror_dest = mirror_root / dest.name
+ mirror_dest = _safe_child_path(mirror_root, dest.name, "skill")
if mirror_dest.exists() and mirror_dest.is_dir():
_safe_rmtree(mirror_dest)
@@ -1266,8 +1345,13 @@ class SkillManager:
meta = self._parse_skill_md(src)
if meta is None:
return {"success": False, "detail": "无法解析 skill 文件"}
- skill_name = meta.get("name", src.stem)
- dest = self._skills_dir / skill_name
+ raw_skill_name = meta.get("name", src.stem)
+ try:
+ skill_name = _safe_path_name(raw_skill_name, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.import_local", "skill", raw_skill_name, exc)
+ return {"success": False, "detail": str(exc)}
+ dest = _safe_child_path(self._skills_dir, skill_name, "skill")
if dest.exists():
if not force:
return {"success": False, "detail": f"skill {skill_name} 已存在"}
@@ -1279,8 +1363,13 @@ class SkillManager:
if md is None:
return {"success": False, "detail": f"目录中未找到 SKILL.md: {raw_path}"}
meta = self._parse_skill_md(md) or {}
- skill_name = meta.get("name", src.name)
- dest = self._skills_dir / skill_name
+ raw_skill_name = meta.get("name", src.name)
+ try:
+ skill_name = _safe_path_name(raw_skill_name, "skill")
+ except ValueError as exc:
+ _log_rejected_name("skills.import_local", "skill", raw_skill_name, exc)
+ return {"success": False, "detail": str(exc)}
+ dest = _safe_child_path(self._skills_dir, skill_name, "skill")
if dest.exists():
if not force:
return {"success": False, "detail": f"skill {skill_name} 已存在"}
@@ -1304,6 +1393,11 @@ class SkillManager:
url = params.get("url", "")
if not name or not url:
return {"success": False, "detail": "缺少参数: name 和 url"}
+ try:
+ name = _safe_path_name(name, "marketplace")
+ except ValueError as exc:
+ _log_rejected_name("skills.marketplace.add", "marketplace", name, exc)
+ return {"success": False, "detail": str(exc)}
# 检查是否已存在
for m in self._get_marketplaces():
@@ -1325,6 +1419,11 @@ class SkillManager:
remove_cache = params.get("remove_cache", True)
if not name:
return {"success": False, "detail": "缺少参数: name"}
+ try:
+ name = _safe_path_name(name, "marketplace")
+ except ValueError as exc:
+ _log_rejected_name("skills.marketplace.remove", "marketplace", name, exc)
+ return {"success": False, "detail": str(exc)}
removed = self._remove_marketplace(name)
if not removed:
@@ -1332,7 +1431,7 @@ class SkillManager:
cache_removed = False
if bool(remove_cache):
- repo_dir = self._marketplace_dir / name
+ repo_dir = _safe_child_path(self._marketplace_dir, name, "marketplace")
if repo_dir.exists() and repo_dir.is_dir():
try:
_safe_rmtree(repo_dir)
@@ -1359,6 +1458,11 @@ class SkillManager:
return {"success": False, "detail": "缺少参数: name"}
if not isinstance(enabled, bool):
return {"success": False, "detail": "缺少参数: enabled (bool)"}
+ try:
+ name = _safe_path_name(name, "marketplace")
+ except ValueError as exc:
+ _log_rejected_name("skills.marketplace.toggle", "marketplace", name, exc)
+ return {"success": False, "detail": str(exc)}
marketplace = next(
(m for m in self._get_marketplaces() if m.get("name") == name),
@@ -1368,7 +1472,7 @@ class SkillManager:
return {"success": False, "detail": f"marketplace 不存在: {name}"}
if enabled:
- repo_dir = self._marketplace_dir / name
+ repo_dir = _safe_child_path(self._marketplace_dir, name, "marketplace")
url = marketplace.get("url", "")
if not url:
return {"success": False, "detail": f"marketplace {name} 缺少 url"}
@@ -1390,7 +1494,7 @@ class SkillManager:
return {"success": True, "name": name, "enabled": True, "detail": detail}
# 禁用:删除本地缓存目录,不卸载已安装 skill。
- repo_dir = self._marketplace_dir / name
+ repo_dir = _safe_child_path(self._marketplace_dir, name, "marketplace")
cache_removed = False
if repo_dir.exists() and repo_dir.is_dir():
cache_removed = _safe_rmtree(repo_dir)
@@ -1544,7 +1648,7 @@ class SkillManager:
# 没有提供 skill_path 时,回退到通过 skill_name 判断(兼容旧代码)
builtin_dir = get_builtin_skills_dir()
if builtin_dir.exists():
- builtin_skill_path = builtin_dir / skill_name
+ builtin_skill_path = _safe_child_path(builtin_dir, skill_name, "skill")
return builtin_skill_path.exists() and builtin_skill_path.is_dir()
return False
except Exception:
@@ -1669,7 +1773,10 @@ class SkillManager:
def _resolve_local_skill_dir(self, skill_name: str) -> Path | None:
"""根据 skill name 定位本地技能目录(仅 agent/skills 下)."""
- direct = self._skills_dir / skill_name
+ try:
+ direct = _safe_child_path(self._skills_dir, skill_name, "skill")
+ except ValueError:
+ return None
if direct.is_dir():
return direct
@@ -2133,8 +2240,11 @@ class SkillManager:
url = marketplace.get("url", "")
if not name or not url:
continue
-
- repo_dir = self._marketplace_dir / name
+ try:
+ repo_dir = _safe_child_path(self._marketplace_dir, name, "marketplace")
+ except ValueError as exc:
+ _log_rejected_name("skills.marketplace.sync", "marketplace", name, exc)
+ continue
try:
if repo_dir.exists():
await self._git_pull(repo_dir)
@@ -2289,11 +2399,17 @@ class SkillManager:
"""判断当前运行目录中的 skill 是否为真正的内置技能。"""
if not skill_name:
return False
- dest = self._skills_dir / skill_name
+ try:
+ dest = _safe_child_path(self._skills_dir, skill_name, "skill")
+ except ValueError:
+ return False
builtin_dir = get_builtin_skills_dir()
if not builtin_dir.exists():
return False
- builtin_skill_path = builtin_dir / skill_name
+ try:
+ builtin_skill_path = _safe_child_path(builtin_dir, skill_name, "skill")
+ except ValueError:
+ return False
if not builtin_skill_path.exists() or not builtin_skill_path.is_dir():
return False
return dest.exists() and dest.is_dir() and dest.resolve() == builtin_skill_path.resolve()
diff --git a/jiuwenclaw/agentserver/tools/browser-move/src/openjiuwen_patch_sources/openjiuwen/core/single_agent/agents/react_agent.py b/jiuwenclaw/agentserver/tools/browser-move/src/openjiuwen_patch_sources/openjiuwen/core/single_agent/agents/react_agent.py
index 40c9b9e5e6..f2a1dcdd47 100644
--- a/jiuwenclaw/agentserver/tools/browser-move/src/openjiuwen_patch_sources/openjiuwen/core/single_agent/agents/react_agent.py
+++ b/jiuwenclaw/agentserver/tools/browser-move/src/openjiuwen_patch_sources/openjiuwen/core/single_agent/agents/react_agent.py
@@ -4,7 +4,6 @@
ReAct (Reasoning + Acting) paradigm Agent implementation
Created on: 2025-11-25
"""
from __future__ import annotations
diff --git a/jiuwenclaw/channel/web_channel.py b/jiuwenclaw/channel/web_channel.py
index db9b36634b..706b502e3d 100644
--- a/jiuwenclaw/channel/web_channel.py
+++ b/jiuwenclaw/channel/web_channel.py
@@ -23,6 +23,12 @@ import aiohttp
from jiuwenclaw.utils import get_agent_workspace_dir
from jiuwenclaw.channel.base import BaseChannel, ChannelMetadata, RobotMessageRouter
+from jiuwenclaw.security.ws_origin import (
+ extract_handshake_request,
+ forbidden_origin_response,
+ get_header_value,
+ is_allowed_browser_origin,
+)
from jiuwenclaw.schema.message import Message, Mode, ReqMethod
logger = logging.getLogger(__name__)
@@ -234,6 +240,7 @@ class WebChannel(BaseChannel):
self._connection_handler,
self.config.host,
self.config.port,
+ process_request=self._process_request,
ping_interval=20,
ping_timeout=20,
)
@@ -266,6 +273,27 @@ class WebChannel(BaseChannel):
"""兼容方法:调用 stop."""
await self.stop()
+ async def _process_request(self, *args: Any) -> Any:
+ """在握手阶段执行 Origin 校验,兼容 legacy/new websockets APIs。"""
+ path, request_headers = extract_handshake_request(args)
+ origin = get_header_value(request_headers, "Origin")
+ allowed = is_allowed_browser_origin(origin)
+ logger.info(
+ "WebChannel 握手检查 path=%s origin=%s allowed=%s",
+ path,
+ origin,
+ allowed,
+ )
+ if allowed:
+ return None
+
+ logger.warning(
+ "WebChannel 握手拒绝 path=%s origin=%s reason=origin_not_allowed",
+ path,
+ origin,
+ )
+ return forbidden_origin_response(args)
+
async def send(self, msg: Message) -> None:
"""向客户端发送消息(默认封装为 event 帧广播)."""
if not self._clients:
diff --git a/jiuwenclaw/gateway/agent_client.py b/jiuwenclaw/gateway/agent_client.py
index 29963eeb45..01bae3368d 100644
--- a/jiuwenclaw/gateway/agent_client.py
+++ b/jiuwenclaw/gateway/agent_client.py
@@ -11,6 +11,7 @@ from abc import ABC, abstractmethod
from collections.abc import Awaitable, Callable
from dataclasses import asdict
from typing import Any, AsyncIterator
+from urllib.parse import urlsplit
from jiuwenclaw.e2a.constants import E2A_WIRE_SERVER_PUSH_KEY
from jiuwenclaw.e2a.models import E2AEnvelope
@@ -42,6 +43,20 @@ def _to_json(data: Any) -> str:
return repr(data)
+def _build_ws_origin(uri: str) -> str | None:
+ """将 ws/wss URI 转为标准浏览器 Origin。"""
+ try:
+ parsed = urlsplit(uri)
+ except ValueError:
+ return None
+
+ if not parsed.netloc:
+ return None
+
+ scheme = "https" if parsed.scheme == "wss" else "http"
+ return f"{scheme}://{parsed.netloc}"
+
+
class AgentServerClient(ABC):
"""AgentServer WebSocket 客户端接口."""
@@ -135,6 +150,7 @@ class WebSocketAgentServerClient(AgentServerClient):
logger.info("[WebSocketAgentServerClient] 正在连接: %s", uri)
self._uri = uri
self._server_ready = False
+ origin = _build_ws_origin(uri)
try:
from websockets.legacy.client import connect as legacy_connect
connect_fn = legacy_connect
@@ -143,6 +159,7 @@ class WebSocketAgentServerClient(AgentServerClient):
connect_fn = websockets.connect
self._ws = await connect_fn(
uri,
+ origin=origin,
ping_interval=self._ping_interval,
ping_timeout=self._ping_timeout,
close_timeout=5.0,
diff --git a/jiuwenclaw/security/ws_origin.py b/jiuwenclaw/security/ws_origin.py
new file mode 100644
index 0000000000..ed35f96530
--- /dev/null
+++ b/jiuwenclaw/security/ws_origin.py
@@ -0,0 +1,72 @@
+# Copyright (c) Huawei Technologies Co., Ltd. 2025. All rights reserved.
+
+"""Shared WebSocket Origin validation helpers."""
+
+from __future__ import annotations
+
+from http import HTTPStatus
+from typing import Any
+from urllib.parse import urlsplit
+
+_ALLOWED_WS_ORIGIN_HOSTS = {"127.0.0.1", "localhost"}
+_FORBIDDEN_BODY = b"Forbidden: Origin not allowed\n"
+
+
+def is_allowed_browser_origin(origin: str | None) -> bool:
+ """校验浏览器 Origin 是否来自允许的本机地址。"""
+ if origin is None:
+ return False
+
+ try:
+ parsed = urlsplit(origin)
+ except ValueError:
+ return False
+
+ return parsed.hostname in _ALLOWED_WS_ORIGIN_HOSTS
+
+
+def extract_handshake_request(args: tuple[Any, ...]) -> tuple[str, Any]:
+ """Extract path and headers from legacy/new websockets process_request args."""
+ path = ""
+ headers = None
+
+ if len(args) >= 2:
+ first, second = args[0], args[1]
+ if isinstance(first, str):
+ path = first
+ headers = second
+ else:
+ path = getattr(second, "path", "") or ""
+ headers = getattr(second, "headers", second)
+
+ return path, headers
+
+
+def get_header_value(headers: Any, key: str) -> str | None:
+ """Read a header from either legacy or modern websockets header containers."""
+ if headers is None:
+ return None
+ get = getattr(headers, "get", None)
+ if callable(get):
+ value = get(key)
+ if value is None:
+ value = get(key.lower())
+ return str(value) if value is not None else None
+ return None
+
+
+def forbidden_origin_response(process_request_args: tuple[Any, ...]) -> Any:
+ """Build a 403 response for legacy/new websockets process_request APIs."""
+ status = HTTPStatus.FORBIDDEN
+ headers = [
+ ("Content-Type", "text/plain; charset=utf-8"),
+ ("Content-Length", str(len(_FORBIDDEN_BODY))),
+ ]
+
+ if process_request_args and not isinstance(process_request_args[0], str):
+ from websockets.datastructures import Headers
+ from websockets.http11 import Response
+
+ return Response(status.value, status.phrase, Headers(headers), _FORBIDDEN_BODY)
+
+ return status, headers, _FORBIDDEN_BODY
diff --git a/tests/unit_tests/agentserver/test_skill_manager_path_safety.py b/tests/unit_tests/agentserver/test_skill_manager_path_safety.py
new file mode 100644
index 0000000000..80ae2a81a8
--- /dev/null
+++ b/tests/unit_tests/agentserver/test_skill_manager_path_safety.py
@@ -0,0 +1,48 @@
+import pytest
+
+from jiuwenclaw.agentserver.skill_manager import (
+ SkillManager,
+ _safe_child_path,
+ _safe_path_name,
+)
+
+
[email protected]("name", ["../evil", "nested/skill", r"C:\tmp\skill", ".", "..", ""])
+def test_safe_path_name_rejects_path_like_names(name):
+ with pytest.raises(ValueError):
+ _safe_path_name(name, "skill")
+
+
+def test_safe_child_path_stays_under_base(tmp_path):
+ child = _safe_child_path(tmp_path, "good-skill", "skill")
+
+ assert child == (tmp_path / "good-skill").resolve()
+ with pytest.raises(ValueError):
+ _safe_child_path(tmp_path, "../evil", "skill")
+
+
+async def test_import_local_rejects_skill_name_path_traversal(tmp_path):
+ manager = SkillManager(workspace_dir=str(tmp_path / "workspace"))
+ src = tmp_path / "src"
+ src.mkdir()
+ (src / "SKILL.md").write_text(
+ "---\nname: ../evil\n---\nbody\n",
+ encoding="utf-8",
+ )
+
+ result = await manager.handle_skills_import_local({"path": str(src)})
+
+ assert result["success"] is False
+ assert "invalid skill name" in result["detail"]
+ assert not (tmp_path / "evil").exists()
+
+
+async def test_uninstall_rejects_skill_name_path_traversal(tmp_path):
+ manager = SkillManager(workspace_dir=str(tmp_path / "workspace"))
+
+ result = await manager.handle_skills_uninstall({"name": "../evil"})
+
+ assert result["success"] is False
+ assert "invalid skill name" in result["detail"]