Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(marketplace): harden the community skills path per review
rubenluetke10-beepbd66a44af5d3
diff --git a/jarvis/marketplace/agent_plugins_loader.py b/jarvis/marketplace/agent_plugins_loader.pyindex 1878dd5846..acc6bf3430 100644--- a/jarvis/marketplace/agent_plugins_loader.py+++ b/jarvis/marketplace/agent_plugins_loader.py@@ -38,9 +38,11 @@ _NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$")_STDIO_LAUNCHERS = ("npx", "uvx", "docker")# Token placeholders the runtime resolves at connect time. Everything else in-# an env value is treated as a smuggled literal credential.-_ENV_PLACEHOLDER_RE = re.compile(r"^\$\{?plugin_[a-z0-9_]+\}?$")-_HEADER_PLACEHOLDER_RE = re.compile(r"\$\{?plugin_[a-z0-9_]+\}?")+# an env value is treated as a smuggled literal credential. Braces must be+# MATCHED (both or neither), and the charset includes '-'/'.' because plugin+# ids may carry them ("$plugin_todo-fox_access_token").+_ENV_PLACEHOLDER_RE = re.compile(r"^\$(?:plugin_[a-z0-9_.-]+|\{plugin_[a-z0-9_.-]+\})$")+_HEADER_PLACEHOLDER_RE = re.compile(r"\$(?:plugin_[a-z0-9_.-]+|\{plugin_[a-z0-9_.-]+\})")# A long unbroken token-ish run left over once placeholders are removed._TOKEN_LITERAL_RE = re.compile(r"[A-Za-z0-9_\-]{20,}")diff --git a/jarvis/marketplace/community_source.py b/jarvis/marketplace/community_source.pyindex 5c46183a18..a24b1757e5 100644--- a/jarvis/marketplace/community_source.py+++ b/jarvis/marketplace/community_source.py@@ -16,12 +16,13 @@ from __future__ import annotationsimport asyncioimport jsonimport logging+import reimport timefrom pathlib import Pathfrom typing import Anyimport httpx-from pydantic import BaseModel, ConfigDict, Field, ValidationError+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validatorlogger = logging.getLogger(__name__)@@ -62,6 +63,13 @@ class CommunityPluginEntry(_Tolerant):usage_card: str | None = None+# The Agent Plugins name rules (same as agent_plugins_loader.validate_spec_name+# and the registry CI). A skill's name later becomes a DIRECTORY under the+# user's skills folder, so this is a security boundary, not cosmetics: a name+# like "../../evil" or "C:/anywhere" must never survive index validation.+_SKILL_NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$")++class CommunitySkillEntry(_Tolerant):name: strtitle: str | None = None@@ -75,6 +83,18 @@ class CommunitySkillEntry(_Tolerant):# /api/skills/catalog/install route.raw_url: str | None = None+ @field_validator("raw_url")+ @classmethod+ def _https_only(cls, value: str | None) -> str | None:+ # The backend fetches this URL server-side at install time. Anything+ # but https is an SSRF vector (metadata endpoints, LAN admin pages),+ # so a non-https URL degrades the entry to "Manual" instead of being+ # fetched. The finder re-checks before the actual download.+ if value is not None and not value.lower().startswith("https://"):+ logger.warning("community index: dropping non-https raw_url %r", value)+ return None+ return value+class CommunityIndex(_Tolerant):revision: int = 0@@ -82,6 +102,21 @@ class CommunityIndex(_Tolerant):plugins: list[CommunityPluginEntry] = Field(default_factory=list)skills: list[CommunitySkillEntry] = Field(default_factory=list)+ @field_validator("skills", mode="after")+ @classmethod+ def _drop_unsafe_skill_names(+ cls, value: list[CommunitySkillEntry]+ ) -> list[CommunitySkillEntry]:+ kept: list[CommunitySkillEntry] = []+ for entry in value:+ if _SKILL_NAME_RE.fullmatch(entry.name) and ".." not in entry.name:+ kept.append(entry)+ else:+ # One malicious or malformed entry must cost exactly itself,+ # never the whole index (that would be a delisting DoS).+ logger.warning("community index: dropping skill with unsafe name %r", entry.name)+ return kept+def index_url() -> str:"""The configured index URL (empty string = community section disabled)."""diff --git a/jarvis/marketplace/usage_cards/loader.py b/jarvis/marketplace/usage_cards/loader.pyindex 07fe357578..6c9e0c9466 100644--- a/jarvis/marketplace/usage_cards/loader.py+++ b/jarvis/marketplace/usage_cards/loader.py@@ -7,9 +7,11 @@ hand. Missing card = None (a plugin without a card still works, just withoutcurated keywords/guidance; the relevance gate then keeps it only when the turnNAMES it or a noun auto-derived from its own tools matches — not always-include)."""+from __future__ import annotationsimport functools+import loggingfrom dataclasses import dataclass, fieldfrom pathlib import Path@@ -128,8 +130,10 @@ def delete_usage_card(plugin_id: str) -> None:returntry:path.unlink(missing_ok=True)- except OSError:+ except OSError as exc:# An undeletable card only means stale keywords until the next try;- # never let it abort an uninstall.+ # never let it abort an uninstall — but say so (contract §7: no+ # silent except).+ logging.getLogger(__name__).warning("usage card %s not deleted: %s", path, exc)returnload_usage_card.cache_clear()diff --git a/jarvis/skills/finder.py b/jarvis/skills/finder.pyindex c1bc675668..8581817234 100644--- a/jarvis/skills/finder.py+++ b/jarvis/skills/finder.py@@ -128,6 +128,11 @@ class SearchFilters:_RISK_ORDER = {"safe": 0, "monitor": 1, "ask": 2, "block": 3}+# Slug rule for the install target directory — same shape as the paste-import+# guard in skills_routes (`_IMPORT_NAME_RE`), plus dots for spec-style names.+# No separator can pass, so `user_skills_dir() / name` stays inside the root.+_INSTALL_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$")+def _passes_filter(entry: dict[str, Any], f: SearchFilters) -> bool:"""Hard filter before ranking — excludes on trust/stars/category/risk."""@@ -406,6 +411,30 @@ class SkillFinder:f"No direct download available for '{candidate.name}'. "f"Open {candidate.source_url} and install manually.")+ # Fail-closed guards for UNTRUSTED candidates (the community index is+ # auto-merged registry data, and the catalog-install route accepts a+ # caller-supplied name):+ # - https only — the download runs SERVER-side, so a plain-http or+ # internal address would be an SSRF primitive;+ # - the name becomes a directory under user_skills_dir(), and+ # pathlib's `/` DISCARDS the base on an absolute right-hand side,+ # so a non-slug name could write anywhere the process can.+ if not candidate.raw_url.lower().startswith("https://"):+ raise RuntimeError(+ f"Refusing non-https download URL: {candidate.raw_url}"+ )+ if not _INSTALL_NAME_RE.fullmatch(candidate.name or ""):+ raise RuntimeError(+ f"Skill name {candidate.name!r} is not a valid slug "+ "(letters, digits, '-', '_', '.'; max 64 chars)."+ )+ base = user_skills_dir().resolve()+ resolved_target = (base / candidate.name).resolve()+ if resolved_target.parent != base:+ raise RuntimeError(+ f"Skill name {candidate.name!r} resolves outside the skills "+ "directory."+ )# httpx is in the runtime deps (mcp_routes etc.)import httpxdiff --git a/jarvis/ui/web/frontend/src/views/PluginsCommunity.test.tsx b/jarvis/ui/web/frontend/src/views/PluginsCommunity.test.tsxindex e6ff97ae34..aa34fa4184 100644--- a/jarvis/ui/web/frontend/src/views/PluginsCommunity.test.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsCommunity.test.tsx@@ -141,7 +141,7 @@ describe("CommunityTab", () => {});});- it("installs a skill through the existing skill-catalog route", async () => {+ it("installs a skill only after consent showing the download URL", async () => {const fetchMock = installFetchMock();renderTab();await screen.findByText("Three Point Check");@@ -152,6 +152,21 @@ describe("CommunityTab", () => {).find((b) => b.textContent === "Install");fireEvent.click(installButton!);+ // Consent first: the dialog names the exact source URL, nothing posted yet.+ const dialog = await screen.findByRole("dialog");+ expect(dialog.textContent).toContain("Install Three Point Check?");+ expect(dialog.textContent).toContain(+ "https://raw.example/skills/three-point-check/SKILL.md",+ );+ expect(+ fetchMock.mock.calls.filter(([, init]) => (init as RequestInit)?.method === "POST"),+ ).toHaveLength(0);++ const confirm = Array.from(dialog.querySelectorAll("button")).find(+ (b) => b.textContent === "Install",+ );+ fireEvent.click(confirm!);+await waitFor(() => {expect(fetchMock).toHaveBeenCalledWith("/api/skills/catalog/install",diff --git a/jarvis/ui/web/frontend/src/views/PluginsCommunity.tsx b/jarvis/ui/web/frontend/src/views/PluginsCommunity.tsxindex 9c40fe37bc..463df08143 100644--- a/jarvis/ui/web/frontend/src/views/PluginsCommunity.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsCommunity.tsx@@ -99,6 +99,7 @@ export function CommunityTab() {});const [query, setQuery] = useState("");const [consentPlugin, setConsentPlugin] = useState<CommunityPluginWire | null>(null);+ const [consentSkill, setConsentSkill] = useState<CommunitySkillWire | null>(null);const refreshMutation = useMutation({mutationFn: async (): Promise<CommunityResponse> => {@@ -174,6 +175,7 @@ export function CommunityTab() {return res.json();},onSuccess: () => {+ setConsentSkill(null);queryClient.invalidateQueries({ queryKey: ["marketplace-community"] });queryClient.invalidateQueries({ queryKey: ["skills"] });},@@ -286,7 +288,7 @@ export function CommunityTab() {<CommunitySkillRowkey={s.name}skill={s}- onInstall={() => skillInstallMutation.mutate(s)}+ onInstall={() => setConsentSkill(s)}installing={skillInstallMutation.isPending &&skillInstallMutation.variables?.name === s.name@@ -319,6 +321,23 @@ export function CommunityTab() {onConfirm={() => installMutation.mutate(consentPlugin.name)}/>)}++ {consentSkill && (+ <SkillInstallConsentDialog+ skill={consentSkill}+ isPending={skillInstallMutation.isPending}+ errorMessage={+ skillInstallMutation.error instanceof Error+ ? skillInstallMutation.error.message+ : null+ }+ onCancel={() => {+ setConsentSkill(null);+ skillInstallMutation.reset();+ }}+ onConfirm={() => skillInstallMutation.mutate(consentSkill)}+ />+ )}</div>);}@@ -605,6 +624,99 @@ function CommunitySkillRow({);}+/** Skills get the same trust boundary as plugins: a community skill is+ * instructions the assistant will follow, downloaded from a URL nobody+ * reviewed — so the dialog shows that exact URL and reminds the user to+ * read the instructions before switching the skill on. */+export function SkillInstallConsentDialog({+ skill,+ isPending,+ errorMessage,+ onCancel,+ onConfirm,+}: {+ skill: CommunitySkillWire;+ isPending: boolean;+ errorMessage: string | null;+ onCancel: () => void;+ onConfirm: () => void;+}) {+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => {+ if (e.key === "Escape" && !isPending) onCancel();+ };+ window.addEventListener("keydown", onKey);+ return () => window.removeEventListener("keydown", onKey);+ }, [onCancel, isPending]);++ return (+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="community-skill-install-title"+ className="fixed inset-0 z-50 flex items-center justify-center bg-scrim/70 backdrop-blur-sm"+ onClick={(e) => {+ if (e.target === e.currentTarget && !isPending) onCancel();+ }}+ >+ <div className="relative w-full max-w-md overflow-hidden rounded-2xl border border-border bg-card shadow-[0_20px_60px_rgba(0,0,0,0.6)]">+ <header className="border-b border-border px-5 py-4">+ <h2+ id="community-skill-install-title"+ className="font-display text-base font-semibold tracking-tight"+ >+ Install {skill.title}?+ </h2>+ <p className="text-[11px] uppercase tracking-wider text-amber-500/80">+ Community skill · not reviewed+ </p>+ </header>++ <div className="space-y-3 px-5 py-4 text-sm">+ <p className="text-muted-foreground">{skill.description}</p>+ <p className="text-xs text-muted-foreground">+ Published by{" "}+ <span className="text-foreground">+ {skill.publisher ?? "an unknown author"}+ </span>+ {skill.version ? ` · version ${skill.version}` : ""}+ </p>+ <div>+ <p className="mb-1 text-xs font-medium text-foreground">+ The instructions are downloaded from:+ </p>+ <code className="block break-all rounded-md border border-border bg-muted/40 px-2 py-1.5 text-xs text-foreground">+ {skill.raw_url}+ </code>+ </div>+ <p className="text-xs text-muted-foreground">+ A skill is a set of instructions the assistant follows. Read the+ installed instructions before you switch it on.+ </p>+ {errorMessage && (+ <p className="flex items-start gap-2 rounded-md border border-destructive/40 bg-destructive/5 px-2 py-1.5 text-xs text-destructive">+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {errorMessage}+ </p>+ )}+ </div>++ <footer className="flex justify-end gap-2 border-t border-border px-5 py-3">+ <Button size="sm" variant="ghost" onClick={onCancel} disabled={isPending}>+ Cancel+ </Button>+ <Button size="sm" onClick={onConfirm} disabled={isPending}>+ {isPending ? (+ <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />+ ) : null}+ Install+ </Button>+ </footer>+ </div>+ </div>+ );+}+/** The trust boundary. Nothing was human-reviewed, so BEFORE the install this* dialog states verbatim where requests (and later the token) would go, or* which command would run locally — the two fields a malicious submissiondiff --git a/jarvis/ui/web/marketplace_routes.py b/jarvis/ui/web/marketplace_routes.pyindex 2c7ec1d959..2aa897d67f 100644--- a/jarvis/ui/web/marketplace_routes.py+++ b/jarvis/ui/web/marketplace_routes.py@@ -931,21 +931,30 @@ async def community_uninstall(plugin_id: str) -> dict[str, Any]:"instead of uninstalling",)+ # ALL local state changes happen before the first await: the provider+ # revocation below can take seconds, and an install of the same id that+ # completes inside that window must not be wiped when this handler+ # resumes. The loaded tokens object stays in memory, so revoking after+ # the local delete loses nothing.store = TokenStore()- revocation = "unsupported"+ tokens: Tokens | None = Nonetry:tokens = store.load(plugin_id)- if tokens is not None:- revocation = await revoke_tokens(spec, tokens)except Exception as exc: # noqa: BLE001 - never block the uninstall- log.info("plugin %s revocation skipped: %s", plugin_id, exc)- revocation = "failed"+ log.info("plugin %s token load for revocation skipped: %s", plugin_id, exc)store.delete(plugin_id)-try:removed = remove_community_plugin(plugin_id)except RuntimeError as exc:raise HTTPException(status_code=500, detail=str(exc)) from excdelete_usage_card(plugin_id)_refresh_plugin_in_live_registry(plugin_id)++ revocation = "unsupported"+ if tokens is not None:+ try:+ revocation = await revoke_tokens(spec, tokens)+ except Exception as exc: # noqa: BLE001 - never block the uninstall+ log.info("plugin %s revocation skipped: %s", plugin_id, exc)+ revocation = "failed"return {"ok": True, "removed": removed, "revocation": revocation}diff --git a/tests/unit/marketplace/test_community_hardening.py b/tests/unit/marketplace/test_community_hardening.pynew file mode 100644index 0000000000..70ecfe69f0--- /dev/null+++ b/tests/unit/marketplace/test_community_hardening.py@@ -0,0 +1,104 @@+"""Hardening from the 2026-08-12 review: the community feed is untrusted.++Two exploit classes, both on the SKILLS path (the plugin path already had+its guards in agent_plugins_loader):+- a skill name is a directory under user_skills_dir(), and pathlib's ``/``+ discards the base for an absolute right-hand side → path traversal;+- raw_url is fetched SERVER-side → plain-http/internal targets are SSRF.+"""++from __future__ import annotations++from pathlib import Path++import pytest++from jarvis.marketplace.community_source import CommunityIndex+from jarvis.skills.finder import SkillCandidate, SkillFinder+++def _dir_is_empty(path: Path) -> bool:+ return list(path.rglob("*")) == []+++def _candidate(name: str, raw_url: str) -> SkillCandidate:+ return SkillCandidate(+ name=name,+ title=name,+ description="",+ source="marketplace",+ source_url="https://example.com",+ raw_url=raw_url,+ trust="community",+ stars=None,+ categories=(),+ languages=(),+ risk="monitor",+ tags=(),+ )+++def test_index_drops_skills_with_traversal_names() -> None:+ index = CommunityIndex.model_validate(+ {+ "skills": [+ {"name": "../../evil", "raw_url": "https://x.example/SKILL.md"},+ {"name": "C:/Windows/Temp/evil", "raw_url": "https://x.example/SKILL.md"},+ {"name": "Good_Name", "raw_url": "https://x.example/SKILL.md"},+ {"name": "good-name", "raw_url": "https://x.example/SKILL.md"},+ ]+ }+ )+ assert [s.name for s in index.skills] == ["good-name"]+++def test_index_nulls_non_https_raw_urls() -> None:+ index = CommunityIndex.model_validate(+ {+ "skills": [+ {"name": "ssrf-probe", "raw_url": "http://169.254.169.254/latest/meta-data"},+ ]+ }+ )+ assert index.skills[0].raw_url is None # degrades to "Manual", never fetched+++ "name",+ ["../../evil", "..", "a/b", "a\\b", "C:/Windows/Temp/evil", ""],+)+async def test_finder_install_rejects_unsafe_names(+ name: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr("jarvis.skills.finder.user_skills_dir", lambda: tmp_path)+ with pytest.raises(RuntimeError, match="slug|outside"):+ await SkillFinder().install(_candidate(name, "https://x.example/SKILL.md"))+ assert _dir_is_empty(tmp_path)+++ "raw_url",+ [+ "http://169.254.169.254/latest/meta-data",+ "http://router.local/admin",+ "file:///etc/passwd",+ "ftp://x.example/SKILL.md",+ ],+)+async def test_finder_install_rejects_non_https_urls(+ raw_url: str, tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr("jarvis.skills.finder.user_skills_dir", lambda: tmp_path)+ with pytest.raises(RuntimeError, match="non-https"):+ await SkillFinder().install(_candidate("fine-name", raw_url))+ assert _dir_is_empty(tmp_path)+++def test_env_placeholder_braces_must_match() -> None:+ from jarvis.marketplace.agent_plugins_loader import _ENV_PLACEHOLDER_RE++ assert _ENV_PLACEHOLDER_RE.fullmatch("$plugin_todo_fox_access_token")+ assert _ENV_PLACEHOLDER_RE.fullmatch("${plugin_todo-fox_access_token}")+ assert not _ENV_PLACEHOLDER_RE.fullmatch("$plugin_todo_fox}")+ assert not _ENV_PLACEHOLDER_RE.fullmatch("${plugin_todo_fox")+ assert not _ENV_PLACEHOLDER_RE.fullmatch("tfx_realtoken")