Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
Vaults: address-based signing keys + create-form & dialog UX fixes (#768)
Call White42a5fc5ce62a
diff --git a/pyproject.toml b/pyproject.tomlindex 8b77b5de2..9b23cda81 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -70,6 +70,9 @@ dependencies = ["imagesize>=1.4.1","pywebpush>=2.0.3","cryptography>=42.0",+ # keccak256 + ripemd160 for vault signing-key address derivation+ # (storage/vault_addresses.py); cryptography ships neither.+ "pycryptodome>=3.20",][project.urls]diff --git a/storage/vault_addresses.py b/storage/vault_addresses.pynew file mode 100644index 000000000..f35111d92--- /dev/null+++ b/storage/vault_addresses.py@@ -0,0 +1,221 @@+"""Public blockchain address derivation for secp256k1 signing keys.++A vault signing key is a chain-agnostic secp256k1 keypair. From its (public)+compressed public key we derive the standard receive addresses so the Web UI and+the agent can identify a key by address instead of raw hex. Only PUBLIC key+material is used here — never the private key — so this derivation is safe to run+outside the avault custody core.++Addresses derived (mainnet):+ eth Ethereum, EIP-55 checksummed ``0x`` address+ btc_legacy Bitcoin P2PKH, base58check ``1...``+ btc_segwit Bitcoin P2WPKH native segwit v0, bech32 ``bc1q...``+ btc_taproot Bitcoin P2TR key-path taproot v1, bech32m ``bc1p...``++Correctness is custody-critical; ``tests/test_vault_addresses.py`` pins every+output to published BIP/EIP test vectors.+"""++from __future__ import annotations++import hashlib++from Crypto.Hash import keccak+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric import ec++# secp256k1 field prime (P) and group order (N).+_P = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F+_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141++_BECH32_CHARSET = "qpzry9x8gf2tvdw0s3jn54khce6mua7l"+_BECH32_CONST = 1+_BECH32M_CONST = 0x2BC830A3+_B58_CHARSET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"+++# ---- hashing --------------------------------------------------------------+++def _keccak256(data: bytes) -> bytes:+ h = keccak.new(digest_bits=256)+ h.update(data)+ return h.digest()+++def _ripemd160(data: bytes) -> bytes:+ # hashlib exposes ripemd160 only when the OpenSSL build provides it (often+ # disabled on OpenSSL 3); fall back to pycryptodome, which always ships it.+ try:+ h = hashlib.new("ripemd160")+ h.update(data)+ return h.digest()+ except (ValueError, TypeError):+ from Crypto.Hash import RIPEMD160++ return RIPEMD160.new(data).digest()+++def _hash160(data: bytes) -> bytes:+ return _ripemd160(hashlib.sha256(data).digest())+++def _tagged_hash(tag: str, msg: bytes) -> bytes:+ prefix = hashlib.sha256(tag.encode()).digest()+ return hashlib.sha256(prefix + prefix + msg).digest()+++# ---- secp256k1 points -----------------------------------------------------+++def _point(encoded: bytes) -> tuple[int, int]:+ """Affine (x, y) of a SEC1-encoded point; validates it is on the curve."""+ pk = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), encoded)+ nums = pk.public_numbers()+ return nums.x, nums.y+++def _uncompressed(compressed: bytes) -> bytes:+ pk = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), compressed)+ return pk.public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint)+++def _point_add(p1: tuple[int, int], p2: tuple[int, int]) -> tuple[int, int]:+ """Affine point addition on secp256k1 (handles the doubling case)."""+ x1, y1 = p1+ x2, y2 = p2+ if x1 == x2 and (y1 + y2) % _P == 0:+ raise ValueError("point addition resulted in the point at infinity")+ if x1 == x2 and y1 == y2:+ lam = (3 * x1 * x1) * pow(2 * y1, -1, _P) % _P+ else:+ lam = (y2 - y1) * pow((x2 - x1) % _P, -1, _P) % _P+ x3 = (lam * lam - x1 - x2) % _P+ y3 = (lam * (x1 - x3) - y1) % _P+ return x3, y3+++def _normalize_compressed(public_key_hex: str) -> bytes:+ """Return the 33-byte compressed form, accepting compressed or uncompressed hex."""+ raw = bytes.fromhex(public_key_hex.strip())+ if len(raw) == 65 and raw[0] == 0x04:+ # Validate the FULL uncompressed point on-curve before trusting its Y parity, then+ # compress from the validated coordinates — an off-curve X||Y must be rejected, not+ # silently "corrected" to a different valid point with the same X.+ x, y = _point(raw)+ raw = bytes([0x02 + (y & 1)]) + x.to_bytes(32, "big")+ if len(raw) != 33 or raw[0] not in (0x02, 0x03):+ raise ValueError("expected a compressed secp256k1 public key")+ _point(raw) # raises if not on curve+ return raw+++# ---- encoders -------------------------------------------------------------+++def _b58check(payload: bytes) -> str:+ checksum = hashlib.sha256(hashlib.sha256(payload).digest()).digest()[:4]+ data = payload + checksum+ n = int.from_bytes(data, "big")+ out = ""+ while n > 0:+ n, rem = divmod(n, 58)+ out = _B58_CHARSET[rem] + out+ pad = len(data) - len(data.lstrip(b"\x00"))+ return "1" * pad + out+++def _bech32_polymod(values: list[int]) -> int:+ generators = (0x3B6A57B2, 0x26508E6D, 0x1EA119FA, 0x3D4233DD, 0x2A1462B3)+ chk = 1+ for value in values:+ top = chk >> 25+ chk = ((chk & 0x1FFFFFF) << 5) ^ value+ for i in range(5):+ chk ^= generators[i] if ((top >> i) & 1) else 0+ return chk+++def _hrp_expand(hrp: str) -> list[int]:+ return [ord(c) >> 5 for c in hrp] + [0] + [ord(c) & 31 for c in hrp]+++def _bech32_checksum(hrp: str, data: list[int], const: int) -> list[int]:+ values = _hrp_expand(hrp) + data+ polymod = _bech32_polymod(values + [0, 0, 0, 0, 0, 0]) ^ const+ return [(polymod >> 5 * (5 - i)) & 31 for i in range(6)]+++def _convertbits(data: bytes, frombits: int, tobits: int) -> list[int]:+ acc = 0+ bits = 0+ ret: list[int] = []+ maxv = (1 << tobits) - 1+ for value in data:+ acc = (acc << frombits) | value+ bits += frombits+ while bits >= tobits:+ bits -= tobits+ ret.append((acc >> bits) & maxv)+ if bits:+ ret.append((acc << (tobits - bits)) & maxv)+ return ret+++def _segwit_encode(hrp: str, witver: int, witprog: bytes) -> str:+ const = _BECH32_CONST if witver == 0 else _BECH32M_CONST+ data = [witver] + _convertbits(witprog, 8, 5)+ combined = data + _bech32_checksum(hrp, data, const)+ return hrp + "1" + "".join(_BECH32_CHARSET[d] for d in combined)+++# ---- address derivations --------------------------------------------------+++def _eip55(addr_hex: str) -> str:+ lower = addr_hex.lower()+ digest = _keccak256(lower.encode()).hex()+ return "".join(c.upper() if c.isalpha() and int(digest[i], 16) >= 8 else c for i, c in enumerate(lower))+++def _eth(compressed: bytes) -> str:+ # keccak256 of the 64-byte X||Y (uncompressed point without the 0x04 prefix).+ digest = _keccak256(_uncompressed(compressed)[1:])+ return "0x" + _eip55(digest[-20:].hex())+++def _p2pkh(compressed: bytes) -> str:+ return _b58check(b"\x00" + _hash160(compressed))+++def _p2wpkh(compressed: bytes) -> str:+ return _segwit_encode("bc", 0, _hash160(compressed))+++def _p2tr(compressed: bytes) -> str:+ x, _ = _point(compressed)+ x_bytes = x.to_bytes(32, "big")+ # BIP341 key-path taproot: internal key is the x-only key lifted to even Y,+ # tweaked by t = tagged_hash("TapTweak", x) with no script tree.+ internal = _point(b"\x02" + x_bytes)+ tweak = int.from_bytes(_tagged_hash("TapTweak", x_bytes), "big")+ if not 0 < tweak < _N:+ raise ValueError("invalid taproot tweak")+ tweak_point = ec.derive_private_key(tweak, ec.SECP256K1()).public_key().public_numbers()+ output_x, _ = _point_add(internal, (tweak_point.x, tweak_point.y))+ return _segwit_encode("bc", 1, output_x.to_bytes(32, "big"))+++def derive_addresses(public_key_hex: str) -> dict[str, str]:+ """Derive the standard mainnet addresses for a compressed secp256k1 public key.++ Raises ``ValueError`` for a malformed / off-curve key. Callers surfacing this+ for a stored key should treat failure as "no addresses", never a hard error.+ """+ compressed = _normalize_compressed(public_key_hex)+ return {+ "eth": _eth(compressed),+ "btc_legacy": _p2pkh(compressed),+ "btc_segwit": _p2wpkh(compressed),+ "btc_taproot": _p2tr(compressed),+ }diff --git a/storage/vault_service.py b/storage/vault_service.pyindex 3c08796bc..031fd22d6 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -15,6 +15,7 @@ the resident avault agent, not by Python.from __future__ import annotationsimport json+import loggingimport threadingimport uuidfrom dataclasses import dataclass@@ -28,8 +29,11 @@ from sqlalchemy.exc import IntegrityErrorfrom storage import vault_cryptofrom storage.models import vault_audit, vault_grants, vault_requests, vault_secrets+from storage.vault_addresses import derive_addressesfrom storage.vault_crypto import Sealed+logger = logging.getLogger(__name__)+SKILL_TAG_PREFIX = "skill:"DEFAULT_ENV_GRANT_TTL_SECONDS = 300DEFAULT_TAG_GRANT_TTL_SECONDS = 900@@ -479,11 +483,15 @@ def _meta_payload(row: dict[str, Any]) -> dict[str, Any]:}signing_public_key = public_meta.get("signing_public_key")if isinstance(signing_public_key, dict):- payload["signing_public_key"] = {- key: value- for key, value in signing_public_key.items()- if key in {"curve", "public_key"}- }+ # Surface derived receive addresses instead of the raw public key: agents and the+ # UI identify a signing key by address, not hex. Derivation is a pure function of the+ # (public) key; a malformed/legacy key degrades to no addresses, never a hard error.+ public_key = signing_public_key.get("public_key")+ if isinstance(public_key, str) and signing_public_key.get("curve") == "secp256k1":+ try:+ payload["signing_addresses"] = derive_addresses(public_key)+ except Exception:+ logger.warning("failed to derive signing addresses for secret %r", row.get("name"))return payload@@ -1182,6 +1190,18 @@ def get_secret_meta(conn: Connection, name: str) -> dict[str, Any]:return _meta_payload(_require_row(conn, name))+def get_signing_public_key(conn: Connection, name: str) -> dict[str, Any] | None:+ """Raw pinned signing public key ({curve, public_key}) from storage.++ The masked meta payload exposes only derived addresses (not the raw key), so+ server-side signature verification reads the pinned key from here instead.+ Returns ``None`` when the secret has no pinned signing key.+ """+ public_meta = _public_meta(_require_row(conn, name).get("public_meta"))+ signing_public_key = public_meta.get("signing_public_key")+ return signing_public_key if isinstance(signing_public_key, dict) else None++def store_pubkey_pin(conn: Connection, name: str, pin: dict[str, Any]) -> dict[str, Any]:"""Store avault pubkey pin/attestation metadata without touching value fields."""row = _require_row(conn, name)diff --git a/tests/test_vault_addresses.py b/tests/test_vault_addresses.pynew file mode 100644index 000000000..715647816--- /dev/null+++ b/tests/test_vault_addresses.py@@ -0,0 +1,59 @@+"""Address derivation pinned to published BIP/EIP test vectors (custody-critical)."""++import pytest++from storage.vault_addresses import derive_addresses++# secp256k1 private key = 1 → the generator point G, compressed. Its addresses are+# widely published reference vectors.+PRIVKEY_1_COMPRESSED = "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"++# BIP341 wallet-test-vectors.json, scriptPubKey[0] (key-path only, no merkle root):+# internal x-only pubkey → mainnet P2TR address.+BIP341_INTERNAL_XONLY = "d6889cb081036e0faefa3a35157ad71086b123b2b144b649798b494c300a961d"+BIP341_P2TR_ADDRESS = "bc1p2wsldez5mud2yam29q22wgfh9439spgduvct83k3pm50fcxa5dps59h4z5"+++def test_privkey_one_reference_addresses():+ addrs = derive_addresses(PRIVKEY_1_COMPRESSED)+ # ETH: privkey 1 → 0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf (EIP-55 checksum).+ assert addrs["eth"] == "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf"+ # P2PKH compressed.+ assert addrs["btc_legacy"] == "1BgGZ9tcN4rm9KBzDn7KprQz87SZ26SAMH"+ # P2WPKH — BIP173 canonical example (witness program = hash160 of G-compressed).+ assert addrs["btc_segwit"] == "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"+++def test_taproot_matches_bip341_vector():+ # Any parity for the x gives the same key-path taproot output (BIP341 lifts x to even Y).+ addrs = derive_addresses("02" + BIP341_INTERNAL_XONLY)+ assert addrs["btc_taproot"] == BIP341_P2TR_ADDRESS+ # Odd-parity encoding of the same x must derive the identical taproot address.+ assert derive_addresses("03" + BIP341_INTERNAL_XONLY)["btc_taproot"] == BIP341_P2TR_ADDRESS+++def test_accepts_uncompressed_and_matches_compressed():+ # privkey 1 uncompressed point (0x04 || X || Y) should normalize to the same addresses.+ gx = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"+ gy = "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"+ assert derive_addresses("04" + gx + gy) == derive_addresses(PRIVKEY_1_COMPRESSED)+++def test_eth_checksum_has_mixed_case():+ # A sanity guard that EIP-55 is applied (not just lowercased).+ eth = derive_addresses(PRIVKEY_1_COMPRESSED)["eth"]+ assert eth.startswith("0x") and eth != eth.lower()++[email protected]("bad", ["", "zz", "02" + "00" * 33, "04" + "11" * 10])+def test_rejects_malformed_keys(bad):+ with pytest.raises((ValueError, Exception)):+ derive_addresses(bad)+++def test_rejects_offcurve_uncompressed_key():+ # Valid x (G's x) but a garbage Y that is not on the curve: must be rejected, never+ # silently re-lifted to a different valid point with the same x.+ gx = "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"+ with pytest.raises((ValueError, Exception)):+ derive_addresses("04" + gx + "11" * 32)diff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex 4b66fe75a..eaf0da846 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -2756,6 +2756,38 @@ def test_protected_sign_completion_verifies_schnorr_browser_signature(monkeypatcassert result["request"]["status"] == "approved"+def test_signing_key_meta_exposes_addresses_not_public_key(monkeypatch):+ from unittest.mock import Mock++ monkeypatch.setattr(api, "avault_seal_blind_box", Mock(return_value=_sealed()))+ # privkey = 1 → generator point G, compressed. Reference addresses are pinned in+ # tests/test_vault_addresses.py.+ created = api.create_vault_secret(+ {+ "name": "ETH_KEY",+ "protection": "protected",+ "kind": "keypair",+ "signer_kind": "local",+ "sealed": {"ciphertext": "ct", "nonce": "n", "wrap_meta": "wm"},+ "public_meta": {+ "signing_public_key": {+ "curve": "secp256k1",+ "public_key": "0279be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",+ }+ },+ }+ )+ secret = created["secret"]+ # Decision: agents and the UI see derived addresses, never the raw public key.+ assert "signing_public_key" not in secret+ assert "signing_public_key" not in json.dumps(secret)+ addresses = secret["signing_addresses"]+ assert set(addresses) == {"eth", "btc_legacy", "btc_segwit", "btc_taproot"}+ assert addresses["eth"] == "0x7E5F4552091A69125d5DfCb7b8C2659029395Bdf"+ assert addresses["btc_segwit"] == "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"+ assert addresses["btc_taproot"].startswith("bc1p")++def test_vault_sign_rejects_malformed_digest_before_request_or_avault(monkeypatch):from unittest.mock import Mockdiff --git a/ui/src/components/ui/signing-address-list.tsx b/ui/src/components/ui/signing-address-list.tsxnew file mode 100644index 000000000..bd7cf929f--- /dev/null+++ b/ui/src/components/ui/signing-address-list.tsx@@ -0,0 +1,63 @@+import { useState } from 'react';+import { Check, Copy } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { SigningAddresses } from '@/context/ApiContext';+import { cn } from '@/lib/utils';++// Display order: ETH first, then BTC modern → legacy. Each entry maps a backend+// signing_addresses key to a short label; missing entries are skipped.+const ROWS: ReadonlyArray<{ key: keyof SigningAddresses; labelKey: string }> = [+ { key: 'eth', labelKey: 'vaults.addresses.eth' },+ { key: 'btc_segwit', labelKey: 'vaults.addresses.btcSegwit' },+ { key: 'btc_taproot', labelKey: 'vaults.addresses.btcTaproot' },+ { key: 'btc_legacy', labelKey: 'vaults.addresses.btcLegacy' },+];++const AddressRow: React.FC<{ label: string; value: string }> = ({ label, value }) => {+ const { t } = useTranslation();+ const [copied, setCopied] = useState(false);+ return (+ <div className="flex min-w-0 items-center gap-2">+ <span className="w-[68px] shrink-0 text-[11px] font-medium text-muted">{label}</span>+ <code className="min-w-0 flex-1 truncate rounded bg-surface-2 px-1.5 py-0.5 font-mono text-[11.5px] text-foreground" title={value}>+ {value}+ </code>+ <button+ type="button"+ onClick={() => {+ void navigator.clipboard?.writeText(value).then(() => {+ setCopied(true);+ window.setTimeout(() => setCopied(false), 1500);+ });+ }}+ aria-label={t('vaults.addresses.copy', { label })}+ className="shrink-0 text-muted transition-colors hover:text-foreground"+ >+ {copied ? <Check className="size-3.5 text-mint" /> : <Copy className="size-3.5" />}+ </button>+ </div>+ );+};++/**+ * Compact labeled list of a signing key's derived receive addresses (ETH + BTC+ * variants), each truncated with a copy button. Shared by the vault list row and+ * the create-form key builder. Renders nothing when there are no addresses.+ */+export const SigningAddressList: React.FC<{ addresses?: SigningAddresses | null; className?: string }> = ({+ addresses,+ className,+}) => {+ const { t } = useTranslation();+ if (!addresses) return null;+ const rows = ROWS.filter((row) => addresses[row.key]);+ if (rows.length === 0) return null;+ return (+ <div className={cn('flex min-w-0 flex-col gap-1', className)}>+ {rows.map((row) => (+ <AddressRow key={row.key} label={t(row.labelKey)} value={addresses[row.key] as string} />+ ))}+ </div>+ );+};diff --git a/ui/src/components/ui/tag-input.tsx b/ui/src/components/ui/tag-input.tsxindex 746cf0273..269b59847 100644--- a/ui/src/components/ui/tag-input.tsx+++ b/ui/src/components/ui/tag-input.tsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useId, useMemo, useState } from 'react';import type { KeyboardEvent, ClipboardEvent } from 'react';import { X } from 'lucide-react';@@ -19,6 +19,13 @@ export type TagInputProps = {/** Notified when the uncommitted draft becomes non-empty / empty, so the form* can block submitting while a chip is half-typed. */onPendingChange?: (pending: boolean) => void;+ /**+ * Selectable candidate values. When present, a dropdown offers them (all on+ * focus, filtered as the user types), so values can be picked instead of typed.+ * Already-selected values are hidden. Entries must be pre-normalized — clicking+ * one adds it verbatim, bypassing {@link normalize}.+ */+ suggestions?: string[];className?: string;inputClassName?: string;};@@ -32,6 +39,10 @@ const defaultNormalize = (raw: string): string | null => {* Chip-style multi-value input: type a value and press Enter or comma to add a* tag, click the × (or Backspace on an empty field) to remove one. Used for* vault secret tags and allowed-host lists.+ *+ * When {@link TagInputProps.suggestions} is passed, a dropdown lets the user pick+ * from candidate values (arrow keys + Enter, or click); otherwise it stays a+ * plain free-text chip input.*/export const TagInput: React.FC<TagInputProps> = ({values,@@ -41,13 +52,19 @@ export const TagInput: React.FC<TagInputProps> = ({ariaLabel,removeLabel = (value) => `Remove ${value}`,onPendingChange,+ suggestions,className,inputClassName,}) => {const [draft, setDraft] = useState('');+ const [focused, setFocused] = useState(false);+ const [highlight, setHighlight] = useState(-1);+ const listId = useId();+ const hasSuggestions = (suggestions?.length ?? 0) > 0;const setDraftSafe = (next: string) => {setDraft(next);+ setHighlight(-1);onPendingChange?.(next.trim().length > 0);};@@ -55,19 +72,50 @@ export const TagInput: React.FC<TagInputProps> = ({// a host:port) is visibly invalid instead of being silently dropped on submit.const draftInvalid = draft.trim().length > 0 && normalize(draft) === null;+ // Candidates not already chosen, matched against the draft (substring, case-insensitive).+ // With an empty draft this is the full list, so focusing reveals everything on offer; the+ // dropdown itself caps height and scrolls, so no arbitrary count limit is imposed.+ const matches = useMemo(() => {+ if (!suggestions?.length) return [];+ const query = draft.trim().toLowerCase();+ const chosen = new Set(values);+ return suggestions.filter((option) => !chosen.has(option) && (!query || option.toLowerCase().includes(query)));+ }, [suggestions, draft, values]);++ // The list shows while focused with candidates on offer. Escape is intentionally not+ // handled here: inside a Radix Dialog it registers Escape on document with capture, so a+ // bubble-phase handler can't scope it to the list — Escape stays the dialog's own close+ // key, and the list dismisses on blur / selection instead.+ const listOpen = focused && matches.length > 0;++ const add = (value: string) => {+ if (!values.includes(value)) onChange([...values, value]);+ setDraft('');+ setHighlight(-1);+ onPendingChange?.(false);+ };+const commit = (raw: string) => {const cleaned = normalize(raw);- if (!cleaned) return;- if (!values.includes(cleaned)) onChange([...values, cleaned]);- setDraftSafe('');+ if (cleaned) add(cleaned);};const removeAt = (index: number) => onChange(values.filter((_, i) => i !== index));const onKeyDown = (event: KeyboardEvent<HTMLInputElement>) => {- if (event.key === 'Enter' || event.key === ',') {+ if (event.key === 'ArrowDown' && matches.length) {+ event.preventDefault();+ setHighlight((h) => (h + 1) % matches.length);+ } else if (event.key === 'ArrowUp' && matches.length) {event.preventDefault();- commit(draft);+ setHighlight((h) => (h <= 0 ? matches.length - 1 : h - 1));+ } else if (event.key === 'Enter' || event.key === ',') {+ event.preventDefault();+ if (event.key === 'Enter' && listOpen && highlight >= 0 && highlight < matches.length) {+ add(matches[highlight]);+ } else {+ commit(draft);+ }} else if (event.key === 'Backspace' && draft === '' && values.length) {event.preventDefault();removeAt(values.length - 1);@@ -89,45 +137,83 @@ export const TagInput: React.FC<TagInputProps> = ({};return (- <div- className={cn(- 'flex flex-wrap items-center gap-1.5 rounded-md border bg-surface px-2 py-1.5',- draftInvalid ? 'border-destructive' : 'border-border focus-within:border-mint',- className,- )}- >- {values.map((value, index) => (- <span- key={value}- className="flex items-center gap-1 rounded bg-surface-2 px-1.5 py-0.5 font-mono text-xs text-foreground"- >- {value}- <button- type="button"- onClick={() => removeAt(index)}- aria-label={removeLabel(value)}- className="text-muted hover:text-foreground"- >- <X className="size-3" />- </button>- </span>- ))}- <input- value={draft}- onChange={(event) => setDraftSafe(event.target.value)}- onKeyDown={onKeyDown}- onPaste={onPaste}- onBlur={() => commit(draft)}- placeholder={values.length ? undefined : placeholder}- aria-label={ariaLabel}- aria-invalid={draftInvalid || undefined}- autoComplete="off"- spellCheck={false}+ <div className="relative">+ <divclassName={cn(- 'min-w-[8ch] flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground',- inputClassName,+ 'flex flex-wrap items-center gap-1.5 rounded-md border bg-surface px-2 py-1.5',+ draftInvalid ? 'border-destructive' : 'border-border focus-within:border-mint',+ className,)}- />+ >+ {values.map((value, index) => (+ <span+ key={value}+ className="flex items-center gap-1 rounded bg-surface-2 px-1.5 py-0.5 font-mono text-xs text-foreground"+ >+ {value}+ <button+ type="button"+ onClick={() => removeAt(index)}+ aria-label={removeLabel(value)}+ className="text-muted hover:text-foreground"+ >+ <X className="size-3" />+ </button>+ </span>+ ))}+ <input+ value={draft}+ onChange={(event) => setDraftSafe(event.target.value)}+ onKeyDown={onKeyDown}+ onPaste={onPaste}+ onFocus={() => setFocused(true)}+ onBlur={() => {+ setFocused(false);+ commit(draft);+ }}+ placeholder={values.length ? undefined : placeholder}+ aria-label={ariaLabel}+ aria-invalid={draftInvalid || undefined}+ role={hasSuggestions ? 'combobox' : undefined}+ aria-expanded={hasSuggestions ? listOpen : undefined}+ aria-controls={hasSuggestions && listOpen ? listId : undefined}+ aria-autocomplete={hasSuggestions ? 'list' : undefined}+ autoComplete="off"+ spellCheck={false}+ className={cn(+ 'min-w-[8ch] flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground',+ inputClassName,+ )}+ />+ </div>+ {listOpen && (+ <ul+ id={listId}+ role="listbox"+ className="absolute left-0 right-0 top-full z-50 mt-1 max-h-48 overflow-y-auto rounded-md border border-border bg-surface py-1 shadow-lg"+ >+ {matches.map((option, index) => (+ <li key={option} role="option" aria-selected={index === highlight}>+ <button+ type="button"+ // mousedown (not click) so the input never blurs first, keeping focus+ // and the list open for picking several in a row.+ onMouseDown={(event) => {+ event.preventDefault();+ add(option);+ }}+ onMouseEnter={() => setHighlight(index)}+ className={cn(+ 'flex w-full items-center px-2.5 py-1.5 text-left font-mono text-xs',+ index === highlight ? 'bg-surface-2 text-foreground' : 'text-muted hover:text-foreground',+ )}+ >+ {option}+ </button>+ </li>+ ))}+ </ul>+ )}</div>);};diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsxindex 7d3035999..71632cffb 100644--- a/ui/src/components/ui/vault-approval-card.tsx+++ b/ui/src/components/ui/vault-approval-card.tsx@@ -276,7 +276,7 @@ export const VaultApprovalCard: React.FC<{const approveDisabled = busy || (needsUnlock && !unlocked) || (!isSign && !option);return (- <div className="flex flex-col gap-4">+ <div className="flex min-w-0 flex-col gap-4">{/* Header — design.pen `SKBld` (access, gold lock) / `pRtHq` (sign, violet pen). */}<div className="flex items-start gap-3"><div@@ -330,7 +330,11 @@ export const VaultApprovalCard: React.FC<{) : null}{!isSign && card.command ? (<DetailRow label={t('vaults.approval.command')}>- <span className="min-w-0 flex-1 truncate rounded-md bg-surface-2 px-2 py-1 font-mono text-xs">{card.command}</span>+ {/* Full command in a wrapping code box — break-all so a long unbroken token+ (URL, flag) can't push the dialog wide. */}+ <code className="block w-full whitespace-pre-wrap break-all rounded-md bg-surface-2 px-2 py-1.5 font-mono text-xs leading-relaxed">+ {card.command}+ </code></DetailRow>) : null}{!isSign && card.egress ? (diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsxindex 3cc38f36f..d4563897e 100644--- a/ui/src/components/ui/vault-secret-form.tsx+++ b/ui/src/components/ui/vault-secret-form.tsx@@ -3,7 +3,6 @@ import type { FormEvent } from 'react';import {Asterisk,Check,- Copy,Eye,EyeOff,FileText,@@ -17,9 +16,9 @@ import {} from 'lucide-react';import { useTranslation } from 'react-i18next';-import { ApiError, useApi, type DependencyItem, type VaultRequestSpec } from '@/context/ApiContext';+import { ApiError, useApi, type DependencyItem, type SigningAddresses, type VaultRequestSpec } from '@/context/ApiContext';import { cn } from '@/lib/utils';-import { mergeTags, normalizeSkillEntry, normalizeTagEntry, partitionTags } from '@/lib/vaultTags';+import { mergeTags, normalizeTagOrSkillEntry, partitionTags, toSkillTag } from '@/lib/vaultTags';import {generateSigningKey,importSigningKey,@@ -33,6 +32,7 @@ import { Badge } from './badge';import { Button } from './button';import { Input } from './input';import { SegmentedRadio } from './segmented';+import { SigningAddressList } from './signing-address-list';import { TagInput } from './tag-input';import { Textarea } from './textarea';import { VaultProtectedUnlock } from './vault-protected-unlock';@@ -133,24 +133,27 @@ export const VaultSecretForm: React.FC<{const [importHex, setImportHex] = useState('');const [signingKey, setSigningKey] = useState<SigningKeyMaterial | null>(null);const [signingError, setSigningError] = useState<string | null>(null);- const [copied, setCopied] = useState(false);- // A spec's `tags` may already carry `skill:<name>` entries; split them so the UI edits- // plain tags and bare skills separately, then re-fold on submit (lib/vaultTags).+ const [signingAddresses, setSigningAddresses] = useState<SigningAddresses | null>(null);+ const [addressesLoading, setAddressesLoading] = useState(false);+ // A spec's `tags` may already carry `skill:<name>` entries; partition once so the seed+ // can fold in the `links.skills` bare-name mirror without duplicating (lib/vaultTags).const specParts = useMemo(() => partitionTags(requestSpec?.tags), [requestSpec]);- const [tags, setTags] = useState<string[]>(() => specParts.tags);- const [skills, setSkills] = useState<string[]>(() => [- ...new Set([...specParts.skills, ...(requestSpec?.links?.skills ?? [])]),- ]);+ // One flat tag list holds plain tags AND reserved `skill:<name>` tags; skills are+ // picked from the field's suggestions rather than a separate input. Seed skill tags+ // from both the spec's tags and its `links.skills` bare-name mirror.+ const [tags, setTags] = useState<string[]>(() =>+ mergeTags(specParts.tags, [...specParts.skills, ...(requestSpec?.links?.skills ?? [])]),+ );+ const [tagSuggestions, setTagSuggestions] = useState<string[]>([]);const [description, setDescription] = useState(requestSpec?.description ?? '');const [allowHosts, setAllowHosts] = useState<string[]>(requestSpec?.policy?.allowed_hosts ?? []);const [fetchAuthMode, setFetchAuthMode] = useState<FetchAuthMode>(requestSpec?.policy?.auth?.type ?? 'bearer');const [fetchAuthName, setFetchAuthName] = useState(requestSpec?.policy?.auth?.name ?? '');- const [advancedOpen, setAdvancedOpen] = useState(- Boolean(requestSpec?.description || requestSpec?.tags?.length || requestSpec?.links?.skills?.length || requestSpec?.policy),- );+ // Advanced now holds only proxy policy (allowed hosts + fetch auth), so it auto-opens+ // for a spec that carries policy; description and tags moved out into the main body.+ const [advancedOpen, setAdvancedOpen] = useState(Boolean(requestSpec?.policy));const [tagsPending, setTagsPending] = useState(false);const [hostsPending, setHostsPending] = useState(false);- const [skillsPending, setSkillsPending] = useState(false);const [protection, setProtection] = useState<VaultProtection>(requestSpec?.protection ?? defaultProtection);const [showValue, setShowValue] = useState(false);const [submitting, setSubmitting] = useState(false);@@ -179,6 +182,36 @@ export const VaultSecretForm: React.FC<{};}, [api]);+ // Suggestions for the Tags field: tags already used across the user's secrets, plus+ // every detected global skill offered as a `skill:<name>` option. Best-effort — a+ // failure just means no dropdown, never a blocked form.+ useEffect(() => {+ let alive = true;+ void Promise.all([+ api.listVaultSecrets().catch(() => null),+ api.listSkills({ scope: 'global' }).catch(() => null),+ ]).then(([secretsRes, skillsRes]) => {+ if (!alive) return;+ const plain = new Set<string>();+ const skillNames = new Set<string>();+ for (const secret of secretsRes?.secrets ?? []) {+ const parts = partitionTags(secret.tags);+ parts.tags.forEach((tag) => plain.add(tag));+ parts.skills.forEach((skill) => skillNames.add(skill));+ }+ if (skillsRes?.ok) {+ for (const skill of skillsRes.skills ?? []) {+ if (skill?.name) skillNames.add(skill.name);+ }+ }+ // Plain tags first (reuse existing labels), then skill options — both alphabetical.+ setTagSuggestions([...[...plain].sort(), ...[...skillNames].sort().map(toSkillTag)]);+ });+ return () => {+ alive = false;+ };+ }, [api]);+const protectedVault = useProtectedVault();useEffect(() => {if (protection === 'protected') void protectedVault.refresh();@@ -192,13 +225,13 @@ export const VaultSecretForm: React.FC<{if (requestSpec.protection) setProtection(requestSpec.protection);if (requestSpec.description) setDescription(requestSpec.description);const parts = partitionTags(requestSpec.tags);- if (requestSpec.tags?.length) setTags(parts.tags);const specSkills = [...new Set([...parts.skills, ...(requestSpec.links?.skills ?? [])])];- if (specSkills.length) setSkills(specSkills);+ if (requestSpec.tags?.length || specSkills.length) setTags(mergeTags(parts.tags, specSkills));if (requestSpec.policy?.allowed_hosts) setAllowHosts(requestSpec.policy.allowed_hosts);if (requestSpec.policy?.auth?.type) setFetchAuthMode(requestSpec.policy.auth.type);if (requestSpec.policy?.auth?.name) setFetchAuthName(requestSpec.policy.auth.name);- if (requestSpec.description || requestSpec.tags?.length || specSkills.length || requestSpec.policy) setAdvancedOpen(true);+ // Only proxy policy lives under Advanced now, so open it only for a policy-bearing spec.+ if (requestSpec.policy) setAdvancedOpen(true);}, [requestSpec]);const p2Ready = useMemo(() => avaultP2Ready(avaultDep), [avaultDep]);@@ -220,7 +253,6 @@ export const VaultSecretForm: React.FC<{}signingKeyRef.current = next;setSigningKey(next);- setCopied(false);};// Zero any held private key when the form unmounts.@@ -232,6 +264,32 @@ export const VaultSecretForm: React.FC<{[],);+ // Preview the key's receive addresses once generated/imported. The daemon derives them+ // from the public key alone (same single source as the saved list) — no private key leaves+ // the browser and a failure just hides the preview.+ useEffect(() => {+ if (!signingKey) {+ setSigningAddresses(null);+ setAddressesLoading(false);+ return;+ }+ let alive = true;+ setSigningAddresses(null);+ setAddressesLoading(true);+ api+ .deriveSigningAddresses(signingKey.publicKey)+ .then((res) => {+ if (alive && res.ok && res.addresses) setSigningAddresses(res.addresses);+ })+ .catch(() => undefined)+ .finally(() => {+ if (alive) setAddressesLoading(false);+ });+ return () => {+ alive = false;+ };+ }, [signingKey, api]);+const staticValueReady = staticSource === 'file' ? selectedFile != null && selectedFile.size > 0 : Boolean(value);const valueReady = isKeypair ? signingKey != null : staticValueReady;const canSubmit =@@ -288,12 +346,12 @@ export const VaultSecretForm: React.FC<{event.preventDefault();if (!canSubmit) return;let fileBytesToWipe: Uint8Array | null = null;- // Don't silently drop a half-typed tag/host chip the user can still see. Tags/hosts live in- // the create-mode Advanced collapsible and are always visible in provision mode — guard- // whichever is on screen. Collapsing Advanced clears the pending flags, so a hidden draft can- // never block submit.- const advancedVisible = isProvision || advancedOpen;- if (advancedVisible && (tagsPending || hostsPending || skillsPending)) {+ // Don't silently drop a half-typed chip the user can still see. Tags sit in the main+ // body (always visible); allowed hosts live in the create-mode Advanced collapsible and+ // are always visible in provision mode. Guard whichever is on screen — collapsing+ // Advanced clears hostsPending, so a hidden host draft can never block submit.+ const hostsVisible = isProvision || advancedOpen;+ if (tagsPending || (hostsVisible && hostsPending)) {setError(t('vaults.dialog.errors.pendingDraft'));return;}@@ -336,8 +394,10 @@ export const VaultSecretForm: React.FC<{} else if (fetchAuthMode === 'query') {policy.auth = { type: 'query', name: normalizedFetchAuthName };}- // Skills are stored as reserved `skill:<name>` tags — fold them into one flat tag list.- const mergedTags = mergeTags(tags, skills);+ // Tags already hold `skill:<name>` entries inline; dedupe to the flat list the backend+ // stores, and mirror the bare skill names into links.skills.+ const mergedTags = mergeTags(tags, []);+ const skillLinks = partitionTags(tags).skills;const base = {name: secretName,protection,@@ -347,7 +407,7 @@ export const VaultSecretForm: React.FC<{// from vault_links (populated by payload.links.skills), so skill-scoped access can't// find this secret from `skill:` tags alone until the refactor lands; `links.skills`// is part of the final request spec as well (design §5), so this is safe on both.- links: skills.length ? { skills } : undefined,+ links: skillLinks.length ? { skills: skillLinks } : undefined,policy: Object.keys(policy).length ? policy : undefined,provision_request_id: provisionRequestId || undefined,...(isKeypair && signingKey@@ -460,7 +520,7 @@ export const VaultSecretForm: React.FC<{requiredspellCheck={false}autoComplete="off"- className="min-h-[96px] min-w-0 flex-1 resize-y font-mono text-xs leading-relaxed"+ className="min-h-[76px] min-w-0 flex-1 resize-y font-mono text-xs leading-relaxed"/>) : (<Input@@ -472,7 +532,7 @@ export const VaultSecretForm: React.FC<{requiredspellCheck={false}autoComplete="off"- className="h-24 min-w-0 flex-1 font-mono text-xs"+ className="min-w-0 flex-1 font-mono text-xs"/>)}<Button@@ -549,15 +609,17 @@ export const VaultSecretForm: React.FC<{</div>);- // Tags + skills — the only grouping/selector model (no groups). Skills are edited as bare- // names and stored as reserved `skill:<name>` tags; both feed grant tag/skill selectors.+ // Tags — one flat field for plain tags and reserved `skill:<name>` tags. Suggestions offer+ // existing tags to reuse plus every detected skill as a `skill:<name>` option; picking one+ // is how a secret is attached to a skill (there is no separate skills input).const tagsField = (<div className="flex flex-col gap-1.5"><span className={FIELD_LABEL}>{t('vaults.dialog.tags')}</span><TagInputvalues={tags}onChange={setTags}- normalize={normalizeTagEntry}+ normalize={normalizeTagOrSkillEntry}+ suggestions={tagSuggestions}placeholder={t('vaults.dialog.tagsPlaceholder')}ariaLabel={t('vaults.dialog.tags')}removeLabel={(value) => t('vaults.dialog.removeChip', { value })}@@ -567,19 +629,21 @@ export const VaultSecretForm: React.FC<{</div>);- const skillsField = (+ // Allowed hosts (for the brokered HTTP proxy fetch) — shared by both the create-mode+ // Advanced section and the always-open provision layout.+ const allowHostsField = (<div className="flex flex-col gap-1.5">- <span className={FIELD_LABEL}>{t('vaults.dialog.skills')}</span>+ <span className={FIELD_LABEL}>{t('vaults.dialog.allowHosts')}</span><TagInput- values={skills}- onChange={setSkills}- normalize={normalizeSkillEntry}- placeholder={t('vaults.dialog.skillsPlaceholder')}- ariaLabel={t('vaults.dialog.skills')}+ values={allowHosts}+ onChange={setAllowHosts}+ normalize={normalizeHost}+ placeholder={t('vaults.dialog.allowHostsPlaceholder')}+ ariaLabel={t('vaults.dialog.allowHosts')}removeLabel={(value) => t('vaults.dialog.removeChip', { value })}- onPendingChange={setSkillsPending}+ onPendingChange={setHostsPending}/>- <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.skillsHelp')}</span>+ <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.allowHostsHelp')}</span></div>);@@ -654,7 +718,7 @@ export const VaultSecretForm: React.FC<{// agent prefilled before anything is saved.if (isProvision) {return (- <form className={cn('flex flex-col gap-4', className)} onSubmit={onSubmit}>+ <form className={cn('flex min-w-0 flex-col gap-4', className)} onSubmit={onSubmit}>{/* Name highlight — the secret the agent is waiting on (design.pen `F4N19`). */}<div className="flex items-center gap-3 rounded-xl bg-accent/15 p-3.5"><Asterisk className="size-[18px] shrink-0 text-accent" />@@ -696,23 +760,10 @@ export const VaultSecretForm: React.FC<{</label>{tagsField}- {skillsField}{/* Allowed hosts — a provisioned secret used for brokered HTTP fetch needs at leastone allowed host, else vibe/cli.py refuses the fetch as proxy_unbound. */}- <div className="flex flex-col gap-1.5">- <span className={FIELD_LABEL}>{t('vaults.dialog.allowHosts')}</span>- <TagInput- values={allowHosts}- onChange={setAllowHosts}- normalize={normalizeHost}- placeholder={t('vaults.dialog.allowHostsPlaceholder')}- ariaLabel={t('vaults.dialog.allowHosts')}- removeLabel={(value) => t('vaults.dialog.removeChip', { value })}- onPendingChange={setHostsPending}- />- <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.allowHostsHelp')}</span>- </div>+ {allowHostsField}{fetchAuthPolicyFields}{gatingNotices}@@ -732,7 +783,7 @@ export const VaultSecretForm: React.FC<{// ---- Create mode — design.pen `vyed5` ----------------------------------------------return (- <form className={cn('flex flex-col gap-4', className)} onSubmit={onSubmit}>+ <form className={cn('flex min-w-0 flex-col gap-4', className)} onSubmit={onSubmit}>{/* Kind — 2-segment toggle (Static value | Signing key). */}<div className="flex flex-col gap-1.5"><span className={FIELD_LABEL}>{t('vaults.dialog.kindLabel')}</span>@@ -846,28 +897,19 @@ export const VaultSecretForm: React.FC<{)}{signingKey && (- <div className="flex flex-col gap-1.5">- <span className="text-xs font-medium text-muted-foreground">{t('vaults.dialog.signingPublicKey')}</span>- <div className="flex items-center gap-2">- <code className="min-w-0 flex-1 truncate rounded-md border border-border bg-surface px-2 py-1.5 font-mono text-xs">- {signingKey.publicKey}- </code>- <Button- type="button"- variant="ghost"- size="icon"- aria-label={t('vaults.dialog.copyPublicKey')}- onClick={() => {- void navigator.clipboard?.writeText(signingKey.publicKey).then(() => {- setCopied(true);- window.setTimeout(() => setCopied(false), 1500);- });- }}- >- {copied ? <Check className="size-4 text-mint" /> : <Copy className="size-4" />}- </Button>- </div>- <span className="text-xs text-muted-foreground">{t('vaults.dialog.signingPublicKeyHint')}</span>+ <div className="flex min-w-0 flex-col gap-1.5">+ <span className="text-xs font-medium text-muted-foreground">{t('vaults.dialog.signingAddresses')}</span>+ {addressesLoading ? (+ <span className="flex items-center gap-1.5 text-xs text-muted">+ <Loader2 className="size-3.5 animate-spin" />+ {t('vaults.dialog.signingAddressesLoading')}+ </span>+ ) : signingAddresses ? (+ <SigningAddressList addresses={signingAddresses} />+ ) : (+ <span className="text-xs text-muted-foreground">{t('vaults.dialog.signingAddressesUnavailable')}</span>+ )}+ <span className="text-xs text-muted-foreground">{t('vaults.dialog.signingAddressesHint')}</span></div>)}@@ -881,22 +923,31 @@ export const VaultSecretForm: React.FC<{</div>)}+ {/* Description + Tags — core metadata, kept directly below the value (not buried under+ Advanced) so they're easy to set while creating a secret. */}+ <label className="flex flex-col gap-1.5">+ <span className={FIELD_LABEL}>{t('vaults.dialog.description')}</span>+ <Input+ value={description}+ onChange={(event) => setDescription(event.target.value)}+ placeholder={t('vaults.dialog.descriptionPlaceholder')}+ />+ </label>++ {tagsField}+{/* Protection */}{protectionCards}- {/* Advanced — collapsible: description, tags, skills, allowed hosts. */}+ {/* Advanced — collapsible: proxy policy (allowed hosts + fetch auth). */}<div className="flex flex-col overflow-hidden rounded-[10px] bg-surface-2"><buttontype="button"onClick={() => {setAdvancedOpen((open) => {- // Collapsing hides the tag/skill/host inputs — drop their pending-draft flags so a- // draft the user can no longer see doesn't block submit.- if (open) {- setHostsPending(false);- setTagsPending(false);- setSkillsPending(false);- }+ // Collapsing hides the allowed-hosts input — drop its pending-draft flag so a+ // host draft the user can no longer see doesn't block submit.+ if (open) setHostsPending(false);return !open;});}}@@ -905,41 +956,13 @@ export const VaultSecretForm: React.FC<{><SlidersHorizontal className="size-3.5 text-muted" /><span className="flex-1 text-xs font-semibold text-foreground">{t('vaults.dialog.advanced')}</span>- {!advancedOpen &&- (description || tags.length > 0 || skills.length > 0 || allowHosts.length > 0 || fetchAuthMode !== 'bearer') && (- <span className="size-1.5 rounded-full bg-mint" aria-hidden />- )}+ {!advancedOpen && (allowHosts.length > 0 || fetchAuthMode !== 'bearer') && (+ <span className="size-1.5 rounded-full bg-mint" aria-hidden />+ )}</button>{advancedOpen && (<div className="flex flex-col gap-3 px-3 pb-3">- {/* Description (kept functional; absent from the vyed5 mock — folded here). */}- <label className="flex flex-col gap-1.5">- <span className={FIELD_LABEL}>{t('vaults.dialog.description')}</span>- <Input- value={description}- onChange={(event) => setDescription(event.target.value)}- placeholder={t('vaults.dialog.descriptionPlaceholder')}- />- </label>-- {/* Tags + skills (the only grouping/selector model; folded under Advanced). */}- {tagsField}- {skillsField}-- {/* Allowed hosts (for proxy fetch). */}- <div className="flex flex-col gap-1.5">- <span className={FIELD_LABEL}>{t('vaults.dialog.allowHosts')}</span>- <TagInput- values={allowHosts}- onChange={setAllowHosts}- normalize={normalizeHost}- placeholder={t('vaults.dialog.allowHostsPlaceholder')}- ariaLabel={t('vaults.dialog.allowHosts')}- removeLabel={(value) => t('vaults.dialog.removeChip', { value })}- onPendingChange={setHostsPending}- />- <span className="text-[11px] text-muted-foreground">{t('vaults.dialog.allowHostsHelp')}</span>- </div>+ {allowHostsField}{fetchAuthPolicyFields}</div>)}diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex 6ebeb799f..c86ef5e2f 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -1,5 +1,5 @@import { useCallback, useEffect, useMemo, useState } from 'react';-import { Check, Clock, Copy, Globe, History, Inbox, KeyRound, Link2, Loader2, Plus, Puzzle, RefreshCw, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';+import { Clock, Globe, History, Inbox, KeyRound, Link2, Loader2, Plus, Puzzle, RefreshCw, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { CapabilityTabs } from './CapabilityTabs';@@ -13,6 +13,7 @@ import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, typeimport { useToast } from '../../context/ToastContext';import { VaultApprovalCard, type ApprovalOutcome } from '../ui/vault-approval-card';import { VaultSecretForm } from '../ui/vault-secret-form';+import { SigningAddressList } from '../ui/signing-address-list';const PENDING_REQUEST_POLL_INTERVAL_MS = 5000;const PENDING_REQUEST_EXPIRY_GRACE_MS = 100;@@ -67,8 +68,6 @@ const SecretRow: React.FC<{ secret: VaultSecret; onDelete: (name: string) => voiconst { t } = useTranslation();const isKeypair = s.kind === 'keypair';const isProtected = s.protection === 'protected';- const [copied, setCopied] = useState(false);- const publicKey = s.signing_public_key?.public_key;// Skills are stored as reserved `skill:<name>` tags; render them as their own chips.const { tags, skills } = useMemo(() => partitionTags(s.tags), [s.tags]);return (@@ -116,23 +115,7 @@ const SecretRow: React.FC<{ secret: VaultSecret; onDelete: (name: string) => voi{s.description ? `${s.description} · ` : ''}{s.last_used_at ? t('vaults.used', { count: s.use_count }) : t('vaults.neverUsed')}</span>- {isKeypair && publicKey && (- <button- type="button"- onClick={() => {- void navigator.clipboard?.writeText(publicKey).then(() => {- setCopied(true);- window.setTimeout(() => setCopied(false), 1500);- });- }}- className="flex max-w-full items-center gap-1 text-xs text-muted hover:text-foreground"- aria-label={t('vaults.dialog.copyPublicKey')}- title={publicKey}- >- <span className="truncate font-mono">{publicKey}</span>- {copied ? <Check className="size-3 shrink-0 text-mint" /> : <Copy className="size-3 shrink-0" />}- </button>- )}+ {isKeypair && s.signing_addresses ? <SigningAddressList addresses={s.signing_addresses} className="mt-1" /> : null}</div><div className="ml-auto"><Button variant="ghost" size="icon" onClick={() => onDelete(s.name)} aria-label={t('vaults.delete')}>diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex c2a984802..af382cad4 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -16,6 +16,14 @@ export type GlobalPromptFile = {read_error: boolean;};+/** Receive addresses derived from a keypair secret's secp256k1 public key. */+export type SigningAddresses = {+ eth?: string;+ btc_legacy?: string;+ btc_segwit?: string;+ btc_taproot?: string;+};+export type VaultSecret = {name: string;/** Flat tag list; skill association is a reserved `skill:<name>` tag (see lib/vaultTags). */@@ -23,9 +31,9 @@ export type VaultSecret = {kind: string;protection: string;signer_kind: string | null;- /** Pinned public key for keypair secrets (non-secret); surfaced so the saved- * signing key's public key is recoverable after the create dialog closes. */- signing_public_key?: { curve?: string; public_key: string } | null;+ /** Receive addresses derived from a keypair secret's public key. Agents and the UI+ * identify a signing key by address; the raw public key is never surfaced here. */+ signing_addresses?: SigningAddresses | null;source: string;description?: string | null;policy: Record<string, unknown>;@@ -364,6 +372,7 @@ export type ApiContextType = {getVaultVmk: () => Promise<VaultVmkResult>;getVaultPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;getVaultAgentPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;+ deriveSigningAddresses: (publicKey: string) => Promise<{ ok: boolean; addresses?: SigningAddresses; code?: string; message?: string }>;createVaultSecret: (payload: VaultCreatePayload, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;deleteVaultSecret: (name: string) => Promise<{ ok: boolean; removed?: boolean; code?: string; message?: string }>;getVaultProvisionRequest: (@@ -2151,6 +2160,8 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrenlistVaultSecrets: () => getCachedJson('/api/vault/secrets', 1500),getVaultPubkey: () => getCachedJson('/api/vault/pubkey', 1500),getVaultAgentPubkey: () => getCachedJson('/api/vault/agent/pubkey', 1500),+ deriveSigningAddresses: (publicKey) =>+ postJson('/api/vault/signing-addresses', { public_key: publicKey }, { handleError: false }),createVaultSecret: (payload, opts) => postJson('/api/vault/secrets', payload, opts),deleteVaultSecret: (name) => deleteJson(`/api/vault/secrets/${encodeURIComponent(name)}`),getVaultProvisionRequest: (name, opts) =>diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 3fe050199..b6a178ef5 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2189,6 +2189,13 @@"neverUsed": "never used","standard": "Standard","signing": "Signing",+ "addresses": {+ "eth": "ETH",+ "btcSegwit": "BTC SegWit",+ "btcTaproot": "BTC Taproot",+ "btcLegacy": "BTC Legacy",+ "copy": "Copy {{label}} address"+ },"filter": {"clear": "Clear filters","empty": "No secrets match the selected tags."@@ -2290,9 +2297,10 @@"signingGenerateCta": "Generate signing key","signingRegenerate": "Generate a different key","signingImportPlaceholder": "Paste a 32-byte hex private key (64 hex chars)",- "signingPublicKey": "Public key",- "copyPublicKey": "Copy public key",- "signingPublicKeyHint": "Share this public key freely. The private key never leaves your vault, and the chain and signature scheme are chosen at signing time.",+ "signingAddresses": "Addresses",+ "signingAddressesLoading": "Deriving addresses…",+ "signingAddressesUnavailable": "Couldn't derive addresses for this key.",+ "signingAddressesHint": "Derived from the key. Share an address to receive funds; the private key never leaves your vault, and the chain and signature scheme are chosen at signing time.","signingNeedsAvault": "Signing keys need avault {{version}} or newer installed.","checkingAvault": "Checking avault…","p2Unavailable": "Browser-side vault create requires avault {{version}} or newer. Installed: {{installed}}. Install a compatible avault release before saving standard secrets.",@@ -2310,11 +2318,8 @@"fetchAuthNamePlaceholder": "X-Api-Key or api_key","fetchAuthHelp": "Defaults to Authorization: Bearer <value>. Use Header or Query for APIs that expect another credential placement.","tags": "Tags",- "tagsPlaceholder": "tag, then Enter",- "tagsHelp": "Labels to find secrets and to select them by tag in runs and grants. Add skills in the Skills field.",- "skills": "Skills",- "skillsPlaceholder": "skill name, then Enter",- "skillsHelp": "Stored as skill:<name> tags. A run or grant that selects the skill includes this secret.",+ "tagsPlaceholder": "Type or pick a tag",+ "tagsHelp": "Labels to find secrets and select them by tag in runs and grants.","removeChip": "Remove {{value}}","protection": "Protection","protectedProtection": "Protected",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 076d9e532..bbb35bb36 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2188,6 +2188,13 @@"neverUsed": "从未使用","standard": "标准档","signing": "签名",+ "addresses": {+ "eth": "ETH",+ "btcSegwit": "BTC SegWit",+ "btcTaproot": "BTC Taproot",+ "btcLegacy": "BTC Legacy",+ "copy": "复制 {{label}} 地址"+ },"filter": {"clear": "清除筛选","empty": "没有匹配所选标签的密钥。"@@ -2289,9 +2296,10 @@"signingGenerateCta": "生成签名密钥","signingRegenerate": "换一把新密钥","signingImportPlaceholder": "粘贴 32 字节十六进制私钥(64 个字符)",- "signingPublicKey": "公钥",- "copyPublicKey": "复制公钥",- "signingPublicKeyHint": "公钥可以放心分享。私钥始终留在你的保险库里;用哪条链、哪种签名方案,在签名时再定。",+ "signingAddresses": "地址",+ "signingAddressesLoading": "正在推导地址…",+ "signingAddressesUnavailable": "无法为该密钥推导地址。",+ "signingAddressesHint": "由密钥推导得到。收款时把地址发给对方即可;私钥始终留在你的保险库里,用哪条链、哪种签名方案在签名时再定。","signingNeedsAvault": "签名密钥需要安装 avault {{version}} 或更新版本。","checkingAvault": "正在检查 avault…","p2Unavailable": "浏览器侧保险库创建需要 avault {{version}} 或更新版本。当前安装:{{installed}}。请先安装兼容的 avault 发布版,再保存标准密钥。",@@ -2309,11 +2317,8 @@"fetchAuthNamePlaceholder": "X-Api-Key 或 api_key","fetchAuthHelp": "默认使用 Authorization: Bearer <value>。如果目标 API 要求其他位置,可改用 Header 或 Query。","tags": "标签",- "tagsPlaceholder": "输入标签后回车",- "tagsHelp": "用于查找密钥,也可在运行和授权中按标签选择密钥。技能请在“技能”栏添加。",- "skills": "技能",- "skillsPlaceholder": "输入技能名称后回车",- "skillsHelp": "以 skill:<名称> 标签存储。按该技能选择的运行或授权会包含这条密钥。",+ "tagsPlaceholder": "输入或选择标签",+ "tagsHelp": "用于查找密钥,也可在运行和授权中按标签选择。","removeChip": "移除 {{value}}","protection": "保护级别","protectedProtection": "受保护",diff --git a/ui/src/lib/vaultTags.test.ts b/ui/src/lib/vaultTags.test.tsindex c81a67301..309408149 100644--- a/ui/src/lib/vaultTags.test.ts+++ b/ui/src/lib/vaultTags.test.ts@@ -6,6 +6,7 @@ import {mergeTags,normalizeSkillEntry,normalizeTagEntry,+ normalizeTagOrSkillEntry,partitionTags,skillName,toSkillTag,@@ -49,6 +50,22 @@ describe('tag entry normalization', () => {});});+describe('unified tag-or-skill entry normalization', () => {+ it('accepts plain tags and keeps skill: entries prefixed', () => {+ expect(normalizeTagOrSkillEntry(' prod ')).toBe('prod');+ expect(normalizeTagOrSkillEntry('skill:github-release')).toBe('skill:github-release');+ // A trimmed skill entry validates its bare name and re-wraps it once.+ expect(normalizeTagOrSkillEntry(' skill:deploy ')).toBe('skill:deploy');+ });++ it('rejects empty, whitespace-bearing, and bare skill: entries', () => {+ expect(normalizeTagOrSkillEntry('')).toBeNull();+ expect(normalizeTagOrSkillEntry('two words')).toBeNull();+ expect(normalizeTagOrSkillEntry('skill:')).toBeNull();+ expect(normalizeTagOrSkillEntry('skill:two words')).toBeNull();+ });+});+describe('partitionTags', () => {it('splits a flat tag list into normal tags and bare skills', () => {const { tags, skills } = partitionTags(['prod', 'skill:github-release', 'deploy', 'skill:deploy-aws']);diff --git a/ui/src/lib/vaultTags.ts b/ui/src/lib/vaultTags.tsindex d546a033a..0c4c4c2ce 100644--- a/ui/src/lib/vaultTags.ts+++ b/ui/src/lib/vaultTags.ts@@ -53,6 +53,22 @@ export function normalizeSkillEntry(raw: string): string | null {return normalizeTagEntry(name);}+/**+ * Normalize an entry for the unified Tags field, which holds both plain tags and+ * reserved `skill:<name>` tags in one flat list (skills are picked from the field's+ * suggestions). A `skill:` entry keeps its prefix (the bare name is validated like a+ * normal tag); a plain entry is validated as a tag. Returns `null` to reject — the+ * shape the {@link import('@/components/ui/tag-input').TagInput} `normalize` prop expects.+ */+export function normalizeTagOrSkillEntry(raw: string): string | null {+ const trimmed = raw.trim();+ if (isSkillTag(trimmed)) {+ const name = normalizeTagEntry(skillName(trimmed));+ return name ? toSkillTag(name) : null;+ }+ return normalizeTagEntry(trimmed);+}+const dedupe = (values: string[]): string[] => [...new Set(values)];/**diff --git a/uv.lock b/uv.lockindex 35c8671e0..e18a35466 100644--- a/uv.lock+++ b/uv.lock@@ -313,6 +313,7 @@ dependencies = [{ name = "markdown-to-mrkdwn" },{ name = "packaging" },{ name = "psutil" },+ { name = "pycryptodome" },{ name = "pyjwt", extra = ["crypto"] },{ name = "python-multipart" },{ name = "python-socks", extra = ["asyncio"] },@@ -349,6 +350,7 @@ requires-dist = [{ name = "markdown-to-mrkdwn", specifier = ">=0.2.0" },{ name = "packaging", specifier = ">=23.0" },{ name = "psutil", specifier = ">=5.9.0" },+ { name = "pycryptodome", specifier = ">=3.20" },{ name = "pyjwt", extras = ["crypto"], specifier = ">=2.9.0" },{ name = "python-multipart", specifier = ">=0.0.9" },{ name = "python-socks", extras = ["asyncio"], specifier = ">=2.0.0" },diff --git a/vibe/api.py b/vibe/api.pyindex 7d4c85bad..6e2172beb 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1394,6 +1394,24 @@ def get_vault_agent_pubkey() -> dict:raise _vault_api_error_from_avault(exc, prefix="avault agent pubkey failed") from exc+def derive_vault_signing_addresses(public_key: str) -> dict:+ """Derive the receive addresses for a compressed secp256k1 public key.++ Value-free: uses only the public key, so it needs no vault/avault access. Lets the+ create form preview a signing key's addresses before the secret is saved.+ """+ from storage.vault_addresses import derive_addresses++ if not isinstance(public_key, str) or not public_key.strip():+ raise VaultApiError("public_key is required", code="invalid_request")+ try:+ return {"ok": True, "addresses": derive_addresses(public_key)}+ except VaultApiError:+ raise+ except Exception as exc:+ raise VaultApiError("invalid secp256k1 public key", code="invalid_public_key") from exc++def get_vault_vmk() -> dict:from storage import vault_service@@ -2639,7 +2657,10 @@ def vault_sign(payload: dict) -> dict:raise VaultApiError("request_id is required to complete protected signing", code="missing_request_id")vault_service.validate_sign_request(conn, request_id, name=name, digest=digest, scheme=scheme)signature = _normalized_protected_signature(signature)- _verify_protected_browser_signature(meta, digest=digest, scheme=scheme, signature=signature)+ # `meta` is the masked payload (derived addresses only, no raw key); source+ # the pinned public key from storage for server-side verification.+ verify_meta = {**meta, "signing_public_key": vault_service.get_signing_public_key(conn, name)}+ _verify_protected_browser_signature(verify_meta, digest=digest, scheme=scheme, signature=signature)request = vault_service.complete_sign_request(conn,request_id,diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex a67defec0..5412df043 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -2695,6 +2695,16 @@ def vault_vmk_get():return jsonify(api.get_vault_vmk())[email protected]("/api/vault/signing-addresses", methods=["POST"])+def vault_signing_addresses_post():+ from vibe import api++ try:+ return jsonify(api.derive_vault_signing_addresses(str((request.json or {}).get("public_key") or "")))+ except ValueError as exc:+ return _vault_error_response(exc)++@app.route("/api/vault/secrets", methods=["POST"])def vault_secrets_post():from vibe import api