Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(vaults): protected-tier secret creation (passkey-first) (#694)
Call Whitec066de9001ff
diff --git a/storage/vault_service.py b/storage/vault_service.pyindex bd68dae53..96a94ed18 100644--- a/storage/vault_service.py+++ b/storage/vault_service.py@@ -90,6 +90,10 @@ class NotGrantableError(VaultServiceError):pass+class VaultAlreadyInitializedError(VaultServiceError):+ pass++class VaultGrantRuntimeCache:"""Process-local grant delivery readiness tracker.@@ -525,6 +529,7 @@ def create_secret(source: str = "manual",policy: dict[str, Any] | None = None,public_meta: dict[str, Any] | None = None,+ establishing_vmk: bool = False,) -> dict[str, Any]:"""Create a secret from a caller-supplied encrypted envelope; return masked metadata.@@ -547,6 +552,17 @@ def create_secret(if conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.name == name)).first() is not None:raise SecretExistsError(name)+ if establishing_vmk and protection == "protected":+ # Atomic single-init guard: this runs inside the write transaction (SQLite+ # serialises writers), so two concurrent first-time setups cannot both pass —+ # the loser is rejected instead of splitting the vault key history with a+ # second VMK. The browser then reloads and unlocks the established vault.+ if (+ conn.execute(select(vault_secrets.c.id).where(vault_secrets.c.protection == "protected").limit(1)).first()+ is not None+ ):+ raise VaultAlreadyInitializedError("a protected vault already exists; unlock it instead of re-initializing")+_ensure_group(conn, group)now = _now()public_meta = dict(public_meta or {})diff --git a/tests/test_vault_api.py b/tests/test_vault_api.pyindex 520ae24fb..b0995868a 100644--- a/tests/test_vault_api.py+++ b/tests/test_vault_api.py@@ -176,6 +176,42 @@ def test_create_protected_stores_browser_envelope_without_avault(monkeypatch):assert json.loads(row["wrap_meta"]) == {"v": 1, "wrapped_dek": "dek"}+def test_protected_create_establishing_vmk_rejects_second_init(monkeypatch):+ first = api.create_vault_secret(+ {+ "name": "FIRST_PROTECTED",+ "protection": "protected",+ "sealed": {"ciphertext": "ct1", "nonce": "n1", "wrap_meta": {"v": 1, "copies": [], "wrapped_dek": "d1"}},+ "establishing_vmk": True,+ }+ )+ assert first["ok"] is True++ # A second "establishing" create (concurrent first-time setup) must be rejected so+ # the vault key history can't split under a different VMK.+ with pytest.raises(api.VaultApiError) as exc:+ api.create_vault_secret(+ {+ "name": "SECOND_PROTECTED",+ "protection": "protected",+ "sealed": {"ciphertext": "ct2", "nonce": "n2", "wrap_meta": {"v": 1, "copies": [], "wrapped_dek": "d2"}},+ "establishing_vmk": True,+ }+ )+ assert exc.value.code == "vault_already_initialized"+ assert exc.value.status == 409++ # Adding a secret under the already-established VMK (not establishing) still works.+ more = api.create_vault_secret(+ {+ "name": "THIRD_PROTECTED",+ "protection": "protected",+ "sealed": {"ciphertext": "ct3", "nonce": "n3", "wrap_meta": {"v": 1, "copies": [], "wrapped_dek": "d3"}},+ }+ )+ assert more["ok"] is True++def test_get_vault_vmk_returns_latest_protected_wrap_meta(monkeypatch):from unittest.mock import Mockdiff --git a/ui/src/components/ui/vault-protected-unlock.tsx b/ui/src/components/ui/vault-protected-unlock.tsxnew file mode 100644index 000000000..125f07be6--- /dev/null+++ b/ui/src/components/ui/vault-protected-unlock.tsx@@ -0,0 +1,182 @@+import { useState } from 'react';+import { Fingerprint, KeyRound, Loader2, Lock, RefreshCw, ShieldCheck } from 'lucide-react';+import { useTranslation } from 'react-i18next';+import type { TFunction } from 'i18next';++import { webauthnAvailable } from '@/lib/useProtectedVault';+import type { useProtectedVault } from '@/lib/useProtectedVault';+import { Button } from './button';+import { Input } from './input';++type Vault = ReturnType<typeof useProtectedVault>;++/** Map thrown codes / WebAuthn DOMExceptions to a friendly localized message. */+function friendlyError(t: TFunction, raw: string): string {+ if (raw.includes('passkey-prf-unavailable')) return t('vaults.protectedUnlock.errors.prfUnavailable');+ if (raw.includes('passkey-cancelled') || raw.includes('NotAllowed') || raw.includes('AbortError')) {+ return t('vaults.protectedUnlock.errors.cancelled');+ }+ if (raw.includes('passkey-not-configured')) return t('vaults.protectedUnlock.errors.noPasskey');+ if (raw.includes('vault-already-initialized')) return t('vaults.protectedUnlock.errors.alreadyInitialized');+ if (raw.includes('vmk-discovery-failed')) return t('vaults.protectedUnlock.errors.discoveryFailed');+ // unwrapVmk throws when no copy decrypts → wrong factor.+ if (raw.includes('decrypt') || raw.includes('No matching') || raw.includes('wrap')) {+ return t('vaults.protectedUnlock.errors.wrongFactor');+ }+ return raw;+}++const PANEL = 'flex flex-col gap-2.5 rounded-lg border border-border bg-surface-2 px-3 py-3';++/**+ * Protected-tier setup / unlock panel. Setup always captures a password (the recovery+ * root) and offers a passkey on top (Touch ID / Windows Hello, when the origin allows+ * WebAuthn); unlock accepts either factor. The unlocked VMK is cached for the session+ * by {@link useProtectedVault}, so multiple protected secrets can be created without+ * re-prompting.+ */+export const VaultProtectedUnlock: React.FC<{ vault: Vault }> = ({ vault }) => {+ const { t } = useTranslation();+ const [password, setPassword] = useState('');+ const [confirm, setConfirm] = useState('');+ const [busy, setBusy] = useState(false);++ const run = async (fn: () => Promise<void>) => {+ setBusy(true);+ vault.setError(null);+ try {+ await fn();+ setPassword('');+ setConfirm('');+ } catch (err) {+ vault.setError(friendlyError(t, err instanceof Error ? err.message : String(err)));+ } finally {+ setBusy(false);+ }+ };++ if (vault.status === 'checking') {+ return (+ <div className="flex items-center gap-2 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-muted">+ <Loader2 className="size-4 animate-spin" />+ {t('vaults.protectedUnlock.checking')}+ </div>+ );+ }++ if (vault.status === 'error') {+ return (+ <div className="flex flex-col gap-2 rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-3 text-sm">+ <span className="font-medium text-destructive">{t('vaults.protectedUnlock.errorTitle')}</span>+ {vault.error && <span className="text-xs text-destructive">{friendlyError(t, vault.error)}</span>}+ <Button type="button" variant="secondary" size="sm" className="self-start" onClick={() => run(vault.refresh)} disabled={busy}>+ {busy ? <Loader2 className="size-3.5 animate-spin" /> : <RefreshCw className="size-3.5" />}+ {t('vaults.protectedUnlock.retry')}+ </Button>+ </div>+ );+ }++ if (vault.status === 'unlocked') {+ return (+ <div className="flex items-center gap-2 rounded-lg border border-mint/40 bg-mint-soft px-3 py-2 text-sm text-mint">+ <ShieldCheck className="size-4 shrink-0" />+ <span className="font-medium">{t('vaults.protectedUnlock.unlocked')}</span>+ <Button type="button" variant="ghost" size="sm" className="ml-auto h-7 text-muted" onClick={vault.lock} disabled={busy}>+ <Lock className="size-3.5" />+ {t('vaults.protectedUnlock.lock')}+ </Button>+ </div>+ );+ }++ const canUsePasskey = webauthnAvailable();++ if (vault.status === 'needs-setup') {+ const valid = password.trim().length > 0 && password === confirm;+ const submitSetup = (withPasskey: boolean) => {+ // Reject blank before any WebAuthn ceremony, or a passkey would be created and then+ // orphaned when buildWrapMeta rejects the empty password (the button is also disabled).+ if (password.trim().length === 0) return;+ if (password !== confirm) {+ vault.setError(t('vaults.protectedUnlock.errors.mismatch'));+ return;+ }+ void run(() => (withPasskey ? vault.setupPasskey(password) : vault.setupPassword(password)));+ };+ return (+ <div className={PANEL}>+ <div className="flex items-start gap-2">+ <Lock className="mt-0.5 size-4 shrink-0 text-muted" />+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-semibold">{t('vaults.protectedUnlock.setupTitle')}</span>+ <span className="text-xs text-muted-foreground">{t('vaults.protectedUnlock.setupHelp')}</span>+ </div>+ </div>+ <label className="flex flex-col gap-1.5 text-xs font-medium text-muted-foreground">+ <span className="flex items-center gap-1.5">+ <KeyRound className="size-3.5" />+ {t('vaults.protectedUnlock.setPasswordLabel')}+ </span>+ <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder={t('vaults.protectedUnlock.passwordPlaceholder')} autoComplete="new-password" />+ </label>+ <label className="flex flex-col gap-1.5 text-xs font-medium text-muted-foreground">+ {t('vaults.protectedUnlock.confirmLabel')}+ <Input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)} placeholder={t('vaults.protectedUnlock.confirmPlaceholder')} autoComplete="new-password" />+ </label>+ <span className="text-xs text-muted-foreground">{t('vaults.protectedUnlock.passwordRecoveryNote')}</span>+ <div className="flex flex-wrap gap-2">+ {canUsePasskey && (+ <Button type="button" onClick={() => submitSetup(true)} disabled={busy || !valid}>+ {busy ? <Loader2 className="size-4 animate-spin" /> : <Fingerprint className="size-4" />}+ {t('vaults.protectedUnlock.setupWithPasskey')}+ </Button>+ )}+ <Button type="button" variant={canUsePasskey ? 'ghost' : 'secondary'} onClick={() => submitSetup(false)} disabled={busy || !valid}>+ {t('vaults.protectedUnlock.setupPasswordOnly')}+ </Button>+ </div>+ {vault.error && <div className="text-xs text-destructive">{friendlyError(t, vault.error)}</div>}+ </div>+ );+ }++ // status === 'locked'+ return (+ <div className={PANEL}>+ <div className="flex items-start gap-2">+ <Lock className="mt-0.5 size-4 shrink-0 text-muted" />+ <div className="flex flex-col gap-0.5">+ <span className="text-sm font-semibold">{t('vaults.protectedUnlock.unlockTitle')}</span>+ <span className="text-xs text-muted-foreground">{t('vaults.protectedUnlock.unlockHelp')}</span>+ </div>+ </div>+ {vault.hasPasskey() && canUsePasskey && (+ <Button type="button" variant="secondary" onClick={() => run(vault.unlockPasskey)} disabled={busy}>+ {busy ? <Loader2 className="size-4 animate-spin" /> : <Fingerprint className="size-4" />}+ {t('vaults.protectedUnlock.unlockPasskey')}+ </Button>+ )}+ <form+ className="flex items-end gap-2"+ onSubmit={(e) => {+ e.preventDefault();+ if (password.trim()) void run(() => vault.unlockPassword(password));+ }}+ >+ <label className="flex flex-1 flex-col gap-1.5 text-xs font-medium text-muted-foreground">+ <span className="flex items-center gap-1.5">+ <KeyRound className="size-3.5" />+ {t('vaults.protectedUnlock.passwordLabel')}+ </span>+ <Input type="password" value={password} onChange={(e) => setPassword(e.target.value)} placeholder={t('vaults.protectedUnlock.passwordPlaceholder')} autoComplete="current-password" />+ </label>+ <Button type="submit" disabled={busy || !password.trim()}>+ {busy && <Loader2 className="size-4 animate-spin" />}+ {t('vaults.protectedUnlock.unlockCta')}+ </Button>+ </form>+ {vault.error && <div className="text-xs text-destructive">{friendlyError(t, vault.error)}</div>}+ </div>+ );+};diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsxindex e696ef78e..9c9366624 100644--- a/ui/src/components/ui/vault-secret-form.tsx+++ b/ui/src/components/ui/vault-secret-form.tsx@@ -5,10 +5,12 @@ import { useTranslation } from 'react-i18next';import { ApiError, useApi, type DependencyItem } from '@/context/ApiContext';import { cn } from '@/lib/utils';-import { sealBlindBox, standardCreateBlindBoxContext } from '@/lib/vaultCrypto';+import { sealBlindBox, standardCreateBlindBoxContext, type ProtectedRecordEnvelope } from '@/lib/vaultCrypto';+import { useProtectedVault } from '@/lib/useProtectedVault';import { Button } from './button';import { Combobox } from './combobox';import { Input } from './input';+import { VaultProtectedUnlock } from './vault-protected-unlock';const AVAULT_P2_MIN_VERSION = '0.1.3';type VaultProtection = 'standard' | 'protected';@@ -95,10 +97,17 @@ export const VaultSecretForm: React.FC<{};}, [api]);+ const protectedVault = useProtectedVault();+ useEffect(() => {+ if (protection === 'protected') void protectedVault.refresh();+ // protectedVault.refresh is stable (useCallback); only re-check when the tier changes.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [protection]);+const p2Ready = useMemo(() => avaultP2Ready(avaultDep), [avaultDep]);const standardCreateReady = useMemo(() => avaultInstalled(avaultDep), [avaultDep]);const secretName = (fixedName ?? name).trim().toUpperCase();- const protectedCreateReady = false;+ const protectedCreateReady = protectedVault.status === 'unlocked';const canSubmit =Boolean(secretName && value) &&!submitting &&@@ -119,28 +128,35 @@ export const VaultSecretForm: React.FC<{setSubmitting(true);setError(null);try {- if (protection === 'protected' && !protectedCreateReady) {- setError(t('vaults.dialog.protectedCreatePending'));- return;- }const hosts = allowHosts.split(',').map((host) => host.trim()).filter(Boolean);- let blindBox: Awaited<ReturnType<typeof sealBlindBox>> | undefined;- if (p2Ready) {+ const base = {+ name: secretName,+ protection,+ group: group.trim() || undefined,+ description: description.trim() || undefined,+ policy: hosts.length ? { allowed_hosts: hosts } : undefined,+ };+ let cryptoFields:+ | { sealed: ProtectedRecordEnvelope }+ | { blind_box: Awaited<ReturnType<typeof sealBlindBox>> }+ | { value: string };+ let establishingVmk = false;+ if (protection === 'protected') {+ // Browser-sealed under the session VMK; the daemon stores it opaquely (no avault, no plaintext).+ const sealed = await protectedVault.sealValue(secretName, value);+ cryptoFields = { sealed: sealed.envelope };+ establishingVmk = sealed.establishingVmk;+ } else if (p2Ready) {const pubkey = await api.getVaultPubkey();- blindBox = await sealBlindBox(value, pubkey, standardCreateBlindBoxContext(secretName));+ cryptoFields = { blind_box: await sealBlindBox(value, pubkey, standardCreateBlindBoxContext(secretName)) };+ } else {+ cryptoFields = { value };}const created = await api.createVaultSecret(- {- name: secretName,- protection,- ...(blindBox ? { blind_box: blindBox } : { value }),- group: group.trim() || undefined,- description: description.trim() || undefined,- policy: hosts.length ? { allowed_hosts: hosts } : undefined,- },+ { ...base, ...cryptoFields, ...(establishingVmk ? { establishing_vmk: true } : {}) },{ handleError: false },);if (!created.ok) {@@ -148,8 +164,16 @@ export const VaultSecretForm: React.FC<{handleExistingSecret();return;}+ if (created.code === 'vault_already_initialized') {+ // Another tab established the vault first — drop the rejected local VMK and+ // reload the server's wrap_meta so the user unlocks it instead of splitting keys.+ await protectedVault.discardAndRefresh();+ setError(t('vaults.protectedUnlock.errors.alreadyInitialized'));+ return;+ }throw new Error(created.message || created.code || t('vaults.request.saveFailed'));}+ if (protection === 'protected') protectedVault.afterCreated();setValue('');onCreated(secretName, 'created');} catch (err: unknown) {@@ -254,18 +278,14 @@ export const VaultSecretForm: React.FC<{})}</div></div>- {protection === 'protected' && (- <div className="rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning">- {t('vaults.dialog.protectedCreatePending')}- </div>- )}- {checkingAvault && (+ {protection === 'protected' && <VaultProtectedUnlock vault={protectedVault} />}+ {protection === 'standard' && checkingAvault && (<div className="flex items-center gap-2 rounded-lg border border-border bg-surface-2 px-3 py-2 text-sm text-muted"><Loader2 className="size-4 animate-spin" />{t('vaults.dialog.checkingAvault')}</div>)}- {!checkingAvault && !p2Ready && (+ {protection === 'standard' && !checkingAvault && !p2Ready && (<div className="rounded-lg border border-warning/40 bg-warning/10 px-3 py-2 text-sm text-warning">{standardCreateReady? t('vaults.dialog.p2UnavailableStandardFallback', {diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 4a4bc115b..76896cbea 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -101,6 +101,8 @@ export type VaultCreatePayload = {signer_kind?: string | null;policy?: Record<string, unknown>;public_meta?: Record<string, unknown>;+ /** Set on the first protected secret so the daemon atomically guards single VMK init. */+ establishing_vmk?: boolean;};export type ApiContextType = {@@ -2011,13 +2013,13 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children},setDefaultVibeAgent: (name) => postJson('/api/agents/default', { name }),removeVibeAgent: (name) => deleteJson(`/api/agents/${encodeURIComponent(name)}`),+ getVaultVmk: () => getCachedJson('/api/vault/vmk', 1500, { handleError: false }),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);},- getVaultVmk: () => getJson('/api/vault/vmk'),getVaultPubkey: () => getCachedJson('/api/vault/pubkey', 1500),getVaultAgentPubkey: () => getCachedJson('/api/vault/agent/pubkey', 1500),createVaultSecret: (payload, opts) => postJson('/api/vault/secrets', payload, opts),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 8e51bc03a..020fdb4f2 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2120,6 +2120,36 @@"deleteConfirm": "Delete secret \"{{name}}\"? Agents will no longer be able to use it.","deleted": "Deleted {{name}}","created": "Saved {{name}}",+ "protectedUnlock": {+ "checking": "Checking your protected vault…",+ "unlocked": "Protected vault unlocked for this session",+ "lock": "Lock",+ "errorTitle": "Couldn't reach your protected vault",+ "retry": "Retry",+ "setupTitle": "Set up your protected vault",+ "unlockTitle": "Unlock to add a protected secret",+ "setupHelp": "Choose how to unlock protected secrets in the browser. The machine alone can never decrypt them.",+ "unlockHelp": "Confirm your unlock factor to seal this secret under your existing vault key.",+ "setPasswordLabel": "Recovery password",+ "passwordLabel": "Vault password",+ "passwordPlaceholder": "Enter a strong password",+ "confirmLabel": "Confirm password",+ "confirmPlaceholder": "Re-enter the password",+ "passwordRecoveryNote": "Your password is the recovery factor — keep it safe. A passkey adds quick, stronger unlock on top.",+ "setupWithPasskey": "Set up with passkey",+ "setupPasswordOnly": "Use password only",+ "unlockPasskey": "Unlock with passkey",+ "unlockCta": "Unlock",+ "errors": {+ "prfUnavailable": "This passkey/browser doesn't support the PRF extension needed for encryption. Try a platform passkey (Touch ID / Windows Hello) or use a password.",+ "cancelled": "Passkey prompt was cancelled.",+ "noPasskey": "No passkey is configured for this vault. Use your password.",+ "wrongFactor": "Couldn't unlock — wrong password or passkey.",+ "discoveryFailed": "Couldn't load your protected vault. Check your connection and retry — don't set up a new one, or you'll split your vault keys.",+ "mismatch": "The passwords don't match.",+ "alreadyInitialized": "This vault was just set up elsewhere. Reload and unlock with your existing password or passkey."+ }+ },"dialog": {"title": "Add a secret","name": "Name",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex fa998190a..e25adcb68 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2119,6 +2119,36 @@"deleteConfirm": "删除密钥「{{name}}」?Agent 将无法再使用它。","deleted": "已删除 {{name}}","created": "已保存 {{name}}",+ "protectedUnlock": {+ "checking": "正在检查你的保护层…",+ "unlocked": "保护层已在本会话解锁",+ "lock": "锁定",+ "errorTitle": "无法访问你的保护层",+ "retry": "重试",+ "setupTitle": "设置你的保护层",+ "unlockTitle": "解锁以添加保护层密钥",+ "setupHelp": "选择在浏览器里如何解锁保护层密钥。机器单独永远无法解密。",+ "unlockHelp": "确认你的解锁因子,用现有的保护层主密钥封装这条密钥。",+ "setPasswordLabel": "恢复密码",+ "passwordLabel": "保护层密码",+ "passwordPlaceholder": "输入一个强密码",+ "confirmLabel": "确认密码",+ "confirmPlaceholder": "再次输入密码",+ "passwordRecoveryNote": "密码是你的恢复因子,务必保管好;passkey 在其上提供更快、更强的解锁。",+ "setupWithPasskey": "用 passkey 设置",+ "setupPasswordOnly": "只用密码",+ "unlockPasskey": "用 passkey 解锁",+ "unlockCta": "解锁",+ "errors": {+ "prfUnavailable": "这个 passkey/浏览器不支持加密所需的 PRF 扩展。请用平台 passkey(Touch ID / Windows Hello)或改用密码。",+ "cancelled": "passkey 提示被取消了。",+ "noPasskey": "这个保护层没有配置 passkey。请用密码。",+ "wrongFactor": "无法解锁——密码或 passkey 不对。",+ "discoveryFailed": "加载保护层失败。请检查网络后重试——不要重新设置,否则会把保护层主密钥分裂。",+ "mismatch": "两次输入的密码不一致。",+ "alreadyInitialized": "这个保护层刚在别处完成了设置。请刷新,用你已有的密码或 passkey 解锁。"+ }+ },"dialog": {"title": "添加密钥","name": "名称",diff --git a/ui/src/lib/useProtectedVault.ts b/ui/src/lib/useProtectedVault.tsnew file mode 100644index 000000000..2c4f99ea1--- /dev/null+++ b/ui/src/lib/useProtectedVault.ts@@ -0,0 +1,275 @@+import { useCallback, useState } from 'react';++import { useApi } from '@/context/ApiContext';+import {+ base64ToBytes,+ buildWrapMeta,+ bytesToBase64,+ newPasskeyPrfSalt,+ newVmk,+ packProtectedRecord,+ passkeyPrfSaltEntries,+ sealProtected,+ unwrapVmk,+ webAuthnPrfExtensionInput,+ type ProtectedRecordEnvelope,+ type VmkWrapFactor,+} from './vaultCrypto';++/**+ * Protected-tier vault lifecycle for the Web UI.+ *+ * The Vault Master Key (VMK) lives only in browser memory and is wrapped by user+ * factors into an opaque `wrap_meta` the daemon stores per protected secret. A+ * **password is always set as the recovery root**; a passkey (WebAuthn-PRF, Touch ID /+ * Windows Hello) can be added on top as the quick primary unlock — so losing a device+ * never makes protected secrets unrecoverable. The daemon never sees the VMK or+ * plaintext. No cross-origin sandbox yet — that hardening is a later version.+ *+ * The unlocked VMK is cached at module scope so it survives `VaultSecretForm`+ * unmount/remount within one page session. A full reload re-initialises the module.+ */+export type ProtectedVaultStatus = 'checking' | 'needs-setup' | 'locked' | 'unlocked' | 'error';++const sessionVault: { vmk: Uint8Array | null; wrapMeta: string | null; freshSetup: boolean } = {+ vmk: null,+ wrapMeta: null,+ freshSetup: false,+};++const WEBAUTHN_RP_NAME = 'Avibe Vault';+const WEBAUTHN_USER_HANDLE = new TextEncoder().encode('avibe-vault');++/**+ * WebAuthn needs a secure context and a domain RP ID. Browsers reject raw IP RP IDs+ * (the default local `http://127.0.0.1:5123` workflow), so the passkey path is only+ * offered on `localhost` or an HTTPS domain (e.g. the tunnel); elsewhere we fall back+ * to the password, which is the recovery root anyway.+ */+export function webauthnAvailable(): boolean {+ if (typeof window === 'undefined' || typeof window.PublicKeyCredential === 'undefined') return false;+ if (!window.isSecureContext) return false;+ const host = window.location.hostname;+ if (host === 'localhost') return true;+ if (host === '' || host.includes(':') || /^\d{1,3}(\.\d{1,3}){3}$/.test(host)) return false; // IPv6/IPv4+ return host.includes('.');+}++/** A fresh ArrayBuffer copy — WebAuthn fields want BufferSource, not Uint8Array<ArrayBufferLike>. */+function bufferSource(bytes: Uint8Array): ArrayBuffer {+ const out = new ArrayBuffer(bytes.byteLength);+ new Uint8Array(out).set(bytes);+ return out;+}++function randomChallenge(): ArrayBuffer {+ return bufferSource(crypto.getRandomValues(new Uint8Array(32)));+}++/** WebAuthn `prf.evalByCredential` keys are base64url-encoded credential ids. */+function base64ToBase64Url(b64: string): string {+ return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');+}++/** Strip a stored record's DEK fields back to the bare VMK wrap_meta ({v, copies}). */+function baseVmkWrapMeta(wrapMeta: string): string {+ const parsed = JSON.parse(wrapMeta) as Record<string, unknown>;+ delete parsed.dek_nonce;+ delete parsed.wrapped_dek;+ return JSON.stringify(parsed);+}++function toUint8(buffer: ArrayBuffer | ArrayBufferView): Uint8Array {+ return buffer instanceof ArrayBuffer ? new Uint8Array(buffer) : new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);+}++function passkeyResult(credential: PublicKeyCredential | null): Uint8Array {+ const ext = credential?.getClientExtensionResults() as { prf?: { results?: { first?: ArrayBuffer } } } | undefined;+ const first = ext?.prf?.results?.first;+ if (!first) throw new Error('passkey-prf-unavailable');+ return toUint8(first);+}++type PasskeyEntry = { credentialId?: string; prfSalt: Uint8Array };++/**+ * Assert one of the vault's passkeys and extract its PRF output. Uses+ * `evalByCredential` so each credential is evaluated with its own stored salt, then+ * returns the salt of whichever credential actually responded.+ */+async function assertPasskeyPrf(entries: PasskeyEntry[]): Promise<{ prfOutput: Uint8Array; prfSalt: Uint8Array }> {+ const withId = entries.filter((entry) => entry.credentialId);+ const evalByCredential: Record<string, { first: ArrayBuffer }> = {};+ for (const entry of withId) {+ evalByCredential[base64ToBase64Url(entry.credentialId as string)] = { first: bufferSource(entry.prfSalt) };+ }+ const extensions = (withId.length > 0+ ? { prf: { evalByCredential } }+ : webAuthnPrfExtensionInput(entries[0].prfSalt)) as AuthenticationExtensionsClientInputs;+ const assertion = (await navigator.credentials.get({+ publicKey: {+ challenge: randomChallenge(),+ allowCredentials: withId.map((entry) => ({+ type: 'public-key' as const,+ id: bufferSource(base64ToBytes(entry.credentialId as string)),+ })),+ userVerification: 'required',+ extensions,+ },+ })) as PublicKeyCredential | null;+ if (!assertion) throw new Error('passkey-cancelled');+ const prfOutput = passkeyResult(assertion);+ const usedId = bytesToBase64(toUint8(assertion.rawId));+ const used = entries.find((entry) => entry.credentialId === usedId);+ return { prfOutput, prfSalt: used?.prfSalt ?? entries[0].prfSalt };+}++/** Create a resident passkey, then assert it once to extract the PRF output. */+async function setupPasskeyFactor(prfSalt: Uint8Array): Promise<{ prfOutput: Uint8Array; credentialId: string }> {+ const created = (await navigator.credentials.create({+ publicKey: {+ rp: { name: WEBAUTHN_RP_NAME, id: window.location.hostname },+ user: { id: bufferSource(WEBAUTHN_USER_HANDLE), name: 'avibe-vault', displayName: WEBAUTHN_RP_NAME },+ challenge: randomChallenge(),+ pubKeyCredParams: [+ { type: 'public-key', alg: -7 },+ { type: 'public-key', alg: -257 },+ ],+ authenticatorSelection: { residentKey: 'preferred', userVerification: 'required' },+ extensions: { prf: {} } as AuthenticationExtensionsClientInputs,+ },+ })) as PublicKeyCredential | null;+ if (!created) throw new Error('passkey-cancelled');+ const credentialId = bytesToBase64(toUint8(created.rawId));+ const { prfOutput } = await assertPasskeyPrf([{ credentialId, prfSalt }]);+ return { prfOutput, credentialId };+}++export function useProtectedVault() {+ const api = useApi();+ const [status, setStatus] = useState<ProtectedVaultStatus>(sessionVault.vmk ? 'unlocked' : 'checking');+ const [error, setError] = useState<string | null>(null);++ const refresh = useCallback(async () => {+ if (sessionVault.vmk) {+ setStatus('unlocked');+ return;+ }+ setStatus('checking');+ setError(null);+ try {+ const res = await api.getVaultVmk();+ if (!res?.ok) throw new Error('vmk-discovery-failed');+ if (res.exists && res.wrap_meta) {+ sessionVault.wrapMeta = baseVmkWrapMeta(res.wrap_meta);+ setStatus('locked');+ } else {+ sessionVault.wrapMeta = null;+ setStatus('needs-setup');+ }+ } catch {+ // A failed/transient discovery must NOT degrade to setup — that would let the+ // user mint a second VMK and split the vault key history. Surface an error.+ setStatus('error');+ setError('vmk-discovery-failed');+ }+ }, [api]);++ const commit = (vmk: Uint8Array, wrapMeta: string, freshSetup: boolean) => {+ sessionVault.vmk?.fill(0);+ sessionVault.vmk = vmk;+ sessionVault.wrapMeta = wrapMeta;+ sessionVault.freshSetup = freshSetup;+ setStatus('unlocked');+ setError(null);+ };++ // First-time setup always includes a password (recovery root); a passkey is layered+ // on top when available so device loss never strands protected secrets.+ const setupPassword = useCallback(async (password: string) => {+ const vmk = newVmk();+ commit(vmk, await buildWrapMeta(vmk, [{ kind: 'password', password }]), true);+ }, []);++ const setupPasskey = useCallback(async (recoveryPassword: string) => {+ const prfSalt = newPasskeyPrfSalt();+ const { prfOutput, credentialId } = await setupPasskeyFactor(prfSalt);+ const vmk = newVmk();+ const factors: VmkWrapFactor[] = [+ { kind: 'password', password: recoveryPassword },+ { kind: 'passkey', prfOutput, prfSalt, credentialId },+ ];+ commit(vmk, await buildWrapMeta(vmk, factors), true);+ }, []);++ const unlockPassword = useCallback(async (password: string) => {+ const wrapMeta = sessionVault.wrapMeta;+ if (!wrapMeta) throw new Error('vault-not-setup');+ commit(await unwrapVmk(wrapMeta, { kind: 'password', password }), wrapMeta, false);+ }, []);++ const unlockPasskey = useCallback(async () => {+ const wrapMeta = sessionVault.wrapMeta;+ if (!wrapMeta) throw new Error('vault-not-setup');+ const entries = passkeyPrfSaltEntries(wrapMeta);+ if (entries.length === 0) throw new Error('passkey-not-configured');+ const { prfOutput, prfSalt } = await assertPasskeyPrf(entries);+ commit(await unwrapVmk(wrapMeta, { kind: 'passkey', prfOutput, prfSalt }), wrapMeta, false);+ }, []);++ /** Seal a value under the unlocked VMK into a stored protected envelope. */+ const sealValue = useCallback(+ async (name: string, value: string): Promise<{ envelope: ProtectedRecordEnvelope; establishingVmk: boolean }> => {+ const { vmk, wrapMeta, freshSetup } = sessionVault;+ if (!vmk || !wrapMeta) throw new Error('vault-locked');+ const sealed = await sealProtected(new TextEncoder().encode(value), vmk, { name });+ // `establishingVmk` lets the create transaction enforce the atomic single-init+ // guard server-side (a UI re-check here can't be race-free); the daemon rejects a+ // second VMK so concurrent first-time setups can't split the key history.+ return { envelope: packProtectedRecord(sealed, wrapMeta), establishingVmk: freshSetup };+ },+ [],+ );++ const afterCreated = useCallback(() => {+ // The vault now exists server-side; subsequent creates this session aren't "establishing".+ sessionVault.freshSetup = false;+ }, []);++ const lock = useCallback(() => {+ sessionVault.vmk?.fill(0);+ sessionVault.vmk = null;+ if (sessionVault.freshSetup) {+ // An uncommitted fresh VMK (set up but no protected secret saved yet) — discard it+ // so a later unlock can't seal under a stale local VMK that skips the init guard.+ sessionVault.wrapMeta = null;+ sessionVault.freshSetup = false;+ setStatus('needs-setup');+ } else {+ setStatus(sessionVault.wrapMeta ? 'locked' : 'needs-setup');+ }+ }, []);++ const discardAndRefresh = useCallback(async () => {+ // After an init collision (another tab established the vault first), drop the+ // rejected local VMK and reload the server's real wrap_meta so the user unlocks the+ // established vault instead of resealing under the loser VMK.+ sessionVault.vmk?.fill(0);+ sessionVault.vmk = null;+ sessionVault.wrapMeta = null;+ sessionVault.freshSetup = false;+ await refresh();+ }, [refresh]);++ const hasPasskey = useCallback(() => {+ const wrapMeta = sessionVault.wrapMeta;+ if (!wrapMeta) return false;+ try {+ return passkeyPrfSaltEntries(wrapMeta).length > 0;+ } catch {+ return false;+ }+ }, []);++ return { status, error, setError, refresh, setupPassword, setupPasskey, unlockPassword, unlockPasskey, sealValue, afterCreated, lock, discardAndRefresh, hasPasskey };+}diff --git a/ui/src/lib/vaultCrypto.test.ts b/ui/src/lib/vaultCrypto.test.tsindex 16b1c8736..21b500af1 100644--- a/ui/src/lib/vaultCrypto.test.ts+++ b/ui/src/lib/vaultCrypto.test.ts@@ -28,6 +28,9 @@ import {releaseProtectedDek,sealBlindBox,sealProtected,+ openProtected,+ packProtectedRecord,+ unpackProtectedRecord,signDigest,SIGN_SCHEME_ECDSA_SECP256K1_DER,SIGN_SCHEME_ECDSA_SECP256K1_RECOVERABLE,@@ -494,3 +497,27 @@ describe('vaultCrypto protected hierarchy', () => {);});});++describe('protected record storage composition', () => {+ it('packs a sealed record and unpacks it for a clean open round-trip', async () => {+ const vmk = newVmk();+ const wrapMeta = await buildWrapMeta(vmk, ['vault-password']);+ const context = { name: 'OPENAI_API_KEY' };+ const sealed = await sealProtected(new TextEncoder().encode('sk-secret-value'), vmk, context);++ const envelope = packProtectedRecord(sealed, wrapMeta);+ const restored = unpackProtectedRecord(envelope);+ const vmkAgain = await unwrapVmk(restored.vmkWrapMeta, 'vault-password');+ const opened = await openProtected(restored.sealed, vmkAgain, context);++ expect(new TextDecoder().decode(opened)).toBe('sk-secret-value');+ });++ it('refuses to fold a DEK into a wrap_meta that already carries one', async () => {+ const vmk = newVmk();+ const wrapMeta = await buildWrapMeta(vmk, ['pw']);+ const sealed = await sealProtected(new TextEncoder().encode('v'), vmk, { name: 'NAME' });+ const once = packProtectedRecord(sealed, wrapMeta);+ expect(() => packProtectedRecord(sealed, once.wrap_meta)).toThrow();+ });+});diff --git a/ui/src/lib/vaultCrypto.ts b/ui/src/lib/vaultCrypto.tsindex c2b9bfee6..2e240a1d5 100644--- a/ui/src/lib/vaultCrypto.ts+++ b/ui/src/lib/vaultCrypto.ts@@ -1246,3 +1246,40 @@ export async function signProtectedDigest(privateKey.fill(0);}}++/**+ * Storage composition for protected-tier records.+ *+ * The daemon stores a protected secret as an opaque `{ciphertext, nonce, wrap_meta}`+ * triple. The browser produces two artifacts on create: the {@link ProtectedSealed}+ * envelope (value encrypted under a per-record DEK, and that DEK wrapped under the+ * VMK) and the VMK `wrap_meta` (the VMK wrapped under the user's factors). We fold the+ * DEK-under-VMK fields into the stored `wrap_meta` so every record is self-contained+ * and round-trippable — pack on create, unpack on open. Field names match the Python+ * reference (`storage/vault_protected.py`).+ */+export type ProtectedRecordEnvelope = { ciphertext: string; nonce: string; wrap_meta: string };++export function packProtectedRecord(sealed: ProtectedSealed, vmkWrapMeta: string): ProtectedRecordEnvelope {+ const meta = JSON.parse(vmkWrapMeta) as Record<string, unknown>;+ if ('dek_nonce' in meta || 'wrapped_dek' in meta) {+ throw new Error('vmk wrap_meta must not already carry a wrapped DEK');+ }+ return {+ ciphertext: sealed.ciphertext,+ nonce: sealed.nonce,+ wrap_meta: JSON.stringify({ ...meta, dek_nonce: sealed.dek_nonce, wrapped_dek: sealed.wrapped_dek }),+ };+}++export function unpackProtectedRecord(envelope: ProtectedRecordEnvelope): { sealed: ProtectedSealed; vmkWrapMeta: string } {+ const parsed = JSON.parse(envelope.wrap_meta) as Record<string, unknown>;+ const { dek_nonce, wrapped_dek, ...vmkMeta } = parsed;+ if (typeof dek_nonce !== 'string' || typeof wrapped_dek !== 'string') {+ throw new Error('protected record wrap_meta is missing the wrapped DEK');+ }+ return {+ sealed: { ciphertext: envelope.ciphertext, nonce: envelope.nonce, dek_nonce, wrapped_dek },+ vmkWrapMeta: JSON.stringify(vmkMeta),+ };+}diff --git a/vibe/api.py b/vibe/api.pyindex fd26d7578..5e045bd41 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1397,6 +1397,7 @@ def create_vault_secret(payload: dict) -> dict:policy = payload.get("policy") if isinstance(payload.get("policy"), dict) else Nonepublic_meta = payload.get("public_meta") if isinstance(payload.get("public_meta"), dict) else Noneprotection = str(payload.get("protection") or "standard").strip().lower()+ establishing_vmk = bool(payload.get("establishing_vmk"))kind = str(payload.get("kind") or "static").strip().lower()signer_kind = payload.get("signer_kind")if signer_kind is not None:@@ -1440,11 +1441,14 @@ def create_vault_secret(payload: dict) -> dict:description=payload.get("description"),policy=policy,public_meta=public_meta,+ establishing_vmk=establishing_vmk,)except vault_service.InvalidSecretNameError as exc:raise VaultApiError("invalid secret name (use ^[A-Z][A-Z0-9_]*$)", code="invalid_name") from excexcept vault_service.SecretExistsError as exc:raise VaultApiError(f"secret '{name}' already exists", code="secret_exists", status=409) from exc+ except vault_service.VaultAlreadyInitializedError as exc:+ raise VaultApiError(str(exc), code="vault_already_initialized", status=409) from excexcept vault_service.VaultServiceError as exc:raise VaultApiError(str(exc), code="vault_error") from excreturn {"ok": True, "secret": meta}