Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(vault): authorize avault's Keychain access and pin avault 0.1.8 (#3006)
Call White87b9ebcd07c1
diff --git a/docs/CLI.md b/docs/CLI.mdindex c46fe1615..514261b9a 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -444,9 +444,31 @@ vibe doctor repair tmux --yes- Stable `vibe` launchers that select different installed versions (fails with both paths and versions; `stable-launchers` points them all at the newest one, and changes nothing when two installs tie as the last activation)- A running service older than the last activated install (warns)- askill, avault, Git Runtime, Model Hub engine (CPA), Show Runtime, tmux, and Node.js readiness through one dependency diagnostic group+- avault's one-time macOS Keychain authorization (warns; Doctor never authorizes, see `vibe vault key authorize`)- `vibe doctor --deep` also probes missing dependencies without downloading their bodies- managed downloads retry transient HTTP, DNS, timeout, and connection failures with bounded backoff+### `vibe vault key authorize`++Authorize avault, once, to read the Vault key in this Mac's Keychain.++```bash+vibe vault key authorize+```++avault 0.1.8 and later are Developer ID signed, and macOS asks once before a newly+signed avault may read a Vault key that an earlier avault created. Until then every+Vault use fails with `avault_authorization_required`, and the Vault page, Settings →+Dependencies, and `vibe doctor` say so. Authorize with **Authorize avault** on the+Vault page, or run this command in Terminal on the Mac's desktop. Either way the macOS+dialog appears on the Mac running Avibe, not in a browser: enter that Mac's login+password and choose **Always Allow**. Later signed avault updates read the key without+asking again.++- A denied or cancelled dialog is not shown again for about 2 minutes.+- Over SSH no dialog can appear; use the Vault page instead.+- Agents never run it: a Vault command that hits this error tells the Agent to ask you.+### `vibe remote`Start the guided Avibe Cloud remote-access setup.diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex 110787330..4b0c77fcd 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -340,9 +340,28 @@ vibe doctor repair tmux --yes- 稳定 `vibe` 启动器是否选中了不同的已安装版本(失败时列出两边的路径和版本;`stable-launchers` 会把它们都指向最新版本;两个安装同为最后激活时不做任何改动)- 正在运行的服务是否比最近一次激活的安装更旧(警告)- 通过统一依赖诊断组检查 askill、avault、Git Runtime、Model Hub 引擎(CPA)、Show Runtime、tmux 和 Node.js+- avault 一次性的 macOS 钥匙串授权(警告;Doctor 从不代为授权,见 `vibe vault key authorize`)- `vibe doctor --deep` 还会在不下载正文的情况下探测缺失依赖的精确地址- 托管下载会对临时 HTTP、DNS、超时和连接故障执行有界退避重试+### `vibe vault key authorize`++授权 avault 一次,让它读取这台 Mac 钥匙串中的 Vault 密钥。++```bash+vibe vault key authorize+```++avault 0.1.8 起使用 Developer ID 签名。由更早的 avault 创建的 Vault 密钥,macOS 会先询问一次,+才允许新签名的 avault 读取。在此之前,每次使用 Vault 都会失败并返回 `avault_authorization_required`,+Vault 页面、「设置 → 依赖」和 `vibe doctor` 都会提示。你可以在 Vault 页面点击「授权 avault」,+或在 Mac 桌面的终端里运行这条命令。两种方式下,macOS 对话框都出现在运行 Avibe 的 Mac 上,而不是浏览器里:+输入那台 Mac 的登录密码,并选择「始终允许」。之后已签名的 avault 更新不会再询问。++- 拒绝或取消对话框后,约 2 分钟内不会再次显示。+- 通过 SSH 运行时无法显示对话框,请改用 Vault 页面。+- Agent 不会运行它:Vault 命令遇到这个错误时,会让 Agent 请你来授权。+### `vibe remote`启动 Avibe Cloud 远程访问的引导式配置流程。diff --git a/docs/plans/avault-custody-core.md b/docs/plans/avault-custody-core.mdindex 03d2154ad..d2ef84edd 100644--- a/docs/plans/avault-custody-core.md+++ b/docs/plans/avault-custody-core.md@@ -378,6 +378,44 @@ as an fd-forwarding special case.This is an internal store selection inside `avault`, not an Avibe-level plugin layer.+### 13.1 macOS Keychain authorization (avault 0.1.8+)++Keychain lets a binary read the master-key item only after the user approves that+binary's code identity. Developer ID releases (identifier `bot.avibe.avault`, Team+`68B2SQ6YK3`) share one designated requirement, so a user approves once; a key an+ad-hoc release created needs that approval once after the upgrade. avault never+prompts from a background call: it reports `keychain_authorization_required` (one-shot+exit 77, agent frame `code`), and only `avault key authorize` may show the dialog+(avault `docs/DESIGN.md`, "Keychain authorization"). Avibe's side:++- **Detection.** Every capturing one-shot verb loads the master key first, so exit 77+ there is the contract; older avault exits 70 for every failure. Resident-agent+ frames map `code` the same way. Both fail before avault decrypts anything, so they+ raise a pre-handoff `AvaultAuthorizationRequiredError`: one-shot grants are+ released, and a claimed standard sign request returns to pending so the user can+ approve it again. One-shot `deliver run` exits with its child's status, so a 77+ there is reported as authorization required only when a fresh `pubkey` check+ (0.1.8+ only) agrees, and even then it stays fail-closed: the check cannot prove+ that no child ran, for example when the Keychain locked during a run.+- **One error.** The Vault API and the `vibe vault` CLI report+ `avault_authorization_required`; the CLI hint tells an Agent to ask the user and+ not retry or run avault itself.+- **Shared record.** `vibe/avault_authorization.py` keeps one "authorization+ required" record under the state directory for every process; any successful+ master-key read clears it. The Vault page, Settings → Dependencies+ (`authorization_required`), and Doctor read it and offer the action.+- **Explicit action only.** The Web "Authorize avault" button (instance managers)+ and `vibe vault key authorize` (refused inside an Agent session) run `avault key+ authorize` once; concurrent Web requests in one process join one attempt, and+ avault's own gate shares one dialog across processes. Pollers, retries, Doctor+ repair, and Agent tools never authorize. A failed attempt is reported by avault's+ exit status plus this process's own login session (`no_gui_session`), never by+ parsing avault's text.+- **Proactive check.** After `install_avault` replaces a binary on macOS with 0.1.8++ and resets the resident agent, one silent `pubkey` sets or clears the record, so+ the UI offers the action before a real request fails. Like a first Vault use, it+ creates the master key when none exists.+---## 14. Project shapediff --git a/skills/use-avibe-vault/SKILL.md b/skills/use-avibe-vault/SKILL.mdindex 12944e4aa..42429cd33 100644--- a/skills/use-avibe-vault/SKILL.md+++ b/skills/use-avibe-vault/SKILL.md@@ -2,7 +2,7 @@name: use-avibe-vaultslug: use-avibe-vaultdescription: Use Avibe Vault for API keys, tokens, passwords, protected credentials, authenticated HTTP requests, or digest signing without exposing secret values to the agent.-version: 0.5.0+version: 0.5.1---# Use Avibe Vault@@ -25,6 +25,7 @@ Rules:- `export` remains deprecated and has no delivery. Prefer `run`; advanced `inject` writes a restricted-permission file, so use it only for tools that require file-based configuration.- With `vibe vault run`, the child process receives static secrets as environment variables, so never run commands that may print env vars, debug config, or secret-bearing errors.- When protected `run` / `fetch` needs approval, Avibe automatically asks the user to decrypt and authorize access, and the command waits for that approval (540 seconds by default; `--approval-wait SECONDS` or `--no-approval-wait` to change it). If the command then succeeds, it ran once: do not run it again. If it returns `approval_required`, `approval_wait_timeout`, or `approval_handed_off`, or your call to it is stopped before it gets the approval, the command did not run; Avibe resumes this session once the request is decided, and after an approval you run the same `run` / `fetch` command once.+- If a Vault command fails with `avault_authorization_required`, avault needs a one-time macOS Keychain authorization on the Mac running Avibe. Do not retry, and do not run `avault` or `vibe vault key authorize` yourself: ask the user to choose Authorize avault on the Vault page (or to run `vibe vault key authorize` on that Mac), then run the command once after they confirm.- When protected `sign` needs approval, Avibe creates a browser signing request and returns immediately. Do not rerun `sign`; when Avibe resumes this session, follow the callback instruction to read the completed request result and continue with the returned signature.Common commands:diff --git a/storage/vault_service.py b/storage/vault_service.pyindex 708c0a342..0cb1dfeac 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -4789,6 +4789,24 @@ def claim_sign_request(return _request_row_payload(dict(updated), conn=conn, audience=REQUEST_AUDIENCE_AGENT)+def release_sign_request_claim(conn: Connection, request_id: str) -> dict[str, Any]:+ """Return a claimed sign request to pending because avault signed nothing.++ Only for a failure before signing that the user can fix and approve again,+ such as avault's one-time Keychain authorization: the claim existed to stop+ a second signature, and there was no first one.+ """+ result = conn.execute(+ vault_requests.update()+ .where(vault_requests.c.id == request_id, vault_requests.c.request_type == "sign", vault_requests.c.status == "signing")+ .values(status="pending", decided_at=None)+ )+ if result.rowcount != 1:+ raise InvalidRequestError("sign request is not signing")+ updated = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().one()+ return _request_row_payload(dict(updated), conn=conn, audience=REQUEST_AUDIENCE_AGENT)++def fail_sign_request(conn: Connection, request_id: str, *, reason: str | None = None) -> dict[str, Any]:row_dict = _load_request_for_transition(conn,diff --git a/tests/fixtures/member_management_existing_read_roles.json b/tests/fixtures/member_management_existing_read_roles.jsonindex 76fb1554f..ff7bd8268 100644--- a/tests/fixtures/member_management_existing_read_roles.json+++ b/tests/fixtures/member_management_existing_read_roles.json@@ -65,6 +65,7 @@"GET /api/skills/find": "editor","GET /api/vault/agent/pubkey": "editor","GET /api/vault/audit": "editor",+ "GET /api/vault/avault-authorization": "editor","GET /api/vault/grants": "editor","GET /api/vault/provision-requests/by-id/example": "editor","GET /api/vault/provision-requests/example": "editor",@@ -124,6 +125,7 @@"POST /api/vault/agent-bindings:batch": "editor","POST /api/vault/authz/factors/webauthn": "editor","POST /api/vault/authz/factors/webauthn/options": "editor",+ "POST /api/vault/avault-authorization": "editor","POST /api/vault/grants": "editor","POST /api/vault/pubkey-pin": "editor","POST /api/vault/requests/access": "editor",diff --git a/tests/scenario_harness/avault_keychain.py b/tests/scenario_harness/avault_keychain.pynew file mode 100644index 000000000..cb6898061--- /dev/null+++ b/tests/scenario_harness/avault_keychain.py@@ -0,0 +1,131 @@+"""A fake avault for the one-time macOS Keychain authorization contract.++Contract (avault 0.1.8+, avault/docs/DESIGN.md "Keychain authorization"): a call+that needs the user's approval exits 77 (one-shot) or sends+``code: keychain_authorization_required`` (resident agent); only+``avault key authorize`` may show the dialog. Older avault exits 70 for every+failure and has no ``key authorize``. The fake is a POSIX-sh script whose+behavior follows files in its state directory, so no real avault, Keychain, or+``~/.local/bin`` is ever touched. Suites that forbid real processes bind it in+process instead, with the same state and answers.+"""++from __future__ import annotations++import subprocess+from dataclasses import dataclass+from pathlib import Path++_UNAUTHORIZED = "avault: failed to read master key from Keychain: run `avault key authorize` in a logged-in session"+++@dataclass(frozen=True)+class FakeAvault:+ script: Path+ state: Path+ version: str+ unauthorized_status: int++ def calls(self) -> list[str]:+ """Every invocation's arguments, without the ``--store`` prefix."""+ path = self.state / "calls"+ return path.read_text().splitlines() if path.exists() else []++ def flag(self, name: str, present: bool = True) -> None:+ """``authorized`` lets it read the master key; ``deny`` makes ``key authorize``+ fail as a refused dialog does; ``hold`` keeps it waiting for ``release``."""+ path = self.state / name+ if present:+ path.touch()+ else:+ path.unlink(missing_ok=True)++ def bind_in_process(self, monkeypatch) -> None:+ """Answer this avault's ``version``, ``pubkey`` and ``key authorize`` without a process.++ Same state and answers as the script, minus ``hold``. Any other command+ still reaches the suite's own ``subprocess.run``, so its guard stands.+ """+ outer = subprocess.run++ def run(argv, *args, **kwargs):+ if not argv or str(argv[0]) != str(self.script):+ return outer(argv, *args, **kwargs)+ command = list(argv[1:])+ if command[:1] == ["--store"]:+ command = command[2:]+ with (self.state / "calls").open("a") as calls:+ calls.write(" ".join(command) + "\n")+ status, stdout, stderr = self._answer(command)+ if not kwargs.get("text"):+ stdout, stderr = stdout.encode(), stderr.encode()+ return subprocess.CompletedProcess(argv, status, stdout, stderr)++ monkeypatch.setattr(subprocess, "run", run)++ def _answer(self, command: list[str]) -> tuple[int, str, str]:+ authorized = (self.state / "authorized").exists()+ if command == ["version"]:+ return 0, f"avault {self.version}\n", ""+ if command == ["pubkey"]:+ if not authorized:+ return self.unauthorized_status, "", _UNAUTHORIZED+ return 0, '{"public_key":"pk","fingerprint":"fp"}', ""+ if command == ["key", "authorize"]:+ if (self.state / "deny").exists():+ return 70, "", "avault: Keychain read failed: User canceled the operation."+ self.flag("authorized")+ return 0, '{"ok":true}', ""+ return 70, "", f"avault: fake has no in-process answer for {' '.join(command)}"+++def make_fake_avault(root: Path, *, version: str = "0.1.8", unauthorized_status: int = 77) -> FakeAvault:+ state = root / "avault-state"+ state.mkdir(parents=True)+ script = root / "avault-bin" / "avault"+ script.parent.mkdir(parents=True)+ unauthorized_message = _UNAUTHORIZED.replace("`", "\\`")+ script.write_text(+ f"""#!/bin/sh+STATE="{state}"+[ "$1" = "--store" ] && shift 2+echo "$*" >> "$STATE/calls"+unauthorized() {{+ echo "{unauthorized_message}" >&2+ exit {unauthorized_status}+}}+case "$1" in+ version) echo "avault {version}"; exit 0 ;;+ pubkey)+ [ -f "$STATE/authorized" ] || unauthorized+ echo '{{"public_key":"pk","fingerprint":"fp"}}'; exit 0 ;;+ key)+ if [ "$2" = "authorize" ]; then+ if [ -f "$STATE/hold" ]; then while [ ! -f "$STATE/release" ]; do sleep 0.02; done; fi+ if [ -f "$STATE/deny" ]; then echo "avault: Keychain read failed: User canceled the operation." >&2; exit 70; fi+ touch "$STATE/authorized"; echo '{{"ok":true}}'; exit 0+ fi ;;+ deliver)+ shift 2+ [ "$1" = "--" ] && shift+ cat > /dev/null+ [ -f "$STATE/authorized" ] || unauthorized+ "$@"; exit $? ;;+esac+exit 70+"""+ )+ script.chmod(0o755)+ return FakeAvault(script=script, state=state, version=version, unauthorized_status=unauthorized_status)+++def use_fake_avault_on_mac(monkeypatch, root: Path, **options) -> FakeAvault:+ """Point Avibe at a fake avault on a Mac with a desktop session and no attempt in flight."""+ from vibe import api, avault_authorization++ avault = make_fake_avault(root, **options)+ monkeypatch.setattr(api.platform, "system", lambda: "Darwin")+ monkeypatch.setattr(api, "_process_cannot_show_macos_dialogs", lambda: False)+ monkeypatch.setattr(api, "_resolve_avault_cli_path", lambda: str(avault.script))+ monkeypatch.setattr(avault_authorization, "_ATTEMPT", None)+ return avaultdiff --git a/tests/scenarios/auth_setup/catalog.yaml b/tests/scenarios/auth_setup/catalog.yamlindex 19ecb4294..f265e25cc 100644--- a/tests/scenarios/auth_setup/catalog.yaml+++ b/tests/scenarios/auth_setup/catalog.yaml@@ -623,4 +623,22 @@ scenarios:- ui/src/components/onboarding/WizardCompletion.test.tsx- ui/src/components/onboarding/entryGate.test.ts- ui/src/components/settings/shared/useBackendRuntime.test.tsx+ - id: AUTH-SETUP-134+ name: A Vault call blocked by avault's one-time macOS Keychain authorization recovers through Authorize avault+ status: covered+ kind: recovery_path+ layer: scenario+ backend: shared+ test: tests/scenarios/auth_setup/test_auth_setup_scenarios.py::test_avault_keychain_authorization_recovers_a_failed_vault_call+ # Real HTTP boundary: the failed Vault call, the shared authorization record, the+ # explicit Web action (single-flight attempt), and the successful retry. avault is a+ # fake honoring the 0.1.8 contract (exit 77, only key authorize may prompt), answered+ # in process under the suite's no-process guard; the fake's real-process form backs+ # the supporting tests. The real Keychain dialog and its 120 s denial cooldown are the+ # owner's manual acceptance on a Mac.+ supporting_tests:+ - tests/test_avault_authorization.py+ - tests/test_avault_agent.py+ - tests/test_local_deps.py+ - ui/src/components/ui/avault-authorization-notice.test.tsxnext_priority: []diff --git a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py b/tests/scenarios/auth_setup/test_auth_setup_scenarios.pyindex da3b9b71a..49ba499f1 100644--- a/tests/scenarios/auth_setup/test_auth_setup_scenarios.py+++ b/tests/scenarios/auth_setup/test_auth_setup_scenarios.py@@ -5005,3 +5005,38 @@ async def test_cloud_pairing_origin_reaches_effective_ui_listener(monkeypatch, s# Closing the disposable listener must remain visible as an unhealthy UI.payload = await asyncio.to_thread(remote_access.runtime_status_payload, config)assert payload["ui_healthy"] is False+++def test_avault_keychain_authorization_recovers_a_failed_vault_call(monkeypatch, tmp_path):+ """AUTH-SETUP-134: failed Vault call -> recorded requirement -> Authorize avault -> retry succeeds.++ avault is a fake honoring the 0.1.8 contract, answered in process under this+ suite's no-process guard; nothing here touches a real Keychain or avault.+ Nothing authorizes until the explicit Web action.+ """+ from tests.scenario_harness.avault_keychain import use_fake_avault_on_mac++ avault = use_fake_avault_on_mac(monkeypatch, tmp_path)+ avault.bind_in_process(monkeypatch)+ client = app.test_client()++ blocked = client.get("/api/vault/pubkey")+ assert blocked.status_code == 409+ assert blocked.get_json()["code"] == "avault_authorization_required"+ status = client.get("/api/vault/avault-authorization").get_json()+ assert status["required"] is True and status["attempt"] is None+ assert "key authorize" not in avault.calls()++ started = client.post("/api/vault/avault-authorization", json={}, headers=csrf_headers(client))+ assert started.status_code == 200, started.get_json()+ deadline = time.monotonic() + 10+ while (attempt := client.get("/api/vault/avault-authorization").get_json()["attempt"])["state"] == "running":+ assert time.monotonic() < deadline, attempt+ time.sleep(0.05)+ assert attempt["state"] == "succeeded"+ assert client.get("/api/vault/avault-authorization").get_json()["required"] is False++ retried = client.get("/api/vault/pubkey")+ assert retried.status_code == 200+ assert retried.get_json()["public_key"] == "pk"+ assert avault.calls().count("key authorize") == 1diff --git a/tests/test_avault_agent.py b/tests/test_avault_agent.pyindex cd4f70216..a9c6a800d 100644--- a/tests/test_avault_agent.py+++ b/tests/test_avault_agent.py@@ -14,6 +14,7 @@ from typing import Anyimport pytestfrom vibe.avault_agent import DEFAULT_AGENT_IDLE_TIMEOUT_SECS, AvaultAgentClient, AvaultAgentError, AvaultAgentManager+from vibe.avault_agent import AvaultAgentAuthorizationRequiredErrorfrom vibe.avault_agent import _ensure_agent_socket_parent, _remove_stale_agent_socket, default_agent_socket_path@@ -120,6 +121,24 @@ def test_agent_client_surfaces_agent_errors(tmp_path):)+ ("frame", "authorization_required"),+ [+ ({"ok": False, "error": "macOS Keychain needs a one-time authorization", "code": "keychain_authorization_required"}, True),+ # Pre-0.1.8 agents send no code; a code Avibe does not know is ignored.+ ({"ok": False, "error": "failed to load the master key"}, False),+ ({"ok": False, "error": "failed to load the master key", "code": "some_future_code"}, False),+ ],+)+def test_agent_client_types_only_the_keychain_authorization_code(frame, authorization_required):+ socket_path = Path(tempfile.mkdtemp(prefix="avault-agent-", dir="/tmp")) / "s"+ with FakeAgentServer(socket_path, [frame]):+ with pytest.raises(AvaultAgentError, match=frame["error"]) as exc:+ AvaultAgentClient(socket_path).release(grant_id="vgr_api")++ assert isinstance(exc.value, AvaultAgentAuthorizationRequiredError) is authorization_required++def test_agent_socket_path_uses_avibe_home_and_secures_directories(tmp_path, monkeypatch):avibe_home = tmp_path / "avibe-home"monkeypatch.setenv("AVIBE_HOME", str(avibe_home))diff --git a/tests/test_avault_authorization.py b/tests/test_avault_authorization.pynew file mode 100644index 000000000..3c08a2826--- /dev/null+++ b/tests/test_avault_authorization.py@@ -0,0 +1,217 @@+"""avault's one-time macOS Keychain authorization, against fake avault binaries.++The contract is described in ``tests/scenario_harness/avault_keychain.py``; the+closed loop through the Web action is AUTH-SETUP-134.+"""++from __future__ import annotations++import threading+import time++import pytest++from storage.vault_crypto import Sealed+from tests.scenario_harness.avault_keychain import use_fake_avault_on_mac+from vibe import api, cli+++def mac_avault(monkeypatch, tmp_path):+ """Point Avibe at a fake avault on a Mac; return a factory taking the fake's options."""+ return lambda **options: use_fake_avault_on_mac(monkeypatch, tmp_path, **options)+++def _secret() -> list[dict]:+ return [{"name": "API_TOKEN", "env": "API_TOKEN", "envelope": Sealed(ciphertext="ct", nonce="n", wrap_meta="wm")}]+++def test_exit_77_reports_authorization_required_until_the_key_reads_again(mac_avault):+ avault = mac_avault()++ with pytest.raises(api.AvaultAuthorizationRequiredError) as exc:+ api.avault_pubkey()++ # Nothing left avault, so one-shot grants are released rather than consumed.+ assert isinstance(exc.value, api.AvaultPreHandoffError)+ assert api.get_avault_authorization_status()["required"] is True+ row = api.dependencies_status(dependency_ids=["avault"])["deps"][0]+ assert row["status"] == "ready" and row["authorization_required"] is True++ avault.flag("authorized")+ assert api.avault_pubkey() == {"public_key": "pk", "fingerprint": "fp"}+ assert api.get_avault_authorization_status()["required"] is False+++def test_avault_without_the_contract_keeps_todays_failures(mac_avault):+ avault = mac_avault(version="0.1.7", unauthorized_status=70)++ with pytest.raises(api.AvaultError) as exc:+ api.avault_pubkey()+ assert not isinstance(exc.value, api.AvaultAuthorizationRequiredError)+ assert api.get_avault_authorization_status()["required"] is False++ # Its child's 77 is just the child's exit code; a pre-0.1.8 avault is never+ # probed again, since its background Keychain reads may still prompt.+ avault.flag("authorized")+ before = len(avault.calls())+ assert api.avault_deliver_run(_secret(), ["sh", "-c", "exit 77"])["exit_code"] == 77+ assert [call for call in avault.calls()[before:] if call.startswith("pubkey")] == []+++def test_deliver_run_77_is_authorization_only_when_the_master_key_check_agrees(mac_avault):+ avault = mac_avault()++ with pytest.raises(api.AvaultAuthorizationRequiredError) as exc:+ api.avault_deliver_run(_secret(), ["sh", "-c", "exit 0"])+ # The probe cannot prove no child ran, so the delivery stays fail-closed.+ assert not isinstance(exc.value, api.AvaultPreHandoffError)+ assert api.get_avault_authorization_status()["required"] is True++ avault.flag("authorized")+ assert api.avault_deliver_run(_secret(), ["sh", "-c", "exit 77"]) == {"exit_code": 77, "delivered": True}+ assert api.get_avault_authorization_status()["required"] is False+++def test_agent_authorization_frame_becomes_the_same_pre_handoff_error(mac_avault, monkeypatch):+ from vibe.avault_agent import AvaultAgentAuthorizationRequiredError++ mac_avault()++ class Client:+ def deliver_inject(self, **_kwargs):+ raise AvaultAgentAuthorizationRequiredError("macOS Keychain needs a one-time authorization")++ monkeypatch.setattr(api, "_avault_agent_client", Client)+ monkeypatch.setattr(api, "_require_avault_grant_delivery_surface", lambda _feature: None)++ with pytest.raises(api.AvaultPreHandoffError) as exc:+ api.avault_agent_deliver_inject(grant_id="vgr_1", path="/tmp/out.env", fmt="dotenv", secrets=[])+ assert isinstance(exc.value, api.AvaultAuthorizationRequiredError)+ assert api.get_avault_authorization_status()["required"] is True+++def _wait_for_attempt() -> dict:+ deadline = time.monotonic() + 10+ while time.monotonic() < deadline:+ attempt = api.get_avault_authorization_status()["attempt"]+ if attempt and attempt["state"] != "running":+ return attempt+ time.sleep(0.02)+ raise AssertionError("authorization attempt did not finish")+++def test_concurrent_authorize_requests_share_one_avault_dialog(mac_avault):+ avault = mac_avault()+ with pytest.raises(api.AvaultAuthorizationRequiredError):+ api.avault_pubkey()+ avault.flag("hold")++ results: list[dict] = []+ threads = [threading.Thread(target=lambda: results.append(api.start_avault_authorization())) for _ in range(4)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join()+ assert {result["attempt"]["state"] for result in results} == {"running"}+ assert len({result["attempt"]["id"] for result in results}) == 1++ avault.flag("release")+ attempt = _wait_for_attempt()++ assert attempt["state"] == "succeeded"+ assert [call for call in avault.calls() if call == "key authorize"] == ["key authorize"]+ assert api.get_avault_authorization_status()["required"] is False+++ ("setup", "reason", "runs_avault"),+ [+ (lambda avault, monkeypatch: avault.flag("deny"), "not_completed", True),+ (+ lambda avault, monkeypatch: (+ avault.flag("deny"),+ monkeypatch.setattr(api, "_process_cannot_show_macos_dialogs", lambda: True),+ ),+ "no_gui_session",+ True,+ ),+ (lambda avault, monkeypatch: monkeypatch.setattr(api, "_resolve_avault_cli_path", lambda: None), "avault_missing", False),+ ],+)+def test_authorize_failures_are_classified_without_parsing_avault_text(mac_avault, monkeypatch, setup, reason, runs_avault):+ avault = mac_avault()+ setup(avault, monkeypatch)++ result = api.avault_key_authorize()++ assert result["ok"] is False and result["reason"] == reason+ assert ("key authorize" in avault.calls()) is runs_avault+ if runs_avault:+ assert result["detail"].startswith("avault:")+++def test_authorize_needs_an_avault_with_the_contract(mac_avault):+ avault = mac_avault(version="0.1.7", unauthorized_status=70)++ assert api.avault_key_authorize() == {"ok": False, "reason": "avault_upgrade_required"}+ assert "key authorize" not in avault.calls()+++def test_authorize_is_not_applicable_off_macos(mac_avault, monkeypatch):+ avault = mac_avault()+ monkeypatch.setattr(api.platform, "system", lambda: "Linux")++ assert api.avault_key_authorize() == {"ok": True, "reason": "not_applicable"}+ assert avault.calls() == []+++def test_status_readers_and_failed_calls_never_authorize(mac_avault, monkeypatch):+ avault = mac_avault()+ real_dependencies_status = api.dependencies_status+ monkeypatch.setattr(api, "dependencies_status", lambda **_kwargs: real_dependencies_status(dependency_ids=["avault"]))+ monkeypatch.setattr(+ "core.git_runtime.git_runtime_status",+ lambda: {"resolution": "system", "version": "2.0", "managed": {}},+ )++ for _ in range(3):+ with pytest.raises(api.AvaultAuthorizationRequiredError):+ api.avault_pubkey()+ api._check_avault_keychain_authorization_after_upgrade()+ api.get_avault_authorization_status()+ items = cli._managed_dependencies_doctor_items()++ assert "key authorize" not in avault.calls()+ doctor = next(item for item in items if item.get("code") == "dependencies.avault.authorization_required")+ assert doctor["status"] == "warn" and "repair" not in doctor+++def test_cli_authorize_is_for_the_user_not_an_agent(mac_avault, monkeypatch, capsys):+ avault = mac_avault()+ monkeypatch.setenv("AVIBE_SESSION_ID", "ses_agent")++ assert cli.cmd_vault_key_authorize(None) == 1++ error = capsys.readouterr().err+ assert '"code": "user_action_required"' in error+ assert avault.calls() == []+++def test_cli_authorize_reports_success_and_failures(mac_avault, monkeypatch, capsys):+ import json++ avault = mac_avault()+ monkeypatch.delenv("AVIBE_SESSION_ID", raising=False)+ avault.flag("deny")++ assert cli.cmd_vault_key_authorize(None) == 1+ err = capsys.readouterr().err+ assert "enter this Mac's login password and choose Always Allow" in err+ failure = json.loads(err[err.index("{"):])+ assert failure["code"] == "avault_authorization_not_completed"+ assert failure["details"]["avault_error"].startswith("avault:")++ avault.flag("deny", False)+ assert cli.cmd_vault_key_authorize(None) == 0+ assert json.loads(capsys.readouterr().out)["status"] == "authorized"diff --git a/tests/test_local_deps.py b/tests/test_local_deps.pyindex d39542d31..e75954843 100644--- a/tests/test_local_deps.py+++ b/tests/test_local_deps.py@@ -141,6 +141,13 @@ def _installable_avault_release(monkeypatch.setattr(api.shutil, "which", lambda _binary: None)monkeypatch.setattr(api, "_candidate_cli_paths", fake_candidate_cli_paths)+ # Resolution also scans raw PATH entries. Drop any that hold an avault, so the+ # developer's own avault is never what these tests resolve, probe, or run.+ ambient = os.environ.get("PATH", "").split(os.pathsep)+ monkeypatch.setenv(+ "PATH",+ os.pathsep.join(entry for entry in ambient if entry and not any((Path(entry) / name).exists() for name in ("avault", "avault.exe"))),+ )return calls, member_name@@ -545,6 +552,45 @@ def test_install_avault_downloads_the_pinned_archive_verifies_and_installs(monkeassert calls == [f"https://dl.avibe.bot/avault/releases/v{api.AVAULT_VERSION}/avault-{api.AVAULT_VERSION}-{target}.tar.gz"]+ ("system", "machine", "target", "had_binary", "new_version", "pubkey_status", "expected_calls", "required"),+ [+ # Replacing an ad-hoc binary on a Mac: one silent master-key read decides.+ ("Darwin", "arm64", "macos-arm64", True, None, 77, ["version", "pubkey"], True),+ ("Darwin", "arm64", "macos-arm64", True, None, 0, ["version", "pubkey"], False),+ # Nothing to migrate, no Keychain, or an avault whose background reads may still prompt.+ ("Darwin", "arm64", "macos-arm64", False, None, 77, [], False),+ ("Linux", "x86_64", "linux-x64", True, None, 77, [], False),+ ("Darwin", "arm64", "macos-arm64", True, "0.1.7", 77, ["version"], False),+ ],+)+def test_install_avault_checks_keychain_authorization_after_replacing_a_binary(+ monkeypatch, tmp_path, system, machine, target, had_binary, new_version, pubkey_status, expected_calls, required+):+ monkeypatch.setattr("platform.system", lambda: system)+ monkeypatch.setattr("platform.machine", lambda: machine)+ calls = tmp_path / "calls"+ content = (+ "#!/bin/sh\n"+ '[ "$1" = "--store" ] && shift 2\n'+ f'echo "$*" >> "{calls}"\n'+ f'case "$1" in version) echo "avault {new_version or api.AVAULT_VERSION}";; pubkey) exit {pubkey_status};; esac\n'+ ).encode()+ _installable_avault_release(monkeypatch, target=target, content=content)+ installed = api._avault_managed_bin_path(target)+ if had_binary:+ installed.parent.mkdir(parents=True, exist_ok=True)+ installed.write_text("#!/bin/sh\necho avault 0.1.7\n")+ installed.chmod(0o755)+ monkeypatch.setattr(api, "_resolve_avault_cli_path", lambda: str(installed) if installed.exists() else None)++ out = api.install_avault(force=True)++ assert out["ok"] is True+ assert (calls.read_text().splitlines() if calls.exists() else []) == expected_calls+ assert api.get_avault_authorization_status()["required"] is required++def test_install_avault_checksum_mismatch_installs_nothing(monkeypatch):monkeypatch.setattr(api, "_configured_avault_cli_path", lambda: "avault")monkeypatch.setattr(api, "_managed_avault_release_satisfies_p2", lambda: True)diff --git a/tests/test_member_management_parity.py b/tests/test_member_management_parity.pyindex 4f08d89f2..f4ee6a89b 100644--- a/tests/test_member_management_parity.py+++ b/tests/test_member_management_parity.py@@ -118,7 +118,12 @@ def test_complete_registered_api_management_inventory():for method in (getattr(route, "methods", None) or ())if method not in {"HEAD", "OPTIONS"}}- assert len(endpoints) == 292+ assert len(endpoints) == 294+ # Editors who use Vault read avault's authorization state; the handler admits only+ # instance managers to raise the Keychain dialog on the host.+ for method in ("GET", "POST"):+ assert (method, "/api/vault/avault-authorization") in endpoints+ assert http_authorization_policy(method, "/api/vault/avault-authorization").minimum_role == "editor"for tool in ("web_search", "web_fetch"):retry_route = f"/api/models/hosted-tools/{tool}/services/{{source_id}}/retry"assert ("POST", retry_route) in endpoints@@ -173,6 +178,19 @@ def test_complete_registered_api_management_inventory():assert actual_read_roles == baseline_read_roles[email protected]("role, status", [("editor", 403), ("member", 200), ("owner", 200)])+def test_authorize_avault_http_needs_instance_management(management_http, monkeypatch, role, status):+ started = []+ monkeypatch.setattr(api, "start_avault_authorization", lambda: started.append(True) or {"ok": True})+ request_http = management_http(role)++ assert request_http("GET", "/api/vault/avault-authorization").status_code == 200+ response = request_http("POST", "/api/vault/avault-authorization", payload={})++ assert response.status_code == status, response.get_json()+ assert started == ([True] if status == 200 else [])++@pytest.mark.parametrize("role, status", [("editor", 403), ("member", 200), ("owner", 200)])def test_approve_delete_http_uses_management_authority(management_http, role, status):"""The real HTTP path must pass remote authority to the deletion transaction."""diff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex 856cd1465..b733ad548 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -2605,6 +2605,39 @@ def test_agent_sign_marks_claimed_request_failed_when_signature_validation_rejecassert fetched["request"]["delivery"]["failure"] == {"request_type": "sign", "reason": "signature_rejected"}+def test_sign_approval_stays_pending_when_avault_needs_keychain_authorization(monkeypatch):+ sign = Mock(side_effect=api.AvaultAuthorizationRequiredBeforeHandoffError("macOS Keychain needs a one-time authorization"))+ monkeypatch.setattr(api, "avault_sign", sign)+ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed("key")))+ api.create_vault_secret(+ {+ "name": "ETH_KEY",+ "kind": "keypair",+ "signer_kind": "local",+ "blind_box": {"scheme": "hpke-x25519-hkdfsha256-aes256gcm-v1", "enc": "enc", "ct": "ct"},+ }+ )+ requested = api.request_vault_sign(+ {"name": "ETH_KEY", "digest": "00" * 32, "scheme": "ecdsa-secp256k1-recoverable", "session_id": "ses_1"}+ )++ with pytest.raises(api.VaultApiError) as exc:+ api.vault_sign(+ {+ "name": "ETH_KEY",+ "digest": "00" * 32,+ "scheme": "ecdsa-secp256k1-recoverable",+ "request_id": requested["request"]["id"],+ }+ )++ # Nothing was signed: the same request can be approved again once avault is authorized.+ assert exc.value.code == "avault_authorization_required"+ fetched = api.get_vault_request(requested["request"]["id"])["request"]+ assert fetched["status"] == "pending" and fetched["decided_at"] is None+ assert "failure" not in fetched["delivery"]++def test_vault_sign_rejects_non_keypair_secret(monkeypatch):from unittest.mock import Mockdiff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.pyindex 212c50e61..d738fdbeb 100644--- a/tests/test_vault_cli.py+++ b/tests/test_vault_cli.py@@ -2065,6 +2065,52 @@ def test_run_releases_standard_always_ask_grant_when_avault_fails_before_handoffassert status == "active"+ ("command", "error", "grant_status"),+ [+ # One-shot deliver run cannot prove its child never ran: the grant stays fail-closed.+ ("run", "AvaultAuthorizationRequiredError", "expired"),+ ("inject", "AvaultAuthorizationRequiredBeforeHandoffError", "active"),+ ],+)+def test_delivery_hands_avault_authorization_to_the_user(tmp_path, capfd, monkeypatch, command, error, grant_status):+ from vibe import api++ grant = _set_always_ask_standard_grant("ASK_KEY", session_id="ses_cli", purpose=command)+ deliver = Mock(side_effect=getattr(api, error)("run `avault key authorize` in a logged-in session"))+ if command == "run":+ monkeypatch.setattr(api, "avault_deliver_run", deliver)+ code = cli.cmd_vault_run(_ns(env=["ASK_KEY"], command_argv=["python3", "-c", "pass"], session_id="ses_cli"))+ else:+ monkeypatch.setattr(api, "avault_deliver_inject", deliver)+ code = cli.cmd_vault_inject(_ns(keys="ASK_KEY", out=str(tmp_path / "out.env"), format="dotenv", session_id="ses_cli"))+ error = json.loads(capfd.readouterr().err)++ assert code == 1+ assert error["code"] == "avault_authorization_required"+ # The Agent is told to hand the step to the user, not to retry or run avault itself.+ assert "Do not retry and do not run avault yourself" in error["hint"]+ assert "Authorize avault" in error["hint"]+ assert "avault key authorize" not in error["error"]+ with cli._open_vault_engine().connect() as conn:+ status = conn.execute(vault_grants.select().where(vault_grants.c.id == grant["id"])).mappings().one()["status"]+ assert status == grant_status+++def test_inline_sign_reports_avault_authorization_like_delivery(capfd, monkeypatch):+ from vibe import api++ monkeypatch.setattr(api, "avault_sign", Mock(side_effect=api.AvaultAuthorizationRequiredBeforeHandoffError("authorize avault")))+ with cli._open_vault_engine().begin() as conn:+ vault_service.create_secret(conn, name="ETH_KEY", kind="keypair", signer_kind="local", sealed=_sealed("key"))++ assert cli.cmd_vault_sign(_ns(name="ETH_KEY", digest="00" * 32, scheme="ecdsa-secp256k1-recoverable")) == 1+ error = json.loads(capfd.readouterr().err)++ assert error["code"] == "avault_authorization_required"+ assert "Authorize avault" in error["hint"]++def test_run_releases_one_shot_grant_when_later_resolution_aborts_before_handoff(tmp_path, capfd, monkeypatch):from vibe import apidiff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsxindex d8f48bd73..ada671e24 100644--- a/ui/src/components/settings/SettingsDependenciesPage.tsx+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx@@ -32,6 +32,7 @@ import {} from './SettingsDependenciesPage.logic';import { errorMessage } from '@/lib/errorMessage';import { useDependencyChecks } from './useDependencyChecks';+import { AvaultAuthorizationNotice } from '../ui/avault-authorization-notice';// Mirrors design.pen "vibe-remote — Settings · Dependencies": one card per// required local runtime (icon tile + name/REQUIRED + detail + status pill +@@ -278,6 +279,10 @@ export const SettingsDependenciesPage: React.FC = () => {>{persistedFailure}</div>+ ) : d.id === 'avault' && d.authorization_required ? (+ <div className="border-t border-border pt-3">+ <AvaultAuthorizationNotice forceVisible />+ </div>) : undefined}/>);diff --git a/ui/src/components/ui/avault-authorization-notice.test.tsx b/ui/src/components/ui/avault-authorization-notice.test.tsxnew file mode 100644index 000000000..7b370d5c9--- /dev/null+++ b/ui/src/components/ui/avault-authorization-notice.test.tsx@@ -0,0 +1,205 @@+// @vitest-environment jsdom++import { createInstance } from 'i18next';+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';+import { I18nextProvider, initReactI18next } from 'react-i18next';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { AvaultAuthorizationStatus } from '@/context/ApiContext';+import en from '@/i18n/en.json';+import zh from '@/i18n/zh.json';+import { isAvaultAuthorizationRequired } from '@/lib/useAvaultAuthorization';+import { AvaultAuthorizationNotice } from './avault-authorization-notice';++const api = vi.hoisted(() => ({+ getAvaultAuthorization: vi.fn(),+ authorizeAvault: vi.fn(),+}));+const authorization = vi.hoisted(() => ({ capabilities: { can_manage_instance: true } }));++vi.mock('@/context/ApiContext', () => ({ useApi: () => api }));+vi.mock('@/context/InstanceAuthorizationContext', () => ({+ useInstanceAuthorization: () => authorization,+}));++const i18n = createInstance();+void i18n.use(initReactI18next).init({+ lng: 'en',+ fallbackLng: 'en',+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+});++const status = (overrides: Partial<AvaultAuthorizationStatus> = {}): AvaultAuthorizationStatus => ({+ ok: true,+ required: true,+ detected_at: '2026-10-26T09:00:00Z',+ attempt: null,+ ...overrides,+});+const attempt = (state: 'running' | 'succeeded' | 'failed', extra: Record<string, string> = {}) => ({+ id: 'att_1',+ state,+ started_at: '2026-10-26T09:01:00Z',+ ...extra,+});++const renderNotice = (props: { forceVisible?: boolean } = {}) =>+ render(+ <I18nextProvider i18n={i18n}>+ <AvaultAuthorizationNotice {...props} />+ </I18nextProvider>,+ );++// Let the mocked API promises and the state updates they trigger settle.+const settle = () => act(async () => {+ await Promise.resolve();+ await Promise.resolve();+});++describe('AvaultAuthorizationNotice', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ api.getAvaultAuthorization.mockReset();+ api.authorizeAvault.mockReset();+ authorization.capabilities.can_manage_instance = true;+ });+ afterEach(() => {+ cleanup();+ vi.useRealTimers();+ });++ it('stays hidden while avault needs no authorization', async () => {+ api.getAvaultAuthorization.mockResolvedValue(status({ required: false }));+ renderNotice();+ await settle();++ expect(screen.queryByRole('alert')).toBeNull();+ });++ // An Agent's failed Vault call records the requirement in another process while the+ // Vault page stays open; the banner must still appear without remounting the page.+ it('shows the notice once the requirement is recorded after the page opened', async () => {+ api.getAvaultAuthorization.mockResolvedValueOnce(status({ required: false }));+ renderNotice();+ await settle();+ expect(screen.queryByRole('alert')).toBeNull();++ api.getAvaultAuthorization.mockResolvedValue(status());+ await act(async () => {+ vi.advanceTimersByTime(15_000);+ });+ await settle();++ expect(screen.getByRole('alert')).toBeTruthy();+ expect(api.authorizeAvault).not.toHaveBeenCalled();+ });++ it('says where the dialog appears and runs one authorization per click until it finishes', async () => {+ api.getAvaultAuthorization.mockResolvedValueOnce(status());+ api.authorizeAvault.mockResolvedValue(status({ attempt: attempt('running') }));+ renderNotice();+ await settle();++ expect(screen.getByText(en.vaults.avaultAuthorization.steps)).toBeTruthy();+ fireEvent.click(screen.getByRole('button', { name: en.vaults.avaultAuthorization.action }));+ await settle();+ expect(screen.getByText(en.vaults.avaultAuthorization.waiting)).toBeTruthy();+ const button = screen.getByRole('button', { name: en.vaults.avaultAuthorization.action }) as HTMLButtonElement;+ expect(button.disabled).toBe(true);+ fireEvent.click(button);+ expect(api.authorizeAvault).toHaveBeenCalledTimes(1);++ // Only the status is polled while the person at the Mac answers.+ api.getAvaultAuthorization.mockResolvedValueOnce(status({ required: false, attempt: attempt('succeeded') }));+ await act(async () => {+ vi.advanceTimersByTime(1600);+ });+ await settle();++ expect(screen.getByText(en.vaults.avaultAuthorization.succeeded)).toBeTruthy();+ expect(api.authorizeAvault).toHaveBeenCalledTimes(1);+ });++ it('keeps polling through a failed status read', async () => {+ api.getAvaultAuthorization.mockResolvedValueOnce(status());+ api.authorizeAvault.mockResolvedValue(status({ attempt: attempt('running') }));+ renderNotice();+ await settle();+ fireEvent.click(screen.getByRole('button', { name: en.vaults.avaultAuthorization.action }));+ await settle();++ api.getAvaultAuthorization+ .mockRejectedValueOnce(new Error('network'))+ .mockResolvedValueOnce(status({ required: false, attempt: attempt('succeeded') }));+ for (let poll = 0; poll < 2; poll += 1) {+ await act(async () => {+ vi.advanceTimersByTime(1600);+ });+ await settle();+ }++ expect(screen.getByText(en.vaults.avaultAuthorization.succeeded)).toBeTruthy();+ });++ it('does not submit a surrounding form', async () => {+ api.getAvaultAuthorization.mockResolvedValue(status());+ api.authorizeAvault.mockResolvedValue(status({ attempt: attempt('running') }));+ const submit = vi.fn((event: { preventDefault: () => void }) => event.preventDefault());+ render(+ <I18nextProvider i18n={i18n}>+ <form onSubmit={submit}>+ <AvaultAuthorizationNotice forceVisible />+ </form>+ </I18nextProvider>,+ );+ await settle();++ fireEvent.click(screen.getByRole('button', { name: en.vaults.avaultAuthorization.action }));+ await settle();++ expect(api.authorizeAvault).toHaveBeenCalledTimes(1);+ expect(submit).not.toHaveBeenCalled();+ });++ it('explains a failed attempt by its reason and shows avault detail', async () => {+ api.getAvaultAuthorization.mockResolvedValue(status());+ api.authorizeAvault.mockResolvedValue(+ status({ attempt: attempt('failed', { reason: 'no_gui_session', detail: 'avault: interaction not allowed' }) }),+ );+ renderNotice({ forceVisible: true });+ await settle();++ fireEvent.click(screen.getByRole('button', { name: en.vaults.avaultAuthorization.action }));+ await settle();++ expect(screen.getByText(en.vaults.avaultAuthorization.failed.no_gui_session)).toBeTruthy();+ expect(screen.getByText('avault: interaction not allowed')).toBeTruthy();+ });++ it('asks an admin when this user cannot manage the instance', async () => {+ authorization.capabilities.can_manage_instance = false;+ api.getAvaultAuthorization.mockResolvedValue(status());+ renderNotice();+ await settle();++ expect(screen.getByText(en.vaults.avaultAuthorization.askAdmin)).toBeTruthy();+ expect(screen.queryByRole('button')).toBeNull();+ });+});++describe('avault authorization copy', () => {+ it('names the code the Vault API sends', () => {+ expect(isAvaultAuthorizationRequired({ code: 'avault_authorization_required' })).toBe(true);+ expect(isAvaultAuthorizationRequired({ code: 'avault_failed' })).toBe(false);+ expect(isAvaultAuthorizationRequired(new Error('avault_authorization_required'))).toBe(false);+ });++ it('localizes every failure reason the backend reports in both languages', () => {+ const reasons = ['not_completed', 'no_gui_session', 'timed_out', 'avault_missing', 'avault_upgrade_required', 'failed'];+ for (const catalog of [en, zh]) {+ expect(Object.keys(catalog.vaults.avaultAuthorization.failed).sort()).toEqual([...reasons].sort());+ expect(catalog.errors.avault_authorization_required).toBeTruthy();+ }+ });+});diff --git a/ui/src/components/ui/avault-authorization-notice.tsx b/ui/src/components/ui/avault-authorization-notice.tsxnew file mode 100644index 000000000..cb7d1a365--- /dev/null+++ b/ui/src/components/ui/avault-authorization-notice.tsx@@ -0,0 +1,81 @@+import { useState } from 'react';+import { useTranslation } from 'react-i18next';+import { CheckCircle2, KeyRound, Loader2 } from 'lucide-react';++import { useInstanceAuthorization } from '@/context/InstanceAuthorizationContext';+import { useAvaultAuthorization } from '@/lib/useAvaultAuthorization';+import { cn } from '@/lib/utils';+import { Button } from './button';++/**+ * Explains avault's one-time macOS Keychain authorization and offers the action. Renders+ * when the backend has recorded that avault needs it, or when `forceVisible` because a+ * Vault call just failed with that code.+ */+export function AvaultAuthorizationNotice({ forceVisible = false, className }: { forceVisible?: boolean; className?: string }) {+ const { t } = useTranslation();+ const { capabilities } = useInstanceAuthorization();+ const { status, authorize } = useAvaultAuthorization();+ // Set once this notice asks; only then does it keep showing that attempt's outcome.+ const [requested, setRequested] = useState(false);+ const attempt = status?.attempt ?? null;+ const running = attempt?.state === 'running';+ const outcome = requested && !running ? attempt : null;+ if (!forceVisible && !status?.required && !running && !outcome) return null;++ const onAuthorize = () => {+ setRequested(true);+ void authorize();+ };++ if (outcome?.state === 'succeeded') {+ return (+ <div+ role="status"+ className={cn('flex items-start gap-2.5 rounded-xl border border-mint/30 bg-mint/[0.08] px-4 py-3 text-sm', className)}+ >+ <CheckCircle2 className="mt-0.5 size-4 shrink-0 text-mint-ink" />+ <span className="text-foreground">{t('vaults.avaultAuthorization.succeeded')}</span>+ </div>+ );+ }++ const failureReason = outcome?.state === 'failed' ? outcome.reason || 'failed' : null;+ return (+ <div+ role="alert"+ className={cn('flex flex-col gap-2.5 rounded-xl border border-gold/40 bg-gold/10 px-4 py-3 text-sm', className)}+ >+ <div className="flex items-start gap-2.5">+ <KeyRound className="mt-0.5 size-4 shrink-0 text-gold-ink" />+ <div className="flex min-w-0 flex-col gap-1">+ <span className="font-semibold text-foreground">{t('vaults.avaultAuthorization.title')}</span>+ <span className="leading-snug text-foreground">{t('vaults.avaultAuthorization.body')}</span>+ <span className="leading-snug text-muted">{t('vaults.avaultAuthorization.steps')}</span>+ </div>+ </div>+ {failureReason ? (+ <div className="flex flex-col gap-1 rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2 text-[12.5px] leading-snug text-destructive-ink">+ <span>+ {t(`vaults.avaultAuthorization.failed.${failureReason}`, {+ defaultValue: t('vaults.avaultAuthorization.failed.failed'),+ })}+ </span>+ {outcome?.detail ? <span className="break-words font-mono text-[11px] text-muted">{outcome.detail}</span> : null}+ </div>+ ) : null}+ <div className="flex flex-wrap items-center gap-2.5 pl-6">+ {/* type="button": the notice also renders inside the secret form, which it must not submit. */}+ {capabilities.can_manage_instance ? (+ <Button type="button" size="sm" variant="brand" disabled={running} onClick={onAuthorize}>+ {running ? <Loader2 className="size-3.5 animate-spin" /> : <KeyRound className="size-3.5" />}+ {t('vaults.avaultAuthorization.action')}+ </Button>+ ) : (+ <span className="text-xs text-muted">{t('vaults.avaultAuthorization.askAdmin')}</span>+ )}+ {running ? <span className="text-xs text-muted">{t('vaults.avaultAuthorization.waiting')}</span> : null}+ </div>+ </div>+ );+}diff --git a/ui/src/components/ui/vault-approval-card.test.tsx b/ui/src/components/ui/vault-approval-card.test.tsxindex d605c5480..a6ed7b4ce 100644--- a/ui/src/components/ui/vault-approval-card.test.tsx+++ b/ui/src/components/ui/vault-approval-card.test.tsx@@ -17,6 +17,10 @@ const api = vi.hoisted(() => ({saveVaultSettings: vi.fn(),denyVaultRequest: vi.fn(),approveVaultDeleteRequest: vi.fn(),+ listVaultSecrets: vi.fn(),+ signVaultDigest: vi.fn(),+ getAvaultAuthorization: vi.fn(),+ authorizeAvault: vi.fn(),}));const useVaultSandboxWarm = vi.hoisted(() => vi.fn((_enabled: boolean) => true));const authorization = vi.hoisted(() => ({ capabilities: { can_use_vault_secrets: true, can_manage_instance: true } }));@@ -63,6 +67,15 @@ const protectedAccess = {},} satisfies VaultRequest;+const standardSignRequest = {+ ...protectedAccess,+ id: 'vrq_sign',+ request_type: 'sign',+ secret_name: 'ETH_KEY',+ delivery: { digest: '00'.repeat(32), scheme: 'ecdsa-secp256k1-recoverable' },+ card: { request_type: 'sign', secret_name: 'ETH_KEY', kind: 'keypair', protection: 'standard' },+} satisfies VaultRequest;+const deleteRequest = {...protectedAccess,id: 'vrq_delete',@@ -352,6 +365,26 @@ describe('VaultApprovalCard protected access approval', () => {expect(screen.getByRole('button', { name: /^delete$/i })).toBeTruthy();});+ it('offers Authorize avault when a standard signature needs the Keychain authorization', async () => {+ api.listVaultSecrets.mockResolvedValue({ ok: true, secrets: [] });+ api.getAvaultAuthorization.mockResolvedValue({ ok: true, required: true, detected_at: null, attempt: null });+ api.signVaultDigest.mockRejectedValue(+ Object.assign(new Error('avault sign failed: run `avault key authorize`'), { code: 'avault_authorization_required' }),+ );+ const onResolved = vi.fn();+ render(+ <I18nextProvider i18n={i18n}>+ <VaultApprovalCard request={standardSignRequest} onResolved={onResolved} onCancel={vi.fn()} />+ </I18nextProvider>,+ );++ fireEvent.click(screen.getByRole('button', { name: en.vaults.approval.sign }));++ await vi.waitFor(() => expect(screen.getByRole('button', { name: en.vaults.avaultAuthorization.action })).toBeTruthy());+ expect(screen.queryByText(/avault key authorize/)).toBeNull();+ expect(onResolved).not.toHaveBeenCalled();+ });+it('renders and approves a standard delete request in one click', async () => {const onResolved = vi.fn();render(diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsxindex 6b0a0c79e..8cabeb0df 100644--- a/ui/src/components/ui/vault-approval-card.tsx+++ b/ui/src/components/ui/vault-approval-card.tsx@@ -22,6 +22,8 @@ import { openVaultAuthorizationWindow } from '@/lib/vaultSandboxClient';import { SigningAddressList } from './signing-address-list';import { type BlindBox, type SignatureResult, type SignatureScheme } from '@/lib/vaultCrypto';import { cn, copyTextToClipboard } from '@/lib/utils';+import { isAvaultAuthorizationRequired } from '@/lib/useAvaultAuthorization';+import { AvaultAuthorizationNotice } from './avault-authorization-notice';import { Badge } from './badge';import { Button } from './button';import { ConfirmDialog } from './confirm-dialog';@@ -205,6 +207,8 @@ export const VaultApprovalCard: React.FC<{const effectiveGrantDuration: GrantDurationChoice = isOneShot ? 'one-time' : grantDuration;const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ // The last approval failed because avault needs its one-time Keychain authorization.+ const [needsAvaultAuthorization, setNeedsAvaultAuthorization] = useState(false);const [signAddresses, setSignAddresses] = useState<SigningAddresses | null>(null);const [copiedDigest, setCopiedDigest] = useState(false);const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false);@@ -282,8 +286,12 @@ export const VaultApprovalCard: React.FC<{(run: () => Promise<void>) => {setBusy(true);setError(null);+ setNeedsAvaultAuthorization(false);run()- .catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)))+ .catch((err: unknown) => {+ setError(err instanceof Error ? err.message : String(err));+ setNeedsAvaultAuthorization(isAvaultAuthorizationRequired(err));+ }).finally(() => setBusy(false));},[],@@ -299,7 +307,9 @@ export const VaultApprovalCard: React.FC<{const sessionBound = needsProtectedApproval && hasRequestSession ? true : thisSessionOnly;const failIfNotOk = (res: { ok: boolean; code?: string; message?: string }) => {- if (!res.ok) throw new Error(res.message || res.code || t('vaults.approval.errors.failed'));+ if (!res.ok) {+ throw Object.assign(new Error(res.message || res.code || t('vaults.approval.errors.failed')), res.code ? { code: res.code } : {});+ }};const approveAccess = () =>@@ -659,7 +669,9 @@ export const VaultApprovalCard: React.FC<{</div>) : null}- {error ? (+ {needsAvaultAuthorization ? (+ <AvaultAuthorizationNotice forceVisible />+ ) : error ? (<div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive-ink">{error}</div>diff --git a/ui/src/components/ui/vault-secret-fields-editor.tsx b/ui/src/components/ui/vault-secret-fields-editor.tsxindex de11d3cd1..7cb8daccc 100644--- a/ui/src/components/ui/vault-secret-fields-editor.tsx+++ b/ui/src/components/ui/vault-secret-fields-editor.tsx@@ -7,6 +7,8 @@ import { vaultErrorMessage } from '@/lib/vaultErrors';import { useProtectedVault } from '@/lib/useProtectedVault';import { openVaultsInBrowser, vaultPasskeyNeedsBrowser } from '@/lib/vaultBrowserHandoff';import { MAX_VAULT_FIELDS, vaultDefaultField, vaultFieldNameIssue, vaultFieldNames, vaultRecordName } from '@/lib/vaultFields';+import { isAvaultAuthorizationRequired } from '@/lib/useAvaultAuthorization';+import { AvaultAuthorizationNotice } from './avault-authorization-notice';import { Button } from './button';import {VaultFieldList,@@ -69,6 +71,8 @@ export function VaultSecretFieldsEditor({const [focusedName, setFocusedName] = useState<'default' | 'new' | null>(null);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ // The last write failed because avault needs its one-time Keychain authorization.+ const [needsAvaultAuthorization, setNeedsAvaultAuthorization] = useState(false);const [saved, setSaved] = useState(false);const [draftNotice, setDraftNotice] = useState<string | null>(null);const fields = vaultFieldNames(current);@@ -180,6 +184,7 @@ export function VaultSecretFieldsEditor({setBusy(true);onBusyChange(true);setError(null);+ setNeedsAvaultAuthorization(false);setSaved(false);setDraftNotice(null);try {@@ -218,6 +223,8 @@ export function VaultSecretFieldsEditor({} catch (refreshError) {setError(vaultErrorMessage(t, refreshError, t('vaults.dialog.errors.updateFailed')));}+ } else if (isAvaultAuthorizationRequired(err)) {+ setNeedsAvaultAuthorization(true);} else {setError(vaultErrorMessage(t, err, t('vaults.dialog.errors.updateFailed')));}@@ -437,6 +444,7 @@ export function VaultSecretFieldsEditor({onContinueInBrowser={() => openVaultsInBrowser({ kind: 'edit', secretName: current.name })} />}{busy && <Loader2 className="size-4 animate-spin text-muted" />}{saved && <p role="status" className="text-xs text-mint-ink">{t('vaults.fields.saved')}</p>}+ {needsAvaultAuthorization && <AvaultAuthorizationNotice forceVisible />}{error && <p role="alert" className="text-xs text-destructive-ink">{error}</p>}</div>);diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsxindex 4d0ae5c2f..de71ba7d6 100644--- a/ui/src/components/ui/vault-secret-form.tsx+++ b/ui/src/components/ui/vault-secret-form.tsx@@ -44,6 +44,8 @@ import { vaultErrorMessage } from '@/lib/vaultErrors';import { useProtectedVault } from '@/lib/useProtectedVault';import { MAX_VAULT_FIELDS, VAULT_FIELD_PATTERN, vaultFieldNameIssue, vaultRecordName } from '@/lib/vaultFields';import { openVaultsInBrowser, vaultPasskeyNeedsBrowser } from '@/lib/vaultBrowserHandoff';+import { isAvaultAuthorizationRequired } from '@/lib/useAvaultAuthorization';+import { AvaultAuthorizationNotice } from './avault-authorization-notice';import { Badge } from './badge';import { Button } from './button';import { Input } from './input';@@ -229,6 +231,8 @@ export const VaultSecretForm: React.FC<{const [checkingAvault, setCheckingAvault] = useState(true);const [avaultDep, setAvaultDep] = useState<DependencyItem | null>(null);const [error, setError] = useState<string | null>(null);+ // Saving failed because avault needs its one-time Keychain authorization.+ const [needsAvaultAuthorization, setNeedsAvaultAuthorization] = useState(false);useEffect(() => {let alive = true;@@ -580,6 +584,7 @@ export const VaultSecretForm: React.FC<{}setSubmitting(true);setError(null);+ setNeedsAvaultAuthorization(false);try {if (isEdit && editSecret) {// Value-free metadata edit: the shared validation above already ran; PATCH@@ -748,7 +753,7 @@ export const VaultSecretForm: React.FC<{setError(t('vaults.protectedUnlock.errors.alreadyInitialized'));return;}- throw new Error(vaultErrorMessage(t, created, t('vaults.request.saveFailed')));+ throw Object.assign(new Error(vaultErrorMessage(t, created, t('vaults.request.saveFailed'))), { code: created.code });}if (protection === 'protected') protectedVault.afterCreated();clearStaticValue();@@ -761,7 +766,9 @@ export const VaultSecretForm: React.FC<{setFetchAuthName('');onCreated(secretName, 'created');} catch (err: unknown) {- if (err instanceof Error && err.message.includes('fingerprint mismatch')) {+ if (isAvaultAuthorizationRequired(err)) {+ setNeedsAvaultAuthorization(true);+ } else if (err instanceof Error && err.message.includes('fingerprint mismatch')) {setError(t('vaults.dialog.errors.fingerprintMismatch'));} else if (err instanceof Error && err.message.includes('AAD field is too large')) {setError(t('vaults.dialog.errors.aadFieldTooLarge'));@@ -1137,6 +1144,7 @@ export const VaultSecretForm: React.FC<{})}</div>)}+ {needsAvaultAuthorization && <AvaultAuthorizationNotice forceVisible />}{error && (<div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive-ink">{error}diff --git a/ui/src/components/workbench/VaultsPage.test.tsx b/ui/src/components/workbench/VaultsPage.test.tsxindex 3b5066b37..4e87c9a4e 100644--- a/ui/src/components/workbench/VaultsPage.test.tsx+++ b/ui/src/components/workbench/VaultsPage.test.tsx@@ -27,6 +27,7 @@ const api = vi.hoisted(() => ({connectWorkbenchEvents: vi.fn(() => () => undefined),createVaultRevealContext: vi.fn(),getVaultAudit: vi.fn(),+ getAvaultAuthorization: vi.fn(),getVaultGrants: vi.fn(),getVaultRequests: vi.fn(),listVaultSecrets: vi.fn(),@@ -121,6 +122,7 @@ function renderPage(context: InstanceAuthorizationValue = remoteOwner, entry = 'beforeEach(async () => {await testI18n.changeLanguage('en');eventHandlers.length = 0;+ api.getAvaultAuthorization.mockResolvedValue({ ok: true, required: false, detected_at: null, attempt: null });api.connectWorkbenchEvents.mockImplementation((handlers: WorkbenchEventHandlers) => {eventHandlers.push(handlers);return () => {@@ -168,6 +170,18 @@ describe('VaultsPage remote audit history', () => {expect(await screen.findByRole('button', { name: 'Add secret' })).toBeTruthy();expect(screen.queryByText('Read-only')).toBeNull();});++ it('offers Authorize avault before a Vault call fails, and only to an instance manager', async () => {+ api.getAvaultAuthorization.mockResolvedValue({ ok: true, required: true, detected_at: '2026-10-26T09:00:00Z', attempt: null });++ renderPage(member);+ expect(await screen.findByRole('button', { name: 'Authorize avault' })).toBeTruthy();+ cleanup();++ renderPage(editor);+ expect(await screen.findByText(en.vaults.avaultAuthorization.askAdmin)).toBeTruthy();+ expect(screen.queryByRole('button', { name: 'Authorize avault' })).toBeNull();+ });});describe('PERMISSIONS-013 VaultsPage capability-gated management actions', () => {diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex f2b4cae28..e787ebfb8 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -5,6 +5,7 @@ import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { CapabilityTabs } from './CapabilityTabs';import { WorkbenchPageHeader } from './WorkbenchPageHeader';+import { AvaultAuthorizationNotice } from '../ui/avault-authorization-notice';import { Badge } from '../ui/badge';import { Button } from '../ui/button';import { ConfirmDialog } from '../ui/confirm-dialog';@@ -973,6 +974,7 @@ export const VaultsPage: React.FC = () => {{error && (<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive-ink">{error}</div>)}+ {canReadVaultState ? <AvaultAuthorizationNotice /> : null}{canUseVaultSecrets ? (<PendingRequestsSectiononResolved={refresh}diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex f58743968..ede2a12bf 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -835,6 +835,9 @@ export type ApiContextType = {getVaultVmk: () => Promise<VaultVmkResult>;getVaultPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;getVaultAgentPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;+ getAvaultAuthorization: () => Promise<AvaultAuthorizationStatus>;+ /** Starts the one-time macOS Keychain authorization, or joins the one already running. */+ authorizeAvault: () => Promise<AvaultAuthorizationStatus>;getVaultSandboxRootMetadata: () => Promise<VaultSandboxRootMetadataResult>;/** One batch of signed agent-delivery contexts for every protected member of a request (§7.1). */createVaultAgentBindingsBatch: (payload: {@@ -1973,6 +1976,25 @@ export type DependencyItem = {release_state?: 'published' | 'unavailable' | null;download_error?: DependencyDownloadError | null;inspection_error?: { kind: string; message: string } | null;+ /** avault only: the binary cannot read the Vault key until the user authorizes it once. */+ authorization_required?: boolean;+};++/** avault's one-time macOS Keychain authorization (see vibe/avault_authorization.py). */+export type AvaultAuthorizationAttempt = {+ id: string;+ state: 'running' | 'succeeded' | 'failed';+ reason?: string | null;+ detail?: string;+ started_at: string;+ finished_at?: string;+};++export type AvaultAuthorizationStatus = {+ ok: boolean;+ required: boolean;+ detected_at: string | null;+ attempt: AvaultAuthorizationAttempt | null;};export type DependenciesResult = {@@ -4048,6 +4070,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenlistVaultSecrets: (opts) => getCachedJson('/api/vault/secrets', 1500, opts),getVaultPubkey: () => getCachedJson('/api/vault/pubkey', 1500),getVaultAgentPubkey: () => getCachedJson('/api/vault/agent/pubkey', 1500),+ getAvaultAuthorization: async () => {+ // Polled while an attempt runs: a failed read rejects quietly, so the caller keeps+ // its last status and keeps polling instead of taking an error body for a status.+ const path = '/api/vault/avault-authorization';+ const res = await apiFetch(path);+ if (!res.ok) throw new ApiError(`Request failed: ${path} (${res.status})`, res.status, null);+ return res.json();+ },+ authorizeAvault: () => postJson('/api/vault/avault-authorization', {}),getVaultSandboxRootMetadata: () => getCachedJson('/api/vault/sandbox/root-metadata', 1500, { handleError: false }),createVaultAgentBindingsBatch: (payload) =>postJson('/api/vault/agent-bindings:batch', payload, { handleError: false }),diff --git a/ui/src/context/ApiContext.vault.test.tsx b/ui/src/context/ApiContext.vault.test.tsxindex 1547ef980..c9bd844c5 100644--- a/ui/src/context/ApiContext.vault.test.tsx+++ b/ui/src/context/ApiContext.vault.test.tsx@@ -46,6 +46,15 @@ it('keeps a stale field DELETE inline instead of showing a global toast', asyncexpect(showToast).not.toHaveBeenCalled();});+// The Authorize avault notice polls this read; an error body taken for a status would+// drop the running attempt and end the polling before the person at the Mac answers.+it('rejects a failed avault authorization status read without a toast', async () => {+ apiFetch.mockResolvedValue(new Response(JSON.stringify({ ok: false, error: 'unavailable' }), { status: 503 }));+ const { result } = renderHook(useApi, { wrapper: ApiProvider });+ await expect(result.current.getAvaultAuthorization()).rejects.toMatchObject({ status: 503 });+ expect(showToast).not.toHaveBeenCalled();+});+it.each(['invalid_field_name', 'field_exists', 'field_not_found', 'too_many_fields','fields_not_supported', 'record_mismatch', 'secret_conflict', 'fields_corrupt',diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex a8776dd20..5ef136db4 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2839,6 +2839,7 @@"retry": "Retry"},"errors": {+ "avault_authorization_required": "avault needs a one-time macOS Keychain authorization on the Mac running Avibe. Choose Authorize avault, then answer the dialog on that Mac.","invalid_field_name": "Use 1–64 lowercase letters, digits or underscores for field names, starting with a letter.","field_exists": "A field with this name already exists. Choose a different name.","field_not_found": "This field no longer exists. Refresh the secret and choose one of its current fields.",@@ -5386,6 +5387,23 @@}},"vaults": {+ "avaultAuthorization": {+ "title": "Authorize avault once",+ "body": "avault keeps the Vault key in this Mac's Keychain. After the update to the signed avault, macOS must approve it once before Vault can use the key again.",+ "steps": "Choose Authorize avault. A macOS dialog then appears on the Mac running Avibe, not in this browser: enter that Mac's login password and choose Always Allow.",+ "action": "Authorize avault",+ "askAdmin": "Ask an admin of this Avibe to authorize avault.",+ "waiting": "Waiting for an answer on the Mac running Avibe…",+ "succeeded": "avault is authorized. Retry what you were doing.",+ "failed": {+ "not_completed": "Authorization did not complete. If you chose Deny or closed the dialog, macOS will not show it again for about 2 minutes; try again after that.",+ "no_gui_session": "The Mac running Avibe cannot show the dialog: Avibe is not running in a logged-in desktop session (for example, it was started over SSH). Log in to that Mac's desktop, start Avibe there, and try again.",+ "timed_out": "Nobody answered the dialog within 10 minutes. Try again when you can reach the Mac running Avibe.",+ "avault_missing": "avault is not installed. Install it under Settings → Dependencies first.",+ "avault_upgrade_required": "This avault version cannot be authorized. Update it under Settings → Dependencies first.",+ "failed": "Authorization failed. Try again."+ }+ },"remoteReadOnly": "Read-only","remoteReadOnlyHint": "Vaults are read-only in remote mode.","title": "Vaults",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex c82d56237..1fcc7482b 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2839,6 +2839,7 @@"retry": "重试"},"errors": {+ "avault_authorization_required": "avault 需要在运行 Avibe 的 Mac 上完成一次性的 macOS 钥匙串授权。请选择「授权 avault」,然后在那台 Mac 上回应对话框。","invalid_field_name": "字段名须为 1–64 个小写字母、数字或下划线,且以字母开头。","field_exists": "此字段名已存在,请使用其他名称。","field_not_found": "此字段已不存在。请刷新密钥并选择当前字段。",@@ -5386,6 +5387,23 @@}},"vaults": {+ "avaultAuthorization": {+ "title": "授权 avault 一次",+ "body": "avault 把 Vault 密钥保存在这台 Mac 的钥匙串中。更新到已签名的 avault 后,macOS 需要先批准一次,Vault 才能重新使用该密钥。",+ "steps": "选择「授权 avault」后,macOS 对话框会出现在运行 Avibe 的 Mac 上,而不是这个浏览器里:输入那台 Mac 的登录密码,并选择「始终允许」。",+ "action": "授权 avault",+ "askAdmin": "请让这个 Avibe 的管理员授权 avault。",+ "waiting": "正在等待运行 Avibe 的 Mac 上的回应…",+ "succeeded": "avault 已授权。请重试刚才的操作。",+ "failed": {+ "not_completed": "授权未完成。如果你选择了「拒绝」或关闭了对话框,macOS 约 2 分钟内不会再次显示它,请稍后再试。",+ "no_gui_session": "运行 Avibe 的 Mac 无法显示对话框:Avibe 没有运行在已登录的桌面会话中(例如通过 SSH 启动)。请登录那台 Mac 的桌面,在那里启动 Avibe 后再试。",+ "timed_out": "10 分钟内没有人回应对话框。请在能操作运行 Avibe 的 Mac 时再试。",+ "avault_missing": "avault 尚未安装。请先在「设置 → 依赖」中安装。",+ "avault_upgrade_required": "当前 avault 版本无法授权。请先在「设置 → 依赖」中更新。",+ "failed": "授权失败,请重试。"+ }+ },"remoteReadOnly": "只读","remoteReadOnlyHint": "远程模式下 Vaults 为只读。","title": "保险库",diff --git a/ui/src/lib/useAvaultAuthorization.ts b/ui/src/lib/useAvaultAuthorization.tsnew file mode 100644index 000000000..9fab10725--- /dev/null+++ b/ui/src/lib/useAvaultAuthorization.ts@@ -0,0 +1,83 @@+import { useCallback, useEffect, useState } from 'react';++import { useApi, type AvaultAuthorizationStatus } from '@/context/ApiContext';++import { useDocumentVisible } from './pageActivity';++/** The Vault API's code for avault's one-time macOS Keychain authorization. */+export const AVAULT_AUTHORIZATION_REQUIRED_CODE = 'avault_authorization_required';++export function isAvaultAuthorizationRequired(error: unknown): boolean {+ return (+ typeof error === 'object' &&+ error !== null &&+ (error as { code?: unknown }).code === AVAULT_AUTHORIZATION_REQUIRED_CODE+ );+}++const ATTEMPT_POLL_MS = 1500;+const IDLE_POLL_MS = 15_000;++/**+ * avault's authorization state, and the user's "Authorize avault" action.+ *+ * Reading never prompts; only `authorize`, bound to a click, asks the backend to run+ * `avault key authorize`. Another process, such as an Agent's failed Vault call, can+ * record the requirement while this page stays open, so the status is re-read whenever+ * the page is shown again and on a slow beat while it is; while an attempt runs (on the+ * Mac, waiting for the person at it) it is re-read quickly until it finishes.+ */+export function useAvaultAuthorization() {+ const api = useApi();+ const [status, setStatus] = useState<AvaultAuthorizationStatus | null>(null);+ const running = status?.attempt?.state === 'running';+ const visible = useDocumentVisible();++ useEffect(() => {+ if (!visible) return;+ let alive = true;+ const read = () => {+ api+ .getAvaultAuthorization()+ .then((next) => {+ if (alive) setStatus(next);+ })+ // A failed read keeps the last status; a backend without the route has nothing to authorize.+ .catch(() => undefined);+ };+ read();+ const timer = window.setInterval(read, IDLE_POLL_MS);+ return () => {+ alive = false;+ window.clearInterval(timer);+ };+ }, [api, visible]);++ useEffect(() => {+ if (!running) return;+ let alive = true;+ // An interval, not a chained timeout, so a failed read cannot end the polling.+ const timer = window.setInterval(() => {+ api+ .getAvaultAuthorization()+ .then((next) => {+ if (alive) setStatus(next);+ })+ .catch(() => undefined);+ }, ATTEMPT_POLL_MS);+ return () => {+ alive = false;+ window.clearInterval(timer);+ };+ }, [api, running]);++ const authorize = useCallback(async () => {+ try {+ setStatus(await api.authorizeAvault());+ } catch {+ // The API layer already reported the failure.+ }+ }, [api]);++ return { status, authorize };+}diff --git a/ui/src/lib/vaultBrowserHandoff.test.tsx b/ui/src/lib/vaultBrowserHandoff.test.tsxindex f2580d680..55fa60bfd 100644--- a/ui/src/lib/vaultBrowserHandoff.test.tsx+++ b/ui/src/lib/vaultBrowserHandoff.test.tsx@@ -23,6 +23,7 @@ const api = vi.hoisted(() => ({createVaultRevealContext: vi.fn(),denyVaultRequest: vi.fn(),fulfillVaultAccessRequest: vi.fn(),+ getAvaultAuthorization: vi.fn(async () => ({ ok: true, required: false, detected_at: null, attempt: null })),getVaultGrants: vi.fn(),getVaultRequests: vi.fn(),getVaultSettings: vi.fn(),diff --git a/vibe/api.py b/vibe/api.pyindex 25f7d9044..2493aeaf3 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -109,7 +109,7 @@ from vibe.upgrade import (verify_upgrade_candidate,)from vibe.restart_supervisor import schedule_restart-from vibe import backend_model_catalog+from vibe import avault_authorization, backend_model_catalogfrom vibe.i18n import t as backend_tfrom modules.agents.catalog import (AGENT_BACKENDS,@@ -2528,6 +2528,8 @@ def _notify_vault_request_created(request: dict | None) -> None:def _vault_api_error_from_avault(exc: "AvaultError", *, prefix: str) -> VaultApiError:message = str(exc)+ if isinstance(exc, AvaultAuthorizationRequiredError):+ return VaultApiError(f"{prefix}: {message}", code=exc.code, status=409)if "requires avault >=" in message:return VaultApiError(f"{prefix}: {message}", code="avault_upgrade_required", status=409)return VaultApiError(f"{prefix}: {message}", code="avault_failed")@@ -2748,7 +2750,7 @@ def get_vault_pubkey() -> dict:try:return {"ok": True, **avault_pubkey()}except AvaultError as exc:- raise VaultApiError(f"avault pubkey failed: {exc}", code="avault_failed") from exc+ raise _vault_api_error_from_avault(exc, prefix="avault pubkey failed") from excdef get_vault_agent_pubkey() -> dict:@@ -3750,7 +3752,7 @@ def create_vault_secret(try:sealed = avault_seal_blind_box(name, blind_box)except AvaultError as exc:- raise VaultApiError(f"avault blind-box seal failed: {exc}", code="avault_failed") from exc+ raise _vault_api_error_from_avault(exc, prefix="avault blind-box seal failed") from excelse:raise VaultApiError("standard create requires a browser blind_box",@@ -3770,7 +3772,7 @@ def create_vault_secret(try:field_sealed = avault_seal_blind_box(record_name, spec["blind_box"])except AvaultError as exc:- raise VaultApiError(f"avault blind-box seal failed: {exc}", code="avault_failed") from exc+ raise _vault_api_error_from_avault(exc, prefix="avault blind-box seal failed") from excelse:field_sealed = _sealed_from_payload(spec["sealed"])sealed_fields.append({"name": field_name, "record": record_name, "sealed": field_sealed})@@ -3972,7 +3974,7 @@ def update_vault_secret_field(try:sealed = avault_seal_blind_box(record_name, blind_box)except AvaultError as exc:- raise VaultApiError(f"avault blind-box seal failed: {exc}", code="avault_failed") from exc+ raise _vault_api_error_from_avault(exc, prefix="avault blind-box seal failed") from excelif protection == "protected":if "blind_box" in payload:raise VaultApiError("protected field updates require sealed", code="invalid_request", status=409)@@ -5572,13 +5574,13 @@ def vault_sign(payload: dict) -> dict:_notify_vault_request_created(approval_required_request)return protected_response- def _fail_claimed_request(reason: str) -> None:+ def _settle_claimed_request(settle: Callable[[Any, str], dict]) -> None:request_id = str(payload.get("request_id") or "")if not request_id:returnwith contextlib.suppress(Exception):with engine.begin() as conn:- request = vault_service.fail_sign_request(conn, request_id, reason=reason)+ request = settle(conn, request_id)_publish_vaults_updated(scope="request",request_id=request.get("id") or request_id,@@ -5586,8 +5588,16 @@ def vault_sign(payload: dict) -> dict:secret_name=request.get("secret_name"),)+ def _fail_claimed_request(reason: str) -> None:+ _settle_claimed_request(lambda conn, request_id: vault_service.fail_sign_request(conn, request_id, reason=reason))+try:signature = avault_sign(key_envelope, digest, scheme, name=name)+ except AvaultAuthorizationRequiredBeforeHandoffError as exc:+ # Nothing was signed, so the approval stays pending: the user authorizes+ # avault and approves the same request again instead of the Agent re-asking.+ _settle_claimed_request(vault_service.release_sign_request_claim)+ raise _vault_api_error_from_avault(exc, prefix="avault sign failed") from excexcept AvaultError as exc:_fail_claimed_request("avault_failed")raise VaultApiError(f"avault sign failed: {exc}", code="avault_failed") from exc@@ -8686,19 +8696,26 @@ AVAULT_PROTECTED_RECORD_MIN_VERSION = "0.1.6"# 0.103.16) to reject the compromised eMudhra/emSign intermediates, so older# binaries must not receive credentials for HTTPS egress.AVAULT_FETCH_TLS_MIN_VERSION = "0.1.7"-# Installer pin must reference a published release. v0.1.7 refreshes the-# outbound TLS trust (webpki-roots 1.0.10 / rustls-webpki 0.103.16) so delivery-# fetches reject the compromised eMudhra/emSign intermediates.-AVAULT_VERSION = "0.1.7"+# avault 0.1.8 is the first Developer ID signed release. From it on, no+# background Keychain read shows a dialog: one the item does not trust yet+# reports keychain_authorization_required (one-shot exit 77, agent frame+# ``code``), and ``avault key authorize`` is the only verb that may prompt.+# Older binaries have neither, and their background reads may still prompt.+AVAULT_KEYCHAIN_AUTHORIZATION_MIN_VERSION = "0.1.8"+# Installer pin must reference a published release. v0.1.8 is the first+# Developer ID signed release (identifier bot.avibe.avault, Team 68B2SQ6YK3): a+# master key an ad-hoc release created needs one "Authorize avault" after the+# upgrade, and later signed releases read it without asking again.+AVAULT_VERSION = "0.1.8"# (sha256, size) of each AVAULT_VERSION archive by target, copied from that# release's manifest.json so the download is verified whichever source served it._AVAULT_ARCHIVES = {- "linux-arm64": ("22bbed967ba7403e323549eb8b161c2d918c1f5ed692f38d4e3b1049ad7d23dd", 3256706),- "linux-x64": ("ccc329b92a70c2d5b583b66725b0780a0f182975f2cbe6e7501232d9963ceb4c", 3580615),- "macos-arm64": ("d6e5fe7911c571d05734213af5c1b17332b3d7a71635f60c68887bd2dc977998", 1462107),- "macos-x64": ("56874a51ef37aab01be137898b3220c4a78bdbff0fc5362a862a42dd18a0abcc", 1583787),- "windows-arm64": ("6f7f7cbc69decb280a78e4936cfef7c15e95820168df981a3020393937f4c7aa", 1325310),- "windows-x64": ("c49cf29062fa5f22eab76e7785c040006a6fcf9fabf84667c120f8e99f5ccf0a", 1406456),+ "linux-arm64": ("b22d237b97ab2ed3143f498bebce4affbe6a2617c2d50abcb48c1c668351799f", 3273950),+ "linux-x64": ("6f64d8e089fa859889db53472616a065c9bb3e500b4ad04267bd1b2dd29366e1", 3596395),+ "macos-arm64": ("2dc4b81c4ab3995e519e86854011ee1c38ae9696310d94d1eeaa8d0fe25725bd", 1480823),+ "macos-x64": ("f3c46c612c2bee449d29f9480552437349ba97f9a89f523f2d4d368a4e5a3959", 1643862),+ "windows-arm64": ("0cc42e23e63218f4301b89c527a9109ed02adf6c0e226d1332046e6af0eb4c8f", 1324833),+ "windows-x64": ("5432be1d9e07b3069a1a010f71f885481b72f694175f2b7e46d92162ea6adee3", 1406676),}@@ -9128,6 +9145,8 @@ def install_avault(force: bool = False) -> dict:_clear_macos_quarantine(install_path)_persist_avault_cli_path(str(install_path))_reset_avault_agent_after_binary_change(reason="install_avault")+ if path:+ _check_avault_keychain_authorization_after_upgrade()return {"ok": True,@@ -9410,6 +9429,38 @@ class AvaultPreHandoffError(AvaultError):"""avault failed before receiving an envelope or performing delivery."""+class AvaultAuthorizationRequiredError(AvaultError):+ """macOS Keychain has not yet approved this avault binary for the master key.++ The user fixes it once with an explicit "Authorize avault" action; retrying+ the call cannot. One-shot ``deliver run`` raises this class itself, because+ it cannot prove its child never ran, so that delivery stays fail-closed.+ """++ code = "avault_authorization_required"+++class AvaultAuthorizationRequiredBeforeHandoffError(AvaultAuthorizationRequiredError, AvaultPreHandoffError):+ """avault could not load the master key, so nothing was decrypted, delivered, or signed."""+++# One-shot exit status for keychain_authorization_required (avault 0.1.8+, EX_NOPERM).+_AVAULT_EXIT_AUTHORIZATION_REQUIRED = 77+# ``avault key authorize`` waits for a person to reach the Mac and answer the dialog.+_AVAULT_AUTHORIZE_TIMEOUT_SECONDS = 600.0+_AVAULT_AUTHORIZE_DETAIL_LIMIT = 500+++def _avault_authorization_required(+ detail: str | None = None,+ *,+ before_handoff: bool = True,+) -> AvaultAuthorizationRequiredError:+ avault_authorization.record_authorization_required()+ error = AvaultAuthorizationRequiredBeforeHandoffError if before_handoff else AvaultAuthorizationRequiredError+ return error(detail or "avault needs a one-time macOS Keychain authorization on the Mac running Avibe")++def _avault_detail(proc: "subprocess.CompletedProcess") -> str:"""Best-effort, secret-free detail from a failed avault run (its stderr)."""raw = proc.stderr@@ -9461,10 +9512,15 @@ def _run_avault(stdin: bytes | None = None,timeout: float = _AVAULT_TIMEOUT_SECONDS,) -> "subprocess.CompletedProcess":- """Run a capturing one-shot avault command. Bulk blobs go via ``stdin``."""+ """Run a capturing one-shot avault command. Bulk blobs go via ``stdin``.++ Every capturing verb loads the master key first, so exit 77 here is always+ avault's keychain_authorization_required (older releases exit 70 for every+ failure) and success shows the key is readable.+ """path = _require_avault_path()try:- return subprocess.run(+ proc = subprocess.run([path, *_avault_args(args)],input=stdin,capture_output=True,@@ -9476,6 +9532,59 @@ def _run_avault(raise AvaultPreHandoffError("avault binary not found") from excexcept subprocess.TimeoutExpired as exc:raise AvaultError("avault timed out") from exc+ if proc.returncode == _AVAULT_EXIT_AUTHORIZATION_REQUIRED:+ raise _avault_authorization_required(_avault_detail(proc))+ if proc.returncode == 0:+ avault_authorization.clear_authorization_required()+ return proc+++def _raise_if_agent_authorization_required(exc: Exception) -> None:+ """Re-raise a resident-agent ``keychain_authorization_required`` frame as Avibe's error."""+ from vibe.avault_agent import AvaultAgentAuthorizationRequiredError++ if isinstance(exc, AvaultAgentAuthorizationRequiredError):+ raise _avault_authorization_required(str(exc)) from exc+++def _avault_supports_keychain_authorization(path: str | None) -> bool:+ return _version_at_least(_probe_avault_version(path), AVAULT_KEYCHAIN_AUTHORIZATION_MIN_VERSION)+++def _avault_master_key_needs_authorization() -> bool | None:+ """Ask avault, without any prompt, whether it can read the master key.++ Runs one-shot ``pubkey``, which loads the master key (and, like the first+ Vault use, creates it when none exists). True means authorization is+ required, False that the key loaded, None that the check failed otherwise.+ Callers must gate this on AVAULT_KEYCHAIN_AUTHORIZATION_MIN_VERSION: an+ older binary's background read may still prompt.+ """+ try:+ _run_avault(["pubkey"])+ except AvaultAuthorizationRequiredError:+ return True+ except AvaultError:+ logger.warning("avault master-key check failed", exc_info=True)+ return None+ return False+++def _check_avault_keychain_authorization_after_upgrade() -> None:+ """Record, without prompting, whether the binary just installed needs authorization.++ A Developer ID avault cannot read a master key an ad-hoc release created+ until the user authorizes it once, so look right after replacing the binary+ and let the Web UI offer the action before a real Vault call fails.+ """+ if platform.system() != "Darwin":+ return+ try:+ if not _avault_supports_keychain_authorization(_resolve_avault_cli_path()):+ return+ _avault_master_key_needs_authorization()+ except Exception: # noqa: BLE001 - the install already succeeded+ logger.warning("install_avault: avault Keychain authorization check failed", exc_info=True)def _envelope_payload(sealed) -> dict:@@ -9508,6 +9617,7 @@ def avault_agent_pubkey() -> dict:try:payload = _avault_agent_client().pubkey()except AvaultAgentError as exc:+ _raise_if_agent_authorization_required(exc)raise AvaultError(str(exc)) from excpublic_key = payload.get("public_key")fingerprint = payload.get("fingerprint")@@ -9596,6 +9706,9 @@ def avault_deliver_run(secrets: list[dict], command: list[str]) -> dict:(``128 + signal`` if signalled). Delivery is fail-closed: once avault returnsan exit code, callers must treat the secret as handed to the child unless afuture avault protocol provides a distinct pre-handoff failure signal.+ keychain_authorization_required is not one here: 77 may be the child's own+ status, so it is raised as ``AvaultAuthorizationRequiredError`` (still+ fail-closed) only when ``_deliver_run_needed_authorization`` confirms it."""path = _require_avault_path()payload = json.dumps(@@ -9622,9 +9735,23 @@ def avault_deliver_run(secrets: list[dict], command: list[str]) -> dict:# which surfaces its exit code.passexit_code = proc.wait()+ if exit_code == _AVAULT_EXIT_AUTHORIZATION_REQUIRED and _deliver_run_needed_authorization(path):+ raise _avault_authorization_required(before_handoff=False)return {"exit_code": exit_code, "delivered": True}+def _deliver_run_needed_authorization(path: str) -> bool:+ """Whether one-shot ``deliver run``'s exit 77 most likely was avault's own.++ ``deliver run`` exits with its child's status, so 77 alone is ambiguous. A+ fresh master-key check that also needs authorization makes avault's own+ failure the likely cause, but it cannot prove that no child ran (the+ Keychain may have locked while one did), so callers keep the delivery+ fail-closed and only report the authorization the user must give.+ """+ return _avault_supports_keychain_authorization(path) and _avault_master_key_needs_authorization() is True++def _agent_secret_payload(secret: dict, *, target_field: str) -> dict:payload = {"name": secret["name"],@@ -9658,6 +9785,7 @@ def avault_agent_grant(deks=deks,)except AvaultAgentError as exc:+ _raise_if_agent_authorization_required(exc)raise AvaultError(str(exc)) from exc@@ -9682,6 +9810,7 @@ def avault_agent_release(*, grant_id: str) -> dict:try:return AvaultAgentClient(_avault_agent_manager().socket_path, timeout=1.0).release(grant_id=grant_id)except AvaultAgentError as exc:+ _raise_if_agent_authorization_required(exc)raise AvaultError(str(exc)) from exc@@ -9784,6 +9913,7 @@ def avault_agent_deliver_run(context=context,)except AvaultAgentError as exc:+ _raise_if_agent_authorization_required(exc)if _avault_agent_error_is_absent(str(exc)):raise AvaultPreHandoffError(str(exc)) from excraise AvaultError(str(exc)) from exc@@ -9826,6 +9956,7 @@ def avault_agent_deliver_fetch(context=context,)except AvaultAgentError as exc:+ _raise_if_agent_authorization_required(exc)if _avault_agent_error_is_absent(str(exc)):raise AvaultPreHandoffError(str(exc)) from excraise AvaultError(str(exc)) from exc@@ -9850,6 +9981,7 @@ def avault_agent_deliver_inject(secrets=[_agent_secret_payload(secret, target_field="key") for secret in secrets],)except AvaultAgentError as exc:+ _raise_if_agent_authorization_required(exc)if _avault_agent_error_is_absent(str(exc)):raise AvaultPreHandoffError(str(exc)) from excraise AvaultError(str(exc)) from exc@@ -9918,6 +10050,88 @@ def avault_key_import(blob: dict, passphrase: str, *, force: bool = False) -> Noraise AvaultError(_avault_detail(proc) or "avault key import failed")+def avault_key_authorize() -> dict:+ """Run ``avault key authorize`` once: the only avault call that may show a dialog.++ It asks macOS to let this avault binary read the existing master key; the+ dialog appears on the screen of the Mac running this process, never in a+ browser. Call it only for an explicit user action (the Web "Authorize+ avault" button or ``vibe vault key authorize``), never from a poller, a+ retry, or an Agent tool. avault itself shares one dialog among concurrent+ callers and suppresses new ones for 120 s after a deny or cancel.++ Returns ``{"ok", "reason", "detail"?}``. ``reason`` is ``authorized``,+ ``not_applicable`` (no Keychain off macOS), ``avault_missing``,+ ``avault_upgrade_required``, ``timed_out``, ``no_gui_session`` (this process+ provably cannot show the dialog), or ``not_completed`` (denied, cancelled,+ still cooling down, or failed; avault's own ``detail`` says which).+ """+ if platform.system() != "Darwin":+ return {"ok": True, "reason": "not_applicable"}+ path = _resolve_avault_cli_path()+ if not path:+ return {"ok": False, "reason": "avault_missing"}+ if not _avault_supports_keychain_authorization(path):+ return {"ok": False, "reason": "avault_upgrade_required"}+ try:+ proc = subprocess.run(+ [path, *_avault_args(["key", "authorize"])],+ stdin=subprocess.DEVNULL,+ capture_output=True,+ timeout=_AVAULT_AUTHORIZE_TIMEOUT_SECONDS,+ env=_command_env_for(path),+ **isolated_subprocess_kwargs(),+ )+ except FileNotFoundError:+ return {"ok": False, "reason": "avault_missing"}+ except subprocess.TimeoutExpired:+ return {"ok": False, "reason": "timed_out"}+ if proc.returncode == 0:+ avault_authorization.clear_authorization_required()+ return {"ok": True, "reason": "authorized"}+ # avault exits 70 for a deny, a cancel, the cooldown after one, and a session+ # that cannot show the dialog alike; tell the last apart from this process's+ # own login session instead of parsing avault's text.+ result = {"ok": False, "reason": "no_gui_session" if _process_cannot_show_macos_dialogs() else "not_completed"}+ detail = _avault_detail(proc)+ if detail:+ result["detail"] = detail[-_AVAULT_AUTHORIZE_DETAIL_LIMIT:]+ return result+++def _process_cannot_show_macos_dialogs() -> bool:+ """True only when this process provably runs outside the logged-in desktop session.++ A process started over SSH, or with nobody logged in at the desktop, has no+ window server to show the Keychain dialog on. An inconclusive probe is not+ proof, so it reads as False.+ """+ try:+ from vibe.macos_session_diagnostics import MacOSSessionProbe++ context = MacOSSessionProbe().capture_context()+ except Exception: # noqa: BLE001 - a diagnostic only refines the message+ return False+ return context.gui_domain_available is False or context.asid_match is False+++def get_avault_authorization_status() -> dict:+ """Whether avault needs the one-time Keychain authorization, and this process's last attempt."""+ record = avault_authorization.read_record()+ return {+ "ok": True,+ "required": record is not None,+ "detected_at": record.get("detected_at") if record else None,+ "attempt": avault_authorization.current_attempt(),+ }+++def start_avault_authorization() -> dict:+ """Start the user's "Authorize avault" action, or join the one already running."""+ avault_authorization.start_authorization(avault_key_authorize)+ return get_avault_authorization_status()++def _askill_auto_update_disabled() -> bool:"""Return whether the managed askill reconcile loop is explicitly disabled."""skip_value = os.environ.get(_ASKILL_SKIP_ENV, "").strip().lower()@@ -10326,6 +10540,7 @@ def dependencies_status(*, offline: bool = False, dependency_ids: list[str] | No"latest_version": AVAULT_VERSION,"has_update": bool(av["installed"] and not _version_at_least(av.get("version"), AVAULT_VERSION)),"status": av["status"],+ "authorization_required": bool(av["installed"]) and avault_authorization.authorization_required(),}if requested.intersection({"show-runtime", "node"}):deps["show-runtime"], deps["node"] = _show_runtime_dependencies_status(offline=offline)diff --git a/vibe/avault_agent.py b/vibe/avault_agent.pyindex 0a5c1a45e..fb48a88e4 100644--- a/vibe/avault_agent.py+++ b/vibe/avault_agent.py@@ -31,10 +31,19 @@ DEFAULT_AGENT_START_TIMEOUT = 5.0DEFAULT_AGENT_IDLE_TIMEOUT_SECS = 3600+# Error-frame ``code`` avault 0.1.8+ sets when macOS Keychain has not yet+# approved the binary; older agents never send ``code``.+KEYCHAIN_AUTHORIZATION_REQUIRED_CODE = "keychain_authorization_required"++class AvaultAgentError(Exception):"""The resident avault agent failed a request."""+class AvaultAgentAuthorizationRequiredError(AvaultAgentError):+ """The agent could not read the master key until the user authorizes avault."""++class AvaultAgentClient:"""Length-prefixed JSON client for ``avault agent``."""@@ -59,8 +68,10 @@ class AvaultAgentClient:if not isinstance(response, dict):raise AvaultAgentError("agent returned malformed response")if response.get("ok") is not True:- error = response.get("error")- raise AvaultAgentError(str(error or "avault agent request failed"))+ error = str(response.get("error") or "avault agent request failed")+ if response.get("code") == KEYCHAIN_AUTHORIZATION_REQUIRED_CODE:+ raise AvaultAgentAuthorizationRequiredError(error)+ raise AvaultAgentError(error)result = response.get("result")if not isinstance(result, dict):raise AvaultAgentError("agent returned malformed response")diff --git a/vibe/avault_authorization.py b/vibe/avault_authorization.pynew file mode 100644index 000000000..d3b2a7064--- /dev/null+++ b/vibe/avault_authorization.py@@ -0,0 +1,158 @@+"""Avibe's side of avault's one-time macOS Keychain authorization.++macOS lets a binary read a Keychain item only after the user approves that+binary's code identity once. Developer ID signed avault (0.1.8 and later) never+shows that dialog from a background call: when the item does not trust it yet,+the call fails with the ``keychain_authorization_required`` contract (one-shot+exit status 77, or ``code`` on a resident-agent error frame), and only+``avault key authorize`` may show the dialog. An existing user whose master key+an ad-hoc release created meets this once after upgrading to the signed+release; later signed releases read the key without asking again.++This module owns the state Avibe keeps for that:++- the "authorization required" record every process shares, written when an+ avault call reports the contract and removed once the master key is read;+- the single authorization a Web action runs at a time in this process.++Running avault stays in ``vibe.api`` with every other avault call. Nothing here+starts an authorization on its own: only an explicit user action may.+"""++from __future__ import annotations++import json+import logging+import os+import threading+import uuid+from datetime import datetime, timezone+from pathlib import Path+from typing import Any, Callable++from config import paths++logger = logging.getLogger(__name__)++AUTHORIZATION_REQUIRED_CODE = "avault_authorization_required"+_RECORD_FILE = "avault_authorization.json"+_RECORD_SCHEMA_VERSION = 1++_ATTEMPT_LOCK = threading.Lock()+_ATTEMPT: dict[str, Any] | None = None+++def _record_path() -> Path:+ return paths.get_state_dir() / _RECORD_FILE+++def _now() -> str:+ return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z")+++def read_record() -> dict[str, Any] | None:+ """The recorded requirement, or None when avault is not known to need one.++ A record this version cannot read is ignored with a warning: it must never+ keep Vault behind an authorization nobody can clear.+ """+ path = _record_path()+ try:+ raw = path.read_text(encoding="utf-8")+ except FileNotFoundError:+ return None+ except OSError:+ logger.warning("could not read the avault authorization record at %s", path, exc_info=True)+ return None+ try:+ record = json.loads(raw)+ except ValueError:+ logger.warning("ignoring an unreadable avault authorization record at %s", path)+ return None+ if not isinstance(record, dict) or record.get("required") is not True:+ return None+ return record+++def authorization_required() -> bool:+ return read_record() is not None+++def record_authorization_required() -> None:+ """Remember that avault cannot read the master key until the user authorizes it."""+ if authorization_required():+ return+ path = _record_path()+ payload = {+ "schema_version": _RECORD_SCHEMA_VERSION,+ "required": True,+ "detected_at": _now(),+ }+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")+ try:+ path.parent.mkdir(parents=True, exist_ok=True)+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(fd, "w", encoding="utf-8") as handle:+ json.dump(payload, handle)+ os.replace(tmp, path)+ except OSError:+ tmp.unlink(missing_ok=True)+ logger.warning("could not record that avault needs Keychain authorization", exc_info=True)+ return+ logger.warning("avault needs a one-time macOS Keychain authorization")+++def clear_authorization_required() -> None:+ """Forget the requirement: avault has just read the master key."""+ path = _record_path()+ try:+ path.unlink()+ except FileNotFoundError:+ return+ except OSError:+ logger.warning("could not clear the avault authorization record at %s", path, exc_info=True)+ return+ logger.info("avault Keychain authorization is in place")+++def current_attempt() -> dict[str, Any] | None:+ with _ATTEMPT_LOCK:+ return dict(_ATTEMPT) if _ATTEMPT is not None else None+++def start_authorization(run: Callable[[], dict[str, Any]]) -> dict[str, Any]:+ """Start one authorization in the background, or join the one in flight.++ ``run`` performs it and returns ``{"ok": bool, "reason": str, ...}``. Every+ caller that arrives while it runs gets the same attempt back instead of a+ second avault process, so a repeated click shows at most one dialog.+ """+ global _ATTEMPT+ with _ATTEMPT_LOCK:+ if _ATTEMPT is not None and _ATTEMPT.get("state") == "running":+ return dict(_ATTEMPT)+ attempt = {"id": uuid.uuid4().hex, "state": "running", "started_at": _now()}+ _ATTEMPT = attempt+ snapshot = dict(attempt)++ def _target() -> None:+ global _ATTEMPT+ try:+ outcome = run()+ except Exception as exc: # noqa: BLE001 - the attempt must always finish+ logger.warning("avault authorization failed unexpectedly", exc_info=True)+ outcome = {"ok": False, "reason": "failed", "detail": str(exc)}+ finished = {+ **attempt,+ "state": "succeeded" if outcome.get("ok") else "failed",+ "reason": outcome.get("reason"),+ "finished_at": _now(),+ }+ if outcome.get("detail"):+ finished["detail"] = outcome["detail"]+ with _ATTEMPT_LOCK:+ if _ATTEMPT is attempt:+ _ATTEMPT = finished++ threading.Thread(target=_target, name="avault-authorize", daemon=True).start()+ return snapshotdiff --git a/vibe/cli.py b/vibe/cli.pyindex bc70eba35..efcee9371 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -449,6 +449,39 @@ def _retyped_placement_refusal(return exc+AVAULT_AUTHORIZATION_REQUIRED_CODE = "avault_authorization_required"+++def _is_avault_authorization_required(exc: Exception) -> bool:+ return getattr(exc, "code", None) == AVAULT_AUTHORIZATION_REQUIRED_CODE+++def _avault_authorization_required_cli_error(help_command: str | None) -> TaskCliError:+ """The one Agent-facing report of avault's one-time Keychain authorization.++ Typed at the printer so every Vault command that reaches avault reports it+ the same way. avault's own text tells a person to run ``avault key+ authorize``; an Agent must instead hand the step to the user and stop.+ """+ return TaskCliError(+ "avault needs a one-time macOS Keychain authorization on the Mac running Avibe",+ code=AVAULT_AUTHORIZATION_REQUIRED_CODE,+ hint=(+ "Do not retry and do not run avault yourself. Ask the user to choose Authorize avault on "+ "the Vault page in Avibe (or to run `vibe vault key authorize` themselves on the Mac running "+ "Avibe), then answer the macOS dialog on that Mac with its login password and Always Allow. "+ "Run this command once after they confirm."+ ),+ help_command=help_command,+ )+++def _avault_cli_error(exc: Exception, message: str, *, code: str = "avault_failed", help_command: str | None = None) -> TaskCliError:+ if _is_avault_authorization_required(exc):+ code = AVAULT_AUTHORIZATION_REQUIRED_CODE+ return TaskCliError(message, code=code, help_command=help_command)++def _print_task_error(exc: Exception, *, help_command: str | None = None) -> None:# Re-typed BEFORE the ``TaskCliError`` branch, and here rather than in each command's# own ``except``, because this is the one printer every CLI admission door funnels its@@ -460,6 +493,8 @@ def _print_task_error(exc: Exception, *, help_command: str | None = None) -> Non# payload builder below.if isinstance(exc, UnresolvableSessionTarget) and exc.reason == "reserved":exc = _reserved_session_cli_error(exc)+ if _is_avault_authorization_required(exc):+ exc = _avault_authorization_required_cli_error(getattr(exc, "help_command", None) or help_command)from storage.resource_access_service import (HARNESS_ACCESS_FORBIDDEN_CODE,ResourceAccessError,@@ -9693,7 +9728,7 @@ def cmd_vault_run(args):_print_task_error(TaskCliError("protected grant expired; approve the request again", code="approval_required", help_command=help_command))return 1_finish_one_shot_after_avault_error(engine, one_shot_grants, exc, reason="vault-run-one-shot")- _print_task_error(TaskCliError(f"avault deliver failed: {exc}", code="avault_failed", help_command=help_command))+ _print_task_error(_avault_cli_error(exc, f"avault deliver failed: {exc}", help_command=help_command))return 1except Exception as exc:if handoff_started:@@ -10200,7 +10235,7 @@ def cmd_vault_await(args):_print_task_error(TaskCliError(str(exc), code="invalid_request", help_command=help_command))return 1except api.AvaultError as exc:- _print_task_error(TaskCliError(f"avault sign failed: {exc}", code="avault_failed", help_command=help_command))+ _print_task_error(_avault_cli_error(exc, f"avault sign failed: {exc}", help_command=help_command))return 1except TaskCliError as exc:_print_task_error(exc)@@ -10612,7 +10647,7 @@ def cmd_vault_fetch(args):)_print_task_error(TaskCliError("protected grant expired; approve the request again", code="approval_required", help_command=help_command))return 1- _print_task_error(TaskCliError(f"request failed: {exc}", code="request_failed", help_command=help_command))+ _print_task_error(_avault_cli_error(exc, f"request failed: {exc}", code="request_failed", help_command=help_command))return 1except Exception as exc:if handoff_started:@@ -10800,7 +10835,7 @@ def cmd_vault_inject(args):)_print_task_error(TaskCliError("protected grant expired; approve the request again", code="approval_required", help_command=help_command))return 1- _print_task_error(TaskCliError(f"avault inject failed: {exc}", code="avault_failed", help_command=help_command))+ _print_task_error(_avault_cli_error(exc, f"avault inject failed: {exc}", help_command=help_command))return 1except Exception as exc:if handoff_started:@@ -10811,6 +10846,70 @@ def cmd_vault_inject(args):return 1+# (code, message, hint) for each ``api.avault_key_authorize`` failure reason.+_AVAULT_AUTHORIZE_FAILURES = {+ "not_completed": (+ "avault_authorization_not_completed",+ "avault authorization did not complete",+ "If you chose Deny or closed the dialog, macOS will not show it again for about 2 minutes; "+ "run this again after that.",+ ),+ "no_gui_session": (+ "avault_authorization_no_gui_session",+ "this session cannot show the macOS Keychain dialog",+ "Run this in Terminal on the Mac's desktop rather than over SSH, or choose Authorize avault on "+ "the Vault page in Avibe; the dialog then appears on that Mac's screen.",+ ),+ "timed_out": (+ "avault_authorization_timed_out",+ "nobody answered the macOS Keychain dialog within 10 minutes",+ "Run this again when you can answer the dialog on this Mac.",+ ),+ "avault_missing": ("avault_missing", "avault is not installed", "Run: vibe doctor repair avault --yes"),+ "avault_upgrade_required": (+ "avault_upgrade_required",+ f"authorizing avault requires avault >= {api.AVAULT_KEYCHAIN_AUTHORIZATION_MIN_VERSION}",+ "Run: vibe doctor repair avault --yes",+ ),+}+++def cmd_vault_key_authorize(args):+ """Run avault's one Keychain dialog for the person at this Mac."""+ help_command = "vibe vault key authorize --help"+ if caller_context_from_env() is not None:+ # Only an explicit user action may raise the dialog; an Agent hands the step back.+ _print_task_error(+ TaskCliError(+ "vibe vault key authorize must be run by the user, not by an Agent",+ code="user_action_required",+ hint=(+ "Ask the user to choose Authorize avault on the Vault page in Avibe, or to run "+ "`vibe vault key authorize` themselves on the Mac running Avibe."+ ),+ help_command=help_command,+ )+ )+ return 1+ if platform.system() == "Darwin":+ print(+ "Waiting for the macOS Keychain dialog on this Mac: enter this Mac's login password "+ "and choose Always Allow.",+ file=sys.stderr,+ flush=True,+ )+ result = api.avault_key_authorize()+ if result.get("ok"):+ _print_cli_payload("vault_key_authorize", status=result.get("reason"))+ return 0+ code, message, hint = _AVAULT_AUTHORIZE_FAILURES.get(+ str(result.get("reason")), _AVAULT_AUTHORIZE_FAILURES["not_completed"]+ )+ details = {"avault_error": result["detail"]} if result.get("detail") else None+ _print_task_error(TaskCliError(message, code=code, hint=hint, help_command=help_command, details=details))+ return 1++def _read_passphrase_stdin(help_command: str) -> str:data = sys.stdin.read()phrase = data.split("\n", 1)[0].strip() if data else ""@@ -10859,7 +10958,7 @@ def cmd_vault_key_export(args):passreturn 0except api.AvaultError as exc:- _print_task_error(TaskCliError(f"avault key export failed: {exc}", code="vault_key_export_failed", help_command=help_command))+ _print_task_error(_avault_cli_error(exc, f"avault key export failed: {exc}", code="vault_key_export_failed", help_command=help_command))return 1except TaskCliError as exc:_print_task_error(exc)@@ -10894,7 +10993,7 @@ def cmd_vault_key_import(args):_print_cli_payload("vault_key_import", imported=True)return 0except api.AvaultError as exc:- _print_task_error(TaskCliError(f"avault key import failed: {exc}", code="vault_key_import_failed", help_command=help_command))+ _print_task_error(_avault_cli_error(exc, f"avault key import failed: {exc}", code="vault_key_import_failed", help_command=help_command))return 1except TaskCliError as exc:_print_task_error(exc)@@ -11701,6 +11800,15 @@ def _managed_dependencies_doctor_items(*, language: str = "en", deep: bool = Falcode=f"dependencies.{dependency_id}.ready",dependency_status=None,)+ if dependency_id == "avault" and dependency.get("authorization_required"):+ # No repair target: only the user may raise the macOS dialog.+ _add_doctor_item(+ items,+ "warn",+ i18n_t("doctor.item.avaultAuthorizationRequired", language),+ i18n_t("doctor.action.avaultAuthorizationRequired", language),+ code="dependencies.avault.authorization_required",+ )continuerequired = bool(dependency.get("required"))@@ -17715,9 +17823,9 @@ def build_parser():),formatter_class=argparse.RawDescriptionHelpFormatter,error_help_command="vibe vault key --help",- error_hint="Run: vibe vault key export | vibe vault key import <file>",+ error_hint="Run: vibe vault key export | vibe vault key import <file> | vibe vault key authorize",)- vault_key_sub = vault_key_parser.add_subparsers(dest="vault_key_command", metavar="{export,import}")+ vault_key_sub = vault_key_parser.add_subparsers(dest="vault_key_command", metavar="{export,import,authorize}")vault_key_sub.required = Truevault_key_export_parser = vault_key_sub.add_parser("export",@@ -17738,6 +17846,20 @@ def build_parser():vault_key_import_parser.add_argument("file", help="Export blob file produced by 'vibe vault key export'")vault_key_import_parser.add_argument("--force", action="store_true", help="Overwrite an existing machine key")_add_json_noop(vault_key_import_parser)+ vault_key_authorize_parser = vault_key_sub.add_parser(+ "authorize",+ help="Let avault read the machine key after macOS asks (one macOS dialog)",+ description=(+ "Run once when Vault reports avault_authorization_required, usually right after the first "+ "Developer ID signed avault replaced an older one. macOS shows one Keychain dialog on this "+ "Mac's screen: enter this Mac's login password and choose Always Allow. Run it yourself in a "+ "logged-in desktop session; over SSH, use Authorize avault on the Vault page in Avibe "+ "instead. Agents must ask the user rather than run it."+ ),+ formatter_class=argparse.RawDescriptionHelpFormatter,+ error_help_command="vibe vault key authorize --help",+ )+ _add_json_noop(vault_key_authorize_parser)vault_request_parser = vault_subparsers.add_parser("request",@@ -18729,6 +18851,8 @@ _CLI_COMMAND_FLOORS: dict[tuple[str, ...], Optional[str]] = {("vault", "remove"): "editor",("vault", "key", "export"): "owner",("vault", "key", "import"): "owner",+ # Lets this machine's avault read its key; the Web action is instance-level too.+ ("vault", "key", "authorize"): "owner",# Show: reading a page is Viewer work and writing to one is Editor work; the# page's own ACL still decides which page, on both sides.("show", "list"): "viewer",@@ -19021,6 +19145,8 @@ def _dispatch_parsed_command(parser: argparse.ArgumentParser, args) -> None:sys.exit(cmd_vault_key_export(args))if args.vault_key_command == "import":sys.exit(cmd_vault_key_import(args))+ if args.vault_key_command == "authorize":+ sys.exit(cmd_vault_key_authorize(args))parser.error("vault key command is required")parser.error("vault command is required")if args.command == "data":diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex ec6c7ccbc..741b9c008 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -1308,6 +1308,7 @@"gitSystemReady": "Git is ready via the system runtime","dependencyReady": "{label} is ready","dependencyReadyVersioned": "{label} {version} is ready",+ "avaultAuthorizationRequired": "avault needs a one-time macOS Keychain authorization before Vault can use its key","nodeNotReady": "{label} is missing or unsupported","dependencyPlatformUnsupported": "{label} is not published for this platform","dependencyArchiveUrlUnsupported": "{label} archive URL uses an unsupported scheme: {url}",@@ -1418,6 +1419,7 @@"nodeNotReady": "Install a supported Node.js release (^20.19.0 or >=22.12.0).","dependencyPlatformUnsupported": "Use a system dependency where supported, or run Avibe on a platform with a published runtime.","dependencyArchiveUrlUnsupported": "Configure the dependency manifest with an HTTPS or file URL.",+ "avaultAuthorizationRequired": "On the Vault page in Avibe choose Authorize avault, or run `vibe vault key authorize` on the Mac running Avibe. The macOS dialog appears on that Mac, not in the browser: enter its login password and choose Always Allow.","dependencyNotReady": "{retry}","dependencyProbeUnsupported": "{retry}","dependencyProbeUnavailable": "Inspect the dependency manifest and platform mapping before retrying.",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 8c2b0e50a..3acb4db91 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -1308,6 +1308,7 @@"gitSystemReady": "Git 已通过系统运行时就绪","dependencyReady": "{label} 已就绪","dependencyReadyVersioned": "{label} {version} 已就绪",+ "avaultAuthorizationRequired": "avault 需要一次性的 macOS 钥匙串授权,Vault 才能使用其密钥","nodeNotReady": "{label} 缺失或不受支持","dependencyPlatformUnsupported": "该平台未发布 {label}","dependencyArchiveUrlUnsupported": "{label} 归档 URL 使用不支持的协议:{url}",@@ -1418,6 +1419,7 @@"nodeNotReady": "安装受支持的 Node.js 版本(^20.19.0 或 >=22.12.0)。","dependencyPlatformUnsupported": "在支持的情况下使用系统依赖,或在发布该运行时的平台上运行 Avibe。","dependencyArchiveUrlUnsupported": "将依赖清单配置为 HTTPS 或 file URL。",+ "avaultAuthorizationRequired": "在 Avibe 的 Vault 页面选择「授权 avault」,或在运行 Avibe 的 Mac 上执行 `vibe vault key authorize`。macOS 对话框会出现在那台 Mac 上,而不是浏览器里:输入它的登录密码并选择「始终允许」。","dependencyNotReady": "{retry}","dependencyProbeUnsupported": "{retry}","dependencyProbeUnavailable": "重试前检查依赖清单和平台映射。",diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 83055e0b9..951ba6c16 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -5848,6 +5848,24 @@ def vault_agent_pubkey_get():return _vault_error_response(exc)[email protected]("/api/vault/avault-authorization", methods=["GET"])+def vault_avault_authorization_get():+ from vibe import api++ return jsonify(api.get_avault_authorization_status())++[email protected]("/api/vault/avault-authorization", methods=["POST"])+def vault_avault_authorization_post():+ from vibe import api++ # Machine-level, like dependency repair: the Keychain dialog appears on the host's screen.+ authorization_context = getattr(g, "authorization_context", None)+ if authorization_context is None or not authorization_context.can_manage_instance:+ return jsonify({"ok": False, "error": "instance_access_forbidden"}), 403+ return jsonify(api.start_avault_authorization())++@app.route("/api/vault/sandbox/root-metadata", methods=["GET"])def vault_sandbox_root_metadata_get():from vibe import api