Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(vault): protected-vault hardening — auto-lock + lock UI + passkey-gated delete (#817)
Call White6bcd3c6f9983
diff --git a/ui/src/components/ui/confirm-dialog.tsx b/ui/src/components/ui/confirm-dialog.tsxindex 268e148f8..5b7d9d869 100644--- a/ui/src/components/ui/confirm-dialog.tsx+++ b/ui/src/components/ui/confirm-dialog.tsx@@ -22,6 +22,9 @@ export interface ConfirmDialogProps {* irreversible action.*/holdSeconds?: number;+ /** External gate: keep the confirm button disabled while true (independent of the hold+ * countdown) — e.g. while a required unlock ceremony is still pending. */+ confirmDisabled?: boolean;/** Runs on confirm; while it's pending a spinner shows and the dialog can't be dismissed. */onConfirm: () => void | Promise<void>;}@@ -41,6 +44,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({cancelLabel,destructive = false,holdSeconds = 0,+ confirmDisabled = false,onConfirm,}) => {const { t } = useTranslation();@@ -70,7 +74,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({const confirmText = confirmLabel ?? t('common.confirm');const handleConfirm = async () => {- if (locked || busy) return;+ if (locked || busy || confirmDisabled) return;setBusy(true);try {await onConfirm();@@ -100,7 +104,7 @@ export const ConfirmDialog: React.FC<ConfirmDialogProps> = ({<Buttonvariant={destructive ? 'destructive' : 'default'}onClick={handleConfirm}- disabled={locked || busy}+ disabled={locked || busy || confirmDisabled}>{busy ? <Loader2 className="size-4 animate-spin" /> : null}{locked ? `${confirmText} (${displayRemaining})` : confirmText}diff --git a/ui/src/components/ui/vault-lock-indicator.tsx b/ui/src/components/ui/vault-lock-indicator.tsxnew file mode 100644index 000000000..c4dbaef54--- /dev/null+++ b/ui/src/components/ui/vault-lock-indicator.tsx@@ -0,0 +1,39 @@+import { Lock, Unlock } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useVaultLock } from '@/lib/useProtectedVault';+import { cn } from '@/lib/utils';+import { Button } from './button';++/** mm:ss for a millisecond duration (rounded up so it never shows 0:00 while still ticking). */+function formatRemaining(ms: number): string {+ const total = Math.max(0, Math.ceil(ms / 1000));+ const minutes = Math.floor(total / 60);+ const seconds = total % 60;+ return `${minutes}:${String(seconds).padStart(2, '0')}`;+}++/**+ * Shown while the protected vault is unlocked: a pill with the time left before the plaintext+ * key auto-locks, plus a one-tap "Lock now". Renders nothing while the vault is locked.+ */+export function VaultLockIndicator({ className }: { className?: string }) {+ const { t } = useTranslation();+ const { unlocked, remainingMs, lockNow } = useVaultLock();+ if (!unlocked) return null;+ return (+ <div+ className={cn('flex items-center gap-2 rounded-full border border-mint/40 bg-mint-soft py-1 pl-3 pr-1', className)}+ title={t('vaults.lock.autoLockHint')}+ >+ <Unlock className="size-3.5 shrink-0 text-mint" />+ <span className="text-xs font-medium text-foreground">+ {t('vaults.lock.unlocked')} · <span className="tabular-nums">{formatRemaining(remainingMs)}</span>+ </span>+ <Button variant="ghost" size="sm" className="h-6 gap-1 rounded-full px-2 text-xs" onClick={lockNow}>+ <Lock className="size-3" />+ {t('vaults.lock.lockNow')}+ </Button>+ </div>+ );+}diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex 389d394aa..40ba66c2b 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -9,8 +9,11 @@ import { Badge } from '../ui/badge';import { Button } from '../ui/button';import { ConfirmDialog } from '../ui/confirm-dialog';import { Popover, PopoverContent, PopoverTrigger } from '../ui/popover';+import { VaultLockIndicator } from '../ui/vault-lock-indicator';+import { VaultProtectedUnlock } from '../ui/vault-protected-unlock';import { cn } from '../../lib/utils';import { partitionTags } from '../../lib/vaultTags';+import { useProtectedVault, vaultFreshSetup, vaultUnlocked } from '../../lib/useProtectedVault';import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultSecret } from '../../context/ApiContext';import { useToast } from '../../context/ToastContext';import type { ApprovalOutcome } from '../ui/vault-approval-card';@@ -672,13 +675,34 @@ export const VaultsPage: React.FC = () => {}}, [api, showAudit]);+ const protectedVault = useProtectedVault();const [deleteTarget, setDeleteTarget] = useState<VaultSecret | null>(null);const [editTarget, setEditTarget] = useState<VaultSecret | null>(null);+ // Deleting a protected secret requires the user present at an unlocked vault (a passkey/password+ // ceremony) — discover the current lock state when the delete dialog opens for one.+ useEffect(() => {+ if (deleteTarget?.protection !== 'protected') return;+ // A freshly set-up, uncommitted local VMK isn't a proven unlock of this secret's real vault+ // (first-init collision) — drop it and rediscover the server vault so the user must unlock the+ // actual one; otherwise just discover the current lock state.+ if (vaultFreshSetup()) void protectedVault.discardAndRefresh();+ else void protectedVault.refresh();+ // eslint-disable-next-line react-hooks/exhaustive-deps -- vault callbacks are stable; re-run only on target change+ }, [deleteTarget]);+ // Gate on the wall-clock lock state (vaultUnlocked), not the hook's cached status — a delayed+ // auto-lock timer (tab resumed after the deadline) can leave status stale-'unlocked', which must+ // NOT enable a protected delete without a fresh unlock.+ const deleteNeedsUnlock =+ deleteTarget?.protection === 'protected' && (!vaultUnlocked() || vaultFreshSetup());const onDelete = (secret: VaultSecret) => setDeleteTarget(secret);const onEdit = (secret: VaultSecret) => setEditTarget(secret);const confirmDelete = async () => {const secret = deleteTarget;if (!secret) return;+ // Belt-and-suspenders at the mutation point: a protected secret must have a committed,+ // wall-clock-valid unlock right now — closes the delayed-auto-lock resume window where the+ // button could momentarily be stale-enabled.+ if (secret.protection === 'protected' && (!vaultUnlocked() || vaultFreshSetup())) return;try {await api.deleteVaultSecret(secret.name);showToast(t('vaults.deleted', { name: secret.name }), 'success');@@ -713,6 +737,7 @@ export const VaultsPage: React.FC = () => {subtitle={t('vaults.subtitle')}actions={<>+ <VaultLockIndicator /><Button variant={showAudit ? 'secondary' : 'ghost'} size="icon" onClick={toggleAudit} aria-label={t('vaults.history')}><History className="size-4" /></Button>@@ -847,6 +872,7 @@ export const VaultsPage: React.FC = () => {description={t('vaults.deleteDialog.description')}confirmLabel={t('common.delete')}holdSeconds={deleteTarget?.kind === 'keypair' ? 5 : 0}+ confirmDisabled={deleteNeedsUnlock}onConfirm={confirmDelete}>{deleteTarget?.kind === 'keypair' ? (@@ -861,6 +887,12 @@ export const VaultsPage: React.FC = () => {</span></div>) : null}+ {deleteNeedsUnlock ? (+ <div className="flex flex-col gap-2">+ <p className="text-[12.5px] leading-snug text-muted-foreground">{t('vaults.deleteDialog.protectedUnlockNote')}</p>+ <VaultProtectedUnlock vault={protectedVault} secretName={deleteTarget?.name} />+ </div>+ ) : null}</ConfirmDialog></div>);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 1110fe198..b5624fa6d 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2240,10 +2240,16 @@"title": "Delete \"{{name}}\"?","description": "Agents will no longer be able to use this secret.","keypairIrreversible": "This is a signing key — deleting it permanently destroys the private key. There is no backup and it cannot be recovered.",- "keypairFunds": "If this key's address holds any funds, move them out first, or they will be lost for good."+ "keypairFunds": "If this key's address holds any funds, move them out first, or they will be lost for good.",+ "protectedUnlockNote": "This is a protected secret — unlock the vault to confirm it's you before deleting."},"deleted": "Deleted {{name}}","created": "Saved {{name}}",+ "lock": {+ "unlocked": "Unlocked",+ "lockNow": "Lock now",+ "autoLockHint": "Auto-locks after 10 minutes idle — the key is wiped from this browser. Lock now to wipe it immediately."+ },"saved": "Updated {{name}}","editSecret": "Edit info","rowActions": "More actions",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex ab17ef82f..1fcaf0d05 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2240,10 +2240,16 @@"title": "删除「{{name}}」?","description": "Agent 将无法再使用这条密钥。","keypairIrreversible": "这是一把签名密钥——删除会永久销毁私钥,没有备份,无法恢复。",- "keypairFunds": "如果这把密钥的地址里还有资金,请先转出,否则将永久丢失。"+ "keypairFunds": "如果这把密钥的地址里还有资金,请先转出,否则将永久丢失。",+ "protectedUnlockNote": "这是保护档密钥——删除前先解锁保险库,验证是你本人。"},"deleted": "已删除 {{name}}","created": "已保存 {{name}}",+ "lock": {+ "unlocked": "已解锁",+ "lockNow": "立即锁定",+ "autoLockHint": "闲置 10 分钟后自动锁定——密钥会从浏览器内存中抹除。点「立即锁定」可马上抹除。"+ },"saved": "已更新 {{name}}","editSecret": "编辑信息","rowActions": "更多操作",diff --git a/ui/src/lib/useProtectedVault.ts b/ui/src/lib/useProtectedVault.tsindex d2f21ad8f..4b479c17b 100644--- a/ui/src/lib/useProtectedVault.ts+++ b/ui/src/lib/useProtectedVault.ts@@ -1,4 +1,4 @@-import { useCallback, useState } from 'react';+import { useCallback, useEffect, useReducer, useState } from 'react';import { useApi } from '@/context/ApiContext';import {@@ -55,6 +55,139 @@ const sessionVault: { vmk: Uint8Array | null; wrapMeta: string | null; freshSetufreshSetup: false,};+/**+ * Auto-lock. The plaintext VMK is zeroed this long after it was unlocked (the timer is+ * refreshed on every use), shrinking the window it sits in browser memory from "until reload"+ * to a few idle minutes. A manual "Lock now" or a full page reload also clears it.+ */+const VAULT_AUTO_LOCK_MS = 10 * 60 * 1000;+let vaultLockExpiresAt: number | null = null;+let vaultAutoLockTimer: ReturnType<typeof setTimeout> | null = null;+const vaultLockListeners = new Set<() => void>();++/**+ * Cross-tab lock: a manual "Lock now" broadcasts here so every open tab for this origin wipes its+ * own cached VMK, not just the tab that clicked. Auto-lock stays per-tab (each tab's idle timer is+ * independent, so an idle tab locking shouldn't wipe a tab you're actively using).+ *+ * Created lazily on first unlock (never at module import): `BroadcastChannel` also exists in+ * Node/Vitest, and an open-at-import channel keeps the process alive and can hang the UI test run.+ */+let vaultLockChannel: BroadcastChannel | null = null;+let vaultLockChannelInit = false;+function getVaultLockChannel(): BroadcastChannel | null {+ if (vaultLockChannelInit) return vaultLockChannel;+ vaultLockChannelInit = true;+ if (typeof BroadcastChannel === 'undefined') return null;+ vaultLockChannel = new BroadcastChannel('avibe-vault-lock');+ vaultLockChannel.onmessage = (event: MessageEvent) => {+ if (event.data === 'lock') lockVault(false);+ };+ return vaultLockChannel;+}++function notifyVaultLockChange(): void {+ for (const listener of [...vaultLockListeners]) listener();+}++/** Subscribe to VMK unlock/auto-lock/lock transitions (module-global). Returns an unsubscribe. */+export function subscribeVaultLock(listener: () => void): () => void {+ vaultLockListeners.add(listener);+ return () => {+ vaultLockListeners.delete(listener);+ };+}++/** Wall-clock ms when the VMK auto-locks, or null while locked. */+export function vaultUnlockExpiresAt(): number | null {+ return sessionVault.vmk ? vaultLockExpiresAt : null;+}++/** True once the auto-lock wall-clock deadline has passed (independent of the setTimeout). */+function autoLockExpired(): boolean {+ return vaultLockExpiresAt != null && Date.now() >= vaultLockExpiresAt;+}++export function vaultUnlocked(): boolean {+ if (sessionVault.vmk && autoLockExpired()) {+ // Zero an expired VMK the instant anything checks the lock state, even if the (delayed) timer+ // hasn't fired — so no flow (delete gate, create/provision, approval) can treat a past-deadline+ // vault as unlocked.+ clearVmk();+ // Notify subscribers so other mounted forms/approval cards drop out of 'unlocked' too. Deferred+ // to a microtask because this may run during render (can't synchronously setState here).+ queueMicrotask(notifyVaultLockChange);+ return false;+ }+ return sessionVault.vmk != null;+}++/**+ * Enforce the auto-lock deadline synchronously. Browser timers fire late when a tab is+ * backgrounded/suspended or the machine sleeps, so `setTimeout(lockVault)` can lag well past the+ * deadline; call this before trusting or using the VMK to lock the moment the wall clock is past+ * due. Safe in event/effect contexts (it notifies). Returns whether the vault is still unlocked.+ */+function enforceAutoLock(): boolean {+ if (sessionVault.vmk && autoLockExpired()) {+ lockVault();+ return false;+ }+ return sessionVault.vmk != null;+}++/**+ * True when the in-memory VMK is a fresh, uncommitted first-time setup — NOT a proven unlock of+ * the server's established vault. In the first-init collision path (another tab established the+ * real vault after this tab set up but before it saved a secret) a fresh-setup VMK is a loser key+ * that must not be treated as authorization to act on a real protected secret.+ */+export function vaultFreshSetup(): boolean {+ return sessionVault.freshSetup;+}++function vaultStatusNow(): ProtectedVaultStatus {+ if (sessionVault.vmk) return 'unlocked';+ return sessionVault.wrapMeta ? 'locked' : 'needs-setup';+}++/** Zero the VMK and cancel the pending auto-lock. Does not notify — callers decide. */+function clearVmk(): void {+ sessionVault.vmk?.fill(0);+ sessionVault.vmk = null;+ vaultLockExpiresAt = null;+ if (vaultAutoLockTimer) {+ clearTimeout(vaultAutoLockTimer);+ vaultAutoLockTimer = null;+ }+ if (sessionVault.freshSetup) {+ // An uncommitted fresh VMK (set up but no protected secret saved yet) — drop it so a later+ // unlock can't seal under a stale local VMK that skips the atomic first-init guard. Done here+ // (not only in lockVault) so EVERY teardown path — manual lock, auto-lock, and the render-time+ // expiry in vaultUnlocked() — leaves a consistent state.+ sessionVault.wrapMeta = null;+ sessionVault.freshSetup = false;+ }+}++/** Lock the vault now: zero the VMK, drop an uncommitted fresh-setup VMK, notify subscribers. */+function lockVault(broadcast = false): void {+ clearVmk(); // zeros the VMK and drops any uncommitted fresh-setup state+ notifyVaultLockChange();+ // A manual "Lock now" wipes every open tab for this origin, not just this one.+ if (broadcast) getVaultLockChannel()?.postMessage('lock');+}++/** (Re)start the auto-lock countdown; call on unlock and on every VMK use. Notifies subscribers. */+function armVaultAutoLock(): void {+ if (!sessionVault.vmk) return;+ getVaultLockChannel(); // ensure this (unlocked) tab can receive a cross-tab "Lock now"+ vaultLockExpiresAt = Date.now() + VAULT_AUTO_LOCK_MS;+ if (vaultAutoLockTimer) clearTimeout(vaultAutoLockTimer);+ vaultAutoLockTimer = setTimeout(() => lockVault(), VAULT_AUTO_LOCK_MS);+ notifyVaultLockChange();+}+const WEBAUTHN_RP_NAME = 'Avibe Vault';const WEBAUTHN_USER_HANDLE = new TextEncoder().encode('avibe-vault');@@ -192,7 +325,25 @@ export function useProtectedVault() {const [status, setStatus] = useState<ProtectedVaultStatus>(sessionVault.vmk ? 'unlocked' : 'checking');const [error, setError] = useState<string | null>(null);+ // Re-sync this instance when the module VMK locks/unlocks elsewhere — notably when the+ // auto-lock timer fires while this component is mounted, or another instance unlocks. Don't+ // clobber the async discovery states ('checking'/'error').+ useEffect(+ () =>+ subscribeVaultLock(() => {+ setStatus((prev) => {+ // A global unlock (from another dialog/tab) should win even over a stale 'error'/'checking'+ // discovery state — otherwise that instance stays disabled though the vault is now unlocked.+ if (sessionVault.vmk) return 'unlocked';+ // No VMK: don't clobber an in-flight discovery; otherwise reflect locked/needs-setup.+ return prev === 'checking' || prev === 'error' ? prev : vaultStatusNow();+ });+ }),+ [],+ );+const refresh = useCallback(async () => {+ enforceAutoLock(); // a cached VMK past its deadline isn't "unlocked" — lock it before trusting itif (sessionVault.vmk) {setStatus('unlocked');return;@@ -222,6 +373,7 @@ export function useProtectedVault() {sessionVault.vmk = vmk;sessionVault.wrapMeta = wrapMeta;sessionVault.freshSetup = freshSetup;+ armVaultAutoLock();setStatus('unlocked');setError(null);};@@ -264,8 +416,10 @@ export function useProtectedVault() {*/const sealValue = useCallback(async (name: string, value: Uint8Array | string): Promise<{ envelope: ProtectedRecordEnvelope; establishingVmk: boolean }> => {+ if (!enforceAutoLock()) throw new Error('vault-locked');const { vmk, wrapMeta, freshSetup } = sessionVault;if (!vmk || !wrapMeta) throw new Error('vault-locked');+ armVaultAutoLock();const valueBytes = typeof value === 'string' ? new TextEncoder().encode(value) : value;const sealed = await sealProtected(valueBytes, vmk, { name });// `establishingVmk` lets the create transaction enforce the atomic single-init@@ -289,8 +443,10 @@ export function useProtectedVault() {*/const signProtectedRequest = useCallback(async (material: ProtectedUnlockMaterial, digest: string, scheme: SignatureScheme): Promise<SignatureResult> => {+ if (!enforceAutoLock()) throw new Error('vault-locked');const { vmk } = sessionVault;if (!vmk) throw new Error('vault-locked');+ armVaultAutoLock();const { sealed } = unpackProtectedRecord(material.envelope);return signProtectedDigest(sealed, vmk, { name: material.name }, digest, scheme);},@@ -309,8 +465,10 @@ export function useProtectedVault() {publicKey: AvaultPublicKey,context: ProtectedDekDeliveryBlindBoxContext,): Promise<BlindBox> => {+ if (!enforceAutoLock()) throw new Error('vault-locked');const { vmk } = sessionVault;if (!vmk) throw new Error('vault-locked');+ armVaultAutoLock();const { sealed } = unpackProtectedRecord(material.envelope);return releaseProtectedDek(sealed, vmk, publicKey, { name: material.name }, context);},@@ -318,27 +476,18 @@ export function useProtectedVault() {);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');- }+ lockVault(true);+ setStatus(vaultStatusNow());}, []);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;+ clearVmk();sessionVault.wrapMeta = null;sessionVault.freshSetup = false;+ notifyVaultLockChange();await refresh();}, [refresh]);@@ -379,3 +528,33 @@ export function useProtectedVault() {return { status, error, setError, refresh, setupPassword, setupPasskey, unlockPassword, unlockPasskey, sealValue, signProtectedRequest, releaseProtectedDelivery, afterCreated, lock, discardAndRefresh, hasPasskey, hasPassword, passkeyUsableHere };}++/**+ * Reactive VMK lock state for a lightweight status/countdown UI. Subscribes to the+ * module-global auto-lock so an indicator can show the time left before the vault+ * auto-locks and offer an immediate "Lock now", without taking the full+ * {@link useProtectedVault} surface.+ */+export function useVaultLock(): { unlocked: boolean; remainingMs: number; lockNow: () => void } {+ const [, forceRender] = useReducer((n: number) => n + 1, 0);+ useEffect(() => subscribeVaultLock(forceRender), []);++ const unlocked = vaultUnlocked();+ const [now, setNow] = useState(() => Date.now());+ useEffect(() => {+ if (!unlocked) return;+ setNow(Date.now());+ // Tick the countdown, and enforce the deadline by wall-clock so a delayed timer (e.g. the tab+ // was suspended) locks promptly on resume instead of lingering unlocked.+ const id = setInterval(() => {+ enforceAutoLock();+ setNow(Date.now());+ }, 1000);+ return () => clearInterval(id);+ }, [unlocked]);++ const expiresAt = vaultUnlockExpiresAt();+ const remainingMs = expiresAt ? Math.max(0, expiresAt - now) : 0;+ // "Lock now" broadcasts so every open tab for this origin wipes its VMK, not just this one.+ return { unlocked, remainingMs, lockNow: () => lockVault(true) };+}