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(ui): vaults protocol v2 frontend (#850)
Call White5cdc4eb71a93
diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsxindex b09f365dd..c3f705cf2 100644--- a/ui/src/components/ui/vault-approval-card.tsx+++ b/ui/src/components/ui/vault-approval-card.tsx@@ -1,8 +1,15 @@-import { useCallback, useEffect, useMemo, useState } from 'react';-import { Check, Clock, Copy, Globe, KeyRound, Loader2, LockKeyhole, PenTool, Puzzle, ShieldCheck, Tag, Wallet } from 'lucide-react';+import { useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { Check, Copy, Globe, KeyRound, Link2, Loader2, LockKeyhole, PenTool, Puzzle, ShieldCheck, Tag, Wallet } from 'lucide-react';import { useTranslation } from 'react-i18next';-import { useApi, type SigningAddresses, type VaultRequest, type VaultSourceSelector } from '@/context/ApiContext';+import {+ useApi,+ type SigningAddresses,+ type VaultGrantDuration,+ type VaultRequest,+ type VaultSignedOperationContext,+ type VaultSourceSelector,+} from '@/context/ApiContext';import { partitionTags } from '@/lib/vaultTags';import { useProtectedVault, type ProtectedUnlockMaterial } from '@/lib/useProtectedVault';import { SigningAddressList } from './signing-address-list';@@ -10,9 +17,23 @@ import { type BlindBox, type SignatureScheme } from '@/lib/vaultCrypto';import { cn, copyTextToClipboard } from '@/lib/utils';import { Badge } from './badge';import { Button } from './button';+import { SegmentedRadio } from './segmented';import { Switch } from './switch';import { VaultRequestSessionLink, vaultRequestSessionDisplay } from './vault-request-session-link';+/** The three approver-chosen grant-duration options (protocol v2 §7.1), as SegmentedRadio ids. */+type GrantDurationChoice = 'one-time' | '300' | '900';++function grantChoiceFromLastTtl(value: VaultGrantDuration | undefined): GrantDurationChoice {+ if (value === 'one-time') return 'one-time';+ if (value === 900) return '900';+ return '300';+}++function grantDurationApiValue(choice: GrantDurationChoice): VaultGrantDuration {+ return choice === 'one-time' ? 'one-time' : Number(choice);+}+/*** The fixed protected grant the daemon attaches to an access request's card. In the* grant-id model there is exactly one: the protected set covered by the request's@@ -22,6 +43,8 @@ type GrantOption = {grant_id: string;default_ttl_seconds?: number;session_binding_default?: boolean;+ /** The grant is consumed after a single delivery — the agent never gets a timed window. */+ one_shot?: boolean;member_count?: number;member_snapshot?: string[];source_selector?: VaultSourceSelector;@@ -46,6 +69,8 @@ type ApprovalCard = {default_ttl_seconds?: number;/** The fixed protected grant. */grant_options?: GrantOption[];+ /** The whole request is one-shot (a single delivery, no timed window). */+ one_shot?: boolean;/** Hydrated for UI audience when the requested secret is protected. */secret_unlock_material?: ProtectedUnlockMaterial | null;};@@ -73,18 +98,6 @@ const DetailRow: React.FC<{ label: string; children: React.ReactNode }> = ({ lab</div>);-/** Localized TTL label ("15 min" / "2 h") from a seconds value. */-function useTtlLabel() {- const { t } = useTranslation();- return useCallback(- (seconds: number) => {- if (seconds >= 3600 && seconds % 3600 === 0) return t('vaults.approval.ttlHours', { count: seconds / 3600 });- return t('vaults.approval.ttlMinutes', { count: Math.max(1, Math.round(seconds / 60)) });- },- [t],- );-}-/*** Full approval surface for a single pending vault request (access or sign), rendering* the daemon's approval card (design.pen frames ① / ②). Standard and protected tiers are@@ -100,7 +113,6 @@ export const VaultApprovalCard: React.FC<{const { t } = useTranslation();const api = useApi();const vault = useProtectedVault();- const ttlLabel = useTtlLabel();// The request is passed in already hydrated by the UI-audience inbox list// (`getVaultRequests`, #708), so `card.secret_unlock_material` /@@ -113,6 +125,8 @@ export const VaultApprovalCard: React.FC<{scheme?: string;signing_context?: Record<string, unknown>;signingContext?: Record<string, unknown>;+ // The daemon-signed sign context (protocol v2 §6.2); the sandbox renders + verifies it.+ operation_context?: VaultSignedOperationContext;};const isSign = (card?.request_type ?? request.request_type) === 'sign';const isKeypair = card?.kind === 'keypair';@@ -120,6 +134,10 @@ export const VaultApprovalCard: React.FC<{// A grant covers a fixed protected set — there is no scope picker.const grantOptions = useMemo(() => card?.grant_options ?? [], [card]);const option = useMemo(() => grantOptions[0], [grantOptions]);+ // A one-shot request is consumed after a single delivery — the agent never gets a timed window,+ // so the duration control is forced to and locked on "one-time" (showing 5/15 min would promise+ // a window the agent won't receive).+ const isOneShot = Boolean(option?.one_shot || card?.one_shot);const materials = useMemo(() => option?.unlock_material ?? [], [option]);const memberNames = useMemo(() => {if (isSign) return card?.secret_name ? [card.secret_name] : [];@@ -140,15 +158,41 @@ export const VaultApprovalCard: React.FC<{for (const tag of tags) chips.push({ key: `tag:${tag}`, label: t('vaults.approval.sourceTag', { name: tag }), icon: Tag });return chips;}, [source, t]);- // TTL is a fixed product default (env-list 300s, tag/skill 900s), not a user control.- const ttlSeconds = option?.default_ttl_seconds ?? card?.default_ttl_seconds ?? (source.tags?.length ? 900 : 300);-const [thisSessionOnly, setThisSessionOnly] = useState(() => option?.session_binding_default !== false);+ // Approver-chosen agent access duration (protocol v2 §7.1): the daemon remembers the last choice,+ // so seed from `GET /api/vault/settings` and default to 5 min until it loads. Access requests only.+ const [grantDuration, setGrantDuration] = useState<GrantDurationChoice>('300');+ // Once the approver has picked a duration, the async settings seed must not clobber it if the GET+ // happens to resolve after the click.+ const grantTouchedRef = useRef(false);+ const pickGrantDuration = useCallback((next: GrantDurationChoice) => {+ grantTouchedRef.current = true;+ setGrantDuration(next);+ }, []);+ // A one-shot grant is always one-time regardless of the picker; everything downstream (submit,+ // persistence, the rendered control) reads this rather than the raw picker state.+ const effectiveGrantDuration: GrantDurationChoice = isOneShot ? 'one-time' : grantDuration;const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);const [signAddresses, setSignAddresses] = useState<SigningAddresses | null>(null);const [copiedDigest, setCopiedDigest] = useState(false);+ useEffect(() => {+ // Skip the remembered-choice seed for sign requests and one-shot grants (one-shot is forced to+ // one-time, so seeding a remembered 5/15 min would be misleading and pointless).+ if (isSign || isOneShot) return;+ let alive = true;+ api+ .getVaultSettings()+ .then((res) => {+ if (alive && !grantTouchedRef.current && res?.ok) setGrantDuration(grantChoiceFromLastTtl(res.settings?.last_grant_ttl));+ })+ .catch(() => undefined);+ return () => {+ alive = false;+ };+ }, [api, isSign, isOneShot]);+// Sign approvals: fetch the key's derived addresses (best-effort) so the human sees which// on-chain identity is about to sign — not just an opaque digest. Addresses are public.const signName = isSign ? card?.secret_name : undefined;@@ -193,6 +237,15 @@ export const VaultApprovalCard: React.FC<{[],);+ // Protected access with a session is bound to it: the daemon-signed contexts the sandbox consents+ // to carry that session's label, and the batch endpoint mints them from the request scope (no+ // session-scope choice), so granting any-session would exceed the session-labeled card the user+ // approved. But a session-less request (e.g. a CLI ask with no session) has nothing to bind to —+ // the daemon records session_id=None (unscoped) regardless — so don't force or claim binding+ // there. The "This session only" toggle is offered for standard access only.+ const hasRequestSession = Boolean(requestSession);+ const sessionBound = needsProtectedApproval && hasRequestSession ? true : thisSessionOnly;+const failIfNotOk = (res: { ok: boolean; code?: string; message?: string }) => {if (!res.ok) throw new Error(res.message || res.code || t('vaults.approval.errors.failed'));};@@ -206,51 +259,48 @@ export const VaultApprovalCard: React.FC<{// without UI-audience hydration — fail clearly instead of taking the standard path// (which the daemon rejects for a protected secret anyway).if (isProtected && materials.length === 0) throw new Error(t('vaults.approval.errors.missingMaterial'));+ const durationValue = grantDurationApiValue(effectiveGrantDuration);if (materials.length === 0) {// No protected members (a hidden always-ask standard case) — metadata-only grant, no DEK.failIfNotOk(await api.createVaultGrant({request_id: request.id,grant_id: grantId,- ttl_seconds: ttlSeconds,- this_session_only: thisSessionOnly,+ grant_duration: durationValue,+ this_session_only: sessionBound,}),);} else {- // Protected members — ask the daemon for signed, value-free agent bindings, then let the- // sandbox release each DEK as an opaque HPKE blind box for that pinned resident agent.- let agentPubkey: { public_key: string; fingerprint: string } | null = null;- const deks: Array<{ name: string; dek_blindbox: BlindBox; approval: { nonce: string; expires_at_unix: number } }> = [];- for (const material of materials) {- const binding = await api.createVaultAgentBinding({- request_id: request.id,- grant_id: grantId,- name: material.name,- ttl_seconds: ttlSeconds,- });- failIfNotOk(binding);- if (agentPubkey && binding.agent_pubkey.fingerprint !== agentPubkey.fingerprint) {- throw new Error(t('vaults.approval.errors.failed'));- }- agentPubkey = binding.agent_pubkey;- const dekBlindbox = await vault.releaseProtectedDelivery(material, binding.binding);- deks.push({- name: material.name,- dek_blindbox: dekBlindbox,- approval: binding.approval,- });- }- if (!agentPubkey) throw new Error(t('vaults.approval.errors.failed'));+ // Protected members — ONE batch call returns signed, value-free agent-delivery contexts+ // for the whole selector; the sandbox then releases every DEK behind ONE confirm (protocol+ // v2 §7.1) as opaque HPKE blind boxes for the pinned resident agent.+ const issued = await api.createVaultAgentBindingsBatch({ request_id: request.id, grant_duration: durationValue });+ failIfNotOk(issued);+ const materialByName = new Map(materials.map((m) => [m.name, m]));+ const approveItems = issued.items.map((item) => {+ const material = materialByName.get(item.name);+ if (!material) throw new Error(t('vaults.approval.errors.missingMaterial'));+ return { material, context: item.context };+ });+ // One confirm card lists every member; the blind boxes come back in item order.+ const blindBoxes = await vault.approveProtectedRelease(approveItems);+ if (blindBoxes.length !== issued.items.length) throw new Error(t('vaults.approval.errors.failed'));+ const deks: Array<{ name: string; dek_blindbox: BlindBox; approval: { nonce: string; expires_at_unix: number } }> =+ issued.items.map((item, index) => ({ name: item.name, dek_blindbox: blindBoxes[index], approval: item.approval }));failIfNotOk(await api.fulfillVaultAccessRequest(request.id, {grant_id: grantId,- ttl_seconds: ttlSeconds,- this_session_only: thisSessionOnly,- agent_pubkey: agentPubkey,+ grant_duration: durationValue,+ this_session_only: sessionBound,+ agent_pubkey: issued.agent_pubkey,deks,}),);}+ // Remember the approver's choice as next time's default — but not for one-shot, where the+ // duration was forced to one-time (not chosen), so persisting it would wrongly bias the next+ // approval. Best-effort: the daemon also persists a real choice on the grant/binding.+ if (!isOneShot) void api.saveVaultSettings({ last_grant_ttl: durationValue }).catch(() => undefined);onResolved({ kind: 'approved', requestType: 'access' });});@@ -266,7 +316,12 @@ export const VaultApprovalCard: React.FC<{if (!material) throw new Error(t('vaults.approval.errors.missingMaterial'));const signingContext = delivery.signing_context ?? delivery.signingContext;if (!signingContext || typeof signingContext !== 'object') throw new Error(t('vaults.approval.errors.missingDigest'));- const sig = await vault.signProtectedRequest(material, signingContext, scheme as SignatureScheme);+ // The daemon-signed sign context (protocol v2 §6.2) is attached to the request; the sandbox+ // renders + verifies it alongside the decoded signing payload.+ const operationContext =+ delivery.operation_context ?? (card as { operation_context?: VaultSignedOperationContext } | null)?.operation_context;+ if (!operationContext) throw new Error(t('vaults.approval.errors.missingMaterial'));+ const sig = await vault.signProtectedRequest(material, signingContext, scheme as SignatureScheme, operationContext);const signature: Record<string, unknown> = { signature: sig.signature };if (sig.recovery_id != null) signature.recovery_id = sig.recovery_id;failIfNotOk(await api.signVaultDigest({ name, request_id: request.id, digest, scheme, signature }));@@ -412,9 +467,9 @@ export const VaultApprovalCard: React.FC<{<div className="h-px bg-border" />- {/* Access grant summary (access only): how the set was selected, the fixed protected- secret names to be granted, and the fixed access duration. There is no scope- picker — the grant is a fixed protected set determined by the request's selector. */}+ {/* Access grant summary (access only): how the set was selected and the fixed protected+ secret names to be granted. There is no scope picker — the grant is a fixed protected+ set determined by the request's selector. */}{!isSign ? (<div className="flex flex-col gap-3.5">{sourceChips.length > 0 ? (@@ -439,12 +494,6 @@ export const VaultApprovalCard: React.FC<{))}</DetailRow>) : null}- <DetailRow label={t('vaults.approval.duration')}>- <span className="flex items-center gap-1.5 text-[13px] text-foreground">- <Clock className="size-3.5 shrink-0 text-muted" />- {t('vaults.approval.durationValue', { time: ttlLabel(ttlSeconds) })}- </span>- </DetailRow></div>) : null}@@ -457,6 +506,33 @@ export const VaultApprovalCard: React.FC<{</span>) : null}+ {/* Agent access duration (access only) — the approver picks how long the agent may use the+ set (protocol v2 §7.1). "授权时长 / Agent access duration" language (§8): this is what the+ agent receives, distinct from the browser unlock window; never a countdown pill. */}+ {!isSign ? (+ <div className="flex flex-col gap-1.5">+ <span className="text-[13px] font-medium text-foreground">{t('vaults.approval.grantDuration')}</span>+ <SegmentedRadio<GrantDurationChoice>+ value={effectiveGrantDuration}+ onChange={pickGrantDuration}+ disabled={busy || isOneShot}+ ariaLabel={t('vaults.approval.grantDuration')}+ options={[+ { id: 'one-time', label: t('vaults.approval.grantOneTime') },+ { id: '300', label: t('vaults.approval.grantMinutes', { count: 5 }) },+ { id: '900', label: t('vaults.approval.grantMinutes', { count: 15 }) },+ ]}+ />+ <span className="text-[11px] text-muted-foreground">+ {isOneShot+ ? t('vaults.approval.grantOneShotHelp')+ : effectiveGrantDuration === 'one-time'+ ? t('vaults.approval.grantOneTimeHelp')+ : t('vaults.approval.grantDurationHelp')}+ </span>+ </div>+ ) : null}+{error ? (<div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">{error}@@ -465,7 +541,7 @@ export const VaultApprovalCard: React.FC<{{/* Footer */}<div className="flex items-center gap-3">- {!isSign ? (+ {!isSign && !needsProtectedApproval ? (<label className="flex items-center gap-2 text-xs font-medium text-muted"><Switchchecked={thisSessionOnly}@@ -476,6 +552,15 @@ export const VaultApprovalCard: React.FC<{{t('vaults.approval.thisSessionOnly')}</label>) : null}+ {!isSign && needsProtectedApproval && hasRequestSession ? (+ // Protected access with a session is session-bound (see `sessionBound`); show it read-only+ // so the scope the approver grants matches the session on the sandbox consent card. Hidden+ // for session-less requests, where the grant is unscoped and claiming binding would lie.+ <span className="flex items-center gap-1.5 text-xs font-medium text-muted">+ <Link2 className="size-3.5 shrink-0" />+ {t('vaults.approval.sessionBound')}+ </span>+ ) : null}<div className="ml-auto flex items-center gap-2"><Button type="button" variant="outline" onClick={deny} disabled={busy}>{t('vaults.approval.deny')}diff --git a/ui/src/components/ui/vault-lock-indicator.tsx b/ui/src/components/ui/vault-lock-indicator.tsxindex c4dbaef54..bab34d950 100644--- a/ui/src/components/ui/vault-lock-indicator.tsx+++ b/ui/src/components/ui/vault-lock-indicator.tsx@@ -14,8 +14,11 @@ function formatRemaining(ms: number): string {}/**- * 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.+ * The **unlock window** pill (解锁窗口 / Unlock window, protocol v2 §8): shown while the vault is+ * unlocked, it renders the time left in this browser session — a pure countdown off the sandbox's+ * `expiresAt`, never a parent-owned clock. Its tooltip explains what the window buys: approvals+ * skip the passkey, signing always asks. Distinct from an agent's grant duration, which is only+ * ever shown inside approval/consent cards. Renders nothing while the vault is locked.*/export function VaultLockIndicator({ className }: { className?: string }) {const { t } = useTranslation();@@ -24,7 +27,7 @@ export function VaultLockIndicator({ className }: { className?: string }) {return (<divclassName={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')}+ title={t('vaults.lock.windowTooltip')}><Unlock className="size-3.5 shrink-0 text-mint" /><span className="text-xs font-medium text-foreground">diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsxindex ec94ef9d3..d63a68a7a 100644--- a/ui/src/components/ui/vault-secret-form.tsx+++ b/ui/src/components/ui/vault-secret-form.tsx@@ -17,7 +17,16 @@ import {} from 'lucide-react';import { useTranslation } from 'react-i18next';-import { ApiError, useApi, type DependencyItem, type SigningAddresses, type VaultRequestSpec, type VaultSecret } from '@/context/ApiContext';+import {+ ApiError,+ useApi,+ type DependencyItem,+ type SigningAddresses,+ type VaultRequestSpec,+ type VaultSecret,+ type VaultWebAuthnRegistrationPayload,+} from '@/context/ApiContext';+import type { VaultSandboxSealResult } from '@/lib/vaultSandboxClient';import { cn } from '@/lib/utils';import { mergeTags, normalizeTagOrSkillEntry, partitionTags, toSkillTag } from '@/lib/vaultTags';import { buildMetadataPatch } from '@/lib/vaultPolicy';@@ -106,6 +115,9 @@ function avaultP2Ready(dep: DependencyItem | null): boolean {/** Shared field label — 13px medium, matches design.pen create-dialog field labels. */const FIELD_LABEL = 'text-[13px] font-medium text-foreground';+/** The sandbox-sealed protected keypair the form holds between "Generate key" and submit. */+type ProtectedKeypairSeal = VaultSandboxSealResult & { authzFactorRegistration?: VaultWebAuthnRegistrationPayload };+export const VaultSecretForm: React.FC<{fixedName?: string;onCancel: () => void;@@ -151,6 +163,13 @@ export const VaultSecretForm: React.FC<{const [signingError, setSigningError] = useState<string | null>(null);const [signingAddresses, setSigningAddresses] = useState<SigningAddresses | null>(null);const [addressesLoading, setAddressesLoading] = useState(false);+ // Protected keypair: the key is generated inside the sandbox up front (protocol v2 §7.2), so the+ // parent only ever holds the returned ciphertext + public material — never a private key. Kept+ // until submit; cleared on regenerate/cancel and whenever the name changes (the envelope AAD+ // binds the name, so a stale envelope must not be submitted under a different name).+ const [protectedKeypair, setProtectedKeypair] = useState<ProtectedKeypairSeal | null>(null);+ const [generatingKeypair, setGeneratingKeypair] = useState(false);+ const [keypairError, setKeypairError] = useState<string | null>(null);// 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]);@@ -233,6 +252,10 @@ export const VaultSecretForm: React.FC<{}, [api]);const protectedVault = useProtectedVault();+ // The vault status the current protected keypair was generated under. A transition away from+ // 'unlocked' (manual/auto lock, or an abandoned fresh setup that discards the VMK) means the+ // held envelope is sealed to a VMK that's no longer active — see the render-phase reset below.+ const [keypairSessionStatus, setKeypairSessionStatus] = useState(protectedVault.status);useEffect(() => {if (protection === 'protected') void protectedVault.refresh();// protectedVault.refresh is stable (useCallback); only re-check when the tier changes.@@ -337,11 +360,20 @@ export const VaultSecretForm: React.FC<{}, [signingKey, api]);const staticValueReady = staticSource === 'file' ? selectedFile != null && selectedFile.size > 0 : Boolean(value);- const valueReady = isKeypair ? protection === 'protected' || signingKey != null : staticValueReady;+ const valueReady = isKeypair+ ? // Protected keypair must be generated in-sandbox first (below); standard keypair needs the+ // locally-built signing key. Static readiness is the entered/selected value.+ protection === 'protected'+ ? protectedKeypair != null+ : signingKey != null+ : staticValueReady;const canSubmit = isEdit? !submitting: Boolean(secretName && valueReady) &&!submitting &&+ // Block submit while a protected keypair is (re)generating in the sandbox, so the user can't+ // submit the previous envelope mid-ceremony and persist a key they're actively replacing.+ !generatingKeypair &&((protection === 'standard' && p2Ready) || (protection === 'protected' && protectedCreateReady));const clearSelectedFile = useCallback(() => {@@ -409,6 +441,60 @@ export const VaultSecretForm: React.FC<{setSigningAddresses(null);}, [protection, kind, clearStaticValue, clearSelectedFile, applySigningKey]);+ // Monotonic token guarding the async generate: bumped on every clear/regenerate so a slow+ // in-flight seal that resolves after the form moved on (rename, kind/tier switch, or a newer+ // generate) is discarded instead of applied. Without it, an envelope sealed for the old name —+ // whose AAD binds that name — could be submitted under a different name and be unopenable.+ const keypairGenRef = useRef(0);++ // Drop a pre-generated protected keypair and invalidate any in-flight generate. Only ciphertext ++ // public data is held, so there is no private-key material to zero — but a stale envelope (bound+ // to an old name/kind) must never be submitted, so callers clear it whenever the name, kind, or+ // tier changes.+ const clearProtectedKeypair = useCallback(() => {+ keypairGenRef.current += 1;+ setProtectedKeypair(null);+ setKeypairError(null);+ setGeneratingKeypair(false);+ }, []);++ // Generate the protected signing key inside the sandbox (protocol v2 §7.2): the secp256k1 key is+ // born in the sandbox, sealed under the VMK, and only its ciphertext + public addresses come back+ // here. R1 semantics — silent while unlocked (the form's gate covers the locked case). Regenerate+ // just calls again and discards the previous envelope.+ const generateProtectedKeypair = async () => {+ if (!secretName || generatingKeypair) return;+ const gen = (keypairGenRef.current += 1);+ setGeneratingKeypair(true);+ setKeypairError(null);+ try {+ const sealed = await protectedVault.sealValue(secretName, 'keypair');+ // The form moved on (rename / kind or tier switch / newer generate) — discard this result so a+ // name-bound envelope can't be submitted under a name it wasn't sealed for.+ if (gen !== keypairGenRef.current) return;+ if (!sealed.publicKey) throw new Error(t('vaults.dialog.errors.invalidPublicKey'));+ setProtectedKeypair(sealed);+ } catch (err) {+ if (gen !== keypairGenRef.current) return;+ setProtectedKeypair(null);+ setKeypairError(err instanceof Error ? err.message : String(err));+ } finally {+ if (gen === keypairGenRef.current) setGeneratingKeypair(false);+ }+ };++ // React-sanctioned "adjust state during render": when the vault leaves the unlocked session the+ // keypair was sealed under, discard the envelope. Critically this covers the first-ever protected+ // secret — if the user generates a keypair, then locks/auto-locks before submit, the unpersisted+ // fresh-setup VMK is dropped; re-setting-up mints a NEW VMK, and submitting the old envelope would+ // bind the first persisted key to the abandoned VMK (unopenable). Runs once per transition (the+ // `setKeypairSessionStatus` update makes the guard false on the next render), and `clearProtected-+ // Keypair` bumps the generation token so any in-flight generate is invalidated too.+ if (keypairSessionStatus !== protectedVault.status) {+ setKeypairSessionStatus(protectedVault.status);+ if (protectedVault.status !== 'unlocked') clearProtectedKeypair();+ }+const onSubmit = async (event: FormEvent) => {event.preventDefault();if (!canSubmit) return;@@ -515,31 +601,30 @@ export const VaultSecretForm: React.FC<{let authzFactorRegistration: Awaited<ReturnType<typeof protectedVault.sealValue>>['authzFactorRegistration'];let protectedPublicMeta: Record<string, unknown> | undefined;if (protection === 'protected') {- if (!isKeypair) {- // Protected static values are typed text only — the source toggle is hidden for- // protected and reset to text (see the value field + the protection effect). No- // file/binary path here on purpose: TextDecoder would corrupt non-UTF-8 bytes, so a- // file secret can't round-trip through the string-based parent-value contract.- staticValueRef.current = value;- }- // Static protected values are entered in this form and handed to the sandbox once;- // keypairs still generate/import inside the sandbox and return only public metadata.- const sealed = await protectedVault.sealValue(- secretName,- kind,- isKeypair ? undefined : { valueRef: staticValueRef, clear: clearStaticValue },- );- cryptoFields = { sealed: sealed.envelope };- establishingVmk = sealed.establishingVmk;- authzFactorRegistration = sealed.authzFactorRegistration;- if (isKeypair && !sealed.publicKey) {- throw new Error(t('vaults.dialog.errors.invalidPublicKey'));- }if (isKeypair) {+ // Keypair was already sealed in-sandbox by "Generate key" (protocol v2 §7.2). Submit the+ // held envelope + public metadata; no second seal, and the private key never existed here.+ if (!protectedKeypair?.publicKey) throw new Error(t('vaults.dialog.errors.invalidPublicKey'));+ cryptoFields = { sealed: protectedKeypair.envelope };+ establishingVmk = protectedKeypair.establishingVmk;+ authzFactorRegistration = protectedKeypair.authzFactorRegistration;protectedPublicMeta = {- signing_public_key: { curve: 'secp256k1', public_key: sealed.publicKey },- ...(sealed.addresses ? { signing_addresses: sealed.addresses } : {}),+ signing_public_key: { curve: 'secp256k1', public_key: protectedKeypair.publicKey },+ ...(protectedKeypair.addresses ? { signing_addresses: protectedKeypair.addresses } : {}),};+ } else {+ // Protected static values are typed text only — the source toggle is hidden for protected+ // and reset to text (see the value field + the protection effect). No file/binary path+ // here: TextDecoder would corrupt non-UTF-8 bytes, so a file can't round-trip through the+ // string-based parent-value contract. Handed to the sandbox once, at submit.+ staticValueRef.current = value;+ const sealed = await protectedVault.sealValue(secretName, 'static', {+ valueRef: staticValueRef,+ clear: clearStaticValue,+ });+ cryptoFields = { sealed: sealed.envelope };+ establishingVmk = sealed.establishingVmk;+ authzFactorRegistration = sealed.authzFactorRegistration;}} else {// For a standard signing key the sealed value is the raw 32-byte private key@@ -598,6 +683,7 @@ export const VaultSecretForm: React.FC<{setStaticSource('text');clearSelectedFile();applySigningKey(null);+ clearProtectedKeypair();setImportHex('');setFetchAuthMode('bearer');setFetchAuthName('');@@ -796,7 +882,12 @@ export const VaultSecretForm: React.FC<{key={key}type="button"aria-pressed={selected}- onClick={() => setProtection(key)}+ onClick={() => {+ setProtection(key);+ // Switching tier invalidates a sandbox-sealed protected keypair (sealed under the+ // protected tier); drop it so a stale envelope can't be submitted as standard.+ clearProtectedKeypair();+ }}className={cn('flex flex-col gap-1.5 rounded-[10px] border p-3 text-left transition-colors',selected ? 'border-[1.5px] border-mint bg-mint-soft' : 'border-border bg-surface hover:bg-surface-2',@@ -1027,6 +1118,8 @@ export const VaultSecretForm: React.FC<{} else {clearStaticValue();}+ // A sandbox-sealed protected keypair is bound to its kind; switching kind invalidates it.+ clearProtectedKeypair();}}disabled={submitting}ariaLabel={t('vaults.dialog.kindLabel')}@@ -1040,7 +1133,18 @@ export const VaultSecretForm: React.FC<{{/* Name */}<label className="flex flex-col gap-1.5"><span className={FIELD_LABEL}>{t('vaults.dialog.name')}</span>- <Input value={name} onChange={(event) => setName(event.target.value)} autoFocus required className="font-mono" />+ <Input+ value={name}+ onChange={(event) => {+ setName(event.target.value);+ // The protected-keypair envelope AAD binds the name it was sealed under, so a rename+ // invalidates a pre-generated key — drop it and let the user regenerate.+ clearProtectedKeypair();+ }}+ autoFocus+ required+ className="font-mono"+ /><span className="text-[11px] text-muted-foreground">{t('vaults.dialog.nameHint')}</span></label>@@ -1149,6 +1253,37 @@ export const VaultSecretForm: React.FC<{</div>)}+ {/* Protected signing key — same shape as the standard tier (a Generate button + address+ preview), but the key is born inside the sandbox and only ciphertext + public data comes+ back (protocol v2 §7.2). Shown once the vault is unlocked; the gating panel below handles+ the locked case. No import option — generate is the single path. */}+ {isKeypair && protection === 'protected' && protectedCreateReady && (+ <div className="flex flex-col gap-2.5 rounded-[10px] border border-border bg-surface-2 px-3 py-3">+ <span className="text-xs text-muted-foreground">{t('vaults.dialog.signingKeyProtectedHelp')}</span>+ <Button+ type="button"+ variant="secondary"+ disabled={submitting || generatingKeypair || !secretName}+ onClick={() => void generateProtectedKeypair()}+ >+ {generatingKeypair ? <Loader2 className="size-4 animate-spin" /> : <RefreshCw className="size-4" />}+ {protectedKeypair ? t('vaults.dialog.signingRegenerate') : t('vaults.dialog.signingGenerateCta')}+ </Button>+ {protectedKeypair && (+ <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>+ {protectedKeypair.addresses ? (+ <SigningAddressList addresses={protectedKeypair.addresses} />+ ) : (+ <span className="text-xs text-muted-foreground">{t('vaults.dialog.signingAddressesUnavailable')}</span>+ )}+ <span className="text-xs text-muted-foreground">{t('vaults.dialog.signingKeyProtectedBornHint')}</span>+ </div>+ )}+ {keypairError && <span className="text-xs text-destructive">{keypairError}</span>}+ </div>+ )}+{/* Description + Tags — core metadata, kept directly below the value (not buried underAdvanced) so they're easy to set while creating a secret. */}<label className="flex flex-col gap-1.5">diff --git a/ui/src/components/ui/vault-settings-dialog.tsx b/ui/src/components/ui/vault-settings-dialog.tsxnew file mode 100644index 000000000..42259781f--- /dev/null+++ b/ui/src/components/ui/vault-settings-dialog.tsx@@ -0,0 +1,202 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { Loader2, ShieldCheck } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useApi, type VaultSettings } from '@/context/ApiContext';+import { isValidVaultSessionPolicyShape, setVaultSandboxPolicy } from '@/lib/vaultSandboxPolicy';+import { useProtectedVault } from '@/lib/useProtectedVault';+import { Dialog, DialogContent, DialogTitle } from './dialog';+import { SegmentedRadio } from './segmented';+import { Switch } from './switch';++type UnlockWindowChoice = '300' | '600' | '1800';++function unlockWindowChoice(seconds: number | undefined): UnlockWindowChoice {+ if (seconds === 300) return '300';+ if (seconds === 1800) return '1800';+ return '600';+}++// A response's `policy` must be a complete, well-formed policy before we confirm it into the+// sandbox mirror. An `ok:true` payload that omits/malforms `policy` (skewed deploy, partial+// failure) must be treated as a load/save failure — never confirmed — so it can't bypass the+// fail-closed handshake path (a policy object with missing fields would normalize to relaxed).+function hasValidPolicy(res: { policy?: unknown } | null | undefined): boolean {+ return isValidVaultSessionPolicyShape(res?.policy);+}++/**+ * Vault session settings (protocol v2 §8): the unlock-window length and the Strict-approvals+ * toggle, persisted daemon-side via `GET/PATCH /api/vault/settings`. Saving also refreshes the+ * parent's policy mirror so the next sandbox handshake/unlock runs under the new values (the+ * sandbox is the enforcer; this mirror is display + unlock-hint only).+ */+export const VaultSettingsDialog: React.FC<{ open: boolean; onOpenChange: (open: boolean) => void }> = ({+ open,+ onOpenChange,+}) => {+ const { t } = useTranslation();+ const api = useApi();+ const vault = useProtectedVault();+ const [loading, setLoading] = useState(false);+ const [saving, setSaving] = useState(false);+ const [error, setError] = useState<string | null>(null);+ const [unlockWindow, setUnlockWindow] = useState<UnlockWindowChoice>('600');+ const [strict, setStrict] = useState(false);+ // Serialize autosaves: only one PATCH in flight at a time. The controls are `disabled` while+ // saving, but this synchronous ref also blocks the sub-frame race (two changes fired before the+ // disable renders), so responses never interleave — a stale failure can't leave an optimistic+ // value displayed, and a slow response can't overwrite a newer one.+ const saveInFlightRef = useRef(false);++ useEffect(() => {+ if (!open) return;+ let alive = true;+ setLoading(true);+ setError(null);+ api+ .getVaultSettings()+ .then((res) => {+ if (!alive) return;+ if (res?.ok && hasValidPolicy(res)) {+ // Derive the controls from the validated `policy`, not the unvalidated `settings` — a+ // skewed deploy could return a valid policy with a missing/malformed `settings` block,+ // and reading `settings` would default the controls to relaxed values.+ setUnlockWindow(unlockWindowChoice(res.policy.windowSeconds));+ setStrict(res.policy.strictApprovals);+ setVaultSandboxPolicy(res.policy);+ } else {+ setError(res?.message || t('vaults.settings.loadFailed'));+ }+ })+ .catch((err: unknown) => {+ if (alive) setError(err instanceof Error ? err.message : String(err));+ })+ .finally(() => {+ if (alive) setLoading(false);+ });+ return () => {+ alive = false;+ };+ }, [open, api, t]);++ // Auto-save on change — a settings dialog with two controls reads best as immediate toggles. The+ // control is updated optimistically for instant feedback, so `revert` restores the prior value if+ // the daemon rejects the change (otherwise the control would show a value that wasn't saved). The+ // daemon returns the normalized settings + policy, so mirror both back on success.+ const save = useCallback(+ async (patch: Partial<VaultSettings>, revert: () => void): Promise<boolean> => {+ saveInFlightRef.current = true;+ setSaving(true);+ setError(null);+ try {+ const res = await api.saveVaultSettings(patch);+ if (!res?.ok || !hasValidPolicy(res)) {+ setError(res?.message || t('vaults.settings.saveFailed'));+ revert();+ return false;+ }+ setUnlockWindow(unlockWindowChoice(res.settings?.unlock_window_seconds));+ setStrict(Boolean(res.settings?.strict_approvals));+ setVaultSandboxPolicy(res.policy);+ return true;+ } catch (err: unknown) {+ setError(err instanceof Error ? err.message : String(err));+ revert();+ return false;+ } finally {+ setSaving(false);+ saveInFlightRef.current = false;+ }+ },+ [api, t],+ );++ const onUnlockWindowChange = (next: UnlockWindowChoice) => {+ // Ignore a change that races an in-flight save (controls are also `disabled` while saving); the+ // controlled value stays put, so nothing optimistic is left unsaved.+ if (saveInFlightRef.current) return;+ const prev = unlockWindow;+ setUnlockWindow(next);+ void save({ unlock_window_seconds: Number(next) }, () => setUnlockWindow(prev)).then((ok) => {+ // Shortening the window is a tightening (the vault locks sooner) — force the same cross-tab+ // re-handshake as enabling Strict so it applies on every unlock path immediately, not just on+ // the next explicit unlock. Lengthening is a relaxation and safely waits for the next unlock.+ if (ok && Number(next) < Number(prev)) vault.lockAndResetForPolicyChange();+ });+ };++ const onStrictChange = (next: boolean) => {+ if (saveInFlightRef.current) return;+ const prev = strict;+ setStrict(next);+ void save({ strict_approvals: next }, () => setStrict(prev)).then((ok) => {+ if (!(ok && next && !prev)) return;+ // Enabling Strict must bite immediately, in every tab — not only on the next explicit unlock.+ // The sandbox pins its enforced policy at handshake and its internal auto-unlock reuses that+ // pin, so `lockAndResetForPolicyChange` broadcasts a reset that makes every tab drop its+ // sandbox client and re-handshake under the new Strict policy (a plain lock would leave+ // siblings re-unlocking stale). Disabling is a relaxation and safely waits for the next unlock.+ vault.lockAndResetForPolicyChange();+ });+ };++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent>+ <DialogTitle className="sr-only">{t('vaults.settings.title')}</DialogTitle>+ <div className="flex items-start gap-3 pr-6">+ <span className="flex size-10 shrink-0 items-center justify-center rounded-xl bg-mint-soft text-mint">+ <ShieldCheck className="size-5" />+ </span>+ <div className="flex flex-col gap-0.5">+ <span className="text-[15px] font-semibold text-foreground">{t('vaults.settings.title')}</span>+ <span className="text-xs text-muted-foreground">{t('vaults.settings.subtitle')}</span>+ </div>+ </div>++ {loading ? (+ <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.settings.loading')}+ </div>+ ) : (+ <div className="flex flex-col gap-5">+ {/* Unlock window — "解锁窗口 / Unlock window" language (§8): the browser session, not the+ agent grant. Changes apply on the next unlock. */}+ <div className="flex flex-col gap-1.5">+ <span className="text-[13px] font-medium text-foreground">{t('vaults.settings.unlockWindow')}</span>+ <SegmentedRadio<UnlockWindowChoice>+ value={unlockWindow}+ onChange={onUnlockWindowChange}+ disabled={saving}+ ariaLabel={t('vaults.settings.unlockWindow')}+ options={[+ { id: '300', label: t('vaults.settings.minutes', { count: 5 }) },+ { id: '600', label: t('vaults.settings.minutes', { count: 10 }) },+ { id: '1800', label: t('vaults.settings.minutes', { count: 30 }) },+ ]}+ />+ <span className="text-[11px] text-muted-foreground">{t('vaults.settings.unlockWindowHelp')}</span>+ </div>++ {/* Strict approvals — R2 behaves like R3 (a passkey every approve/reveal). */}+ <div className="flex items-start gap-3 rounded-[10px] border border-border bg-surface-2 px-3 py-3">+ <div className="flex min-w-0 flex-1 flex-col gap-1">+ <span className="text-[13px] font-semibold text-foreground">{t('vaults.settings.strict')}</span>+ <span className="text-[11.5px] leading-snug text-muted-foreground">{t('vaults.settings.strictHelp')}</span>+ </div>+ <Switch checked={strict} onCheckedChange={onStrictChange} disabled={saving} label={t('vaults.settings.strict')} />+ </div>+ </div>+ )}++ {error ? (+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">+ {error}+ </div>+ ) : null}+ </DialogContent>+ </Dialog>+ );+};diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsxindex 52728d656..3d1064330 100644--- a/ui/src/components/workbench/VaultsPage.tsx+++ b/ui/src/components/workbench/VaultsPage.tsx@@ -1,6 +1,6 @@import { useCallback, useEffect, useMemo, useState } from 'react';import { useSearchParams } from 'react-router-dom';-import { AlertTriangle, Clock, Globe, History, Inbox, KeyRound, Link2, Loader2, MoreHorizontal, Pencil, Plus, Puzzle, RefreshCw, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';+import { AlertTriangle, Clock, Copy, Eye, Globe, History, Inbox, KeyRound, Link2, Loader2, MoreHorizontal, Pencil, Plus, Puzzle, RefreshCw, Settings, ShieldCheck, Tag, Trash2, Wallet, X } from 'lucide-react';import type { TFunction } from 'i18next';import { useTranslation } from 'react-i18next';import { CapabilityTabs } from './CapabilityTabs';@@ -19,6 +19,8 @@ import { SigningAddressList } from '../ui/signing-address-list';import { VaultApprovalDialog } from '../ui/vault-approval-dialog';import { VaultRequestSessionLink, vaultRequestSessionDisplay } from '../ui/vault-request-session-link';import { VaultSecretDialog } from '../ui/vault-secret-dialog';+import { VaultSettingsDialog } from '../ui/vault-settings-dialog';+import { useProtectedVault } from '../../lib/useProtectedVault';const PENDING_REQUEST_POLL_INTERVAL_MS = 5000;const PENDING_REQUEST_EXPIRY_GRACE_MS = 100;@@ -31,11 +33,19 @@ const proxyHosts = (s: VaultSecret): string[] => {return Array.isArray(hosts) ? hosts : [];};-const SecretRow: React.FC<{ secret: VaultSecret; onEdit: (secret: VaultSecret) => void; onDelete: (secret: VaultSecret) => void }> = ({ secret: s, onEdit, onDelete }) => {+const SecretRow: React.FC<{+ secret: VaultSecret;+ onEdit: (secret: VaultSecret) => void;+ onDelete: (secret: VaultSecret) => void;+ onReveal: (secret: VaultSecret) => void;+}> = ({ secret: s, onEdit, onDelete, onReveal }) => {const { t } = useTranslation();const [menuOpen, setMenuOpen] = useState(false);const isKeypair = s.kind === 'keypair';const isProtected = s.protection === 'protected';+ // Reveal is only meaningful for a protected static secret: its plaintext lives sealed and can be+ // shown in-sandbox. Standard values aren't sandbox-sealed, and a keypair has no plaintext value.+ const canReveal = isProtected && !isKeypair;// Skills are stored as reserved `skill:<name>` tags; render them as their own chips.const { tags, skills } = useMemo(() => partitionTags(s.tags), [s.tags]);return (@@ -93,6 +103,38 @@ const SecretRow: React.FC<{ secret: VaultSecret; onEdit: (secret: VaultSecret) =</Button></PopoverTrigger><PopoverContent align="end" className="w-44 p-1" role="menu">+ {canReveal ? (+ <>+ {/* Reveal opens the value inside the sandbox frame; the plaintext is never returned+ to Avibe. "Copy value" leads to the same sandbox card, where copying is the+ sandbox's own explicit action (protocol v2 §7.4). */}+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setMenuOpen(false);+ onReveal(s);+ }}+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm text-foreground transition-colors hover:bg-surface-2"+ >+ <Eye className="size-4 text-muted" />+ {t('vaults.reveal.show')}+ </button>+ <button+ type="button"+ role="menuitem"+ onClick={() => {+ setMenuOpen(false);+ onReveal(s);+ }}+ className="flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-sm text-foreground transition-colors hover:bg-surface-2"+ >+ <Copy className="size-4 text-muted" />+ {t('vaults.reveal.copy')}+ </button>+ <div className="my-1 h-px bg-border" />+ </>+ ) : null}<buttontype="button"role="menuitem"@@ -501,12 +543,14 @@ export const VaultsPage: React.FC = () => {const { t } = useTranslation();const api = useApi();const { showToast } = useToast();+ const vault = useProtectedVault();const [searchParams, setSearchParams] = useSearchParams();const [secrets, setSecrets] = useState<VaultSecret[]>([]);const [grants, setGrants] = useState<VaultGrant[]>([]);const [loading, setLoading] = useState(false);const [error, setError] = useState<string | null>(null);const [adding, setAdding] = useState(false);+ const [showSettings, setShowSettings] = useState(false);const [showAudit, setShowAudit] = useState(false);const [audit, setAudit] = useState<VaultAuditEvent[]>([]);const [activeTags, setActiveTags] = useState<string[]>([]);@@ -679,6 +723,30 @@ export const VaultsPage: React.FC = () => {const [editTarget, setEditTarget] = useState<VaultSecret | null>(null);const onDelete = (secret: VaultSecret) => setDeleteTarget(secret);const onEdit = (secret: VaultSecret) => setEditTarget(secret);++ // Reveal a protected static value inside the sandbox frame (protocol v2 §7.4): fetch a signed+ // reveal context + the sealed envelope, then let the sandbox open + display it. Plaintext never+ // returns to Avibe; the sandbox performs the in-frame confirm (and passkey when locked/Strict).+ const revealSecret = useCallback(+ async (secret: VaultSecret) => {+ try {+ const res = await api.createVaultRevealContext(secret.name, { session_label: t('vaults.title') });+ if (!res?.ok || !res.context) throw new Error(res?.message || t('vaults.reveal.errors.contextFailed'));+ // The sandbox needs the sealed record to open it. The daemon returns it alongside the signed+ // reveal context; if it's absent, surface a clear message rather than a cryptic sandbox error.+ if (!res.envelope) throw new Error(t('vaults.reveal.errors.unavailable'));+ const wrapMeta =+ typeof res.envelope.wrap_meta === 'string' ? res.envelope.wrap_meta : JSON.stringify(res.envelope.wrap_meta);+ await vault.revealProtectedValue(+ { name: secret.name, kind: 'static', envelope: { ciphertext: res.envelope.ciphertext, nonce: res.envelope.nonce, wrap_meta: wrapMeta } },+ res.context,+ );+ } catch (err: unknown) {+ showToast(messageFromError(err), 'warning');+ }+ },+ [api, vault, showToast, t],+ );const confirmDelete = async () => {const secret = deleteTarget;if (!secret) return;@@ -721,6 +789,14 @@ export const VaultsPage: React.FC = () => {<Button variant={showAudit ? 'secondary' : 'ghost'} size="icon" onClick={toggleAudit} aria-label={t('vaults.history')}><History className="size-4" /></Button>+ <Button+ variant={showSettings ? 'secondary' : 'ghost'}+ size="icon"+ onClick={() => setShowSettings(true)}+ aria-label={t('vaults.settings.title')}+ >+ <Settings className="size-4" />+ </Button><Button variant="ghost" size="icon" onClick={refresh} aria-label={t('vaults.refresh')}><RefreshCw className="size-4" /></Button>@@ -794,7 +870,7 @@ export const VaultsPage: React.FC = () => {) : (<div className="flex flex-col gap-2">{visibleSecrets.map((s) => (- <SecretRow key={s.name} secret={s} onEdit={onEdit} onDelete={onDelete} />+ <SecretRow key={s.name} secret={s} onEdit={onEdit} onDelete={onDelete} onReveal={revealSecret} />))}</div>)}@@ -816,6 +892,7 @@ export const VaultsPage: React.FC = () => {)}</div>)}+ <VaultSettingsDialog open={showSettings} onOpenChange={setShowSettings} /><VaultSecretDialogopen={adding}onOpenChange={(o) => {diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex a3a0cb8cd..614341189 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -2,6 +2,7 @@ import React, { createContext, useContext, useMemo, useRef } from 'react';import { useTranslation } from 'react-i18next';import { useToast } from './ToastContext';import { apiFetch } from '../lib/apiFetch';+import type { VaultSessionPolicy } from '../lib/vaultSandboxPolicy';// One backend's *global* instructions file, surfaced by the Global Prompts// editor. ``backend`` is an agent backend id (claude / opencode / codex).@@ -134,7 +135,8 @@ type VaultBlindBox = {export type VaultAccessFulfillmentPayload = {grant_id?: string;session_id?: string | null;- ttl_seconds?: number;+ /** Approver-chosen agent access duration (protocol v2 §7.1); supersedes the old fixed ttl. */+ grant_duration?: VaultGrantDuration;this_session_only?: boolean;agent_pubkey?: { public_key?: string; fingerprint?: string };deks?: Array<{ name: string; dek_blindbox: VaultBlindBox; approval: Record<string, unknown> }>;@@ -151,22 +153,79 @@ export type VaultSandboxRootMetadataResult = {message?: string;};-export type VaultAgentBindingResult = {+/** Approver-chosen agent access duration (protocol v2 §7.1). `'one-time'` = a single delivery. */+export type VaultGrantDuration = 'one-time' | number;++/**+ * The ed25519-signed operation context the daemon issues and the sandbox renders verbatim+ * (protocol v2 §6.2). Everything a human authorizes — the covered secrets, session, command,+ * egress, source, and agent access duration — travels inside the signed `display` block so a+ * compromised parent can't rewrite the consent story.+ */+export type VaultSignedOperationContext = {+ v: 2;+ purpose: 'agent-deliver' | 'sign' | 'reveal';+ requestId: string;+ grantId?: string;+ display: {+ secrets: Array<{ name: string; kind: 'static' | 'keypair' }>;+ sessionLabel?: string;+ command?: string;+ egress?: string;+ source?: { env?: string[]; tags?: string[]; skills?: string[] };+ grantTtlSeconds?: number;+ };+ agent?: { publicKey: { public_key: string; fingerprint?: string }; fingerprint: string };+ expiresAt: string;+ signature: { alg: 'ed25519'; keyId: string; value: string };+};++/**+ * One `POST /api/vault/agent-bindings:batch` call returns per-secret signed contexts sharing one+ * display block (protocol v2 §7.1) — the parent brokers all members to the sandbox in a single+ * `approveRelease`, then submits the resulting blind boxes with the matching `approval` handles.+ */+export type VaultAgentBindingsBatchResult = {ok: boolean;+ request_id?: string;+ grant_id?: string;+ grant_duration?: VaultGrantDuration;+ ttl_seconds?: number;+ agent?: { publicKey: { public_key: string; fingerprint?: string }; fingerprint: string };agent_pubkey: { public_key: string; fingerprint: string };- binding: {- challengeId: string;- requestId: string;- grantId: string;- agent: {- publicKey: { public_key: string; fingerprint?: string };- fingerprint: string;- };- context: Record<string, unknown>;- expiresAt: string;- signature: { alg: 'ed25519'; keyId: string; value: string };- };- approval: { nonce: string; expires_at_unix: number };+ items: Array<{+ name: string;+ context: VaultSignedOperationContext;+ approval: { nonce: string; expires_at_unix: number };+ }>;+ code?: string;+ message?: string;+};++/** Persisted vault session settings (daemon side). Mirrors `GET/PATCH /api/vault/settings`. */+export type VaultSettings = {+ unlock_window_seconds: number;+ strict_approvals: boolean;+ last_grant_ttl: VaultGrantDuration;+};++export type VaultSettingsResult = {+ ok: boolean;+ settings: VaultSettings;+ policy: VaultSessionPolicy;+ code?: string;+ message?: string;+};++/**+ * `POST /api/vault/secrets/<name>/reveal-context`. The daemon signs a `reveal` context naming the+ * secret; the sandbox renders it and displays the plaintext in-frame. The protected record+ * `envelope` is relayed alongside so the sandbox can open it (the parent only holds ciphertext).+ */+export type VaultRevealContextResult = {+ ok: boolean;+ context?: VaultSignedOperationContext;+ envelope?: VaultSealedEnvelope;code?: string;message?: string;};@@ -487,12 +546,17 @@ export type ApiContextType = {getVaultPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;getVaultAgentPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;getVaultSandboxRootMetadata: () => Promise<VaultSandboxRootMetadataResult>;- createVaultAgentBinding: (payload: {+ /** One batch of signed agent-delivery contexts for every protected member of a request (§7.1). */+ createVaultAgentBindingsBatch: (payload: {request_id: string;- grant_id: string;- name: string;- ttl_seconds?: number;- }) => Promise<VaultAgentBindingResult>;+ grant_duration?: VaultGrantDuration;+ }) => Promise<VaultAgentBindingsBatchResult>;+ getVaultSettings: () => Promise<VaultSettingsResult>;+ saveVaultSettings: (payload: Partial<VaultSettings>) => Promise<VaultSettingsResult>;+ createVaultRevealContext: (+ name: string,+ payload?: { session_label?: string },+ ) => Promise<VaultRevealContextResult>;deriveSigningAddresses: (publicKey: string) => Promise<{ ok: boolean; addresses?: SigningAddresses; code?: string; message?: string }>;createVaultAuthzWebAuthnOptions: () => Promise<VaultWebAuthnRegistrationOptions>;registerVaultAuthzWebAuthnFactor: (@@ -2292,8 +2356,12 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ childrengetVaultPubkey: () => getCachedJson('/api/vault/pubkey', 1500),getVaultAgentPubkey: () => getCachedJson('/api/vault/agent/pubkey', 1500),getVaultSandboxRootMetadata: () => getCachedJson('/api/vault/sandbox/root-metadata', 1500, { handleError: false }),- createVaultAgentBinding: (payload) =>- postJson('/api/vault/agent-binding', payload, { handleError: false }),+ createVaultAgentBindingsBatch: (payload) =>+ postJson('/api/vault/agent-bindings:batch', payload, { handleError: false }),+ getVaultSettings: () => getJson('/api/vault/settings', { handleError: false }),+ saveVaultSettings: (payload) => patchJson('/api/vault/settings', payload, { handleError: false }),+ createVaultRevealContext: (name, payload) =>+ postJson(`/api/vault/secrets/${encodeURIComponent(name)}/reveal-context`, payload ?? {}, { handleError: false }),deriveSigningAddresses: (publicKey) =>postJson('/api/vault/signing-addresses', { public_key: publicKey }, { handleError: false }),createVaultAuthzWebAuthnOptions: () => postJson('/api/vault/authz/factors/webauthn/options', {}),diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex fb3b3d9b7..2c1ddc516 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2271,7 +2271,27 @@"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."+ "windowTooltip": "Unlock window — while unlocked, approvals don't re-ask for your passkey; signing always does. Lock now to wipe the key from this browser."+ },+ "settings": {+ "title": "Vault settings",+ "subtitle": "How long the vault stays unlocked, and how strictly approvals ask.",+ "loading": "Loading settings…",+ "loadFailed": "Couldn't load vault settings.",+ "saveFailed": "Couldn't save vault settings.",+ "unlockWindow": "Unlock window",+ "unlockWindowHelp": "How long the vault stays unlocked in this browser after you unlock it. Applies the next time you unlock.",+ "minutes": "{{count}} min",+ "strict": "Strict approvals",+ "strictHelp": "Ask for your passkey on every approval and reveal — not just an in-sandbox confirmation. Signing always asks regardless. Turning this on re-locks the vault so it takes effect right away."+ },+ "reveal": {+ "show": "Show value",+ "copy": "Copy value",+ "errors": {+ "contextFailed": "Couldn't prepare the reveal. Please try again.",+ "unavailable": "Reveal isn't available for this secret yet."+ }},"saved": "Updated {{name}}","editSecret": "Edit info",@@ -2335,6 +2355,8 @@"kindKeypairHelp": "A signing key generated in your browser.","nameHint": "Start with a letter or underscore; then use letters, numbers, or underscore · case preserved","signingKeyHelp": "A new secp256k1 signing key is created in your browser. The private key is sealed in your browser — standard keys are signed by avault locally, protected keys are signed in your browser — and only the public key is stored in the clear.",+ "signingKeyProtectedHelp": "A new secp256k1 signing key is generated inside the sandbox and sealed there. Only the ciphertext and public addresses reach Avibe — the private key never leaves the sandbox.",+ "signingKeyProtectedBornHint": "The private key was born inside the sandbox and never entered this app.","signingGenerate": "Generate","signingImport": "Import","signingGenerateCta": "Generate signing key",@@ -2426,7 +2448,14 @@"protectedSecrets": "Protected","duration": "Duration","durationValue": "Access lasts {{time}}",+ "grantDuration": "Agent access duration",+ "grantOneTime": "One-time",+ "grantMinutes": "{{count}} min",+ "grantDurationHelp": "How long the agent may use the secret after you approve.",+ "grantOneTimeHelp": "The agent completes this one delivery, then access ends.",+ "grantOneShotHelp": "This request is one-time only — the agent gets a single delivery, so the duration is fixed.","thisSessionOnly": "This session only",+ "sessionBound": "Bound to this session","approve": "Approve","sign": "Sign","deny": "Deny",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex e1ce73c97..d23572ad9 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2271,7 +2271,27 @@"lock": {"unlocked": "已解锁","lockNow": "立即锁定",- "autoLockHint": "闲置 10 分钟后自动锁定——密钥会从浏览器内存中抹除。点「立即锁定」可马上抹除。"+ "windowTooltip": "解锁窗口——解锁期间,授权不会再次要求 passkey;签名始终需要。点「立即锁定」可立刻从浏览器抹除密钥。"+ },+ "settings": {+ "title": "保护档设置",+ "subtitle": "保险库保持解锁的时长,以及授权提示的严格程度。",+ "loading": "正在加载设置…",+ "loadFailed": "无法加载保护档设置。",+ "saveFailed": "无法保存保护档设置。",+ "unlockWindow": "解锁窗口",+ "unlockWindowHelp": "解锁后保险库在此浏览器中保持解锁的时长。下次解锁时生效。",+ "minutes": "{{count}} 分钟",+ "strict": "严格授权",+ "strictHelp": "每次授权和查看都要求 passkey,而不仅是沙箱内确认。签名无论如何都会要求。开启时会重新锁定保险库,使其立即生效。"+ },+ "reveal": {+ "show": "查看值",+ "copy": "复制值",+ "errors": {+ "contextFailed": "无法准备查看,请重试。",+ "unavailable": "此保护档暂不支持查看。"+ }},"saved": "已更新 {{name}}","editSecret": "编辑信息",@@ -2335,6 +2355,8 @@"kindKeypairHelp": "在你浏览器里生成的签名私钥。","nameHint": "首字符必须是字母或下划线;后续可用字母、数字、下划线 · 保留大小写","signingKeyHelp": "会在你的浏览器里新生成一把 secp256k1 签名密钥。私钥在浏览器中封存——标准密钥由本机 avault 签名,保护层密钥在浏览器中签名——只有公钥明文保存。",+ "signingKeyProtectedHelp": "在沙箱内新生成一把 secp256k1 签名密钥并就地封存。只有密文和公开地址会到达 Avibe——私钥绝不离开沙箱。",+ "signingKeyProtectedBornHint": "私钥在沙箱内生成,从未进入本应用。","signingGenerate": "生成","signingImport": "导入","signingGenerateCta": "生成签名密钥",@@ -2426,7 +2448,14 @@"protectedSecrets": "保护档","duration": "时长","durationValue": "访问持续 {{time}}",+ "grantDuration": "Agent 授权时长",+ "grantOneTime": "一次性",+ "grantMinutes": "{{count}} 分钟",+ "grantDurationHelp": "批准后 Agent 可以使用该保护档的时长。",+ "grantOneTimeHelp": "Agent 完成这一次投递后,访问即结束。",+ "grantOneShotHelp": "此请求为一次性——Agent 只获得单次投递,时长固定。","thisSessionOnly": "仅限本会话",+ "sessionBound": "绑定到此会话","approve": "批准","sign": "签名","deny": "拒绝",diff --git a/ui/src/lib/useProtectedVault.test.ts b/ui/src/lib/useProtectedVault.test.tsindex 1a11c246e..57a20e8bd 100644--- a/ui/src/lib/useProtectedVault.test.ts+++ b/ui/src/lib/useProtectedVault.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { webauthnAvailable } from './useProtectedVault';+import { vaultFreshSetup, vaultUnlocked, vaultUnlockExpiresAt, webauthnAvailable } from './useProtectedVault';import {VAULT_SANDBOX_EXPECTED_BUILD_HASH,VAULT_SANDBOX_IFRAME_URL,@@ -25,3 +25,13 @@ describe('protected vault sandbox cutover', () => {expect(webauthnAvailable()).toBe(false);});});++describe('event-driven lock state (parent shadow clock removed)', () => {+ it('starts locked with no mirrored expiry — nothing unlocks without a sandbox vault.state event', () => {+ // The parent no longer owns an auto-lock timer or a default window; lock state is derived only+ // from sandbox events and status results (protocol v2 §8), so the module boots fully locked.+ expect(vaultUnlocked()).toBe(false);+ expect(vaultUnlockExpiresAt()).toBeNull();+ expect(vaultFreshSetup()).toBe(false);+ });+});diff --git a/ui/src/lib/useProtectedVault.ts b/ui/src/lib/useProtectedVault.tsindex 9c6648c61..de8a71a34 100644--- a/ui/src/lib/useProtectedVault.ts+++ b/ui/src/lib/useProtectedVault.ts@@ -2,16 +2,21 @@ import { useCallback, useEffect, useReducer, useState } from 'react';import {useApi,+ type VaultSignedOperationContext,type VaultWebAuthnRegistrationPayload,type VaultWebAuthnSerializedCredential,} from '@/context/ApiContext';import {getVaultSandboxClient,- type DaemonAgentBinding,+ resetVaultSandboxClient,+ subscribeVaultStateEvents,+ type ApproveReleaseItem,type VaultSandboxSealResult,type VaultSandboxSigningContext,+ type VaultStateEvent,} from './vaultSandboxClient';import { type BlindBox, type ProtectedRecordEnvelope, type SignatureResult, type SignatureScheme } from './vaultCrypto';+import { invalidateVaultSandboxPolicy } from './vaultSandboxPolicy';/*** Value-free protected material hydrated into UI approval cards. The parent app brokers it to the@@ -30,8 +35,6 @@ type ParentStaticSealValue = {export type ProtectedVaultStatus = 'checking' | 'needs-setup' | 'locked' | 'unlocked' | 'error';-const VAULT_AUTO_LOCK_MS = 10 * 60 * 1000;-const sessionVault: {status: Exclude<ProtectedVaultStatus, 'checking' | 'error'>;wrapMeta: string | null;@@ -44,8 +47,11 @@ const sessionVault: {authzFactorRegistration: null,};+// The unlock-window deadline (ms epoch) is now owned by the sandbox — the parent only *mirrors*+// the value it receives from `vault.state` events and `status` results (protocol v2 §6.4/§8).+// There is no parent-side auto-lock timer anymore: the sandbox holds the single clock and emits a+// `vault.state { locked, auto-lock }` event when it expires. See the module subscription below.let vaultLockExpiresAt: number | null = null;-let vaultAutoLockTimer: ReturnType<typeof setTimeout> | null = null;const vaultLockListeners = new Set<() => void>();let vaultLockChannel: BroadcastChannel | null = null;@@ -57,6 +63,10 @@ function getVaultLockChannel(): BroadcastChannel | null {vaultLockChannel = new BroadcastChannel('avibe-vault-lock');vaultLockChannel.onmessage = (event: MessageEvent) => {if (event.data === 'lock') void lockVault(false);+ // A policy tightening (enabling Strict) in another tab: lock AND drop this tab's sandbox client+ // so it re-handshakes under the new policy — a plain lock would leave this tab's client pinned+ // to the stale policy, and its next auto-unlock would run non-Strict.+ else if (event.data === 'reset') applyPolicyResetLock();};return vaultLockChannel;}@@ -76,27 +86,10 @@ export function vaultUnlockExpiresAt(): number | null {return sessionVault.status === 'unlocked' ? vaultLockExpiresAt : null;}-function autoLockExpired(): boolean {- return vaultLockExpiresAt != null && Date.now() >= vaultLockExpiresAt;-}-export function vaultUnlocked(): boolean {- if (sessionVault.status === 'unlocked' && autoLockExpired()) {- clearUnlockState();- queueMicrotask(notifyVaultLockChange);- void getVaultSandboxClient()- .then((client) => client.lock())- .catch(() => undefined);- return false;- }- return sessionVault.status === 'unlocked';-}--function enforceAutoLock(): boolean {- if (sessionVault.status === 'unlocked' && autoLockExpired()) {- void lockVault(false);- return false;- }+ // The sandbox is authoritative: it auto-locks and emits a `vault.state` event we mirror, so the+ // parent no longer second-guesses the clock. A rendered countdown reaching 0 is cosmetic; the+ // real transition arrives as an event (or the next `status` reconciliation).return sessionVault.status === 'unlocked';}@@ -109,12 +102,10 @@ function vaultStatusNow(): ProtectedVaultStatus {}function clearUnlockState(): void {- if (vaultAutoLockTimer) {- clearTimeout(vaultAutoLockTimer);- vaultAutoLockTimer = null;- }vaultLockExpiresAt = null;if (sessionVault.freshSetup) {+ // A fresh setup that never persisted a secret: locking reverts to needs-setup (the daemon has+ // no wrap_meta yet), so drop the in-memory handle rather than pretend a vault exists.sessionVault.wrapMeta = null;sessionVault.freshSetup = false;sessionVault.authzFactorRegistration = null;@@ -124,6 +115,26 @@ function clearUnlockState(): void {}}+// The single source of truth for lock state: sandbox `vault.state` events. One module-level+// subscription mirrors every transition (unlock / renew / auto-lock / manual-lock / unload) into+// the shared session state and notifies React subscribers. Registered once at module load so it is+// live before any component mounts and survives sandbox-client recreation.+function applyVaultStateEvent(event: VaultStateEvent): void {+ if (event.state === 'unlocked') {+ // The sandbox only unlocks material the parent handed it, so wrapMeta should already be known;+ // guard anyway so a stray event can't flip us to a wrapMeta-less "unlocked".+ if (!sessionVault.wrapMeta) return;+ sessionVault.status = 'unlocked';+ if (typeof event.expiresAt === 'number' && Number.isFinite(event.expiresAt)) vaultLockExpiresAt = event.expiresAt;+ notifyVaultLockChange();+ return;+ }+ clearUnlockState();+ notifyVaultLockChange();+}++subscribeVaultStateEvents(applyVaultStateEvent);+async function lockVault(broadcast = false): Promise<void> {clearUnlockState();notifyVaultLockChange();@@ -135,13 +146,24 @@ async function lockVault(broadcast = false): Promise<void> {}}-function armVaultAutoLock(expiresAt?: number | null): void {- getVaultLockChannel();- const sandboxDeadline = typeof expiresAt === 'number' && Number.isFinite(expiresAt) ? expiresAt : null;- vaultLockExpiresAt = sandboxDeadline ?? Date.now() + VAULT_AUTO_LOCK_MS;- if (vaultAutoLockTimer) clearTimeout(vaultAutoLockTimer);- vaultAutoLockTimer = setTimeout(() => void lockVault(false), Math.max(0, vaultLockExpiresAt - Date.now()));+// Lock this tab AND discard its sandbox client so the next ceremony re-handshakes under the fresh+// policy. Used for a policy tightening (enabling Strict): the sandbox pins policy at handshake and+// its internal auto-unlock reuses that pin, so locking alone would let this tab re-unlock stale.+function applyPolicyResetLock(): void {+ clearUnlockState();notifyVaultLockChange();+ // Invalidate the parent policy mirror too: the reset is a tightening, so if the next handshake's+ // settings fetch fails we must fail closed (strict) rather than re-pin the old confirmed policy.+ invalidateVaultSandboxPolicy();+ resetVaultSandboxClient();+}++// Broadcast a policy reset to every tab (including this one): all drop their pinned sandbox client+// and re-handshake under the new policy on the next ceremony. This is the cross-tab counterpart to+// the local reset — a plain `lock` broadcast would leave siblings re-unlocking under stale policy.+function lockAndResetAllTabs(): void {+ getVaultLockChannel()?.postMessage('reset');+ applyPolicyResetLock();}function baseVmkWrapMeta(wrapMeta: string): string {@@ -172,14 +194,13 @@ function commitUnlocked(sessionVault.status = 'unlocked';sessionVault.freshSetup = freshSetup;sessionVault.authzFactorRegistration = authzFactorRegistration;- armVaultAutoLock(expiresAt);+ // Mirror the sandbox-provided deadline directly; the event stream keeps it fresh on renewal.+ vaultLockExpiresAt = typeof expiresAt === 'number' && Number.isFinite(expiresAt) ? expiresAt : null;+ getVaultLockChannel();+ notifyVaultLockChange();}function commitLocked(wrapMeta: string): void {- if (vaultAutoLockTimer) {- clearTimeout(vaultAutoLockTimer);- vaultAutoLockTimer = null;- }vaultLockExpiresAt = null;sessionVault.wrapMeta = baseVmkWrapMeta(wrapMeta);sessionVault.status = 'locked';@@ -210,17 +231,20 @@ export function useProtectedVault() {const [status, setStatus] = useState<ProtectedVaultStatus>(sessionVault.status);const [error, setError] = useState<string | null>(null);- useEffect(- () =>- subscribeVaultLock(() => {- setStatus((prev) => (prev === 'checking' || prev === 'error' ? prev : vaultStatusNow()));- }),- [],- );+ useEffect(() => {+ // Initialize the cross-tab lock channel as soon as any vault UI mounts, so this tab receives+ // `reset`/`lock` broadcasts regardless of which path later creates a sandbox client (reveal,+ // approve, sign, and seal all acquire the client directly, not only refresh()). Idempotent.+ getVaultLockChannel();+ return subscribeVaultLock(() => {+ setStatus((prev) => (prev === 'checking' || prev === 'error' ? prev : vaultStatusNow()));+ });+ }, []);const refresh = useCallback(async () => {- enforceAutoLock();if (sessionVault.status === 'unlocked') {+ // Already unlocked and kept honest by the event stream — don't flash a "checking" state or+ // re-query (a `status` call is silent but pointless here).setStatus('unlocked');return;}@@ -230,19 +254,31 @@ export function useProtectedVault() {const res = await api.getVaultVmk();if (!res?.ok) throw new Error('vmk-discovery-failed');const sandbox = await getVaultSandboxClient();+ // A sandbox client now exists for this tab (even while locked); make sure the cross-tab lock+ // channel is live so a policy `reset` broadcast reaches this tab and drops its pinned client.+ getVaultLockChannel();if (res.exists && res.wrap_meta) {sessionVault.wrapMeta = baseVmkWrapMeta(res.wrap_meta);const sandboxStatus = await sandbox.status(sessionVault.wrapMeta);if (sandboxStatus.state === 'unlocked') {sessionVault.status = 'unlocked';- armVaultAutoLock(sandboxStatus.expiresAt);+ vaultLockExpiresAt =+ typeof sandboxStatus.expiresAt === 'number' && Number.isFinite(sandboxStatus.expiresAt) ? sandboxStatus.expiresAt : null;} else {sessionVault.status = 'locked';+ vaultLockExpiresAt = null;}} else {sessionVault.wrapMeta = null;sessionVault.status = 'needs-setup';+ vaultLockExpiresAt = null;}+ // Reconciling an existing sandbox session mutates the shared module state, so wake every+ // `subscribeVaultLock` listener (e.g. sibling VaultLockIndicators) — not just this hook's+ // `setStatus` below. The deleted `armVaultAutoLock()` path used to do this; without it a+ // remount that finds an already-unlocked session leaves siblings on stale lock state until+ // the next `vault.state` event.+ notifyVaultLockChange();setStatus(sessionVault.status);} catch (err) {sessionVault.status = sessionVault.wrapMeta ? 'locked' : 'needs-setup';@@ -291,36 +327,24 @@ export function useProtectedVault() {authzFactorRegistration?: VaultWebAuthnRegistrationPayload;}> => {- if (!enforceAutoLock()) throw new Error('vault-locked');const wrapMeta = sessionVault.wrapMeta;if (!wrapMeta) throw new Error('vault-locked');- armVaultAutoLock();+ const sandbox = await getVaultSandboxClient();let sealed: VaultSandboxSealResult;if (kind === 'static') {if (!parentStaticValue) throw new Error('protected-static-value-required');- const sandbox = await getVaultSandboxClient();- // Hand the plaintext to the sandbox, then drop the parent-held copy IMMEDIATELY.- // `seal()` captures `value` into the request payload synchronously here, so we can- // clear the persistent ref + revealed field right away rather than leaving the- // plaintext in parent memory for the whole interactive ceremony (up to a 5-min timeout).- const sealing = sandbox.seal({- name,- kind: 'static',- inputMode: 'parent-value',- value: parentStaticValue.valueRef.current,- wrapMeta,- });+ // Hand the plaintext to the sandbox, then drop the parent-held copy IMMEDIATELY. `seal()`+ // captures `value` into the request payload synchronously here, so we clear the persistent+ // ref + revealed field right away rather than leaving plaintext in parent memory for the+ // whole ceremony (R1 seal is silent while unlocked, but the value must not linger).+ const sealing = sandbox.seal({ name, kind: 'static', value: parentStaticValue.valueRef.current, wrapMeta });parentStaticValue.valueRef.current = '';parentStaticValue.clear();sealed = await sealing;} else {- const sandbox = await getVaultSandboxClient();- sealed = await sandbox.seal({- name,- kind,- inputMode: 'sandbox-entry',- wrapMeta,- });+ // Keypair is generate-only: the secp256k1 key is born inside the sandbox and never crosses+ // the boundary; the parent receives only ciphertext + public key/addresses (protocol v2 §7.2).+ sealed = await sandbox.seal({ name, kind: 'keypair', wrapMeta });}return {...sealed,@@ -356,10 +380,11 @@ export function useProtectedVault() {material: ProtectedUnlockMaterial,signingContext: VaultSandboxSigningContext,scheme: SignatureScheme,+ context: VaultSignedOperationContext,): Promise<SignatureResult> => {const sandbox = await getVaultSandboxClient();try {- return await sandbox.sign({ material, scheme, signingContext });+ return await sandbox.sign({ material, scheme, signingContext, context });} finally {void syncProtectedOperationStatus(material.envelope.wrap_meta).catch(() => undefined);}@@ -367,11 +392,36 @@ export function useProtectedVault() {[syncProtectedOperationStatus],);- const releaseProtectedDelivery = useCallback(- async (material: ProtectedUnlockMaterial, agentBinding: DaemonAgentBinding): Promise<BlindBox> => {+ /**+ * Batch DEK release for an access approval: one confirm card covers every protected member and+ * the sandbox returns one HPKE blind box per item (order matches `items`). Replaces the v1+ * per-secret `releaseProtectedDelivery` loop.+ */+ const approveProtectedRelease = useCallback(+ async (items: ApproveReleaseItem[]): Promise<BlindBox[]> => {+ if (items.length === 0) return [];+ const sandbox = await getVaultSandboxClient();+ try {+ const result = await sandbox.approveRelease({ items });+ return result.blindBoxes;+ } finally {+ const wrapMeta = items[0]?.material.envelope.wrap_meta;+ if (wrapMeta) void syncProtectedOperationStatus(wrapMeta).catch(() => undefined);+ }+ },+ [syncProtectedOperationStatus],+ );++ /**+ * Reveal a protected static value inside the sandbox frame. Plaintext is displayed (and, on the+ * sandbox-side explicit action, copied) entirely within the sandbox — it is never returned to+ * the parent. R2: an in-sandbox confirm while unlocked, a passkey while locked or under Strict.+ */+ const revealProtectedValue = useCallback(+ async (material: ProtectedUnlockMaterial, context: VaultSignedOperationContext): Promise<{ completed: boolean }> => {const sandbox = await getVaultSandboxClient();try {- return await sandbox.releaseDEK({ material, agentBinding });+ return await sandbox.reveal({ material, context });} finally {void syncProtectedOperationStatus(material.envelope.wrap_meta).catch(() => undefined);}@@ -384,6 +434,14 @@ export function useProtectedVault() {setStatus(vaultStatusNow());}, []);+ // Lock + force a sandbox re-handshake across ALL tabs. Used when a policy tightening (Strict)+ // must take effect immediately everywhere: the sandbox pins policy at handshake, so every tab+ // must drop its client and re-handshake under the new policy, not merely lock.+ const lockAndResetForPolicyChange = useCallback(() => {+ lockAndResetAllTabs();+ setStatus(vaultStatusNow());+ }, []);+const discardAndRefresh = useCallback(async () => {clearUnlockState();sessionVault.wrapMeta = null;@@ -406,9 +464,11 @@ export function useProtectedVault() {unlockPasskey,sealValue,signProtectedRequest,- releaseProtectedDelivery,+ approveProtectedRelease,+ revealProtectedValue,afterCreated,lock,+ lockAndResetForPolicyChange,discardAndRefresh,hasPasskey,passkeyUsableHere,@@ -423,12 +483,13 @@ export function useVaultLock(): { unlocked: boolean; remainingMs: number; lockNoconst [now, setNow] = useState(() => Date.now());useEffect(() => {if (!unlocked) return;- const updateNow = () => {- enforceAutoLock();- setNow(Date.now());- };- const immediate = window.setTimeout(updateNow, 0);- const id = setInterval(updateNow, 1000);+ // Pure render clock: tick `now` once a second so the countdown advances. The sandbox owns the+ // actual auto-lock and emits a `vault.state` event when it fires — the parent never locks off+ // this timer (protocol v2 §8). The 0ms timer syncs `now` right after unlock without a+ // setState directly in the effect body (which would trigger a cascading render).+ const sync = () => setNow(Date.now());+ const immediate = window.setTimeout(sync, 0);+ const id = setInterval(sync, 1000);return () => {window.clearTimeout(immediate);clearInterval(id);diff --git a/ui/src/lib/vaultSandboxClient.ts b/ui/src/lib/vaultSandboxClient.tsindex aefd0ff7d..67b2ca212 100644--- a/ui/src/lib/vaultSandboxClient.ts+++ b/ui/src/lib/vaultSandboxClient.ts@@ -1,5 +1,6 @@import type {SigningAddresses,+ VaultSignedOperationContext,VaultWebAuthnRegistrationPayload,} from '@/context/ApiContext';import type { BlindBox, ProtectedRecordEnvelope, SignatureResult, SignatureScheme } from './vaultCrypto';@@ -14,20 +15,15 @@ import {VAULT_SANDBOX_REQUIRED_RESOURCE_PATHS,} from './vaultSandboxManifest';import { getVaultSandboxAppearance, type VaultSandboxAppearance } from './vaultSandboxAppearance';+import { getVaultSandboxPolicy, refreshVaultSandboxPolicy, type VaultSessionPolicy } from './vaultSandboxPolicy';const CHANNEL = 'avibe.vault.crypto';-const VERSION = 1;-const REQUIRED_OPS = [- 'status',- 'setup',- 'unlock',- 'lock',- 'seal',- 'unseal',- 'sign',- 'releaseDEK',-] as const;+const VERSION = 2;+// Protocol v2 operation surface (vault-sandbox #9): `unseal`→`reveal`, `releaseDEK`→`approveRelease`.+const REQUIRED_OPS = ['status', 'setup', 'unlock', 'lock', 'seal', 'reveal', 'sign', 'approveRelease'] as const;const DEFAULT_TIMEOUT_MS = 15_000;+// Ops that may raise an in-sandbox card (confirm / passkey / plaintext display) can sit open for+// as long as the user takes to act, so they get the long ceremony timeout regardless of tier.const INTERACTIVE_TIMEOUT_MS = 5 * 60_000;type VaultSandboxOp = (typeof REQUIRED_OPS)[number] | 'handshake';@@ -36,7 +32,6 @@ type PendingRequest = {resolve: (value: unknown) => void;reject: (err: Error) => void;timer: number;- interactive: boolean;};type SandboxBuild = {@@ -56,12 +51,32 @@ type TerminalMessage =| { channel: typeof CHANNEL; version: typeof VERSION; id: string; ok: true; result: unknown }| { channel: typeof CHANNEL; version: typeof VERSION; id: string; ok: false; error: { code?: string; message?: string; retryable?: boolean } | string };+/** Sandbox→parent one-way notification (protocol v2 §6.4). */+type EventMessage = {+ channel: typeof CHANNEL;+ version: typeof VERSION;+ kind: 'event';+ event: 'vault.state' | 'ui.show' | 'ui.hide';+ payload?: unknown;+};+export type VaultSandboxState = 'needs-setup' | 'locked' | 'unlocked';+export type VaultStateReason = 'unlock' | 'renew' | 'manual-lock' | 'auto-lock' | 'unload';++/** The `vault.state` event payload — the single clock the parent mirrors (protocol v2 §6.4). */+export type VaultStateEvent = {+ state: VaultSandboxState;+ expiresAt?: number | null;+ reason: VaultStateReason;+};+export type VaultSandboxStatusResult = {state: VaultSandboxState;expiresAt?: number | null;freshSetup?: boolean;+ policy?: VaultSessionPolicy;+ session?: { expiresAt?: number; strict?: boolean };};export type VaultSandboxSetupResult = {@@ -71,12 +86,14 @@ export type VaultSandboxSetupResult = {authzRegistration?: VaultWebAuthnRegistrationPayload;state: 'unlocked';expiresAt?: number;+ policy?: VaultSessionPolicy;};export type VaultSandboxUnlockResult = {state: 'unlocked';expiresAt?: number;wrapMeta?: string;+ policy?: VaultSessionPolicy;};export type VaultSandboxSealResult = {@@ -86,17 +103,10 @@ export type VaultSandboxSealResult = {addresses?: SigningAddresses;};-export type DaemonAgentBinding = {- challengeId: string;- requestId: string;- grantId: string;- agent: {- publicKey: { public_key: string; fingerprint?: string };- fingerprint: string;- };- context: Record<string, unknown>;- expiresAt: string;- signature: { alg: 'ed25519'; keyId: string; value: string };+/** One member of a batch `approveRelease` — the sandbox releases one blind box per item. */+export type ApproveReleaseItem = {+ material: ProtectedUnlockMaterialLike;+ context: VaultSignedOperationContext;};export type VaultSandboxSigningContext = Record<string, unknown>;@@ -116,6 +126,26 @@ export class VaultSandboxError extends Error {let integrityPromise: Promise<void> | null = null;let singleton: Promise<VaultSandboxClient> | null = null;let activeClient: VaultSandboxClient | null = null;+// Bumped on every reset. A create() that started before a reset checks this after its handshake:+// if it advanced, the client handshook under the pre-reset (stale) policy and is discarded instead+// of being adopted, so a reset takes effect even for an in-flight client creation.+let clientGeneration = 0;++// Module-level so subscribers survive client recreation (a singleton reset on error) and can+// register before any client exists — the active client forwards every `vault.state` event here.+const vaultStateListeners = new Set<(event: VaultStateEvent) => void>();++/**+ * Subscribe to sandbox `vault.state` events (unlock / renew / lock transitions). This is the+ * single clock the parent renders off of — {@link useProtectedVault} wires one listener that+ * mirrors state + `expiresAt`. Returns an unsubscribe function.+ */+export function subscribeVaultStateEvents(listener: (event: VaultStateEvent) => void): () => void {+ vaultStateListeners.add(listener);+ return () => {+ vaultStateListeners.delete(listener);+ };+}function isObject(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value != null && !Array.isArray(value);@@ -215,13 +245,34 @@ function parseTerminalMessage(data: unknown): TerminalMessage | null {return null;}+function parseEventMessage(data: unknown): EventMessage | null {+ if (!isObject(data)) return null;+ if (data.channel !== CHANNEL || data.version !== VERSION || data.kind !== 'event') return null;+ if (data.event !== 'vault.state' && data.event !== 'ui.show' && data.event !== 'ui.hide') return null;+ return data as EventMessage;+}++function parseVaultStateEvent(payload: unknown): VaultStateEvent | null {+ if (!isObject(payload)) return null;+ const state = payload.state;+ if (state !== 'needs-setup' && state !== 'locked' && state !== 'unlocked') return null;+ const reason = payload.reason;+ const validReason =+ reason === 'unlock' || reason === 'renew' || reason === 'manual-lock' || reason === 'auto-lock' || reason === 'unload';+ return {+ state,+ reason: validReason ? reason : 'manual-lock',+ expiresAt: typeof payload.expiresAt === 'number' && Number.isFinite(payload.expiresAt) ? payload.expiresAt : null,+ };+}+export class VaultSandboxClient {private iframe: HTMLIFrameElement;private backdrop: HTMLDivElement | null = null;private pending = new Map<string, PendingRequest>();private readyPromise: Promise<ReadyMessage>;- private interactiveDepth = 0;private handshaken = false;+ private modalVisible = false;private constructor(iframe: HTMLIFrameElement) {this.iframe = iframe;@@ -230,6 +281,8 @@ export class VaultSandboxClient {}static async create(): Promise<VaultSandboxClient> {+ // Snapshot the reset generation so we can discard this client if a reset lands mid-creation.+ const generation = clientGeneration;// Gated during pre-launch iteration — see VAULT_SANDBOX_INTEGRITY_ENFORCED. When off, the// parent still origin-isolates the sandbox; it just doesn't fail-closed on a manifest mismatch.if (VAULT_SANDBOX_INTEGRITY_ENFORCED) await verifyVaultSandboxIntegrity();@@ -250,8 +303,8 @@ export class VaultSandboxClient {iframe.style.boxShadow = 'none';// At rest the sandbox is a headless RPC worker: keep it in the DOM (so// postMessage works) but 0-sized + hidden so it never covers the app. It- // only expands to a centered modal while an interactive ceremony is- // active — see setInteractive().+ // only expands to a centered modal while the sandbox asks for its slot via+ // a `ui.show` event — see setModalVisible().iframe.style.width = '0';iframe.style.height = '0';iframe.style.visibility = 'hidden';@@ -261,6 +314,13 @@ export class VaultSandboxClient {iframe.src = VAULT_SANDBOX_IFRAME_URL;document.body.appendChild(iframe);await client.handshake();+ if (generation !== clientGeneration) {+ // A reset (e.g. Strict enabled) landed while we were handshaking — this client pinned the+ // pre-reset policy. Discard it and fail so the caller re-acquires a fresh, correctly-pinned+ // client instead of proceeding under the stale policy.+ client.destroy();+ throw new VaultSandboxError('sandbox_reset', 'Sandbox client was reset during creation', true);+ }activeClient = client;return client;}@@ -285,23 +345,22 @@ export class VaultSandboxClient {return backdrop;}- private setInteractive(active: boolean): void {- this.interactiveDepth += active ? 1 : -1;- this.interactiveDepth = Math.max(0, this.interactiveDepth);- const interactive = this.interactiveDepth > 0;- if (interactive) {+ // Expand to a lightweight centered modal while the sandbox holds its slot (`ui.show`), otherwise+ // collapse to a hidden 0-size worker (`ui.hide`) so silent R1/R2 ops never cover the app. Driven+ // by sandbox events, not per-call flags — a silent operation emits no `ui.show` and stays hidden.+ private setModalVisible(visible: boolean): void {+ this.modalVisible = visible;+ if (visible) {this.ensureBackdrop();} else {this.backdrop?.remove();this.backdrop = null;}- // Expand to a lightweight centered modal only while a ceremony is active;- // otherwise collapse to a hidden 0-size worker so the sandbox never covers the app.- this.iframe.style.width = interactive ? 'min(440px, 92vw)' : '0';- this.iframe.style.height = interactive ? 'min(640px, 88vh)' : '0';- this.iframe.style.visibility = interactive ? 'visible' : 'hidden';- this.iframe.style.pointerEvents = interactive ? 'auto' : 'none';- this.iframe.style.boxShadow = interactive ? '0 24px 80px rgba(15, 23, 42, 0.38)' : 'none';+ this.iframe.style.width = visible ? 'min(440px, 92vw)' : '0';+ this.iframe.style.height = visible ? 'min(640px, 88vh)' : '0';+ this.iframe.style.visibility = visible ? 'visible' : 'hidden';+ this.iframe.style.pointerEvents = visible ? 'auto' : 'none';+ this.iframe.style.boxShadow = visible ? '0 24px 80px rgba(15, 23, 42, 0.38)' : 'none';}private waitForReady(): Promise<ReadyMessage> {@@ -332,13 +391,20 @@ export class VaultSandboxClient {private handleMessage = (event: MessageEvent): void => {if (event.origin !== VAULT_SANDBOX_ORIGIN || event.source !== this.iframe.contentWindow) return;+ const eventMessage = parseEventMessage(event.data);+ if (eventMessage) {+ this.handleEvent(eventMessage);+ return;+ }const reply = parseTerminalMessage(event.data);if (!reply) return;const pending = this.pending.get(reply.id);if (!pending) return;this.pending.delete(reply.id);window.clearTimeout(pending.timer);- if (pending.interactive) this.setInteractive(false);+ // Safety net: if the sandbox errored out of a card without emitting `ui.hide`, collapse once+ // the last in-flight request settles so a stale modal can't strand the app behind a backdrop.+ if (this.pending.size === 0 && this.modalVisible) this.setModalVisible(false);if (reply.ok) {pending.resolve(reply.result);} else {@@ -346,8 +412,25 @@ export class VaultSandboxClient {}};+ private handleEvent(message: EventMessage): void {+ if (message.event === 'ui.show') {+ this.setModalVisible(true);+ return;+ }+ if (message.event === 'ui.hide') {+ this.setModalVisible(false);+ return;+ }+ const state = parseVaultStateEvent(message.payload);+ if (!state) return;+ for (const listener of [...vaultStateListeners]) listener(state);+ }+private async handshake(): Promise<void> {await this.readyPromise;+ // Pull the daemon-persisted policy so the very first ceremony runs under the configured+ // window/strict values; best-effort — a failure leaves the default policy in place.+ await refreshVaultSandboxPolicy();await this.request('handshake',{@@ -355,6 +438,7 @@ export class VaultSandboxClient {nonce: randomId(),expectedBuildHash: VAULT_SANDBOX_EXPECTED_BUILD_HASH,appearance: getVaultSandboxAppearance(),+ policy: getVaultSandboxPolicy(),},{ timeoutMs: DEFAULT_TIMEOUT_MS },);@@ -381,26 +465,19 @@ export class VaultSandboxClient {}}- private async request<T>(- op: VaultSandboxOp,- payload?: unknown,- options: { timeoutMs?: number; interactive?: boolean } = {},- ): Promise<T> {+ private async request<T>(op: VaultSandboxOp, payload?: unknown, options: { timeoutMs?: number } = {}): Promise<T> {await this.readyPromise;const id = randomId();- const interactive = Boolean(options.interactive);- if (interactive) this.setInteractive(true);const promise = new Promise<T>((resolve, reject) => {const timer = window.setTimeout(() => {this.pending.delete(id);- if (interactive) this.setInteractive(false);+ if (this.pending.size === 0 && this.modalVisible) this.setModalVisible(false);reject(new VaultSandboxError('sandbox_request_timeout', `Sandbox ${op} request timed out`, true));}, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);this.pending.set(id, {resolve: (value) => resolve(value as T),reject,timer,- interactive,});});this.target.postMessage({ channel: CHANNEL, version: VERSION, id, op, payload: payload ?? {} }, VAULT_SANDBOX_ORIGIN);@@ -411,72 +488,94 @@ export class VaultSandboxClient {return this.request<VaultSandboxStatusResult>('status', wrapMeta ? { wrapMeta } : {});}- setup(payload: {+ async setup(payload: {vaultUserHandle: string;displayName: string;existingProtectedVault: boolean;authzCreationOptions?: unknown;rootMetadata?: unknown;}): Promise<VaultSandboxSetupResult> {- return this.request<VaultSandboxSetupResult>('setup', payload, {- timeoutMs: INTERACTIVE_TIMEOUT_MS,- interactive: true,- });+ // Symmetric with unlock(): refresh the daemon policy and pass it so the first-ever unlocked+ // session (the setup ceremony) reflects a window/Strict change made after handshake but before+ // setup. The sandbox applies the passed policy on setup (protocol v2 §6.5).+ await refreshVaultSandboxPolicy();+ return this.request<VaultSandboxSetupResult>(+ 'setup',+ { ...payload, policy: getVaultSandboxPolicy() },+ { timeoutMs: INTERACTIVE_TIMEOUT_MS },+ );}- unlock(payload: { wrapMeta: string }): Promise<VaultSandboxUnlockResult> {- return this.request<VaultSandboxUnlockResult>('unlock', payload, {- timeoutMs: INTERACTIVE_TIMEOUT_MS,- interactive: true,- });+ async unlock(payload: { wrapMeta: string }): Promise<VaultSandboxUnlockResult> {+ // Pull the freshest daemon policy and pass it (protocol v2 §6.5): a settings change made in+ // another tab only broadcasts a lock, not the new policy, and the handshake fetch is+ // best-effort, so the cached mirror alone can carry stale settings. The sandbox applies the+ // passed policy on unlock. Note this covers *explicit* unlocks; the sandbox's internal+ // auto-unlock (a protected op run while locked) still uses the policy pinned at handshake, so a+ // policy tightening like enabling Strict forces a fresh handshake (resetVaultSandboxClient) to+ // re-pin — see the settings dialog. Best-effort: a failed refresh fails closed (strict).+ await refreshVaultSandboxPolicy();+ return this.request<VaultSandboxUnlockResult>(+ 'unlock',+ { wrapMeta: payload.wrapMeta, policy: getVaultSandboxPolicy() },+ { timeoutMs: INTERACTIVE_TIMEOUT_MS },+ );}- lock(): Promise<{ ok?: boolean }> {- return this.request<{ ok?: boolean }>('lock', {}, { timeoutMs: DEFAULT_TIMEOUT_MS });+ lock(): Promise<{ ok?: boolean; state?: VaultSandboxState }> {+ return this.request<{ ok?: boolean; state?: VaultSandboxState }>('lock', {}, { timeoutMs: DEFAULT_TIMEOUT_MS });}- seal(payload: {- name: string;- kind: 'static' | 'keypair';- inputMode: 'sandbox-entry' | 'parent-value';- value?: string;- wrapMeta?: string | null;- }): Promise<VaultSandboxSealResult> {- return this.request<VaultSandboxSealResult>('seal', payload, {- timeoutMs: INTERACTIVE_TIMEOUT_MS,- interactive: true,- });+ seal(+ payload:+ | { name: string; kind: 'static'; value: string; wrapMeta?: string | null }+ | { name: string; kind: 'keypair'; wrapMeta?: string | null },+ ): Promise<VaultSandboxSealResult> {+ // Static = parent-typed value handed in for sealing (the #842 concession). Keypair = generated+ // entirely inside the sandbox (generate-only, no input) returning ciphertext + public material.+ const wire =+ payload.kind === 'static'+ ? { name: payload.name, kind: 'static', inputMode: 'parent-value', value: payload.value, wrapMeta: payload.wrapMeta }+ : { name: payload.name, kind: 'keypair', wrapMeta: payload.wrapMeta };+ return this.request<VaultSandboxSealResult>('seal', wire, { timeoutMs: INTERACTIVE_TIMEOUT_MS });}- unseal(payload: {- material: ProtectedUnlockMaterialLike;- mode: 'sandbox-display' | 'sandbox-copy';- }): Promise<{ completed: boolean }> {- return this.request<{ completed: boolean }>('unseal', payload, {- timeoutMs: INTERACTIVE_TIMEOUT_MS,- interactive: true,- });+ reveal(payload: { material: ProtectedUnlockMaterialLike; context: VaultSignedOperationContext }): Promise<{ completed: boolean }> {+ return this.request<{ completed: boolean }>('reveal', payload, { timeoutMs: INTERACTIVE_TIMEOUT_MS });}sign(payload: {material: ProtectedUnlockMaterialLike;scheme: SignatureScheme;signingContext: VaultSandboxSigningContext;+ context: VaultSignedOperationContext;}): Promise<SignatureResult> {- return this.request<SignatureResult>('sign', payload, {- timeoutMs: INTERACTIVE_TIMEOUT_MS,- interactive: true,- });+ return this.request<SignatureResult>('sign', payload, { timeoutMs: INTERACTIVE_TIMEOUT_MS });}- releaseDEK(payload: {- material: ProtectedUnlockMaterialLike;- agentBinding: DaemonAgentBinding;- }): Promise<BlindBox> {- return this.request<BlindBox>('releaseDEK', payload, {- timeoutMs: INTERACTIVE_TIMEOUT_MS,- interactive: true,- });+ /**+ * Batch DEK release: one confirm card lists every member, then the sandbox emits one HPKE blind+ * box per item (order matches `items`). Replaces v1 `releaseDEK`'s per-secret ceremony.+ */+ approveRelease(payload: { items: ApproveReleaseItem[] }): Promise<{ blindBoxes: BlindBox[] }> {+ return this.request<{ blindBoxes: BlindBox[] }>('approveRelease', payload, { timeoutMs: INTERACTIVE_TIMEOUT_MS });+ }++ /**+ * Tear down this client: stop listening, collapse the modal, drop the iframe, and fail any+ * in-flight request. Used by resetVaultSandboxClient() to force a fresh handshake (e.g. after a+ * policy tightening) — the sandbox pins its enforced policy at handshake, so a new client is how+ * a Strict change reaches the internal auto-unlock path immediately.+ */+ destroy(): void {+ window.removeEventListener('message', this.handleMessage);+ for (const [, pending] of this.pending) {+ window.clearTimeout(pending.timer);+ pending.reject(new VaultSandboxError('sandbox_reset', 'Sandbox client was reset', true));+ }+ this.pending.clear();+ this.setModalVisible(false);+ this.iframe.remove();}}@@ -488,15 +587,39 @@ type ProtectedUnlockMaterialLike = {export async function getVaultSandboxClient(): Promise<VaultSandboxClient> {if (!singleton) {- singleton = VaultSandboxClient.create().catch((err) => {- singleton = null;- activeClient = null;+ const pending: Promise<VaultSandboxClient> = VaultSandboxClient.create().catch((err) => {+ // Only clear the globals if they still refer to THIS attempt. A reset may have already+ // replaced `singleton` with a newer create and `activeClient` with a live client; clearing+ // them here unconditionally would orphan that client's iframe (leaving its session state+ // behind while a fresh client is built on the next call). create() already destroyed its own+ // client on the reset-throw path, so there's nothing else to clean up here.+ if (singleton === pending) {+ singleton = null;+ activeClient = null;+ }throw err;});+ singleton = pending;}return singleton;}+/**+ * Discard the current sandbox client so the next {@link getVaultSandboxClient} builds a fresh one+ * and re-handshakes. The sandbox pins its enforced session policy at the first handshake, so this+ * is how a policy tightening (enabling Strict) takes effect immediately on *every* path — including+ * the sandbox's internal auto-unlock — rather than only on the next explicit unlock. The caller is+ * responsible for reflecting the resulting locked state in the parent (see the settings dialog).+ */+export function resetVaultSandboxClient(): void {+ // Advance the generation first so any in-flight create() discards itself on completion.+ clientGeneration += 1;+ const client = activeClient;+ singleton = null;+ activeClient = null;+ client?.destroy();+}+export function getActiveVaultSandboxClient(): VaultSandboxClient | null {return activeClient;}diff --git a/ui/src/lib/vaultSandboxPolicy.test.ts b/ui/src/lib/vaultSandboxPolicy.test.tsnew file mode 100644index 000000000..855946fb4--- /dev/null+++ b/ui/src/lib/vaultSandboxPolicy.test.ts@@ -0,0 +1,140 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++// The policy module fetches `/api/vault/settings` via apiFetch; mock it so the fail-closed path is+// deterministic (the fetch outcome is controlled per test rather than depending on the environment).+vi.mock('./apiFetch', () => ({ apiFetch: vi.fn() }));++import { apiFetch } from './apiFetch';+import {+ DEFAULT_VAULT_SESSION_POLICY,+ STRICT_FALLBACK_VAULT_SESSION_POLICY,+ getVaultSandboxPolicy,+ invalidateVaultSandboxPolicy,+ isValidVaultSessionPolicyShape,+ normalizeVaultSessionPolicy,+ refreshVaultSandboxPolicy,+ resetVaultSandboxPolicyForTests,+ setVaultSandboxPolicy,+} from './vaultSandboxPolicy';++const mockedApiFetch = vi.mocked(apiFetch);++beforeEach(() => {+ resetVaultSandboxPolicyForTests();+ mockedApiFetch.mockReset();+});++afterEach(() => {+ resetVaultSandboxPolicyForTests();+});++describe('normalizeVaultSessionPolicy', () => {+ it('defaults a non-object to the safe default policy', () => {+ expect(normalizeVaultSessionPolicy(undefined)).toEqual(DEFAULT_VAULT_SESSION_POLICY);+ expect(normalizeVaultSessionPolicy(null)).toEqual(DEFAULT_VAULT_SESSION_POLICY);+ expect(normalizeVaultSessionPolicy('nope')).toEqual(DEFAULT_VAULT_SESSION_POLICY);+ });++ it('accepts only the fixed unlock-window options, else falls back to 10 min', () => {+ expect(normalizeVaultSessionPolicy({ windowSeconds: 300 }).windowSeconds).toBe(300);+ expect(normalizeVaultSessionPolicy({ windowSeconds: 600 }).windowSeconds).toBe(600);+ expect(normalizeVaultSessionPolicy({ windowSeconds: 1800 }).windowSeconds).toBe(1800);+ // Off-menu values (incl. the old 3600 option) normalize to the default.+ expect(normalizeVaultSessionPolicy({ windowSeconds: 3600 }).windowSeconds).toBe(600);+ expect(normalizeVaultSessionPolicy({ windowSeconds: 'x' }).windowSeconds).toBe(600);+ });++ it('is default-safe for the booleans — only an explicit flag weakens posture', () => {+ // strictApprovals only relaxes to true on an explicit true.+ expect(normalizeVaultSessionPolicy({ strictApprovals: true }).strictApprovals).toBe(true);+ expect(normalizeVaultSessionPolicy({ strictApprovals: 'yes' }).strictApprovals).toBe(false);+ expect(normalizeVaultSessionPolicy({}).strictApprovals).toBe(false);+ // parentValueSealAllowed only disables on an explicit false.+ expect(normalizeVaultSessionPolicy({ parentValueSealAllowed: false }).parentValueSealAllowed).toBe(false);+ expect(normalizeVaultSessionPolicy({ parentValueSealAllowed: 0 }).parentValueSealAllowed).toBe(true);+ expect(normalizeVaultSessionPolicy({}).parentValueSealAllowed).toBe(true);+ });+});++describe('policy mirror', () => {+ it('round-trips a set policy and hands back copies (no shared reference)', () => {+ const stored = setVaultSandboxPolicy({ windowSeconds: 1800, strictApprovals: true, parentValueSealAllowed: false });+ expect(stored).toEqual({ windowSeconds: 1800, strictApprovals: true, parentValueSealAllowed: false });+ const a = getVaultSandboxPolicy();+ const b = getVaultSandboxPolicy();+ expect(a).toEqual(stored);+ expect(a).not.toBe(b);+ a.strictApprovals = false;+ expect(getVaultSandboxPolicy().strictApprovals).toBe(true);+ });+});++describe('refreshVaultSandboxPolicy — fail closed', () => {+ it('adopts the daemon policy on a successful fetch', async () => {+ mockedApiFetch.mockResolvedValue({+ ok: true,+ json: async () => ({ policy: { windowSeconds: 1800, strictApprovals: true, parentValueSealAllowed: true } }),+ } as unknown as Response);+ const policy = await refreshVaultSandboxPolicy();+ expect(policy).toEqual({ windowSeconds: 1800, strictApprovals: true, parentValueSealAllowed: true });+ });++ it('fails closed to the strict fallback when the fetch fails before any confirmation', async () => {+ mockedApiFetch.mockRejectedValue(new Error('offline'));+ const policy = await refreshVaultSandboxPolicy();+ // Not the permissive default — a fetch failure on a fresh tab must not relax Strict/window.+ expect(policy).toEqual(STRICT_FALLBACK_VAULT_SESSION_POLICY);+ expect(policy.strictApprovals).toBe(true);+ expect(policy.windowSeconds).toBe(300);+ });++ it('fails closed on a non-ok response too', async () => {+ mockedApiFetch.mockResolvedValue({ ok: false, json: async () => ({}) } as unknown as Response);+ expect(await refreshVaultSandboxPolicy()).toEqual(STRICT_FALLBACK_VAULT_SESSION_POLICY);+ });++ it('fails closed on a 200 that carries no policy (malformed / app-level failure)', async () => {+ // HTTP 200 but no policy object — must not confirm the permissive default.+ mockedApiFetch.mockResolvedValue({ ok: true, json: async () => ({ ok: false }) } as unknown as Response);+ expect(await refreshVaultSandboxPolicy()).toEqual(STRICT_FALLBACK_VAULT_SESSION_POLICY);+ });++ it('fails closed on a 200 whose policy object is missing/misnamed fields', async () => {+ // A policy object that lacks the security fields would normalize to relaxed — must fail closed.+ mockedApiFetch.mockResolvedValue({ ok: true, json: async () => ({ ok: true, policy: { windowSeconds: 300 } }) } as unknown as Response);+ expect(await refreshVaultSandboxPolicy()).toEqual(STRICT_FALLBACK_VAULT_SESSION_POLICY);+ });++ it('keeps a previously-confirmed policy on a later fetch failure (no over-restriction)', async () => {+ // A prior successful set confirms the real (relaxed) policy...+ setVaultSandboxPolicy({ windowSeconds: 1800, strictApprovals: false, parentValueSealAllowed: true });+ mockedApiFetch.mockRejectedValue(new Error('offline'));+ const policy = await refreshVaultSandboxPolicy();+ // ...so a transient failure keeps it instead of forcing the strict fallback.+ expect(policy.windowSeconds).toBe(1800);+ expect(policy.strictApprovals).toBe(false);+ });++ it('invalidate drops confirmation so a post-reset fetch failure fails closed (tightening)', async () => {+ // A relaxed policy was confirmed, then a policy reset (Strict enabled elsewhere) invalidates it.+ setVaultSandboxPolicy({ windowSeconds: 1800, strictApprovals: false, parentValueSealAllowed: true });+ invalidateVaultSandboxPolicy();+ expect(getVaultSandboxPolicy()).toEqual(STRICT_FALLBACK_VAULT_SESSION_POLICY);+ mockedApiFetch.mockRejectedValue(new Error('offline'));+ // The next handshake's fetch fails — must stay strict, not re-pin the old relaxed policy.+ expect(await refreshVaultSandboxPolicy()).toEqual(STRICT_FALLBACK_VAULT_SESSION_POLICY);+ });+});++describe('isValidVaultSessionPolicyShape', () => {+ it('accepts a complete well-formed policy and rejects partial/malformed ones', () => {+ expect(isValidVaultSessionPolicyShape({ windowSeconds: 600, strictApprovals: true, parentValueSealAllowed: true })).toBe(true);+ expect(isValidVaultSessionPolicyShape({ windowSeconds: 300, strictApprovals: false, parentValueSealAllowed: false })).toBe(true);+ // Missing / wrong-typed / out-of-set fields → invalid (would otherwise normalize to relaxed).+ expect(isValidVaultSessionPolicyShape({ windowSeconds: 300 })).toBe(false);+ expect(isValidVaultSessionPolicyShape({ windowSeconds: 999, strictApprovals: true, parentValueSealAllowed: true })).toBe(false);+ expect(isValidVaultSessionPolicyShape({ strictApprovals: 'yes', windowSeconds: 600, parentValueSealAllowed: true })).toBe(false);+ expect(isValidVaultSessionPolicyShape(null)).toBe(false);+ expect(isValidVaultSessionPolicyShape(undefined)).toBe(false);+ });+});diff --git a/ui/src/lib/vaultSandboxPolicy.ts b/ui/src/lib/vaultSandboxPolicy.tsnew file mode 100644index 000000000..e33b14bc8--- /dev/null+++ b/ui/src/lib/vaultSandboxPolicy.ts@@ -0,0 +1,140 @@+import { apiFetch } from './apiFetch';++/**+ * The vault session policy the daemon persists and the sandbox enforces (protocol v2 §6.5).+ *+ * This parent-held copy is **display-only**: it is handed to the sandbox at `handshake` and+ * `unlock` so the sandbox knows the unlock-window length and whether Strict approvals is on. The+ * sandbox is the sole enforcer — never gate a real security decision on this mirror.+ */+export type VaultSessionPolicy = {+ /** Unlock-window length. One of the daemon's fixed options (5 / 10 / 30 min). */+ windowSeconds: 300 | 600 | 1800;+ /** When true, R2 (approve/reveal) behaves like R3 — a passkey every time. */+ strictApprovals: boolean;+ /** The #842 concession switch: whether newly-typed static values may be sealed via parent value. */+ parentValueSealAllowed: boolean;+};++export const DEFAULT_VAULT_SESSION_POLICY: VaultSessionPolicy = {+ windowSeconds: 600,+ strictApprovals: false,+ parentValueSealAllowed: true,+};++function normalizeWindowSeconds(value: unknown): 300 | 600 | 1800 {+ return value === 300 || value === 600 || value === 1800 ? value : DEFAULT_VAULT_SESSION_POLICY.windowSeconds;+}++/**+ * Whether a value is a *complete, well-formed* daemon policy — every field present with a valid+ * value. This is stricter than "is an object": it must be validated before confirming so a+ * malformed HTTP-200 payload (missing/misnamed fields during a skewed deploy) can't slip through+ * `normalizeVaultSessionPolicy`, which would silently default the missing security fields to the+ * relaxed values (non-strict / 10 min). A malformed policy must fail closed, not be trusted.+ */+export function isValidVaultSessionPolicyShape(value: unknown): boolean {+ if (typeof value !== 'object' || value === null) return false;+ const record = value as Record<string, unknown>;+ return (+ (record.windowSeconds === 300 || record.windowSeconds === 600 || record.windowSeconds === 1800) &&+ typeof record.strictApprovals === 'boolean' &&+ typeof record.parentValueSealAllowed === 'boolean'+ );+}++/** Coerce any daemon/settings-shaped value into a complete, safe policy object. */+export function normalizeVaultSessionPolicy(value: unknown): VaultSessionPolicy {+ if (typeof value !== 'object' || value == null) return { ...DEFAULT_VAULT_SESSION_POLICY };+ const record = value as Record<string, unknown>;+ return {+ windowSeconds: normalizeWindowSeconds(record.windowSeconds),+ // Default-safe: only an explicit `true` relaxes to Strict / only an explicit `false` disables+ // parent-value sealing, so a malformed field can never silently weaken the posture.+ strictApprovals: record.strictApprovals === true,+ parentValueSealAllowed: record.parentValueSealAllowed !== false,+ };+}++// Module-level mirror so the (non-React) sandbox client can read the latest policy at handshake+// and unlock without threading it through every call site. The settings UI updates it after a+// successful PATCH so the next unlock already runs under the new window/strict values.+let currentPolicy: VaultSessionPolicy = { ...DEFAULT_VAULT_SESSION_POLICY };+// Whether the mirror has ever been confirmed from the daemon (a successful GET, or an explicit set+// from the settings dialog). Until it has, a settings-fetch failure fails closed rather than trust+// the permissive default (see refreshVaultSandboxPolicy).+let policyConfirmed = false;++/**+ * The strictest posture, used as a fail-closed fallback when the daemon settings can't be fetched+ * before the real policy has ever been confirmed: shortest window + a passkey on every+ * approval/reveal. This ensures a settings-fetch failure on a fresh tab can never silently relax a+ * configured Strict/short-window policy down to the permissive default. `parentValueSealAllowed`+ * stays true — it gates protected static *creation* (#842), not approval posture, so failing it+ * closed would only block creation without tightening any authorization.+ */+export const STRICT_FALLBACK_VAULT_SESSION_POLICY: VaultSessionPolicy = {+ windowSeconds: 300,+ strictApprovals: true,+ parentValueSealAllowed: true,+};++export function getVaultSandboxPolicy(): VaultSessionPolicy {+ return { ...currentPolicy };+}++export function setVaultSandboxPolicy(value: unknown): VaultSessionPolicy {+ currentPolicy = normalizeVaultSessionPolicy(value);+ policyConfirmed = true;+ return getVaultSandboxPolicy();+}++// On a settings-fetch failure: keep a previously-confirmed policy (we already know the user's real+// settings, so don't over-restrict on a transient blip), but if the real policy has never been+// confirmed, assume the strict fallback instead of the permissive default so the failure can't+// quietly weaken Strict/window on a fresh tab.+function failClosedVaultSandboxPolicy(): VaultSessionPolicy {+ if (!policyConfirmed) currentPolicy = { ...STRICT_FALLBACK_VAULT_SESSION_POLICY };+ return getVaultSandboxPolicy();+}++/**+ * Refresh the parent's policy mirror from the daemon (`GET /api/vault/settings`). Called by the+ * sandbox client at handshake/unlock/setup so the ceremony runs under the configured window/strict+ * values. On failure it fails **closed** (strict fallback) until a real policy is confirmed, then+ * keeps the last-confirmed policy — a fetch failure must never relax the configured posture.+ */+export async function refreshVaultSandboxPolicy(): Promise<VaultSessionPolicy> {+ try {+ const res = await apiFetch('/api/vault/settings');+ if (!res.ok) return failClosedVaultSandboxPolicy();+ const body = (await res.json()) as { ok?: unknown; policy?: unknown };+ // Require a genuine success payload carrying a *complete, well-formed* policy before trusting+ // it. An application-level failure or a malformed policy returned as HTTP 200 (ok:false, or a+ // policy object missing/misnaming fields) must fail closed — not confirm a default via+ // normalize(), which would silently relax a configured Strict/short-window posture.+ if (body?.ok === false || !isValidVaultSessionPolicyShape(body?.policy)) {+ return failClosedVaultSandboxPolicy();+ }+ return setVaultSandboxPolicy(body.policy);+ } catch {+ return failClosedVaultSandboxPolicy();+ }+}++/**+ * Invalidate the mirror after a policy reset (a tab enabled Strict / shortened the window). Drops+ * the confirmed flag and falls back to the strict posture so that if the next handshake's settings+ * fetch fails, we don't re-pin the old *confirmed* (relaxed) policy — the reset was a tightening,+ * so failing closed is correct. A successful refresh at the next handshake replaces this.+ */+export function invalidateVaultSandboxPolicy(): void {+ currentPolicy = { ...STRICT_FALLBACK_VAULT_SESSION_POLICY };+ policyConfirmed = false;+}++/** Reset the shared mirror for tests (both the value and the confirmed flag). */+export function resetVaultSandboxPolicyForTests(): void {+ currentPolicy = { ...DEFAULT_VAULT_SESSION_POLICY };+ policyConfirmed = false;+}