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
feat(marketplace): the app can sign in with GitHub and publish, by device flow
rubenluetke10-beep77b6f66f3a84
diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 48319aa1b6..4328bd8d9c 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -3480,6 +3480,20 @@ class MarketplaceConfig(BaseModel):community_index_url: str = ("https://personaljarvis.github.io/marketplace/index.json")+ # Where the in-app Publish flow submits packages. The endpoint verifies+ # the GitHub identity and opens the registry PR as the marketplace bot;+ # forks point this at their own deployment. Empty string hides Publish.+ publish_endpoint: str = "https://personaljarvis.ai/api/marketplace/submit"+ # Where the in-app Wallpapers view publishes a picture. A lane of its own+ # because the payload is multipart image bytes, not a JSON manifest — but+ # the same identity, the same registry, the same feed. Empty string hides+ # "Share to community" in the wallpaper picker.+ publish_wallpaper_endpoint: str = (+ "https://personaljarvis.ai/api/marketplace/submit-wallpaper"+ )+ # Client id of the marketplace GitHub App (public by design — device flow+ # needs no secret, which is why a downloadable binary can use it).+ publish_github_client_id: str = "Iv23li1YcX62KJO67whO"model_config = ConfigDict(extra="allow")diff --git a/jarvis/marketplace/agent_plugins_loader.py b/jarvis/marketplace/agent_plugins_loader.pyindex d43b399d29..4344585bdb 100644--- a/jarvis/marketplace/agent_plugins_loader.py+++ b/jarvis/marketplace/agent_plugins_loader.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport refrom collections.abc import Mapping+from dataclasses import dataclassfrom typing import Anyfrom pydantic import ValidationError@@ -130,6 +131,115 @@ def validate_spec_name(name: Any) -> str:return text+# Caps: the registry repo is also the CDN, and every skill lands as a file on+# the user's disk. Generous for instructions, small enough that one package+# cannot bloat the index for everyone.+MAX_BUNDLED_SKILLS = 10+MAX_SKILL_MD_BYTES = 64 * 1024++# Top-level frontmatter keys a community skill may not declare.+#+# `risk_policy` is a privilege boundary, not a preference: skills/runner.py+# evaluates a skill's tools against the SKILL'S OWN declared tier rather than+# the tool's static one ("the skill author's risk_policy is what governs+# here"). That is correct for repo-contributed skills, which pass human+# review — for an auto-merged community skill it would let the author+# downgrade a tool to `safe` and skip the confirmation the tool was given.+# Rejecting is deliberate over silently dropping the key: the author sees why+# (contract §7, no silent swallowing), and the built-in default applies.+_FORBIDDEN_SKILL_FRONTMATTER = ("risk_policy",)++# A top-level YAML key: no indentation, so nested `risk_policy:` inside some+# other author's block is not what we are matching.+_TOP_LEVEL_KEY_RE = re.compile(r"^([A-Za-z_][A-Za-z0-9_-]*)\s*:", re.MULTILINE)+++@dataclass(frozen=True, slots=True)+class BundledSkill:+ """One ``skills/<name>/SKILL.md`` carried by a plugin package."""++ name: str+ skill_md: str+++def _frontmatter_block(skill_md: str) -> str:+ """The raw YAML frontmatter, or "" when the document has none."""+ if not skill_md.startswith("---"):+ return ""+ _, _, rest = skill_md.partition("---")+ block, sep, _ = rest.partition("\n---")+ return block if sep else ""+++def validate_bundled_skills(raw: Any, *, plugin_name: str) -> list[BundledSkill]:+ """Validate the ``skills`` block of an index entry or a submission.++ Each item is ``{"name": ..., "skill_md": ...}``. The name becomes a+ DIRECTORY under the user's skills root, so it carries the same spec name+ rules the plugin name does — this is a path-traversal boundary, not+ cosmetics. The publish pre-check (``publish.py``) calls this exact+ function, so what the store accepts and what the installer accepts is one+ rule set.+ """+ if raw is None:+ return []+ if not isinstance(raw, list):+ raise AgentPluginError("skills must be a list")+ if len(raw) > MAX_BUNDLED_SKILLS:+ raise AgentPluginError(+ f"package bundles {len(raw)} skills — at most {MAX_BUNDLED_SKILLS} are accepted"+ )++ skills: list[BundledSkill] = []+ seen: set[str] = set()+ for item in raw:+ if not isinstance(item, Mapping):+ raise AgentPluginError("each bundled skill must be an object")+ name = validate_spec_name(item.get("name"))+ if name in seen:+ raise AgentPluginError(f"package bundles the skill {name!r} twice")+ seen.add(name)++ # Validate on the trimmed text, but KEEP the author's bytes: a+ # SKILL.md is a document, and silently eating its trailing newline+ # means the file we write is not the file that was published.+ # `lstrip` only, because the parser needs `---` at offset zero.+ _require_str(item.get("skill_md"), f"skill {name!r}: skill_md")+ skill_md = str(item["skill_md"]).lstrip()+ if len(skill_md.encode("utf-8")) > MAX_SKILL_MD_BYTES:+ raise AgentPluginError(+ f"skill {name!r}: SKILL.md exceeds {MAX_SKILL_MD_BYTES // 1024} KB"+ )++ frontmatter = _frontmatter_block(skill_md)+ if not frontmatter.strip():+ raise AgentPluginError(+ f"skill {name!r}: SKILL.md must open with a YAML frontmatter block"+ )+ declared = {match.group(1) for match in _TOP_LEVEL_KEY_RE.finditer(frontmatter)}+ for key in _FORBIDDEN_SKILL_FRONTMATTER:+ if key in declared:+ raise AgentPluginError(+ f"skill {name!r}: {key!r} may not be declared by a "+ "marketplace skill — it governs which tools run without "+ "confirmation, so the built-in default applies instead"+ )+ for required in ("name", "description"):+ if required not in declared:+ raise AgentPluginError(f"skill {name!r}: frontmatter is missing {required!r}")++ skills.append(BundledSkill(name=name, skill_md=skill_md))++ # A skill directory shares the namespace with everything else the user+ # installed; colliding with the package's own name would make uninstall+ # ambiguous (which one does removing the plugin take with it?).+ if plugin_name in seen and len(seen) > 1:+ raise AgentPluginError(+ f"a bundled skill may only be named {plugin_name!r} when it is the package's only skill"+ )+ return skills++def _reject_http_urls(value: Any, where: str) -> None:"""Recursively refuse plaintext-http endpoints anywhere in a block."""if isinstance(value, str):@@ -327,6 +437,42 @@ def _convert_stdio_server(name: str, server: Mapping[str, Any]) -> dict[str, Any}+def validate_mcp_server(+ name: str, server: Mapping[str, Any], extension: Mapping[str, Any] | None = None+) -> dict[str, Any]:+ """Validate and convert ONE ``mcp.json`` server entry.++ Split out of :func:`_convert_mcp_json` so a caller that already knows it+ is looking at exactly one server (``publish.py``'s pre-check, which+ enforces "exactly one server" itself before this is reached) can reuse+ the transport/credential rules — https-only, no ``headers`` on a hosted+ server, ``$plugin_…``-only ``env`` values, the ``npx``/``uvx``/``docker``+ launcher allowlist with its pinned-package rule — without also+ reimplementing the "which server did the author mean" selection.++ ``extension`` is the plugin's ``extensions["io.github.personaljarvis"]``+ block, consulted only for a hosted server's optional+ ``mcp_auth_header_template``; omit it when validating an ``mcp.json`` in+ isolation, before the rest of the manifest exists.+ """+ if not isinstance(server, Mapping):+ raise AgentPluginError(f"mcp.json server {name!r} must be an object")+ server_type = server.get("type")+ if server_type == "streamable-http":+ return _convert_http_server(name, server, extension or {})+ if server_type == "stdio":+ return _convert_stdio_server(name, server)+ if server_type == "sse":+ raise AgentPluginError(+ "mcp.json: the deprecated 'sse' transport is not accepted for "+ "community plugins — publish a streamable-http endpoint"+ )+ raise AgentPluginError(+ f"mcp.json server {name!r}: must declare a 'type' — one of "+ f"'streamable-http', 'stdio', 'sse' (got {server_type!r})"+ )++def _convert_mcp_json(plugin_name: str, mcp_json: Mapping[str, Any], extension: Mapping[str, Any]) -> dict[str, Any]:@@ -342,19 +488,7 @@ def _convert_mcp_json("mcp.json declares several servers and none is named after the ""plugin — community packages ship exactly one server")- if not isinstance(server, Mapping):- raise AgentPluginError(f"mcp.json server {server_name!r} must be an object")- server_type = server.get("type")- if server_type == "streamable-http":- return _convert_http_server(str(server_name), server, extension)- if server_type == "stdio":- return _convert_stdio_server(str(server_name), server)- if server_type == "sse":- raise AgentPluginError(- "mcp.json: the deprecated 'sse' transport is not accepted for "- "community plugins — publish a streamable-http endpoint"- )- raise AgentPluginError(f"mcp.json: unknown server type {server_type!r}")+ return validate_mcp_server(str(server_name), server, extension)def convert_manifest(@@ -439,4 +573,14 @@ def convert_manifest(raise AgentPluginError(f"manifest rejected at {location}: {message}") from exc-__all__ = ["AgentPluginError", "EXTENSION_NAMESPACE", "convert_manifest", "validate_spec_name"]+__all__ = [+ "MAX_BUNDLED_SKILLS",+ "MAX_SKILL_MD_BYTES",+ "AgentPluginError",+ "BundledSkill",+ "EXTENSION_NAMESPACE",+ "convert_manifest",+ "validate_bundled_skills",+ "validate_mcp_server",+ "validate_spec_name",+]diff --git a/jarvis/marketplace/install_standard.py b/jarvis/marketplace/install_standard.pynew file mode 100644index 0000000000..4f1b450cad--- /dev/null+++ b/jarvis/marketplace/install_standard.py@@ -0,0 +1,59 @@+"""The marketplace install standard: one source for the three install surfaces.++Every installable community entry is offered the same three ways (the+CLI / npx / Prompt pattern the comparable stores converged on, adapted to a+Python app):++- ``cli`` — the curated one-liner for a machine that already has the CLI:+ ``jarvis marketplace install <name>``.+- ``runner`` — the zero-install equivalent of ``npx``: ``uvx`` resolves the+ published ``personal-jarvis`` package into a throwaway+ environment and runs the same curated command, so the line+ works on a machine that never ran ``pip install``.+- ``prompt`` — a plain-language sentence to paste at the assistant, which+ honors it through its CLI tool (the same curated command, so+ the confirmation gate is identical).++These strings are computed HERE and nowhere else. The community REST payload+embeds them per entry and the frontend renders them verbatim — a store that+derived its own command strings client-side could drift from what the CLI+actually accepts, and a shown-but-nonexistent command is the one bug a store+is judged on.+"""++from __future__ import annotations++import re+from typing import Literal, TypedDict++# The Agent Plugins name rule (same as agent_plugins_loader.validate_spec_name+# and community_source._SKILL_NAME_RE). Names matching it consist of+# ``[a-z0-9.-]`` only, so they are safe to embed in a shell line unquoted —+# which is what makes a copy-paste one-liner possible at all.+_NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$")++EntryKind = Literal["plugin", "skill", "wallpaper"]+++class InstallBlock(TypedDict):+ cli: str+ runner: str+ prompt: str+++def install_block(name: str, kind: EntryKind) -> InstallBlock | None:+ """The three install strings for one community entry.++ Returns ``None`` when the name would not survive a shell line unquoted.+ Both index validators already enforce the same rule, so a miss here means+ the entry is invalid anyway — no block beats a quoted-and-therefore-scary+ command.+ """+ if not _NAME_RE.fullmatch(name) or ".." in name:+ return None+ cli = f"jarvis marketplace install {name}"+ return {+ "cli": cli,+ "runner": f"uvx --from personal-jarvis {cli}",+ "prompt": f'Install the "{name}" {kind} from the community marketplace.',+ }diff --git a/jarvis/marketplace/publish.py b/jarvis/marketplace/publish.pynew file mode 100644index 0000000000..b8f5fc518e--- /dev/null+++ b/jarvis/marketplace/publish.py@@ -0,0 +1,678 @@+"""In-app publishing: sign in with GitHub, validate, submit, watch it go live.++The desktop half of the marketplace's publish path+(docs/marketplace/github-signin-implementation.md §7): the app must never+hold the website's cookie or any client secret, so identity comes from the+GitHub **device flow** on the marketplace App (public client id), the token+lands in the keyring ``TokenStore``, and the submission is POSTed to the+storefront endpoint as ``Authorization: Bearer``. The endpoint proves the+token belongs to OUR App (confused-deputy check), derives the publisher from+it, and opens the registry PR as the bot — one publishing implementation for+web and app.++Two lanes share that one identity. A **package** (plugin or skill) travels+as JSON to ``/submit``; a **wallpaper** travels as multipart image bytes to+``/submit-wallpaper``, where the endpoint slugifies the title into a name and+commits straight to the public registry. Both end up in the same feed the+store reads back.++Validation here MIRRORS the endpoint's rules (``_lib/validate.ts``, itself a+mirror of the registry CI) for instant field-level feedback in the form. It+is deliberately never the authority: the endpoint and the registry CI re-run+everything, so drift here can only cost a duplicate error message, never let+a bad submission merge.+"""++from __future__ import annotations++import asyncio+import io+import json+import logging+import re+from collections.abc import Mapping+from typing import Any++import httpx++from jarvis.marketplace.agent_plugins_loader import (+ EXTENSION_NAMESPACE,+ MAX_SKILL_MD_BYTES,+ AgentPluginError,+)+from jarvis.marketplace.agent_plugins_loader import (+ validate_bundled_skills as _install_time_validate_bundled_skills,+)+from jarvis.marketplace.agent_plugins_loader import (+ validate_mcp_server as _install_time_validate_mcp_server,+)+from jarvis.marketplace.auth.oauth_device import DeviceFlowConfig, DeviceFlowHandler+from jarvis.marketplace.token_store import Tokens, TokenStore++log = logging.getLogger(__name__)++# TokenStore key for the publisher identity. Not a valid package name (those+# never carry this prefix in the seed catalog), so it cannot collide with a+# plugin's own connect tokens.+PUBLISHER_TOKEN_ID = "marketplace-publisher" # noqa: S105 - keyring key name, not a secret++_GITHUB_DEVICE_URL = "https://github.com/login/device/code"+_GITHUB_VERIFY_URL = "https://github.com/login/device"+_GITHUB_TOKEN_URL = "https://github.com/login/oauth/access_token" # noqa: S105 - URL, not a secret+_GITHUB_USER_URL = "https://api.github.com/user"++_HTTP_TIMEOUT = httpx.Timeout(connect=5.0, read=30.0, write=30.0, pool=30.0)+_UA = {"User-Agent": "Personal-Jarvis/1.0"}++# ---------------------------------------------------------------------------+# The endpoint's rule set, mirrored (keep in sync with functions/_lib/+# validate.ts in the storefront and scripts/validate.py in the registry).+# ---------------------------------------------------------------------------++_NAME_RE = re.compile(r"^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$")+_SEMVER_RE = re.compile(r"^\d+\.\d+\.\d+$")+MAX_FILE_BYTES = 128 * 1024+# The wallpaper lane's own limits, mirrored from the endpoint's+# functions/_lib/wallpapers.ts. Same reasoning as the rules above: a mirror+# that drifts costs a duplicate error message, never a bad publish — the+# endpoint re-checks all of it and the registry CI re-checks it again.+MAX_WALLPAPER_BYTES = 8 * 1024 * 1024+MAX_TITLE_CHARS = 80+# Redistribution licenses only. A wallpaper published here is copied onto+# stranger's machines, so "all rights reserved" has no meaning in this lane.+WALLPAPER_LICENSES = ("CC0-1.0", "CC-BY-4.0", "CC-BY-SA-4.0")+# Re-exported under this module's existing name, but the VALUE comes from+# agent_plugins_loader — the install-time authority — so the two numbers+# cannot silently drift apart.+MAX_SKILL_BYTES = MAX_SKILL_MD_BYTES+MAX_DESCRIPTION_CHARS = 500+# Verbatim copy of validate.ts's SECRET_PATTERNS — a mirror that misses a+# family gives a green "Check" the endpoint then refuses, which reads like a+# store bug. Keep the two lists identical when either changes.+_SECRET_PATTERNS = (+ re.compile(r"gh[pousr]_[A-Za-z0-9]{20,}"), # GitHub token family+ re.compile(r"github_pat_[A-Za-z0-9_]{20,}"), # GitHub fine-grained PAT+ re.compile(r"sk-[A-Za-z0-9_-]{20,}"), # OpenAI-style, incl. - and _+ re.compile(r"xox[baprs]-[A-Za-z0-9-]{10,}"), # Slack+ re.compile(r"AKIA[0-9A-Z]{16}"), # AWS access key+ re.compile(r"AIza[0-9A-Za-z_-]{30,}"), # Google API key+ re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"),+ re.compile(r"eyJ[A-Za-z0-9_-]{20,}\.eyJ[A-Za-z0-9_-]{20,}"), # JWT+)+++def _utf16_len(text: str) -> int:+ """Length in UTF-16 code units — the unit the endpoint's ``.length``+ counts, so an emoji-heavy description cannot pass here and 422 there."""+ return len(text.encode("utf-16-le")) // 2+++class FieldError(dict):+ """``{"field": str | None, "error": str}`` — shaped for the form."""++ def __init__(self, error: str, field: str | None = None) -> None:+ super().__init__(error=error, field=field)+++def _is_valid_name(text: str) -> bool:+ """The Agent Plugins spec name rule, shared by the submission name and+ every bundled/standalone skill name (each becomes a directory)."""+ return bool(_NAME_RE.fullmatch(text)) and ".." not in text and "--" not in text+++def validate_draft(draft: dict[str, Any]) -> tuple[dict[str, Any] | None, list[FieldError]]:+ """Normalize and check a submission draft.++ Returns ``(normalized, [])`` on success or ``(None, errors)`` — all+ collected errors, not just the first, because a form wants every red+ field at once while an API wants any refusal at all.+ """+ errors: list[FieldError] = []+ kind = draft.get("kind")+ if kind not in ("plugin", "skill"):+ return None, [FieldError('kind must be "plugin" or "skill"', "kind")]++ name = str(draft.get("name") or "").strip()+ name_is_valid = _is_valid_name(name)+ if not name_is_valid:+ errors.append(+ FieldError(+ "name must be 1-64 chars of a-z 0-9 - . "+ '(no leading/trailing separators, no ".." or "--")',+ "name",+ )+ )+ version = str(draft.get("version") or "").strip()+ if not _SEMVER_RE.fullmatch(version):+ errors.append(FieldError("version must be plain SemVer, e.g. 1.0.0", "version"))++ value: dict[str, Any] = {"kind": kind, "name": name, "version": version}++ if kind == "skill":+ title = str(draft.get("title") or "").strip()+ description = str(draft.get("description") or "").strip()+ raw_skill_md = draft.get("skill_md")+ skill_md = raw_skill_md if isinstance(raw_skill_md, str) else ""+ if not title:+ errors.append(FieldError("title is required for a skill", "title"))+ if not description:+ errors.append(FieldError("description is required for a skill", "description"))+ elif _utf16_len(description) > MAX_DESCRIPTION_CHARS:+ errors.append(+ FieldError(f"description longer than {MAX_DESCRIPTION_CHARS} chars", "description")+ )+ if not skill_md:+ errors.append(FieldError("skill_md is required for a skill", "skill_md"))+ elif name_is_valid:+ # A standalone skill install runs through the exact same call+ # (community_install.install_community_skill), so this is not a+ # second opinion on the frontmatter shape/size/forbidden-key+ # rules — it is a preview of the one judgment that will actually+ # be made. Skipped when the submission name itself is invalid:+ # that error is already reported above, and using a bad name as+ # `plugin_name` here would only produce a confusing second one.+ try:+ _install_time_validate_bundled_skills(+ [{"name": name, "skill_md": skill_md}], plugin_name=name+ )+ except AgentPluginError as exc:+ errors.append(FieldError(str(exc), "skill_md"))+ raw_categories = draft.get("categories")+ categories = (+ [c for c in raw_categories if isinstance(c, str)][:10]+ if isinstance(raw_categories, list)+ else []+ )+ value.update(title=title, description=description, categories=categories, skill_md=skill_md)+ else:+ plugin_json = draft.get("plugin_json")+ if not isinstance(plugin_json, dict):+ errors.append(FieldError("plugin_json object is required for a plugin", "plugin_json"))+ plugin_json = {}+ desc = plugin_json.get("description")+ if isinstance(desc, str) and _utf16_len(desc) > MAX_DESCRIPTION_CHARS:+ errors.append(+ FieldError(+ f"plugin_json.description longer than {MAX_DESCRIPTION_CHARS} chars",+ "plugin_json",+ )+ )+ mcp_json = draft.get("mcp_json")+ if mcp_json is not None:+ if not isinstance(mcp_json, dict):+ errors.append(FieldError("mcp_json must be an object", "mcp_json"))+ mcp_json = None+ else:+ mcp_error = _validate_mcp(mcp_json, plugin_json=plugin_json)+ if mcp_error:+ errors.append(FieldError(mcp_error, "mcp_json"))+ usage_card = draft.get("usage_card")+ value.update(+ plugin_json=plugin_json,+ mcp_json=mcp_json,+ usage_card=usage_card if isinstance(usage_card, str) else None,+ )+ # Skipped when the submission name itself is invalid, for the same+ # reason as the standalone-skill branch above: that error is already+ # reported, and an invalid `plugin_name` here would only add a+ # confusing second one.+ skills, skill_errors = (+ _validate_bundled_skills(draft.get("skills"), plugin_name=name)+ if name_is_valid+ else ([], [])+ )+ errors.extend(skill_errors)+ if skills:+ # Only present when non-empty, so a plain connector submission+ # keeps the exact body shape older endpoints already accept.+ value["skills"] = skills++ serialized = json.dumps(value, ensure_ascii=False)+ if len(serialized.encode("utf-8")) > MAX_FILE_BYTES:+ errors.append(FieldError(f"submission larger than {MAX_FILE_BYTES} bytes", None))+ for pattern in _SECRET_PATTERNS:+ if pattern.search(serialized):+ errors.append(+ FieldError(+ "submission appears to contain a credential — remove it "+ "and use $plugin_… placeholders",+ None,+ )+ )+ break+ if errors:+ return None, errors+ return value, []+++def validate_wallpaper_draft(+ draft: Mapping[str, Any],+) -> tuple[dict[str, str] | None, list[FieldError]]:+ """Normalize and check a wallpaper submission's text fields.++ The image itself is checked separately (``prepare_wallpaper_image``) —+ bytes and metadata fail for different reasons and the form wants to say+ which. There is no ``name`` or ``version`` field here on purpose: the+ endpoint slugifies the title into a free name and stamps 1.0.0, so a+ client that invented either would only be describing something the server+ ignores.+ """+ errors: list[FieldError] = []+ title = str(draft.get("title") or "").strip()+ if not title:+ errors.append(FieldError("a title is required", "title"))+ elif _utf16_len(title) > MAX_TITLE_CHARS:+ errors.append(FieldError(f"title longer than {MAX_TITLE_CHARS} characters", "title"))+ elif not re.search(r"[a-z0-9]", title.lower()):+ # The endpoint slugifies the title and refuses an empty slug. Saying+ # so here, in the words the endpoint uses, beats a 422 after upload.+ errors.append(FieldError("the title needs at least a few letters or digits", "title"))++ description = str(draft.get("description") or "").strip()+ if _utf16_len(description) > MAX_DESCRIPTION_CHARS:+ errors.append(+ FieldError(f"description longer than {MAX_DESCRIPTION_CHARS} characters", "description")+ )++ license_id = str(draft.get("license") or "").strip()+ if license_id not in WALLPAPER_LICENSES:+ errors.append(FieldError("pick one of the redistribution licenses", "license"))++ theme = str(draft.get("theme") or "").strip()+ if theme not in ("light", "dark", ""):+ errors.append(FieldError("theme must be 'light' or 'dark'", "theme"))++ if draft.get("rights") is not True:+ # Not decoration: this is the uploader's own statement, recorded in a+ # submission published under their name. Nobody inspects the picture+ # before it goes live, which is exactly why the statement is required.+ errors.append(+ FieldError(+ "confirm that you hold the rights and the image is legal to publish", "rights"+ )+ )++ if errors:+ return None, errors+ value = {"title": title, "license": license_id, "rights": "yes"}+ if description:+ value["description"] = description+ if theme:+ value["theme"] = theme+ return value, []+++def prepare_wallpaper_image(data: bytes) -> tuple[bytes, str]:+ """Re-encode a picture into the bytes that will be published.++ Returns ``(webp_bytes, "wallpaper.webp")``. Nothing the caller supplied+ survives the round trip: Pillow decodes and re-encodes, so EXIF (GPS+ included), a forged header and anything appended past the image data are+ all gone. That is the same guarantee the website's uploader gives with a+ canvas, and the registry build re-encodes a third time — no byte an+ uploader crafted is ever served as-is.++ Raises ``SubmitError`` with a sentence meant for the person uploading.+ """+ if not data:+ raise SubmitError(422, "that file is empty", "file")+ try:+ from PIL import Image+ except ImportError as exc: # pragma: no cover - Pillow is a hard dependency+ raise SubmitError(503, "image support is unavailable on this install", "file") from exc++ try:+ with Image.open(io.BytesIO(data)) as probe:+ probe.verify()+ with Image.open(io.BytesIO(data)) as source:+ source.load()+ prepared = source.convert("RGB")+ except Exception as exc: # noqa: BLE001 - any decode failure means "not an image"+ raise SubmitError(422, "that file is not an image the app can read", "file") from exc++ # 4K cap, matching the picker's own store and the website's uploader.+ max_width = 3840+ if prepared.width > max_width:+ height = max(1, round(prepared.height * max_width / prepared.width))+ prepared = prepared.resize((max_width, height), Image.Resampling.LANCZOS)++ # Step down the quality until it fits rather than refusing a picture the+ # user cannot fix by hand — a 4K photograph can exceed 8 MB at q82, and+ # "export a smaller one" is not an instruction a wallpaper picker can act+ # on. The floor is deliberate: below q50 the result is not worth shipping.+ encoded = b""+ for quality in (82, 70, 60, 50):+ buffer = io.BytesIO()+ prepared.save(buffer, "WEBP", quality=quality, method=4)+ encoded = buffer.getvalue()+ if len(encoded) <= MAX_WALLPAPER_BYTES:+ break+ prepared.close()+ if len(encoded) > MAX_WALLPAPER_BYTES:+ raise SubmitError(+ 413,+ f"even re-encoded, that image stays over "+ f"{MAX_WALLPAPER_BYTES // (1024 * 1024)} MB — publish a smaller one",+ "file",+ )+ return encoded, "wallpaper.webp"+++def _validate_bundled_skills(+ raw: Any, *, plugin_name: str+) -> tuple[list[dict[str, str]], list[FieldError]]:+ """Validate a plugin submission's ``skills: [{name, skill_md}]`` block.++ Delegates the per-skill rules — frontmatter shape, the required ``name``/+ ``description`` keys, the forbidden ``risk_policy`` key, the size cap, and+ the "may only share the plugin's own name when it is the sole skill"+ rule — straight to ``agent_plugins_loader.validate_bundled_skills``. That+ is the exact function the install path calls (both for a plugin's bundled+ skills and, via ``community_install.install_community_skill``, for a+ standalone skill submission), so there is no second copy of the rule set+ left to drift out of sync.++ The trade-off against the rest of this module's "collect every error"+ form UX: the authority is fail-fast (one exception), so a bad bundle is+ reported by its first violation rather than all of them at once.+ """+ if raw is None:+ return [], []+ try:+ validated = _install_time_validate_bundled_skills(raw, plugin_name=plugin_name)+ except AgentPluginError as exc:+ return [], [FieldError(str(exc), "skills")]+ return [{"name": skill.name, "skill_md": skill.skill_md} for skill in validated], []+++def _validate_mcp(mcp: dict[str, Any], *, plugin_json: Mapping[str, Any]) -> str | None:+ """Exactly one server, then delegate the transport/credential rules to+ ``agent_plugins_loader.validate_mcp_server`` — the exact function the+ install-time authority applies to a plugin's own ``mcp.json`` — so+ https-only, the ``npx``/``uvx``/``docker`` launcher allowlist, no+ ``headers`` on a hosted server, ``$plugin_…``-only ``env`` values and the+ ``sse``-transport ban are one rule set, not two hand-kept-in-sync copies.++ "Exactly one server" stays a LOCAL check, on top of the delegated one:+ the author-facing contract (docs/marketplace/package-layout.md) promises+ it, but the authority itself tolerates several servers when one is named+ after the plugin (a selection rule this pre-check has no use for). A+ stricter local check can only produce a duplicate error message, never+ let a submission through the authority would refuse+ (validator-parity.md, "the direction of a divergence decides whether it+ matters").++ A second local check stays for the same reason: the authority's own pin+ rule only forbids a literal ``@latest`` suffix, not the absence of any+ version marker at all, so a bare unversioned package name+ (``npx some-package``) would install today without ever being pinned.+ Catching that here is strictly stricter, never looser.+ """+ # Only "mcpServers" is a real key — a "servers" alias would validate here+ # and then vanish once CI (which reads only "mcpServers") looks at it,+ # producing a submission that describes a server nobody can find.+ servers = mcp.get("mcpServers")+ if not isinstance(servers, dict):+ return "mcp_json must contain an mcpServers object"+ if len(servers) != 1:+ return "mcp_json must define exactly one server"+ server_name, server = next(iter(servers.items()))++ extensions = plugin_json.get("extensions") if isinstance(plugin_json, Mapping) else None+ extension = extensions.get(EXTENSION_NAMESPACE) if isinstance(extensions, Mapping) else None+ try:+ converted = _install_time_validate_mcp_server(+ str(server_name), server, extension if isinstance(extension, Mapping) else None+ )+ except AgentPluginError as exc:+ return str(exc)++ if converted.get("transport") == "stdio":+ args = list(converted.get("install") or [])[1:]+ pinned = any(+ re.search(r"@\d+\.\d+\.\d+", a) or re.search(r":[\w.-]*\d[\w.-]*$", a) for a in args+ )+ if not pinned:+ return "stdio server must pin an exact version (e.g. @1.2.0 or image:1.2)"+ return None+++# ---------------------------------------------------------------------------+# Identity: device flow + keyring+# ---------------------------------------------------------------------------+++def _client_id() -> str:+ from jarvis.core.config import load_config++ try:+ return str(load_config().marketplace.publish_github_client_id).strip()+ except Exception: # noqa: BLE001 - config trouble must not kill the view+ log.warning("publish: could not read config for the client id")+ from jarvis.core.config import MarketplaceConfig++ return MarketplaceConfig().publish_github_client_id+++def publish_endpoint() -> str:+ """The configured submit endpoint (empty string = publishing disabled)."""+ from jarvis.core.config import load_config++ try:+ return str(load_config().marketplace.publish_endpoint).strip()+ except Exception: # noqa: BLE001+ log.warning("publish: could not read config for the endpoint")+ from jarvis.core.config import MarketplaceConfig++ return MarketplaceConfig().publish_endpoint+++def publish_wallpaper_endpoint() -> str:+ """The configured wallpaper endpoint (empty string = lane disabled)."""+ from jarvis.core.config import load_config++ try:+ return str(load_config().marketplace.publish_wallpaper_endpoint).strip()+ except Exception: # noqa: BLE001 - config trouble must not kill the picker+ log.warning("publish: could not read config for the wallpaper endpoint")+ from jarvis.core.config import MarketplaceConfig++ return MarketplaceConfig().publish_wallpaper_endpoint+++def make_device_handler() -> DeviceFlowHandler:+ """A device-flow handler for the marketplace GitHub App.++ Identity only — the scope list is empty on purpose, so the consent+ screen shows no repository or account permissions.+ """+ return DeviceFlowHandler(+ DeviceFlowConfig(+ plugin_id=PUBLISHER_TOKEN_ID,+ device_url=_GITHUB_DEVICE_URL,+ verify_url=_GITHUB_VERIFY_URL,+ token_url=_GITHUB_TOKEN_URL,+ client_id=_client_id(),+ scopes=[],+ )+ )+++async def fetch_identity(+ tokens: Tokens, transport: httpx.AsyncBaseTransport | None = None+) -> dict[str, Any] | None:+ """The GitHub account behind the stored token, or ``None`` when invalid.++ ``transport`` is injectable so unit tests can stub the HTTP layer — the+ same pattern as ``marketplace_routes._make_validator``.+ """+ try:+ async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT, transport=transport) as client:+ r = await client.get(+ _GITHUB_USER_URL,+ headers={**_UA, "Authorization": f"Bearer {tokens.access}"},+ )+ except httpx.HTTPError as exc:+ raise RuntimeError(f"GitHub is unreachable: {exc}") from exc+ if r.status_code != 200:+ return None+ data = r.json()+ return {"login": data.get("login"), "avatar_url": data.get("avatar_url")}+++async def current_identity(+ store: TokenStore | None = None,+ transport: httpx.AsyncBaseTransport | None = None,+) -> dict[str, Any]:+ """``{"signed_in": bool, "login": ...}`` — refreshing a stale token once.++ A dead refresh signs the user out honestly instead of caching a broken+ token that would 401 at submit time.+ """+ store = store or TokenStore()+ try:+ # to_thread: the keyring backend talks to the OS credential store+ # synchronously and must not block the event loop.+ tokens = await asyncio.to_thread(store.load, PUBLISHER_TOKEN_ID)+ except Exception: # noqa: BLE001 - a locked keyring reads as signed out+ log.warning("publish: token load failed", exc_info=True)+ return {"signed_in": False}+ if tokens is None:+ return {"signed_in": False}+ identity = await fetch_identity(tokens, transport)+ if identity is not None:+ return {"signed_in": True, **identity}+ try:+ refreshed = await make_device_handler().refresh(tokens)+ except RuntimeError as exc:+ # Expected lifecycle (revoked at GitHub, refresh token aged out) —+ # log it so "I keep getting signed out" is diagnosable.+ log.info("publish: token refresh failed, signing out: %s", exc)+ await asyncio.to_thread(store.delete, PUBLISHER_TOKEN_ID)+ return {"signed_in": False}+ await asyncio.to_thread(store.save, PUBLISHER_TOKEN_ID, refreshed)+ identity = await fetch_identity(refreshed, transport)+ if identity is None:+ await asyncio.to_thread(store.delete, PUBLISHER_TOKEN_ID)+ return {"signed_in": False}+ return {"signed_in": True, **identity}+++# ---------------------------------------------------------------------------+# Submit + live check+# ---------------------------------------------------------------------------+++class SubmitError(RuntimeError):+ """Endpoint refusal, carrying the HTTP status and optional field."""++ def __init__(self, status: int, error: str, field: str | None = None) -> None:+ super().__init__(error)+ self.status = status+ self.error = error+ self.field = field+++async def submit(+ normalized: dict[str, Any],+ store: TokenStore | None = None,+ transport: httpx.AsyncBaseTransport | None = None,+) -> dict[str, Any]:+ """POST an already-validated submission; returns ``{pr_url, submission_path}``.++ The token goes as ``Authorization: Bearer`` — the endpoint verifies it+ belongs to the marketplace App and derives the publisher from it, so+ nothing identity-shaped travels in the body.+ """+ endpoint = publish_endpoint()+ if not endpoint:+ raise SubmitError(503, "publishing is disabled in this deployment")+ store = store or TokenStore()+ tokens = await asyncio.to_thread(store.load, PUBLISHER_TOKEN_ID)+ if tokens is None:+ raise SubmitError(401, "sign in with GitHub first")+ try:+ async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT, transport=transport) as client:+ r = await client.post(+ endpoint,+ json=normalized,+ headers={**_UA, "Authorization": f"Bearer {tokens.access}"},+ )+ except httpx.HTTPError as exc:+ raise SubmitError(502, f"the publish endpoint is unreachable: {exc}") from exc+ try:+ body = r.json()+ except ValueError:+ body = {}+ if r.status_code == 201:+ return {+ "pr_url": body.get("prUrl"),+ "submission_path": body.get("submissionPath"),+ }+ error = str(body.get("error") or f"publish failed (HTTP {r.status_code})")+ field = body.get("field")+ raise SubmitError(r.status_code, error, field if isinstance(field, str) else None)+++async def submit_wallpaper(+ fields: Mapping[str, str],+ image: bytes,+ filename: str = "wallpaper.webp",+ store: TokenStore | None = None,+ transport: httpx.AsyncBaseTransport | None = None,+) -> dict[str, Any]:+ """POST an already-validated wallpaper; returns ``{"name": ...}``.++ Multipart rather than JSON because the payload is image bytes, but the+ identity chain is the one ``submit`` uses: the token travels as+ ``Authorization: Bearer``, the endpoint proves it belongs to the+ marketplace App and derives the publisher from it. Nothing+ identity-shaped is in the form.+ """+ endpoint = publish_wallpaper_endpoint()+ if not endpoint:+ raise SubmitError(503, "wallpaper publishing is disabled in this deployment")+ store = store or TokenStore()+ tokens = await asyncio.to_thread(store.load, PUBLISHER_TOKEN_ID)+ if tokens is None:+ raise SubmitError(401, "sign in with GitHub first")+ try:+ async with httpx.AsyncClient(timeout=_HTTP_TIMEOUT, transport=transport) as client:+ r = await client.post(+ endpoint,+ data=dict(fields),+ files={"file": (filename, image, "image/webp")},+ headers={**_UA, "Authorization": f"Bearer {tokens.access}"},+ )+ except httpx.HTTPError as exc:+ raise SubmitError(502, f"the publish endpoint is unreachable: {exc}") from exc+ try:+ body = r.json()+ except ValueError:+ body = {}+ if r.status_code == 201:+ # The endpoint slugified the title into the name — the caller could+ # not have known it in advance, and it is what the live check needs.+ return {"name": str(body.get("name") or "")}+ error = str(body.get("error") or f"publish failed (HTTP {r.status_code})")+ field = body.get("field")+ raise SubmitError(r.status_code, error, field if isinstance(field, str) else None)+++async def live_status(name: str, version: str, *, force: bool = False) -> dict[str, Any]:+ """Whether ``name`` at ``version`` is in the community index yet.++ This is the honest "it is live" signal: the same feed every store client+ reads. ``force`` bypasses the TTL for the watch-until-live poller.+ """+ from jarvis.marketplace import community_source++ index, status = await community_source.get_index(force=force)+ live = False+ if index is not None:+ entries: list[Any] = [*index.plugins, *index.skills, *index.wallpapers]+ for entry in entries:+ if entry.name == name and (entry.version or "") == version:+ live = True+ break+ return {"name": name, "version": version, "live": live, "feed_status": status}diff --git a/jarvis/ui/web/marketplace_publish_routes.py b/jarvis/ui/web/marketplace_publish_routes.pynew file mode 100644index 0000000000..0250a56072--- /dev/null+++ b/jarvis/ui/web/marketplace_publish_routes.py@@ -0,0 +1,338 @@+"""REST API for in-app marketplace publishing.++Endpoints:+ GET /api/marketplace/publish/identity — signed-in state (+enabled)+ POST /api/marketplace/publish/signin/start — begin GitHub device flow+ GET /api/marketplace/publish/signin/poll/{id} — poll until approved+ DELETE /api/marketplace/publish/identity — sign out (drop token)+ POST /api/marketplace/publish/validate — field-level pre-check+ POST /api/marketplace/publish/submit — publish (opens the bot PR)+ POST /api/marketplace/publish/submit-wallpaper — publish a picker wallpaper+ GET /api/marketplace/publish/status — is name@version live in the feed++The heavy lifting lives in ``jarvis/marketplace/publish.py``; this layer only+shapes it for the view and the auto-generated CLI.+"""++from __future__ import annotations++import asyncio+import logging+from typing import Any, Literal++from fastapi import APIRouter, HTTPException, Response+from pydantic import BaseModel++from jarvis.marketplace.token_store import TokenStore++log = logging.getLogger(__name__)++router = APIRouter(prefix="/api/marketplace/publish", tags=["marketplace"])++# In-flight device flows: flow_id -> completion task. Entries are popped by+# the poll that observes completion, by an explicit cancel, or by the sweep+# in signin_start — an ABANDONED flow's task finishes with GitHub's+# 15-minute expiry but its dict entry would otherwise stay forever.+_flows: dict[str, asyncio.Task[dict[str, Any]]] = {}+++def _sweep_finished_flows() -> None:+ for fid, task in list(_flows.items()):+ if task.done():+ _flows.pop(fid, None)+++async def _complete_signin(handler: Any, session: Any) -> dict[str, Any]:+ from jarvis.marketplace.publish import PUBLISHER_TOKEN_ID, fetch_identity++ result = await handler.await_completion(session)+ if result.tokens is None:+ return {"status": "error", "error": result.error or "sign-in failed"}+ store = TokenStore()+ await asyncio.to_thread(store.save, PUBLISHER_TOKEN_ID, result.tokens)+ try:+ identity = await fetch_identity(result.tokens)+ except RuntimeError as exc:+ # The token is saved; only the name lookup failed. The view falls+ # back to GET /identity, which retries.+ log.warning("publish sign-in: identity lookup failed: %s", exc)+ identity = None+ return {"status": "connected", **(identity or {})}++[email protected]("/identity", openapi_extra={"x-jarvis-readonly": True})+async def publish_identity(response: Response) -> dict[str, Any]:+ """Signed-in state, plus whether publishing is enabled at all."""+ from jarvis.marketplace.publish import (+ current_identity,+ publish_endpoint,+ publish_wallpaper_endpoint,+ )++ response.headers["Cache-Control"] = "no-store"+ enabled = bool(publish_endpoint())+ # Reported separately: the two lanes are separate endpoints and a fork may+ # run one without the other. The wallpaper picker hides its Share button on+ # a false here rather than offering a door that answers 503.+ wallpapers_enabled = bool(publish_wallpaper_endpoint())+ if not enabled and not wallpapers_enabled:+ return {"enabled": False, "wallpapers_enabled": False, "signed_in": False}+ try:+ state = await current_identity()+ except RuntimeError as exc:+ # GitHub unreachable: report the stored token as "unknown", not as+ # signed out — signing the user out over a network blip would drop a+ # perfectly good token.+ log.warning("publish identity: GitHub unreachable: %s", exc)+ return {+ "enabled": enabled,+ "wallpapers_enabled": wallpapers_enabled,+ "signed_in": False,+ "unreachable": str(exc),+ }+ return {"enabled": enabled, "wallpapers_enabled": wallpapers_enabled, **state}++[email protected]("/signin/start")+async def signin_start() -> dict[str, Any]:+ """Begin the device flow: returns the user code to type at GitHub."""+ from jarvis.marketplace.publish import make_device_handler, publish_endpoint++ if not publish_endpoint():+ raise HTTPException(status_code=503, detail="publishing is disabled in this deployment")+ _sweep_finished_flows()+ handler = make_device_handler()+ try:+ session = await handler.start(None)+ except RuntimeError as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from exc+ _flows[session.flow_id] = asyncio.create_task(+ _complete_signin(handler, session), name=f"publish-signin:{session.flow_id}"+ )+ return {+ "flow_id": session.flow_id,+ "user_code": session.user_code,+ "verification_uri": session.verification_uri,+ "verification_uri_complete": session.verification_uri_complete,+ "expires_at_ms": session.expires_at_ms,+ "interval": session.interval,+ }++[email protected]("/signin/poll/{flow_id}", openapi_extra={"x-jarvis-readonly": True})+async def signin_poll(flow_id: str, response: Response) -> dict[str, Any]:+ """Poll an in-progress sign-in until GitHub reports approval."""+ response.headers["Cache-Control"] = "no-store"+ task = _flows.get(flow_id)+ if task is None:+ raise HTTPException(status_code=404, detail="unknown or already-finished flow")+ if not task.done():+ return {"status": "pending"}+ _flows.pop(flow_id, None)+ try:+ return task.result()+ except Exception as exc: # noqa: BLE001 - surface, never crash the poll+ return {"status": "error", "error": str(exc)}++[email protected]("/signin/{flow_id}")+async def signin_cancel(flow_id: str) -> dict[str, Any]:+ """Abandon an in-progress sign-in (mirrors the connect-flow cancel)."""+ task = _flows.pop(flow_id, None)+ if task is None:+ raise HTTPException(status_code=404, detail="unknown or already-finished flow")+ task.cancel()+ return {"ok": True}++[email protected]("/identity")+async def sign_out() -> dict[str, Any]:+ """Sign out: drop the stored publisher token."""+ from jarvis.marketplace.publish import PUBLISHER_TOKEN_ID++ try:+ # Fail-closed by design: TokenStore raises when it cannot VERIFY the+ # credential is gone — surface that as a structured error, never as+ # a bare 500 the view cannot explain.+ await asyncio.to_thread(TokenStore().delete, PUBLISHER_TOKEN_ID)+ except RuntimeError as exc:+ raise HTTPException(+ status_code=502, detail=f"sign-out could not be verified: {exc}"+ ) from exc+ return {"ok": True}+++class SubmissionDraft(BaseModel):+ """The submission as the form holds it — validation happens server-side+ in ``validate_draft`` so the wire shape stays loose on purpose.++ Every field the form can send MUST be declared here even though the real+ rules live in ``validate_draft``: pydantic drops undeclared keys silently,+ so an omission does not surface as an error — it publishes a package with+ a piece quietly missing, under a success message. ``skills`` was exactly+ that: the Publish tab sent bundled skills, this model discarded them, and+ ``validate_draft`` never saw the block it validates.+ """++ kind: str+ name: str = ""+ version: str = ""+ title: str | None = None+ description: str | None = None+ categories: list[str] | None = None+ skill_md: str | None = None+ plugin_json: dict[str, Any] | None = None+ mcp_json: dict[str, Any] | None = None+ usage_card: str | None = None+ # Bundled skills ride inside a plugin submission as [{name, skill_md}]+ # (publishing-plan.md §3). Kept loose on purpose — `validate_draft`+ # delegates to the installer's own rules, which are the authority.+ skills: list[dict[str, Any]] | None = None++[email protected]("/validate", openapi_extra={"x-jarvis-readonly": True})+async def validate(body: SubmissionDraft) -> dict[str, Any]:+ """Field-level pre-check with the endpoint's own rule set (advisory —+ the endpoint and the registry CI remain the authority)."""+ from jarvis.marketplace.publish import validate_draft++ _, errors = validate_draft(body.model_dump())+ return {"ok": not errors, "errors": errors}+++# Dangerous: publishes content publicly under the user's GitHub name. The+# flag makes the auto-generated `jarvis api` layer demand --yes, mirroring+# the view's explicit Publish click.[email protected]("/submit", openapi_extra={"x-jarvis-dangerous": True})+async def submit(body: SubmissionDraft) -> dict[str, Any]:+ """Validate, then POST to the storefront endpoint as the signed-in user."""+ from jarvis.marketplace.publish import SubmitError, validate_draft+ from jarvis.marketplace.publish import submit as do_submit++ normalized, errors = validate_draft(body.model_dump())+ if normalized is None:+ first = errors[0]+ raise HTTPException(+ status_code=422,+ detail={"error": first["error"], "field": first["field"], "errors": errors},+ )+ try:+ result = await do_submit(normalized)+ except SubmitError as exc:+ raise HTTPException(+ status_code=exc.status, detail={"error": exc.error, "field": exc.field}+ ) from exc+ # What the author will hand to everyone else. Computed by the same standard+ # module the store and the CLI use, so the line an author copies here is+ # exactly the line their installers will run. It describes the entry once it+ # is live — the view only shows it after the registry confirms that.+ from jarvis.marketplace.install_standard import install_block++ kind: Literal["plugin", "skill"] = "skill" if normalized["kind"] == "skill" else "plugin"+ return {+ "ok": True,+ "name": normalized["name"],+ "version": normalized["version"],+ "install": install_block(normalized["name"], kind),+ **result,+ }+++class WallpaperDraft(BaseModel):+ """A "share this picture" request from the wallpaper picker.++ The image is named, not uploaded: ``upload_id`` points at a picture the+ picker already holds, whose bytes this app re-encoded when they arrived.+ That keeps the sanitizing in one place and means the browser cannot hand+ the publisher different bytes than the ones the user is looking at.++ There is no ``name`` or ``version``: the endpoint slugifies the title into+ a free name and stamps 1.0.0. A client that sent either would be+ describing something the server ignores.+ """++ upload_id: str+ title: str = ""+ description: str | None = None+ license: str = ""+ theme: str | None = None+ rights: bool = False+++# Dangerous for the same reason as /submit, and more so: this publishes an+# IMAGE publicly under the user's GitHub name, into a lane nobody reviews+# before it goes live.[email protected]("/submit-wallpaper", openapi_extra={"x-jarvis-dangerous": True})+async def submit_wallpaper(body: WallpaperDraft) -> dict[str, Any]:+ """Publish one of the picker's own wallpapers to the community feed."""+ from jarvis.marketplace.publish import (+ SubmitError,+ prepare_wallpaper_image,+ validate_wallpaper_draft,+ )+ from jarvis.marketplace.publish import submit_wallpaper as do_submit+ from jarvis.ui.web.wallpapers import WallpaperUploads++ fields, errors = validate_wallpaper_draft(body.model_dump())+ if fields is None:+ first = errors[0]+ raise HTTPException(+ status_code=422,+ detail={"error": first["error"], "field": first["field"], "errors": errors},+ )++ item = await asyncio.to_thread(WallpaperUploads().get, body.upload_id)+ if item is None:+ raise HTTPException(+ status_code=404, detail={"error": "that wallpaper is gone", "field": "file"}+ )+ if item.origin:+ # An imported community wallpaper is somebody else's picture. Letting+ # it be re-published would launder authorship through the picker and+ # put a stranger's name on a stranger's work.+ raise HTTPException(+ status_code=409,+ detail={+ "error": "that wallpaper came from the community — only your own pictures "+ "can be published",+ "field": "file",+ },+ )+ try:+ raw = await asyncio.to_thread(item.path.read_bytes)+ except OSError as exc:+ raise HTTPException(+ status_code=500,+ detail={"error": f"the image could not be read: {exc}", "field": "file"},+ ) from exc++ try:+ # Pillow work is CPU-bound: off the event loop, like every other+ # image path in the app.+ image, filename = await asyncio.to_thread(prepare_wallpaper_image, raw)+ result = await do_submit(fields, image, filename)+ except SubmitError as exc:+ raise HTTPException(+ status_code=exc.status, detail={"error": exc.error, "field": exc.field}+ ) from exc++ from jarvis.marketplace.install_standard import install_block++ name = result["name"]+ return {+ "ok": True,+ "name": name,+ "version": "1.0.0",+ "install": install_block(name, "wallpaper") if name else None,+ }++[email protected]("/status", openapi_extra={"x-jarvis-readonly": True})+async def status(+ name: str, version: str, response: Response, force: bool = False+) -> dict[str, Any]:+ """Whether name@version has reached the live community feed yet."""+ from jarvis.marketplace.publish import live_status++ response.headers["Cache-Control"] = "no-store"+ return await live_status(name, version, force=force)diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex f54011bfcc..6e8e4b58c8 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -358,6 +358,7 @@ class WebServer:from .friends_routes import router as friends_routerfrom .frontier_routes import router as frontier_routerfrom .grok_build_routes import router as grok_build_router+ from .marketplace_publish_routes import router as marketplace_publish_routerfrom .marketplace_routes import router as marketplace_routerfrom .mcp_routes import router as mcp_routerfrom .missions_auth import router as missions_auth_router@@ -450,6 +451,7 @@ class WebServer:app.include_router(commands_router)app.include_router(friends_router)app.include_router(marketplace_router)+ app.include_router(marketplace_publish_router)app.state.friend_registry = Noneapp.state.channel_manager = Noneapp.state.channel_chat_bridge = Nonediff --git a/tests/unit/marketplace/test_install_standard.py b/tests/unit/marketplace/test_install_standard.pynew file mode 100644index 0000000000..3efcbbe0ae--- /dev/null+++ b/tests/unit/marketplace/test_install_standard.py@@ -0,0 +1,41 @@+"""The install standard: three surfaces, one source, shell-safe by rule."""++from __future__ import annotations++import pytest++from jarvis.marketplace.install_standard import install_block+++def test_plugin_block_contains_the_three_surfaces() -> None:+ block = install_block("todo-fox", "plugin")+ assert block is not None+ assert block["cli"] == "jarvis marketplace install todo-fox"+ assert block["runner"] == "uvx --from personal-jarvis jarvis marketplace install todo-fox"+ assert block["prompt"] == 'Install the "todo-fox" plugin from the community marketplace.'+++def test_skill_prompt_names_the_kind() -> None:+ block = install_block("three-point-check", "skill")+ assert block is not None+ assert '"three-point-check" skill' in block["prompt"]+ # CLI and runner are kind-agnostic: one command resolves either.+ assert block["cli"] == "jarvis marketplace install three-point-check"+++ "name",+ ["../../evil", "UPPER", "has space", "under_score", "-lead", "trail-", "a..b", ""],+)+def test_unsafe_names_get_no_block(name: str) -> None:+ assert install_block(name, "plugin") is None+++def test_valid_names_never_need_shell_quoting() -> None:+ block = install_block("a1.b-2", "skill")+ assert block is not None+ for line in (block["cli"], block["runner"]):+ # The property the copy-paste standard rests on: the two lines typed+ # at a shell never require quoting or escaping in any shell. (The+ # prompt is pasted at the assistant, not a shell — it may quote.)+ assert not set(line) & set("\"'\\$`;|&<>(){}!\n")diff --git a/tests/unit/marketplace/test_publish.py b/tests/unit/marketplace/test_publish.pynew file mode 100644index 0000000000..141034485e--- /dev/null+++ b/tests/unit/marketplace/test_publish.py@@ -0,0 +1,492 @@+"""The in-app publish module: rule mirror, identity, submit — no network."""++from __future__ import annotations++from typing import Any++import httpx+import pytest++from jarvis.marketplace import publish+from jarvis.marketplace.token_store import Tokens+++def _skill_draft(**overrides: Any) -> dict[str, Any]:+ draft: dict[str, Any] = {+ "kind": "skill",+ "name": "three-point-check",+ "version": "1.0.0",+ "title": "Three Point Check",+ "description": "Summarize any topic in three bullets",+ "categories": ["writing"],+ "skill_md": (+ "---\nname: three-point-check\ndescription: Three bullets, done.\n---\n\nDo the thing."+ ),+ }+ draft.update(overrides)+ return draft+++def _plugin_draft(**overrides: Any) -> dict[str, Any]:+ draft: dict[str, Any] = {+ "kind": "plugin",+ "name": "todo-fox",+ "version": "1.2.0",+ "plugin_json": {"name": "todo-fox", "description": "Tasks from TodoFox"},+ "mcp_json": {+ "mcpServers": {+ "todo-fox": {"type": "streamable-http", "url": "https://mcp.todofox.example/mcp"}+ }+ },+ "usage_card": None,+ }+ draft.update(overrides)+ return draft+++class FakeStore:+ def __init__(self, tokens: Tokens | None = None) -> None:+ self._tokens = tokens+ self.deleted = False++ def load(self, key: str) -> Tokens | None:+ return self._tokens++ def save(self, key: str, tokens: Tokens) -> None:+ self._tokens = tokens++ def delete(self, key: str) -> None:+ self._tokens = None+ self.deleted = True+++# --- validate_draft --------------------------------------------------------+++def test_valid_skill_normalizes() -> None:+ value, errors = publish.validate_draft(_skill_draft())+ assert errors == []+ assert value is not None+ assert value["kind"] == "skill" and value["title"] == "Three Point Check"+++def test_valid_plugin_with_pinned_stdio() -> None:+ draft = _plugin_draft(+ mcp_json={+ "mcpServers": {+ "todo-fox": {"type": "stdio", "command": "uvx", "args": ["[email protected]"]}+ }+ }+ )+ value, errors = publish.validate_draft(draft)+ assert errors == [] and value is not None+++ ("overrides", "field"),+ [+ ({"kind": "wat"}, "kind"),+ ({"name": "UPPER"}, "name"),+ ({"name": "double--dash"}, "name"),+ ({"version": "1.0"}, "version"),+ ({"title": ""}, "title"),+ ({"description": ""}, "description"),+ ({"description": "x" * 501}, "description"),+ ({"skill_md": "no frontmatter"}, "skill_md"),+ ({"skill_md": "---\n" + "x" * (publish.MAX_SKILL_BYTES + 1)}, "skill_md"),+ ],+)+def test_skill_rejections_carry_the_field(overrides: dict[str, Any], field: str) -> None:+ value, errors = publish.validate_draft(_skill_draft(**overrides))+ assert value is None+ assert any(e["field"] == field for e in errors)+++ "mcp",+ [+ {"mcpServers": {}},+ {"mcpServers": {"a": {"type": "streamable-http", "url": "http://plain.example"}}},+ {"mcpServers": {"a": {"type": "stdio", "command": "bash", "args": ["[email protected]"]}}},+ # Ends in no version marker at all — the authority only forbids a+ # literal "@latest" suffix, so this one is caught by the local+ # supplementary pin check on top of the delegated rules, not by+ # agent_plugins_loader.validate_mcp_server itself.+ {"mcpServers": {"a": {"type": "stdio", "command": "npx", "args": ["unpinned-thing"]}}},+ {"mcpServers": {"a": {}, "b": {}}},+ ],+)+def test_mcp_rejections(mcp: dict[str, Any]) -> None:+ value, errors = publish.validate_draft(_plugin_draft(mcp_json=mcp))+ assert value is None+ assert any(e["field"] == "mcp_json" for e in errors)+++# --- mcp.json now delegates to agent_plugins_loader.validate_mcp_server ----+#+# validator-parity.md rows 12, 13 and 15, plus the "type" field itself: the+# rules below were NOT enforced by the old hand-rolled _validate_mcp at all,+# so these are net-new rejections, not just refactored ones.+++def test_mcp_missing_type_is_rejected() -> None:+ draft = _plugin_draft(+ mcp_json={"mcpServers": {"todo-fox": {"url": "https://mcp.todofox.example/mcp"}}}+ )+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "mcp_json" and "type" in e["error"] for e in errors)+++def test_mcp_sse_transport_is_rejected() -> None:+ draft = _plugin_draft(+ mcp_json={+ "mcpServers": {"todo-fox": {"type": "sse", "url": "https://mcp.todofox.example/sse"}}+ }+ )+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "mcp_json" and "sse" in e["error"] for e in errors)+++def test_mcp_headers_on_hosted_server_is_rejected() -> None:+ draft = _plugin_draft(+ mcp_json={+ "mcpServers": {+ "todo-fox": {+ "type": "streamable-http",+ "url": "https://mcp.todofox.example/mcp",+ "headers": {"Authorization": "Bearer x"},+ }+ }+ }+ )+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "mcp_json" for e in errors)+++def test_mcp_stdio_env_literal_is_rejected() -> None:+ draft = _plugin_draft(+ mcp_json={+ "mcpServers": {+ "todo-fox": {+ "type": "stdio",+ "command": "npx",+ "args": ["-y", "@todofox/[email protected]"],+ "env": {"TODOFOX_TOKEN": "a-literal-value-not-a-placeholder-at-all"},+ }+ }+ }+ )+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "mcp_json" for e in errors)+++def test_mcp_stdio_env_placeholder_is_accepted() -> None:+ draft = _plugin_draft(+ mcp_json={+ "mcpServers": {+ "todo-fox": {+ "type": "stdio",+ "command": "npx",+ "args": ["-y", "@todofox/[email protected]"],+ "env": {"TODOFOX_TOKEN": "$plugin_todo-fox_access_token"},+ }+ }+ }+ )+ value, errors = publish.validate_draft(draft)+ assert errors == [] and value is not None+++def test_mcp_and_install_authority_agree_on_acceptance() -> None:+ """W3 "done when" (publishing-plan.md): the same mcp.json fixture is+ judged identically by the app's pre-check and by the install-time+ authority (agent_plugins_loader.validate_mcp_server) it delegates to."""+ from jarvis.marketplace import agent_plugins_loader++ server = {+ "type": "stdio",+ "command": "npx",+ "args": ["-y", "@todofox/[email protected]"],+ "env": {"TODOFOX_TOKEN": "$plugin_todo-fox_access_token"},+ }+ mcp_json = {"mcpServers": {"todo-fox": server}}+ value, errors = publish.validate_draft(_plugin_draft(mcp_json=mcp_json))+ assert errors == [] and value is not None++ assert agent_plugins_loader.validate_mcp_server("todo-fox", server) == {+ "transport": "stdio",+ "install": ["npx", "-y", "@todofox/[email protected]"],+ "env_template": {"TODOFOX_TOKEN": "$plugin_todo-fox_access_token"},+ }+++def test_mcp_and_install_authority_agree_on_rejection() -> None:+ from jarvis.marketplace import agent_plugins_loader++ server = {"type": "sse", "url": "https://mcp.todofox.example/sse"}+ mcp_json = {"mcpServers": {"todo-fox": server}}+ value, errors = publish.validate_draft(_plugin_draft(mcp_json=mcp_json))+ assert value is None+ assert any(e["field"] == "mcp_json" and "sse" in e["error"] for e in errors)++ with pytest.raises(agent_plugins_loader.AgentPluginError, match="sse"):+ agent_plugins_loader.validate_mcp_server("todo-fox", server)+++def test_secret_pattern_rejected() -> None:+ draft = _skill_draft(skill_md="---\nname: x\n---\ntoken: ghp_" + "a" * 24)+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any("credential" in e["error"] for e in errors)+++# --- skill_md is judged by the same rule the install path uses -------------+#+# community_install.install_community_skill calls+# agent_plugins_loader.validate_bundled_skills for every standalone skill+# install; validate_draft must reject exactly what that call would reject,+# not a hand-rolled subset of it.+++def test_skill_frontmatter_missing_description_is_rejected() -> None:+ draft = _skill_draft(skill_md="---\nname: three-point-check\n---\n\nDo the thing.")+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "skill_md" for e in errors)+++def test_skill_frontmatter_risk_policy_is_rejected() -> None:+ draft = _skill_draft(+ skill_md=(+ "---\nname: three-point-check\ndescription: d\nrisk_policy: safe\n---\n\nDo the thing."+ )+ )+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "skill_md" and "risk_policy" in e["error"] for e in errors)+++def test_invalid_skill_name_does_not_also_report_skill_md() -> None:+ # A bad top-level name must not be reused as `plugin_name` for the+ # skill_md check — that would attribute a confusing second error to the+ # wrong field for a skill_md that was otherwise fine.+ draft = _skill_draft(name="UPPER")+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "name" for e in errors)+ assert not any(e["field"] == "skill_md" for e in errors)+++# --- bundled skills on a plugin submission ----------------------------------+++def _bundled_skill(name: str = "todo-fox-tips", **overrides: Any) -> dict[str, Any]:+ skill: dict[str, Any] = {+ "name": name,+ "skill_md": f"---\nname: {name}\ndescription: Tips for todo-fox.\n---\n\nDo the thing.",+ }+ skill.update(overrides)+ return skill+++def test_valid_bundled_skill_normalizes() -> None:+ value, errors = publish.validate_draft(_plugin_draft(skills=[_bundled_skill()]))+ assert errors == []+ assert value is not None+ assert value["skills"] == [_bundled_skill()]+++def test_bundled_skill_missing_description_is_rejected() -> None:+ bad = _bundled_skill(skill_md="---\nname: todo-fox-tips\n---\n\nDo the thing.")+ value, errors = publish.validate_draft(_plugin_draft(skills=[bad]))+ assert value is None+ assert any(e["field"] == "skills" for e in errors)+++def test_bundled_skill_risk_policy_is_rejected() -> None:+ bad = _bundled_skill(+ skill_md=(+ "---\nname: todo-fox-tips\ndescription: d\nrisk_policy: safe\n---\n\nDo the thing."+ )+ )+ value, errors = publish.validate_draft(_plugin_draft(skills=[bad]))+ assert value is None+ assert any(e["field"] == "skills" and "risk_policy" in e["error"] for e in errors)+++def test_bundled_skill_duplicate_name_is_rejected() -> None:+ skill = _bundled_skill()+ value, errors = publish.validate_draft(_plugin_draft(skills=[skill, skill]))+ assert value is None+ assert any(e["field"] == "skills" for e in errors)+++def test_bundled_skill_sharing_plugin_name_alone_is_allowed() -> None:+ skill = _bundled_skill(+ name="todo-fox",+ skill_md="---\nname: todo-fox\ndescription: d\n---\n\nDo the thing.",+ )+ value, errors = publish.validate_draft(_plugin_draft(skills=[skill]))+ assert errors == []+ assert value is not None+++def test_bundled_skill_sharing_plugin_name_with_others_is_rejected() -> None:+ same_name = _bundled_skill(+ name="todo-fox",+ skill_md="---\nname: todo-fox\ndescription: d\n---\n\nDo the thing.",+ )+ value, errors = publish.validate_draft(+ _plugin_draft(skills=[same_name, _bundled_skill(name="todo-fox-extra")])+ )+ assert value is None+ assert any(e["field"] == "skills" for e in errors)+++def test_too_many_bundled_skills_is_rejected() -> None:+ skills = [_bundled_skill(name=f"todo-fox-{i}") for i in range(11)]+ value, errors = publish.validate_draft(_plugin_draft(skills=skills))+ assert value is None+ assert any(e["field"] == "skills" for e in errors)+++# --- mcp.json: the two divergences closed in publish.py --------------------+++def test_mcp_rejects_latest_even_when_another_arg_looks_pinned() -> None:+ draft = _plugin_draft(+ mcp_json={+ "mcpServers": {"todo-fox": {"command": "npx", "args": ["[email protected]", "bar@latest"]}}+ }+ )+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "mcp_json" for e in errors)+++def test_mcp_rejects_the_servers_alias() -> None:+ draft = _plugin_draft(+ mcp_json={"servers": {"todo-fox": {"url": "https://mcp.todofox.example/mcp"}}}+ )+ value, errors = publish.validate_draft(draft)+ assert value is None+ assert any(e["field"] == "mcp_json" for e in errors)+++# --- submit ---------------------------------------------------------------+++def _transport(status: int, body: dict[str, Any]) -> httpx.MockTransport:+ return httpx.MockTransport(lambda request: httpx.Response(status, json=body))+++async def test_submit_posts_bearer_and_maps_the_pr(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "https://pj.example/api/submit")+ seen: dict[str, Any] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["auth"] = request.headers.get("Authorization")+ return httpx.Response(+ 201,+ json={"prUrl": "https://github.com/pr/1", "submissionPath": "submissions/x.json"},+ )++ value, _ = publish.validate_draft(_skill_draft())+ assert value is not None+ result = await publish.submit(+ value,+ store=FakeStore(Tokens(access="tok")), # type: ignore[arg-type]+ transport=httpx.MockTransport(handler),+ )+ assert result == {"pr_url": "https://github.com/pr/1", "submission_path": "submissions/x.json"}+ assert seen["auth"] == "Bearer tok"+++async def test_submit_without_token_is_401(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "https://pj.example/api/submit")+ value, _ = publish.validate_draft(_skill_draft())+ assert value is not None+ with pytest.raises(publish.SubmitError) as exc:+ await publish.submit(value, store=FakeStore(None)) # type: ignore[arg-type]+ assert exc.value.status == 401+++async def test_submit_passes_endpoint_refusal_through(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "https://pj.example/api/submit")+ value, _ = publish.validate_draft(_skill_draft())+ assert value is not None+ with pytest.raises(publish.SubmitError) as exc:+ await publish.submit(+ value,+ store=FakeStore(Tokens(access="tok")), # type: ignore[arg-type]+ transport=_transport(409, {"error": "name is owned by octocat", "field": "name"}),+ )+ assert exc.value.status == 409+ assert exc.value.field == "name"+++async def test_submit_disabled_deployment(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "")+ value, _ = publish.validate_draft(_skill_draft())+ assert value is not None+ with pytest.raises(publish.SubmitError) as exc:+ await publish.submit(value, store=FakeStore(Tokens(access="tok"))) # type: ignore[arg-type]+ assert exc.value.status == 503+++# --- live status ----------------------------------------------------------+++async def test_live_status_reports_the_feed_truthfully(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis.marketplace import community_source++ index = community_source.CommunityIndex.model_validate(+ {"skills": [{"name": "three-point-check", "version": "1.0.0"}]}+ )++ async def fake_get_index(force: bool = False) -> tuple[Any, str]:+ return index, "fresh"++ monkeypatch.setattr(community_source, "get_index", fake_get_index)+ assert (await publish.live_status("three-point-check", "1.0.0"))["live"] is True+ assert (await publish.live_status("three-point-check", "2.0.0"))["live"] is False+ assert (await publish.live_status("absent-name", "1.0.0"))["live"] is False+++# --- identity -------------------------------------------------------------+++async def test_identity_signed_in() -> None:+ state = await publish.current_identity(+ store=FakeStore(Tokens(access="tok")), # type: ignore[arg-type]+ transport=_transport(200, {"login": "octocat", "avatar_url": "https://a"}),+ )+ assert state == {"signed_in": True, "login": "octocat", "avatar_url": "https://a"}+++async def test_identity_dead_token_signs_out(monkeypatch: pytest.MonkeyPatch) -> None:+ class NoRefreshHandler:+ async def refresh(self, tokens: Tokens) -> Tokens:+ raise RuntimeError("revoked")++ monkeypatch.setattr(publish, "make_device_handler", lambda: NoRefreshHandler())+ store = FakeStore(Tokens(access="dead"))+ state = await publish.current_identity(+ store=store, # type: ignore[arg-type]+ transport=_transport(401, {}),+ )+ assert state == {"signed_in": False}+ assert store.deleted is Truediff --git a/tests/unit/marketplace/test_publish_routes.py b/tests/unit/marketplace/test_publish_routes.pynew file mode 100644index 0000000000..ad1b9f983e--- /dev/null+++ b/tests/unit/marketplace/test_publish_routes.py@@ -0,0 +1,200 @@+"""The publish routes: sign-in flow, validation, submit mapping — no network."""++from __future__ import annotations++import asyncio+from typing import Any++import httpx+import pytest+from fastapi import FastAPI++from jarvis.marketplace import publish+from jarvis.marketplace.auth.base import AuthSession, FlowResult+from jarvis.marketplace.token_store import Tokens+from jarvis.ui.web import marketplace_publish_routes as routes+++class FakeStore:+ tokens: Tokens | None = None++ def __init__(self) -> None: # each route call constructs one; share state+ pass++ def load(self, key: str) -> Tokens | None:+ return FakeStore.tokens++ def save(self, key: str, tokens: Tokens) -> None:+ FakeStore.tokens = tokens++ def delete(self, key: str) -> None:+ FakeStore.tokens = None+++class FakeHandler:+ """Device flow that approves instantly."""++ async def start(self, spec: object) -> AuthSession:+ return AuthSession(+ flow_id="flow-1",+ plugin_id=publish.PUBLISHER_TOKEN_ID,+ kind="device_flow",+ user_code="ABCD-1234",+ verification_uri="https://github.com/login/device",+ verification_uri_complete=None,+ expires_at_ms=0,+ interval=1,+ )++ async def await_completion(self, session: AuthSession) -> FlowResult:+ return FlowResult(tokens=Tokens(access="tok"), error=None)+++def client(monkeypatch: pytest.MonkeyPatch) -> httpx.AsyncClient:+ FakeStore.tokens = None+ monkeypatch.setattr(routes, "TokenStore", FakeStore)+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "https://pj.example/api/submit")+ monkeypatch.setattr(publish, "make_device_handler", lambda: FakeHandler())++ async def fake_fetch_identity(tokens: Tokens, transport: object = None) -> dict[str, Any]:+ return {"login": "octocat", "avatar_url": None}++ monkeypatch.setattr(publish, "fetch_identity", fake_fetch_identity)+ app = FastAPI()+ app.include_router(routes.router)+ return httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t")+++async def test_signin_start_then_poll_connects(client: httpx.AsyncClient) -> None:+ async with client:+ started = (await client.post("/api/marketplace/publish/signin/start")).json()+ assert started["user_code"] == "ABCD-1234"+ # The completion task runs on the same loop; yield until it settles.+ for _ in range(50):+ poll = (+ await client.get(f"/api/marketplace/publish/signin/poll/{started['flow_id']}")+ ).json()+ if poll["status"] != "pending":+ break+ await asyncio.sleep(0)+ assert poll == {"status": "connected", "login": "octocat", "avatar_url": None}+ assert FakeStore.tokens is not None and FakeStore.tokens.access == "tok"+++async def test_identity_reports_disabled_deployment(+ client: httpx.AsyncClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "")+ monkeypatch.setattr(publish, "publish_wallpaper_endpoint", lambda: "")+ async with client:+ state = (await client.get("/api/marketplace/publish/identity")).json()+ assert state == {"enabled": False, "wallpapers_enabled": False, "signed_in": False}+++async def test_the_two_lanes_are_reported_separately(+ client: httpx.AsyncClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A fork may run one lane without the other, and each surface hides its+ own button accordingly — so one flag cannot speak for both."""+ monkeypatch.setattr(publish, "publish_endpoint", lambda: "")+ monkeypatch.setattr(publish, "publish_wallpaper_endpoint", lambda: "https://pj.example/w")+ async with client:+ state = (await client.get("/api/marketplace/publish/identity")).json()+ assert state["enabled"] is False+ assert state["wallpapers_enabled"] is True+ # Still reports sign-in state: the wallpaper lane needs the same identity.+ assert "signed_in" in state+++async def test_sign_out_drops_the_token(client: httpx.AsyncClient) -> None:+ FakeStore.tokens = Tokens(access="tok")+ async with client:+ resp = await client.delete("/api/marketplace/publish/identity")+ assert resp.status_code == 200+ assert FakeStore.tokens is None+++async def test_validate_reports_every_field(client: httpx.AsyncClient) -> None:+ async with client:+ resp = await client.post(+ "/api/marketplace/publish/validate",+ json={"kind": "skill", "name": "UPPER", "version": "nope"},+ )+ body = resp.json()+ assert body["ok"] is False+ fields = {e["field"] for e in body["errors"]}+ assert {"name", "version", "title", "description", "skill_md"} <= fields+++async def test_submit_maps_endpoint_refusals(+ client: httpx.AsyncClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def refusing_submit(normalized: dict[str, Any], store: object = None) -> dict[str, Any]:+ raise publish.SubmitError(409, "name is owned by octocat", "name")++ monkeypatch.setattr(publish, "submit", refusing_submit)+ async with client:+ resp = await client.post(+ "/api/marketplace/publish/submit",+ json={+ "kind": "skill",+ "name": "taken-name",+ "version": "1.0.0",+ "title": "T",+ "description": "D",+ "skill_md": "---\nname: taken-name\ndescription: D\n---\nBody",+ },+ )+ assert resp.status_code == 409+ assert resp.json()["detail"] == {"error": "name is owned by octocat", "field": "name"}+++async def test_submit_happy_path(+ client: httpx.AsyncClient, monkeypatch: pytest.MonkeyPatch+) -> None:+ async def ok_submit(normalized: dict[str, Any], store: object = None) -> dict[str, Any]:+ return {"pr_url": "https://github.com/pr/9", "submission_path": "submissions/x.json"}++ monkeypatch.setattr(publish, "submit", ok_submit)+ async with client:+ resp = await client.post(+ "/api/marketplace/publish/submit",+ json={+ "kind": "skill",+ "name": "fresh-name",+ "version": "1.0.0",+ "title": "T",+ "description": "D",+ "skill_md": "---\nname: fresh-name\ndescription: D\n---\nBody",+ },+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["ok"] is True and body["pr_url"] == "https://github.com/pr/9"+ assert body["name"] == "fresh-name" and body["version"] == "1.0.0"+ # The line the author hands to everyone else. Computed by the one standard+ # module, so it cannot drift from what `jarvis marketplace install` accepts.+ assert body["install"] == {+ "cli": "jarvis marketplace install fresh-name",+ "runner": "uvx --from personal-jarvis jarvis marketplace install fresh-name",+ "prompt": 'Install the "fresh-name" skill from the community marketplace.',+ }+++async def test_submit_client_side_validation_answers_422(client: httpx.AsyncClient) -> None:+ async with client:+ resp = await client.post(+ "/api/marketplace/publish/submit",+ json={"kind": "skill", "name": "UPPER", "version": "1.0.0"},+ )+ assert resp.status_code == 422+ assert resp.json()["detail"]["field"] == "name"diff --git a/tests/unit/marketplace/test_publish_wallpaper.py b/tests/unit/marketplace/test_publish_wallpaper.pynew file mode 100644index 0000000000..cc10408a24--- /dev/null+++ b/tests/unit/marketplace/test_publish_wallpaper.py@@ -0,0 +1,426 @@+"""The wallpaper publish lane: field rules, byte handling, submit — no network.++The lane's promise is narrower than the package lane's and its failures are+different in kind, so it gets its own file: a wallpaper carries no manifest to+validate, but it does carry bytes a stranger produced, and the rules that+matter most here are the ones about those bytes.+"""++from __future__ import annotations++import io+from typing import Any++import httpx+import pytest++from jarvis.marketplace import publish+from jarvis.marketplace.token_store import Tokens+++def _draft(**overrides: Any) -> dict[str, Any]:+ draft: dict[str, Any] = {+ "title": "Rain Antenna City",+ "description": "Neon rooftops in the rain.",+ "license": "CC0-1.0",+ "theme": "dark",+ "rights": True,+ }+ draft.update(overrides)+ return draft+++class FakeStore:+ def __init__(self, tokens: Tokens | None = None) -> None:+ self._tokens = tokens++ def load(self, key: str) -> Tokens | None:+ return self._tokens++ def save(self, key: str, tokens: Tokens) -> None:+ self._tokens = tokens++ def delete(self, key: str) -> None:+ self._tokens = None+++def _png(width: int = 64, height: int = 32, *, with_exif: bool = False) -> bytes:+ """A real PNG, optionally carrying EXIF, as a browser would hand one over."""+ from PIL import Image++ image = Image.new("RGB", (width, height), (40, 60, 90))+ buffer = io.BytesIO()+ if with_exif:+ exif = Image.Exif()+ # 0x9286 = UserComment, 0x0001 under GPSInfo would be the interesting+ # one in the field; either proves the round trip drops what it carried.+ exif[0x9286] = "shot at home"+ image.save(buffer, "PNG", exif=exif)+ else:+ image.save(buffer, "PNG")+ return buffer.getvalue()+++# --- validate_wallpaper_draft ---------------------------------------------+++def test_valid_draft_normalizes_to_the_form_the_endpoint_reads() -> None:+ fields, errors = publish.validate_wallpaper_draft(_draft())+ assert errors == []+ assert fields == {+ "title": "Rain Antenna City",+ "license": "CC0-1.0",+ "rights": "yes",+ "description": "Neon rooftops in the rain.",+ "theme": "dark",+ }+++def test_optional_fields_are_omitted_rather_than_sent_empty() -> None:+ fields, errors = publish.validate_wallpaper_draft(_draft(description="", theme=""))+ assert errors == [] and fields is not None+ assert "description" not in fields and "theme" not in fields+++ ("overrides", "field"),+ [+ ({"title": ""}, "title"),+ ({"title": "x" * (publish.MAX_TITLE_CHARS + 1)}, "title"),+ # Slugifies to nothing at the endpoint, which would 422 after the+ # upload had already travelled.+ ({"title": "!!! ---"}, "title"),+ ({"description": "x" * (publish.MAX_DESCRIPTION_CHARS + 1)}, "description"),+ ({"license": ""}, "license"),+ ({"license": "MIT"}, "license"),+ ({"license": "All rights reserved"}, "license"),+ ({"theme": "sepia"}, "theme"),+ ({"rights": False}, "rights"),+ ],+)+def test_rejections_carry_the_field(overrides: dict[str, Any], field: str) -> None:+ fields, errors = publish.validate_wallpaper_draft(_draft(**overrides))+ assert fields is None+ assert any(e["field"] == field for e in errors)+++def test_every_advertised_license_is_accepted() -> None:+ for license_id in publish.WALLPAPER_LICENSES:+ fields, errors = publish.validate_wallpaper_draft(_draft(license=license_id))+ assert errors == [] and fields is not None+++def test_the_rights_statement_cannot_be_faked_with_a_truthy_string() -> None:+ """``"no"`` is truthy in Python — the check must be identity, not truth."""+ fields, errors = publish.validate_wallpaper_draft(_draft(rights="no"))+ assert fields is None+ assert any(e["field"] == "rights" for e in errors)+++# --- prepare_wallpaper_image ----------------------------------------------+++def test_the_published_bytes_are_re_encoded_webp_not_the_originals() -> None:+ original = _png()+ encoded, filename = publish.prepare_wallpaper_image(original)+ assert filename == "wallpaper.webp"+ assert encoded[:4] == b"RIFF" and encoded[8:12] == b"WEBP"+ assert encoded != original+++def test_exif_does_not_survive_the_round_trip() -> None:+ from PIL import Image++ carrying = _png(with_exif=True)+ with Image.open(io.BytesIO(carrying)) as before:+ assert dict(before.getexif()) # the fixture really did carry something++ encoded, _ = publish.prepare_wallpaper_image(carrying)+ with Image.open(io.BytesIO(encoded)) as after:+ assert not dict(after.getexif())+++def test_an_oversized_picture_is_capped_at_4k_rather_than_refused() -> None:+ from PIL import Image++ encoded, _ = publish.prepare_wallpaper_image(_png(5000, 2500))+ with Image.open(io.BytesIO(encoded)) as result:+ assert result.width == 3840+++def test_a_picture_under_the_cap_keeps_its_size() -> None:+ from PIL import Image++ encoded, _ = publish.prepare_wallpaper_image(_png(1200, 800))+ with Image.open(io.BytesIO(encoded)) as result:+ assert (result.width, result.height) == (1200, 800)+++ ("data", "status"),+ [+ (b"", 422),+ (b"not an image at all", 422),+ # A forged header with no image behind it: the declared type never+ # decides anything, the decoder does.+ (b"\x89PNG\r\n\x1a\n" + b"junk" * 20, 422),+ ],+)+def test_bytes_that_are_not_an_image_are_refused(data: bytes, status: int) -> None:+ with pytest.raises(publish.SubmitError) as exc:+ publish.prepare_wallpaper_image(data)+ assert exc.value.status == status+ assert exc.value.field == "file"+++def test_the_result_stays_inside_the_endpoints_size_cap() -> None:+ encoded, _ = publish.prepare_wallpaper_image(_png(3840, 2160))+ assert len(encoded) <= publish.MAX_WALLPAPER_BYTES+++# --- submit_wallpaper ------------------------------------------------------+++async def test_submit_sends_bearer_multipart_and_returns_the_server_name(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ publish, "publish_wallpaper_endpoint", lambda: "https://pj.example/api/submit-wallpaper"+ )+ seen: dict[str, Any] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["auth"] = request.headers.get("Authorization")+ seen["type"] = request.headers.get("Content-Type", "")+ seen["body"] = request.content+ return httpx.Response(201, json={"name": "rain-antenna-city"})++ fields, _ = publish.validate_wallpaper_draft(_draft())+ assert fields is not None+ result = await publish.submit_wallpaper(+ fields,+ b"IMAGEBYTES",+ store=FakeStore(Tokens(access="tok")), # type: ignore[arg-type]+ transport=httpx.MockTransport(handler),+ )++ assert result == {"name": "rain-antenna-city"}+ assert seen["auth"] == "Bearer tok"+ assert seen["type"].startswith("multipart/form-data")+ # The rights statement and the picture both have to be in the body — the+ # endpoint refuses without either, and a form that quietly dropped one+ # would fail far from where it was caused.+ assert b'name="rights"' in seen["body"] and b"yes" in seen["body"]+ assert b"IMAGEBYTES" in seen["body"]+++async def test_the_client_never_claims_a_publisher(monkeypatch: pytest.MonkeyPatch) -> None:+ """Identity comes from the token. Anything else would be a claim to check."""+ monkeypatch.setattr(+ publish, "publish_wallpaper_endpoint", lambda: "https://pj.example/api/submit-wallpaper"+ )+ seen: dict[str, Any] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen["body"] = request.content+ return httpx.Response(201, json={"name": "x"})++ fields, _ = publish.validate_wallpaper_draft(_draft())+ assert fields is not None+ await publish.submit_wallpaper(+ fields,+ b"IMAGEBYTES",+ store=FakeStore(Tokens(access="tok")), # type: ignore[arg-type]+ transport=httpx.MockTransport(handler),+ )+ assert b'name="publisher"' not in seen["body"]+ assert b'name="publisher_id"' not in seen["body"]+++async def test_submit_without_a_token_is_401(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ publish, "publish_wallpaper_endpoint", lambda: "https://pj.example/api/submit-wallpaper"+ )+ with pytest.raises(publish.SubmitError) as exc:+ await publish.submit_wallpaper({"title": "x"}, b"bytes", store=FakeStore(None)) # type: ignore[arg-type]+ assert exc.value.status == 401+++async def test_the_quota_refusal_reaches_the_user_verbatim(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ publish, "publish_wallpaper_endpoint", lambda: "https://pj.example/api/submit-wallpaper"+ )+ with pytest.raises(publish.SubmitError) as exc:+ await publish.submit_wallpaper(+ {"title": "x"},+ b"bytes",+ store=FakeStore(Tokens(access="tok")), # type: ignore[arg-type]+ transport=httpx.MockTransport(+ lambda request: httpx.Response(+ 429, json={"error": "daily limit of 3 wallpaper uploads reached"}+ )+ ),+ )+ assert exc.value.status == 429+ assert "daily limit" in exc.value.error+++async def test_a_deployment_without_the_lane_says_so(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(publish, "publish_wallpaper_endpoint", lambda: "")+ with pytest.raises(publish.SubmitError) as exc:+ await publish.submit_wallpaper({"title": "x"}, b"bytes", store=FakeStore(None)) # type: ignore[arg-type]+ assert exc.value.status == 503+++async def test_an_unreachable_endpoint_is_502_not_a_crash(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ publish, "publish_wallpaper_endpoint", lambda: "https://pj.example/api/submit-wallpaper"+ )++ def boom(request: httpx.Request) -> httpx.Response:+ raise httpx.ConnectError("no route to host")++ with pytest.raises(publish.SubmitError) as exc:+ await publish.submit_wallpaper(+ {"title": "x"},+ b"bytes",+ store=FakeStore(Tokens(access="tok")), # type: ignore[arg-type]+ transport=httpx.MockTransport(boom),+ )+ assert exc.value.status == 502+++# --- live_status -----------------------------------------------------------+++async def test_live_status_sees_a_published_wallpaper(monkeypatch: pytest.MonkeyPatch) -> None:+ """A wallpaper is live when the same feed the store reads carries it."""+ from jarvis.marketplace import community_source++ index = community_source.CommunityIndex(+ revision=13,+ wallpapers=[+ {+ "name": "rain-antenna-city",+ "version": "1.0.0",+ "title": "Rain Antenna City",+ "image_url": "https://example.invalid/rain.webp",+ }+ ],+ )++ async def fake_get_index(force: bool = False) -> tuple[Any, str]:+ return index, "ok"++ monkeypatch.setattr(community_source, "get_index", fake_get_index)+ assert (await publish.live_status("rain-antenna-city", "1.0.0"))["live"] is True+ assert (await publish.live_status("rain-antenna-city", "2.0.0"))["live"] is False+++# --- POST /api/marketplace/publish/submit-wallpaper ------------------------+++def route_client(monkeypatch: pytest.MonkeyPatch, tmp_path: Any) -> Any:+ """The route wired to a wallpaper store on disk and a stubbed endpoint."""+ from fastapi import FastAPI++ from jarvis.ui.web import marketplace_publish_routes as routes+ from jarvis.ui.web.wallpapers import WallpaperUploads++ store = WallpaperUploads(root=tmp_path / "uploads")+ monkeypatch.setattr(routes, "TokenStore", lambda: FakeStore(Tokens(access="tok")))+ monkeypatch.setattr("jarvis.ui.web.wallpapers.WallpaperUploads", lambda: store)+ monkeypatch.setattr(+ publish, "publish_wallpaper_endpoint", lambda: "https://pj.example/api/submit-wallpaper"+ )++ async def fake_submit(fields: Any, image: bytes, filename: str = "wallpaper.webp") -> Any:+ return {"name": "rain-antenna-city"}++ monkeypatch.setattr(publish, "submit_wallpaper", fake_submit)++ app = FastAPI()+ app.include_router(routes.router)+ client = httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://t")+ return client, store+++async def test_route_publishes_one_of_the_pickers_own_pictures(route_client: Any) -> None:+ client, store = route_client+ item = store.add(_png(), "my-city.png")+ async with client:+ resp = await client.post(+ "/api/marketplace/publish/submit-wallpaper",+ json={**_draft(), "upload_id": item.id},+ )+ assert resp.status_code == 200+ body = resp.json()+ assert body["name"] == "rain-antenna-city"+ assert body["version"] == "1.0.0"+ # The line other people will run to get it — computed by the same module+ # the store and the CLI use, never spelled out in the view.+ assert body["install"]+++async def test_route_refuses_to_republish_an_imported_community_picture(+ route_client: Any,+) -> None:+ """Someone else's wallpaper must not get a new author by passing through+ the picker — that would launder authorship, not share a picture."""+ client, store = route_client+ from jarvis.ui.web.wallpapers import WallpaperOrigin++ item = store.add(+ _png(),+ "borrowed.png",+ source="marketplace",+ origin=WallpaperOrigin(source_id="rain-antenna-city", publisher="someone"),+ )+ async with client:+ resp = await client.post(+ "/api/marketplace/publish/submit-wallpaper",+ json={**_draft(), "upload_id": item.id},+ )+ assert resp.status_code == 409+ assert "community" in resp.json()["detail"]["error"]+++async def test_route_reports_a_vanished_picture_as_404(route_client: Any) -> None:+ client, _ = route_client+ async with client:+ resp = await client.post(+ "/api/marketplace/publish/submit-wallpaper",+ json={**_draft(), "upload_id": "u0000000000000000"},+ )+ assert resp.status_code == 404+++async def test_route_checks_the_fields_before_it_touches_the_image(+ route_client: Any,+) -> None:+ client, _ = route_client+ async with client:+ resp = await client.post(+ "/api/marketplace/publish/submit-wallpaper",+ # No upload exists under this id — a 422 rather than a 404 proves+ # the field check ran first, which is what the form needs.+ json={**_draft(), "upload_id": "u0000000000000000", "rights": False},+ )+ assert resp.status_code == 422+ assert resp.json()["detail"]["field"] == "rights"diff --git a/tests/unit/marketplace/test_publish_wire_shape.py b/tests/unit/marketplace/test_publish_wire_shape.pynew file mode 100644index 0000000000..9d48d1bbb9--- /dev/null+++ b/tests/unit/marketplace/test_publish_wire_shape.py@@ -0,0 +1,69 @@+"""The publish wire model must carry every field the validator reads.++`SubmissionDraft` is a pydantic model with the default `extra="ignore"`, so a+key the form sends but the model does not declare is dropped *silently* — no+error, no warning. The submission then travels on without that piece and the+author is told it succeeded.++That is not hypothetical: the Publish tab sent bundled `skills`, the model+discarded them, and `validate_draft`'s whole bundled-skill rule set ran against+`None` on every real request. A package published with skills arrived in the+store without them.++These tests pin the invariant structurally, so the next field added to the form+cannot repeat it.+"""++from __future__ import annotations++import inspect+import re++from jarvis.marketplace import publish+from jarvis.ui.web.marketplace_publish_routes import SubmissionDraft++# Keys `validate_draft` (and the helpers it calls in the same module) read off+# the incoming draft dict.+_DRAFT_GET_RE = re.compile(r"draft\.get\(\s*[\"']([a-z_]+)[\"']")+++def _keys_the_validator_reads() -> set[str]:+ source = inspect.getsource(publish.validate_draft)+ return set(_DRAFT_GET_RE.findall(source))+++def test_wire_model_declares_every_field_the_validator_reads() -> None:+ """A key the validator reads but the model omits is silently dropped.++ The failure mode is a success message over an incomplete package, which is+ worse than a rejection: the author has no reason to look.+ """+ declared = set(SubmissionDraft.model_fields)+ read = _keys_the_validator_reads()+ missing = read - declared+ assert not missing, (+ f"validate_draft reads {sorted(missing)}, but SubmissionDraft does not "+ f"declare them — pydantic drops undeclared keys silently, so these "+ f"never reach the validator. Declare them on the model."+ )+++def test_bundled_skills_survive_the_wire_model() -> None:+ """The regression itself: skills must reach `validate_draft` intact."""+ draft = SubmissionDraft(+ kind="plugin",+ name="todo-fox",+ version="1.0.0",+ skills=[{"name": "three-bullet-brief", "skill_md": "---\nname: x\n---\n"}],+ )+ dumped = draft.model_dump()+ assert dumped["skills"] == [+ {"name": "three-bullet-brief", "skill_md": "---\nname: x\n---\n"}+ ]+++def test_a_submission_without_skills_still_dumps_the_key_as_none() -> None:+ """A plain connector keeps working — `None`, not a missing key, so the+ validator's `draft.get("skills")` branch reads the same either way."""+ draft = SubmissionDraft(kind="plugin", name="todo-fox", version="1.0.0")+ assert draft.model_dump()["skills"] is None