The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(vault): fill saved logins on Camofox pages through a browser page backend seam
Teknium0a93a2341fb7
diff --git a/agent/browser_page_backend.py b/agent/browser_page_backend.pynew file mode 100644index 00000000000..bf1579413ab--- /dev/null+++ b/agent/browser_page_backend.py@@ -0,0 +1,37 @@+"""Browser page backend ABC: a browser that owns its pages outside Hermes's CDP session.++``browser_vault`` inspects and fills the page the agent is driving. For ``browser_exec`` that page sits+behind the task's CDP supervisor. A plugin browser with its own transport (Camofox's REST server) has+no CDP endpoint, so it registers one of these via :meth:`PluginContext.register_browser_page_backend`+and the vault evaluates its inspection, origin-check and fill scripts through it instead.++Core keeps the secret contract: it wraps every secret-bearing script so a page exception never reaches+the backend's error text, replaces any failure on that path with fixed text, and registers the filled+value with the browser-result redaction boundary. The backend only carries the script to its page.+"""++from __future__ import annotations++import abc+from typing import Any++from agent.provider_base import ProviderBase+++class BrowserPageBackend(ProviderBase):+ """A plugin browser whose live page ``browser_vault`` can evaluate JavaScript on."""++ @abc.abstractmethod+ def has_page(self, task_id: str) -> bool:+ """True when this backend already holds a live page for ``task_id`` (the agent navigated it).++ Cheap and side-effect free: never open a tab or a session to answer. ``False`` lets the vault+ fall back to the CDP session."""++ @abc.abstractmethod+ def evaluate(self, task_id: str, expression: str, *, secret: bool) -> Any:+ """Evaluate ``expression`` on the task's current page and return its value; raise on failure.++ Never open a tab. With ``secret=True`` the expression embeds a credential: send it only over a+ transport that keeps it out of argv and off the network in clear text (loopback or HTTPS), never+ follow a redirect with it, and never log it. Exception text on that path is discarded by core."""diff --git a/agent/browser_page_registry.py b/agent/browser_page_registry.pynew file mode 100644index 00000000000..0e553746c7e--- /dev/null+++ b/agent/browser_page_registry.py@@ -0,0 +1,29 @@+"""Browser page backends registered by plugins via :meth:`PluginContext.register_browser_page_backend`,+consumed by ``tools.browser_vault_tool``. The backend holding the task's live page wins over the CDP+session; with none, the vault uses the CDP supervisor as before."""++from __future__ import annotations++import logging+from typing import Optional++from agent.browser_page_backend import BrowserPageBackend+from agent.provider_registry import ProviderRegistry++logger = logging.getLogger(__name__)++_registry: ProviderRegistry[BrowserPageBackend] = ProviderRegistry(+ label="Browser page backend", provider_cls=BrowserPageBackend, logger=logger,+)+_registry.export(globals())+++def backend_for_task(task_id: str) -> Optional[BrowserPageBackend]:+ """The registered backend holding ``task_id``'s live page, or ``None``."""+ for backend in _registry.list_providers():+ try:+ if backend.has_page(task_id):+ return backend+ except Exception as exc: # health: allow BLE001 -- a probing failure means "no page here"+ logger.debug("browser page backend %s.has_page raised %s", backend.name, exc)+ return Nonediff --git a/hermes_cli/plugin_isolation.py b/hermes_cli/plugin_isolation.pyindex 2582bee07c1..b6014d53946 100644--- a/hermes_cli/plugin_isolation.py+++ b/hermes_cli/plugin_isolation.py@@ -34,6 +34,7 @@ _ISOLATION_MODES = frozenset({ISOLATION_IN_PROCESS, ISOLATION_HOST})# launch-scope dashboard auth registry. A plugin calling one of these runs only in-process.HOST_UNSUPPORTED_CTX_METHODS: dict[str, str] = {"register_login_backend": "browser-vault fills hold a server-local context manager",+ "register_browser_page_backend": "browser-vault fill scripts carry credentials that stay in the Hermes process","register_platform": "platform adapters run on the gateway's event loop with native SDK clients","register_platform_handler": "the handler factory receives the platform's native SDK client","register_telegram_handler": "the handler factory receives the native Telegram Application",diff --git a/hermes_cli/plugins_cmd_catalog.py b/hermes_cli/plugins_cmd_catalog.pyindex 3f3dfd649e1..396f120b38b 100644--- a/hermes_cli/plugins_cmd_catalog.py+++ b/hermes_cli/plugins_cmd_catalog.py@@ -210,7 +210,18 @@ LOGIN_BACKEND_RULE = ("password-manager login backends are accepted only from pl_NON_CATALOG_SOURCES = {"project": "a project .hermes/plugins directory", "entrypoint": "a pip entry point"}-def login_backend_provenance_error(manifest) -> str:+BROWSER_PAGE_BACKEND_RULE = ("browser page backends (which carry browser_vault fill scripts) are accepted only from "+ "plugins bundled with Hermes or installed from the Hermes plugin catalog at tier "+ "verified or official")+++def browser_page_backend_provenance_error(manifest) -> str:+ """Why *manifest*'s plugin may not register a browser page backend, or "" when it may (same record and+ tiers as :func:`login_backend_provenance_error`: the backend receives secret-bearing fill scripts)."""+ return login_backend_provenance_error(manifest, rule=BROWSER_PAGE_BACKEND_RULE)+++def login_backend_provenance_error(manifest, rule: str = LOGIN_BACKEND_RULE) -> str:"""Why *manifest*'s plugin may not register a login backend, or "" when it may.Read from the installer-owned ``.install-metadata.json`` record of the CURRENT home's plugins dir, never@@ -219,19 +230,19 @@ def login_backend_provenance_error(manifest) -> str:if manifest.source == "bundled":return ""if manifest.source in _NON_CATALOG_SOURCES:- return f"{LOGIN_BACKEND_RULE}; this plugin was loaded from {_NON_CATALOG_SOURCES[manifest.source]}"+ return f"{rule}; this plugin was loaded from {_NON_CATALOG_SOURCES[manifest.source]}"record = _install_record(Path(manifest.path)) if manifest.source == "user" and manifest.path else Noneblock = (record or {}).get("catalog")if not isinstance(block, dict) or not block.get("name"):- return (f"{LOGIN_BACKEND_RULE}; this plugin was not installed from the Hermes plugin catalog "+ return (f"{rule}; this plugin was not installed from the Hermes plugin catalog ""(a local directory or Git URL install)")if record.get("allow_removed"):- return f"{LOGIN_BACKEND_RULE}; this plugin was installed with --allow-removed"+ return f"{rule}; this plugin was installed with --allow-removed"tier = str(block.get("tier") or "community")if tier not in LOGIN_BACKEND_TIERS:- return f"{LOGIN_BACKEND_RULE}; catalog entry '{block['name']}' is tier {tier}"+ return f"{rule}; catalog entry '{block['name']}' is tier {tier}"if not block.get("pin"):- return f"{LOGIN_BACKEND_RULE}; this install is not at the catalog's reviewed pin (installed with --ref)"+ return f"{rule}; this install is not at the catalog's reviewed pin (installed with --ref)"return ""diff --git a/hermes_cli/plugins_registrars.py b/hermes_cli/plugins_registrars.pyindex 7323e42a0ef..3bf95e6f7b4 100644--- a/hermes_cli/plugins_registrars.py+++ b/hermes_cli/plugins_registrars.py@@ -31,6 +31,13 @@ _SCOPED_PROVIDER_REGISTRARS: tuple[tuple[str, str, str, str, str, str, dict[str,"plugins and catalog installs at tier verified or official.",{"normalize": None, "reject_message": "Plugin '%s' login backend rejected: %s","admit": "hermes_cli.plugins_cmd_catalog:login_backend_provenance_error", "identity": "static_name"}),+ ("register_browser_page_backend", "browser_page_backend", "agent.browser_page_registry",+ "agent.browser_page_backend:BrowserPageBackend", "browser page backend",+ "Register an :class:`agent.browser_page_backend.BrowserPageBackend` so ``browser_vault`` inspects and "+ "fills the pages of a browser with no CDP endpoint (Camofox). Profile-scoped, removed on plugin "+ "unload; accepted only from bundled plugins and catalog installs at tier verified or official.",+ {"reject_message": "Plugin '%s' browser page backend rejected: %s",+ "admit": "hermes_cli.plugins_cmd_catalog:browser_page_backend_provenance_error"}),("register_image_gen_provider", "image_gen_provider", "agent.image_gen_registry","agent.image_gen_provider:ImageGenProvider", "image_gen provider","Register an :class:`agent.image_gen_provider.ImageGenProvider`; "diff --git a/tests/tools/test_browser_vault_page_backend.py b/tests/tools/test_browser_vault_page_backend.pynew file mode 100644index 00000000000..2c5254e900b--- /dev/null+++ b/tests/tools/test_browser_vault_page_backend.py@@ -0,0 +1,83 @@+"""browser_vault on a plugin browser with no CDP endpoint (Camofox): the registered+``BrowserPageBackend`` holding the task's page carries every vault script, and the secret path never+lets a page or backend error echo the credential."""++import json+from unittest.mock import patch++import pytest++from agent.browser_page_backend import BrowserPageBackend+from agent.vault_store import VaultStore++SECRET = "s3cret-pw"+CONTROLS = [+ {"autocomplete": "email", "formIndex": 0, "index": 0, "label": "", "name": "email", "type": "email"},+ {"autocomplete": "current-password", "formIndex": 0, "index": 1, "label": "", "name": "pw", "type": "password"},+]+++class FakePage(BrowserPageBackend):+ name = "fakepage"++ def __init__(self, url):+ self.url, self.calls, self.fail_secret = url, [], False++ def has_page(self, task_id):+ return True++ def evaluate(self, task_id, expression, *, secret):+ self.calls.append((expression, secret))+ if secret and self.fail_secret:+ raise RuntimeError(f"page.evaluate failed: {expression}")+ if "location.href" in expression:+ return self.url+ if SECRET in expression:+ return json.dumps({"filled": 1})+ return json.dumps(CONTROLS)+++def page(tmp_path, monkeypatch):+ from agent import browser_page_registry+ from tools import browser_vault_tool++ def cdp_used(*args, **kwargs):+ raise AssertionError("CDP supervisor used while a page backend holds the task's page")++ monkeypatch.setattr(browser_vault_tool, "_ensure_supervisor", cdp_used)+ fake = FakePage("https://example.com/login")+ browser_page_registry.register_provider(fake)+ store = VaultStore(base_dir=tmp_path / "vault")+ meta = store.add_item(kind="login", label="Example", origin="https://example.com",+ secret={"identifier_type": "email", "identifier": "[email protected]", "password": SECRET})+ with patch("agent.vault_store.get_vault_store", return_value=store):+ yield fake, meta+ browser_page_registry._reset_for_tests()+++def test_fill_runs_on_the_page_backend_and_refuses_another_origin(page):+ from tools import browser_vault_tool++ fake, meta = page+ raw = browser_vault_tool.browser_vault_fill(meta.id)+ out = json.loads(raw)+ assert out["success"] is True and out["filled_fields"] == 1 and SECRET not in raw+ secret_calls = [expr for expr, secret in fake.calls if SECRET in expr]+ assert len(secret_calls) == 1 and all(secret for expr, secret in fake.calls if SECRET in expr)++ fake.calls.clear()+ fake.url = "https://evil.example/login"+ out = json.loads(browser_vault_tool.browser_vault_fill(meta.id))+ assert out["error_type"] == "origin_mismatch"+ assert not any(SECRET in expr for expr, _ in fake.calls)+++def test_secret_failure_never_echoes_the_script(page):+ from tools import browser_vault_tool++ fake, meta = page+ fake.fail_secret = True+ raw = browser_vault_tool.browser_vault_fill(meta.id)+ out = json.loads(raw)+ assert out["success"] is False and SECRET not in rawdiff --git a/tools/browser_vault_tool.py b/tools/browser_vault_tool.pyindex 547abbcb2b5..b6c8406ba2b 100644--- a/tools/browser_vault_tool.py+++ b/tools/browser_vault_tool.py@@ -13,7 +13,8 @@ paid per request) and available wherever a browser is. Its actions:resolved locally, the page origin must EXACTLY match the item's boundorigin (pre-checked AND re-asserted synchronously inside the fill script),the field is chosen by the ported login-control classifier, injection runs- exclusively over the supervisor CDP WebSocket (never argv), and the tool+ exclusively over the supervisor CDP WebSocket (never argv) — or, for a plugin browser with no CDP+ endpoint, through its registered ``BrowserPageBackend`` (Camofox's REST evaluate) — and the toolresult reports only ``{filled_fields, kind, origin, success}`` — thepassword never appears in tool results, logs, or the session DB, and itsexact bytes are registered with the browser-result redaction boundary so@@ -46,18 +47,50 @@ def _check_vault_available() -> bool:"""Schema-gate: the vault rides with the browser. An empty vault still needs save_login so theagent can offer to remember a login the first time it meets a form; hiding the tool until an itemexists meant nobody ever discovered the feature. Deferral keeps that presence nearly free."""+ from agent.browser_page_registry import list_providersfrom tools.browser_session_cdp import get_cdp_override_rawfrom tools.browser_use_cli import browser_exec_available- return bool(browser_exec_available() or get_cdp_override_raw())+ return bool(browser_exec_available() or get_cdp_override_raw() or list_providers())# ---------------------------------------------------------------------------# JS evaluation plumbing (server-side; results never carry secret values)# ---------------------------------------------------------------------------+# A secret-bearing script runs inside this wrapper on a page backend, so a page exception is answered+# in-page and its message (which may quote the script) never reaches the backend's error path or logs.+_PAGE_FILL_FAILED = {"hermes_vault_eval_failed": True}+++def _page_backend(task_id: str):+ """The plugin browser holding this task's live page (e.g. Camofox), or None for the CDP session."""+ from agent.browser_page_registry import backend_for_task+ return backend_for_task(task_id)+++def _page_eval(backend: Any, task_id: str, expression: str, *, secret: bool) -> dict[str, Any]:+ """Evaluate on a plugin page backend. On the secret path every failure gets fixed text."""+ if secret:+ expression = ("(() => { try { return (" + expression + "); } catch (_) { return "+ + json.dumps(_PAGE_FILL_FAILED) + "; } })()")+ try:+ result = backend.evaluate(task_id, expression, secret=secret)+ except Exception as exc: # health: allow BLE001 -- plugin failure becomes a typed refusal+ detail = "" if secret else f": {str(exc)[:200]}"+ return {"success": False, "error_type": "eval_failed",+ "error": f"The {backend.name} browser could not run the vault script{detail}"}+ if secret and _parse_json_result(result) == _PAGE_FILL_FAILED:+ return {"success": False, "error_type": "eval_failed",+ "error": f"The {backend.name} browser could not run the vault script"}+ return {"success": True, "result": result}++def _eval_js(task_id: str, expression: str) -> dict[str, Any]:- """Evaluate NON-SECRET JS on the current page (inspection, origin reads) over the task's CDP- supervisor. There is no other path: without a supervisor the call reports it."""+ """Evaluate NON-SECRET JS on the current page (inspection, origin reads): on the plugin browser+ holding the task's page, else over the task's CDP supervisor. Without either the call reports it."""+ page = _page_backend(task_id)+ if page is not None:+ return _page_eval(page, task_id, expression, secret=False)supervisor = _ensure_supervisor(task_id)if supervisor is None:return {"success": False, "error": "no supervised browser session for this task; open the page with "@@ -99,15 +132,18 @@ def _eval_js_secret(task_id: str, expression: str) -> dict[str, Any]:place the expression — and therefore the credential bytes — in argv,visible to any process listing. When no supervisor session is availablethe caller gets a typed refusal (``error_type='supervisor_required'``) and- nothing is written.+ nothing is written. A plugin browser holding the task's page (no CDP endpoint) carries the+ expression over its own transport instead; see ``agent.browser_page_backend``."""- try:- supervisor = _ensure_supervisor(task_id)- except Exception as exc:- logger.debug("vault fill: supervisor unavailable (%s)", exc)- supervisor = None+ page = _page_backend(task_id)+ supervisor = None+ if page is None:+ try:+ supervisor = _ensure_supervisor(task_id)+ except Exception as exc:+ logger.debug("vault fill: supervisor unavailable (%s)", exc)- if supervisor is None:+ if page is None and supervisor is None:return {"success": False,"error_type": "supervisor_required",@@ -129,6 +165,8 @@ def _eval_js_secret(task_id: str, expression: str) -> dict[str, Any]:except _bd_lease.HumanHasControl as exc:return {"success": False, "error_type": "human_has_control", "error": str(exc)}+ if page is not None:+ return _page_eval(page, task_id, expression, secret=True)sup = supervisor.evaluate_runtime(expression)if sup.get("ok"):return {"success": True, "result": sup.get("result")}@@ -176,7 +214,10 @@ _TAB_PROBES = {def _focus_bound_origin(task_id: str, origin: str, kind: str) -> Optional[str]:"""Point the supervisor's page session at the open tab on ``origin`` that holds a ``kind`` form(browser_exec sessions open their own tabs, so the tab the supervisor attached to first is rarely the- login page). Returns the origin when a tab was focused, else None (caller falls back to the current page)."""+ login page). Returns the origin when a tab was focused, else None (caller falls back to the current page).+ A plugin page backend's current page IS the tab the agent drove, so there is nothing to focus."""+ if _page_backend(task_id) is not None:+ return Nonetry:supervisor = _ensure_supervisor(task_id)except Exception:diff --git a/website/docs/developer-guide/browser-vault-plugin.md b/website/docs/developer-guide/browser-vault-plugin.mdindex b538b352e12..ec33caa5f86 100644--- a/website/docs/developer-guide/browser-vault-plugin.md+++ b/website/docs/developer-guide/browser-vault-plugin.md@@ -112,3 +112,40 @@ failed. A fill lock does not serialize unrelated browser navigation.Raise exceptions with fixed diagnostics. Hermes discards your exception text, but your own logs maystill record it, so never put credential values or secret-manager response bodies in it. Never exposea model-facing tool that returns a password: it would bypass every rule above.++## Browser page backends++A plugin browser that has no CDP endpoint (Camofox talks to its own REST server) cannot be reached by+the vault's supervisor, so `browser_vault` would refuse every fill with "Could not determine the+current page origin". Such a plugin registers an `agent.browser_page_backend.BrowserPageBackend`:++```python+from agent.browser_page_backend import BrowserPageBackend+++class MyBrowserPages(BrowserPageBackend):+ name = "mybrowser"++ def has_page(self, task_id: str) -> bool:+ ... # True when this task already has a live tab here; never open one to answer++ def evaluate(self, task_id: str, expression: str, *, secret: bool):+ ... # run the script on that tab and return its value; raise on failure+++def register(ctx):+ if hasattr(ctx, "register_browser_page_backend"): # older cores lack the seam+ ctx.register_browser_page_backend(MyBrowserPages())+```++When `has_page(task_id)` is true, the vault reads the page origin, inspects the form and writes the+password through `evaluate` instead of CDP. Everything else stays core's: the exact-origin pre-check+and in-page re-check, payment confirmation, the Bot Desktop takeover check, redaction of the filled+value. A secret-bearing script (`secret=True`) arrives wrapped so a page exception is answered in-page,+and any failure on that path is reported with fixed text, so your exception never reaches the model.+Send a secret script only over a transport that keeps it out of argv and off the network in clear text+(loopback or HTTPS), never follow a redirect with it, and never log it.++The provenance rule above applies here too (bundled, or catalog `verified`/`official` at its pin),+and the registration is refused under `plugins.isolation: host`, because the fill script carries the+credential and must stay in the Hermes process.diff --git a/website/docs/user-guide/features/credential-vault.md b/website/docs/user-guide/features/credential-vault.mdindex f4531f62598..b023c8c7953 100644--- a/website/docs/user-guide/features/credential-vault.md+++ b/website/docs/user-guide/features/credential-vault.md@@ -164,7 +164,10 @@ vault:tool results, logs, the session database, or the CLI arguments of any process.Fills happen over the supervised browser session's direct CDP socket and arerefused unless the page origin exactly matches the saved origin, checked again-inside the page immediately before the write.+inside the page immediately before the write. With the Camofox browser plugin,+which has no CDP endpoint, the same checks run and the fill goes to the Camofox+tab through its REST evaluate endpoint, only when `CAMOFOX_URL` is loopback or+HTTPS.**Does not:** protect against the page itself. Once a password is typed into asite, that site (and any script it runs) has it, exactly as when you type it