Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(vaults): protected-tier approval surface + protected keypair create (#712)

Call White179a5f20f9cb
diff --git a/ui/src/components/ui/vault-approval-card.tsx b/ui/src/components/ui/vault-approval-card.tsx
new file mode 100644
index 000000000..83b91b5e9
--- /dev/null
+++ b/ui/src/components/ui/vault-approval-card.tsx
@@ -0,0 +1,418 @@
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { Check, Globe, KeyRound, Loader2, Lock, ShieldCheck, Terminal, Wallet } from 'lucide-react';
+import { useTranslation } from 'react-i18next';
+
+import { useApi, type VaultRequest } from '@/context/ApiContext';
+import { useProtectedVault, type ProtectedUnlockMaterial } from '@/lib/useProtectedVault';
+import {
+ blindBoxAgentDeliverOperationHash,
+ bytesToBase64,
+ protectedDekReleaseBlindBoxContext,
+ type BlindBox,
+ type SignatureScheme,
+} from '@/lib/vaultCrypto';
+import { cn } from '@/lib/utils';
+import { Badge } from './badge';
+import { Button } from './button';
+import { Switch } from './switch';
+import { VaultProtectedUnlock } from './vault-protected-unlock';
+
+/** The approval `card` the daemon attaches to a request's delivery payload. */
+type ScopeOption = {
+ scope_type: 'secret' | 'skill' | 'group';
+ scope_ref: string;
+ default_ttl_seconds: number;
+ ttl_options_seconds: number[];
+ session_binding_default: boolean;
+ member_count: number;
+ member_snapshot: string[];
+ /** Hydrated for UI audience: the protected members of this scope to release. */
+ unlock_material?: ProtectedUnlockMaterial[];
+};
+
+type ApprovalCard = {
+ card_type?: string;
+ request_type?: 'access' | 'sign';
+ secret_name?: string;
+ kind?: string | null;
+ protection?: string | null;
+ command?: string | null;
+ egress?: string | null;
+ session_id?: string | null;
+ scope_options?: ScopeOption[];
+ /** Hydrated for UI audience when the requested secret is protected. */
+ secret_unlock_material?: ProtectedUnlockMaterial | null;
+};
+
+export type ApprovalOutcome = { kind: 'approved' | 'denied'; requestType: 'access' | 'sign' };
+
+/** A short 0x-prefixed elision of a long hex digest. */
+function shortDigest(hex: string): string {
+ const clean = hex.startsWith('0x') ? hex.slice(2) : hex;
+ if (clean.length <= 20) return `0x${clean}`;
+ return `0x${clean.slice(0, 10)}…${clean.slice(-8)}`;
+}
+
+const PANEL = 'flex flex-col rounded-xl border border-border bg-surface';
+const ROW = 'flex items-start gap-3 px-4 py-2.5 text-sm';
+const ROW_LABEL = 'w-20 shrink-0 pt-0.5 text-xs font-medium uppercase tracking-wide text-muted';
+
+const DetailRow: React.FC<{ label: string; children: React.ReactNode }> = ({ label, children }) => (
+ <div className={ROW}>
+ <span className={ROW_LABEL}>{label}</span>
+ <div className="flex min-w-0 flex-1 flex-wrap items-center gap-1.5">{children}</div>
+ </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
+ * both handled here, upholding the cardinal invariant: protected secrets are unlocked,
+ * signed, or DEK-released entirely in the browser, and only public material (a signature
+ * or an avault-bound DEK blind box) is ever submitted to the daemon.
+ */
+export const VaultApprovalCard: React.FC<{
+ request: VaultRequest;
+ onResolved: (outcome: ApprovalOutcome) => void;
+ onCancel: () => void;
+}> = ({ request, onResolved, onCancel }) => {
+ 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` /
+ // `scope_options[].unlock_material` are present for protected requests. No fetch or
+ // loading state is needed here — the single-request GET is agent-audience (value-free).
+ const card = (request.card ?? null) as ApprovalCard | null;
+ const delivery = (request.delivery ?? {}) as { digest?: string; scheme?: string };
+ const isSign = (card?.request_type ?? request.request_type) === 'sign';
+ const isProtected = card?.protection === 'protected';
+ const isKeypair = card?.kind === 'keypair';
+ const scopeOptions = card?.scope_options ?? [];
+
+ const [scopeIdx, setScopeIdx] = useState(0);
+ const [thisSessionOnly, setThisSessionOnly] = useState(
+ () => scopeOptions.length === 0 || scopeOptions[0].session_binding_default !== false,
+ );
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const selectedOption = scopeOptions[scopeIdx];
+ const selectedMaterials = useMemo(() => selectedOption?.unlock_material ?? [], [selectedOption]);
+
+ // A request needs the browser VMK unlocked when it touches protected key material:
+ // a protected sign, or an access whose chosen scope includes protected members.
+ const needsUnlock = isSign ? isProtected : selectedMaterials.length > 0;
+ const unlocked = vault.status === 'unlocked';
+
+ useEffect(() => {
+ if (needsUnlock) void vault.refresh();
+ // vault.refresh is stable (useCallback); only re-check when unlock becomes required.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [needsUnlock]);
+
+ const finish = useCallback(
+ (run: () => Promise<void>) => {
+ setBusy(true);
+ setError(null);
+ run()
+ .catch((err: unknown) => setError(err instanceof Error ? err.message : String(err)))
+ .finally(() => setBusy(false));
+ },
+ [],
+ );
+
+ const failIfNotOk = (res: { ok: boolean; code?: string; message?: string }) => {
+ if (!res.ok) throw new Error(res.message || res.code || t('vaults.approval.errors.failed'));
+ };
+
+ const approveAccess = () =>
+ finish(async () => {
+ const option = selectedOption;
+ if (!option) throw new Error(t('vaults.approval.errors.noScope'));
+ const ttlSeconds = option.default_ttl_seconds;
+ const materials = option.unlock_material ?? [];
+ // A protected secret with no hydrated unlock material means the request was read
+ // 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'));
+ if (materials.length === 0) {
+ // Standard members only — a metadata-only scope grant, no DEK release.
+ failIfNotOk(
+ await api.createVaultGrant({
+ request_id: request.id,
+ scope_type: option.scope_type,
+ scope_ref: option.scope_ref,
+ ttl_seconds: ttlSeconds,
+ this_session_only: thisSessionOnly,
+ }),
+ );
+ } else {
+ // Protected members — release each DEK in the browser as an opaque HPKE blind box
+ // addressed to the resident avault agent, then relay only those boxes.
+ const pubkey = await api.getVaultAgentPubkey();
+ const agentPubkey = { public_key: pubkey.public_key, fingerprint: pubkey.fingerprint };
+ const expiresAtUnix = Math.floor(Date.now() / 1000) + ttlSeconds;
+ const deks: Array<{ name: string; dek_blindbox: BlindBox; approval: { nonce: string; expires_at_unix: number } }> = [];
+ for (const material of materials) {
+ const approvalNonce = crypto.getRandomValues(new Uint8Array(16));
+ const context = await protectedDekReleaseBlindBoxContext(material.name, {
+ kind: 'agent-deliver',
+ scopeType: option.scope_type,
+ scopeRef: option.scope_ref,
+ ttlSecs: ttlSeconds,
+ approval: { nonce: approvalNonce, expiresAtUnix },
+ operationHash: await blindBoxAgentDeliverOperationHash(material.name, ttlSeconds),
+ });
+ // Value access only ever releases a delivery DEK — never a signing context.
+ if (context.purpose !== 'agent-deliver') throw new Error(t('vaults.approval.errors.failed'));
+ const dekBlindbox = await vault.releaseProtectedDelivery(material, agentPubkey, context);
+ deks.push({
+ name: material.name,
+ dek_blindbox: dekBlindbox,
+ approval: { nonce: bytesToBase64(approvalNonce), expires_at_unix: expiresAtUnix },
+ });
+ }
+ failIfNotOk(
+ await api.fulfillVaultAccessRequest(request.id, {
+ scope_type: option.scope_type,
+ scope_ref: option.scope_ref,
+ ttl_seconds: ttlSeconds,
+ this_session_only: thisSessionOnly,
+ agent_pubkey: agentPubkey,
+ deks,
+ }),
+ );
+ }
+ onResolved({ kind: 'approved', requestType: 'access' });
+ });
+
+ const approveSign = () =>
+ finish(async () => {
+ const name = card?.secret_name;
+ const digest = delivery.digest;
+ const scheme = delivery.scheme;
+ if (!name || !digest || !scheme) throw new Error(t('vaults.approval.errors.missingDigest'));
+ if (isProtected) {
+ // Protected keypair: open + sign locally, submit only the public signature.
+ const material = card?.secret_unlock_material;
+ if (!material) throw new Error(t('vaults.approval.errors.missingMaterial'));
+ const sig = await vault.signProtectedRequest(material, digest, scheme as SignatureScheme);
+ const signature: Record<string, unknown> = { signature: sig.signature, browser_signed: true };
+ if (sig.recovery_id != null) signature.recovery_id = sig.recovery_id;
+ failIfNotOk(await api.signVaultDigest({ name, request_id: request.id, digest, scheme, signature }));
+ } else {
+ // Standard keypair: avault signs; we only relay the approved request.
+ failIfNotOk(await api.signVaultDigest({ name, request_id: request.id, digest, scheme }));
+ }
+ onResolved({ kind: 'approved', requestType: 'sign' });
+ });
+
+ const deny = () =>
+ finish(async () => {
+ await api.denyVaultRequest(request.id);
+ onResolved({ kind: 'denied', requestType: isSign ? 'sign' : 'access' });
+ });
+
+ // The request is provided pre-loaded (hydrated by the inbox list), so there's no async
+ // load to fail. A missing card means a malformed/non-approval request slipped through
+ // the section filter — surface an error instead of rendering a broken form.
+ if (!card) {
+ return (
+ <div className="flex flex-col gap-3">
+ <div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">
+ {t('vaults.approval.errors.loadFailed')}
+ </div>
+ <div className="flex justify-end">
+ <Button type="button" variant="ghost" onClick={onCancel}>
+ {t('vaults.approval.close')}
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ const approveDisabled = busy || (needsUnlock && !unlocked) || (!isSign && !selectedOption);
+
+ return (
+ <div className="flex flex-col gap-4">
+ {/* Header */}
+ <div className="flex items-start gap-3">
+ <div
+ className={cn(
+ 'flex size-10 shrink-0 items-center justify-center rounded-xl',
+ isSign ? 'bg-violet/10 text-violet' : 'bg-accent/10 text-accent',
+ )}
+ >
+ {isSign ? <Wallet className="size-5" /> : <KeyRound className="size-5" />}
+ </div>
+ <div className="flex flex-col gap-0.5">
+ <span className="text-sm font-semibold">
+ {isSign ? t('vaults.approval.signTitle') : t('vaults.approval.accessTitle')}
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {isSign ? t('vaults.approval.signSubtitle') : t('vaults.approval.accessSubtitle')}
+ </span>
+ </div>
+ </div>
+
+ {/* Details */}
+ <div className={PANEL}>
+ <DetailRow label={isSign ? t('vaults.approval.key') : t('vaults.approval.secret')}>
+ <span className="truncate font-mono text-sm font-semibold">{card.secret_name}</span>
+ {isProtected ? (
+ <Badge variant="warning">{t('vaults.protected')}</Badge>
+ ) : (
+ <Badge variant="secondary">{t('vaults.standard')}</Badge>
+ )}
+ {isKeypair ? (
+ <Badge variant="outline" className="border-violet/40 bg-violet-soft text-violet">
+ <Wallet className="size-3" />
+ {t('vaults.signing')}
+ </Badge>
+ ) : null}
+ </DetailRow>
+ {card.session_id ? (
+ <>
+ <div className="h-px bg-border" />
+ <DetailRow label={t('vaults.approval.session')}>
+ <span className="truncate font-mono text-xs text-foreground">{card.session_id}</span>
+ </DetailRow>
+ </>
+ ) : null}
+ {!isSign && card.command ? (
+ <>
+ <div className="h-px bg-border" />
+ <DetailRow label={t('vaults.approval.command')}>
+ <span className="flex items-center gap-1.5 truncate rounded-md bg-surface-2 px-2 py-1 font-mono text-xs">
+ <Terminal className="size-3 shrink-0 text-muted" />
+ {card.command}
+ </span>
+ </DetailRow>
+ </>
+ ) : null}
+ {!isSign && card.egress ? (
+ <>
+ <div className="h-px bg-border" />
+ <DetailRow label={t('vaults.approval.egress')}>
+ <span className="flex items-center gap-1.5 text-xs text-muted">
+ <Globe className="size-3 shrink-0" />
+ {card.egress}
+ </span>
+ </DetailRow>
+ </>
+ ) : null}
+ {isSign && delivery.digest ? (
+ <>
+ <div className="h-px bg-border" />
+ <DetailRow label={t('vaults.approval.digest')}>
+ <span className="truncate font-mono text-xs text-foreground" title={delivery.digest}>
+ {shortDigest(delivery.digest)}
+ </span>
+ {delivery.scheme ? <Badge variant="secondary">{delivery.scheme}</Badge> : null}
+ </DetailRow>
+ </>
+ ) : null}
+ </div>
+
+ {/* Approval scope (access only) */}
+ {!isSign && scopeOptions.length > 0 ? (
+ <div className="flex flex-col gap-2">
+ <span className="px-1 text-xs font-semibold uppercase tracking-wide text-muted">
+ {t('vaults.approval.scopeTitle')}
+ </span>
+ <div className="flex flex-col gap-2">
+ {scopeOptions.map((option, idx) => {
+ const selected = idx === scopeIdx;
+ return (
+ <button
+ key={`${option.scope_type}:${option.scope_ref}`}
+ type="button"
+ aria-pressed={selected}
+ onClick={() => setScopeIdx(idx)}
+ className={cn(
+ 'flex items-start gap-3 rounded-xl border p-3 text-left transition-colors',
+ selected ? 'border-mint bg-mint-soft' : 'border-border bg-surface hover:bg-surface-2',
+ )}
+ >
+ <span
+ className={cn(
+ 'mt-0.5 flex size-4 shrink-0 items-center justify-center rounded-full border',
+ selected ? 'border-mint bg-mint text-background' : 'border-border-strong',
+ )}
+ >
+ {selected ? <Check className="size-3" /> : null}
+ </span>
+ <span className="flex min-w-0 flex-col gap-0.5">
+ <span className="flex flex-wrap items-center gap-1.5 text-sm font-medium">
+ {t(`vaults.approval.scope.${option.scope_type}`, { ref: option.scope_ref })}
+ <Badge variant="secondary">{ttlLabel(option.default_ttl_seconds)}</Badge>
+ </span>
+ <span className="text-xs text-muted-foreground">
+ {t('vaults.approval.scopeMembers', { count: option.member_count })}
+ </span>
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </div>
+ ) : null}
+
+ {/* Protected unlock + invariant note */}
+ {needsUnlock ? (
+ <div className="flex flex-col gap-2">
+ <VaultProtectedUnlock vault={vault} />
+ <span className="flex items-center gap-1.5 rounded-lg border border-mint/40 bg-mint-soft px-3 py-2 text-xs text-mint">
+ <Lock className="size-3.5 shrink-0" />
+ {isSign ? t('vaults.approval.signNote') : t('vaults.approval.accessNote')}
+ </span>
+ </div>
+ ) : null}
+
+ {error ? (
+ <div className="rounded-lg border border-destructive/40 bg-destructive/10 px-3 py-2 text-sm text-destructive">
+ {error}
+ </div>
+ ) : null}
+
+ {/* Footer */}
+ <div className="flex items-center gap-3">
+ {!isSign ? (
+ <label className="flex items-center gap-2 text-xs font-medium text-muted">
+ <Switch
+ checked={thisSessionOnly}
+ onCheckedChange={setThisSessionOnly}
+ label={t('vaults.approval.thisSessionOnly')}
+ disabled={busy}
+ />
+ {t('vaults.approval.thisSessionOnly')}
+ </label>
+ ) : null}
+ <div className="ml-auto flex items-center gap-2">
+ <Button type="button" variant="ghost" onClick={deny} disabled={busy}>
+ {t('vaults.approval.deny')}
+ </Button>
+ <Button type="button" onClick={isSign ? approveSign : approveAccess} disabled={approveDisabled}>
+ {busy ? <Loader2 className="size-4 animate-spin" /> : <ShieldCheck className="size-4" />}
+ {isSign ? t('vaults.approval.sign') : t('vaults.approval.approve')}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
+};
diff --git a/ui/src/components/ui/vault-secret-form.tsx b/ui/src/components/ui/vault-secret-form.tsx
index 72418e0fc..75c359a9a 100644
--- a/ui/src/components/ui/vault-secret-form.tsx
+++ b/ui/src/components/ui/vault-secret-form.tsx
@@ -180,13 +180,6 @@ export const VaultSecretForm: React.FC<{
setCopied(false);
};
- // Signing keys are sealed in the browser and signed locally by avault, so they
- // require the P2 avault surface and (this version) the standard tier; the
- // protected tier's browser signing sandbox lands next version.
- useEffect(() => {
- if (isKeypair && protection !== 'standard') setProtection('standard');
- }, [isKeypair, protection]);
-
// Zero any held private key when the form unmounts.
useEffect(
() => () => {
@@ -197,7 +190,10 @@ export const VaultSecretForm: React.FC<{
);
const valueReady = isKeypair ? signingKey != null : Boolean(value);
- const keypairRequirementsMet = !isKeypair || p2Ready;
+ // Standard signing keys are blind-boxed to avault, so they need the P2 surface;
+ // protected signing keys are sealed under the browser VMK and signed locally, so they
+ // only need the vault unlocked (gated below via protectedCreateReady).
+ const keypairRequirementsMet = !isKeypair || protection === 'protected' || p2Ready;
const canSubmit =
Boolean(secretName && valueReady) &&
keypairRequirementsMet &&
@@ -251,8 +247,9 @@ export const VaultSecretForm: React.FC<{
| { value: string };
let establishingVmk = false;
if (protection === 'protected') {
- // Browser-sealed under the session VMK; the daemon stores it opaquely (no avault, no plaintext).
- const sealed = await protectedVault.sealValue(secretName, value);
+ // Browser-sealed under the session VMK; the daemon stores it opaquely (no avault, no
+ // plaintext). For a signing key this seals the raw 32-byte private key, not a string.
+ const sealed = await protectedVault.sealValue(secretName, plaintext);
cryptoFields = { sealed: sealed.envelope };
establishingVmk = sealed.establishingVmk;
} else if (p2Ready) {
@@ -482,7 +479,7 @@ export const VaultSecretForm: React.FC<{
{signingError && <span className="text-xs text-destructive">{signingError}</span>}
- {!p2Ready && (
+ {!p2Ready && protection !== 'protected' && (
<div className="rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-xs text-warning">
{t('vaults.dialog.signingNeedsAvault', { version: AVAULT_P2_MIN_VERSION })}
</div>
@@ -562,21 +559,14 @@ export const VaultSecretForm: React.FC<{
] as const
).map(({ key, icon: Icon, title, desc }) => {
const selected = protection === key;
- // Protected signing keys need the browser signing sandbox (next version),
- // so the protected tier is disabled while creating a keypair.
- const optionDisabled = key === 'protected' && isKeypair;
return (
<button
key={key}
type="button"
aria-pressed={selected}
- disabled={optionDisabled}
- onClick={() => {
- if (!optionDisabled) setProtection(key);
- }}
+ onClick={() => setProtection(key)}
className={cn(
'flex flex-col gap-1.5 rounded-lg border p-3 text-left transition-colors',
- optionDisabled && 'cursor-not-allowed opacity-50',
selected ? 'border-mint bg-mint-soft' : 'border-border bg-surface hover:bg-surface-2',
)}
>
@@ -589,9 +579,6 @@ export const VaultSecretForm: React.FC<{
);
})}
</div>
- {isKeypair && (
- <span className="text-xs font-normal text-muted-foreground">{t('vaults.dialog.protectedKeypairNextVersion')}</span>
- )}
</div>
{protection === 'protected' && <VaultProtectedUnlock vault={protectedVault} />}
{protection === 'standard' && checkingAvault && (
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index c684fd87c..8d33c88e3 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -1,13 +1,14 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
-import { Check, Clock, Copy, History, KeyRound, Layers, Loader2, Plus, Puzzle, RefreshCw, ShieldCheck, ShieldOff, Trash2, Wallet } from 'lucide-react';
+import { Check, Clock, Copy, History, Inbox, KeyRound, Layers, Loader2, Plus, Puzzle, RefreshCw, ShieldCheck, ShieldOff, Trash2, Wallet } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { CapabilityTabs } from './CapabilityTabs';
import { WorkbenchPageHeader } from './WorkbenchPageHeader';
import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '../ui/dialog';
-import { useApi, type VaultAuditEvent, type VaultGrant, type VaultSecret } from '../../context/ApiContext';
+import { useApi, type VaultAuditEvent, type VaultGrant, type VaultRequest, type VaultSecret } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
+import { VaultApprovalCard, type ApprovalOutcome } from '../ui/vault-approval-card';
import { VaultSecretForm } from '../ui/vault-secret-form';
const AddSecretDialog: React.FC<{
@@ -172,6 +173,132 @@ const GrantRow: React.FC<{ grant: VaultGrant; now: number; onRevoke: (grant: Vau
);
};
+/** A compact pending-request row: who is asking, for what, with a Review action. */
+const RequestRow: React.FC<{ request: VaultRequest; onReview: (request: VaultRequest) => void }> = ({ request: r, onReview }) => {
+ const { t } = useTranslation();
+ const card = (r.card ?? {}) as { request_type?: string; kind?: string; protection?: string; session_id?: string };
+ const isSign = (card.request_type ?? r.request_type) === 'sign';
+ const isProtected = card.protection === 'protected';
+ const Icon = isSign || card.kind === 'keypair' ? Wallet : KeyRound;
+ return (
+ <div className="flex items-center gap-3.5 rounded-xl border border-gold/40 bg-gold/[0.06] px-4 py-3">
+ <div className="flex size-9 shrink-0 items-center justify-center rounded-lg bg-gold/10 text-gold">
+ <Icon className="size-4" />
+ </div>
+ <div className="flex min-w-0 flex-col gap-1">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="truncate font-mono text-sm font-semibold">{r.secret_name}</span>
+ <Badge variant="info">{isSign ? t('vaults.requests.sign') : t('vaults.requests.access')}</Badge>
+ {isProtected ? <Badge variant="warning">{t('vaults.protected')}</Badge> : null}
+ </div>
+ <span className="flex items-center gap-1.5 text-xs text-muted">
+ <Clock className="size-3" />
+ {t('vaults.requests.waiting')}
+ {card.session_id ? (
+ <>
+ <span aria-hidden>·</span>
+ <span className="truncate font-mono">{card.session_id}</span>
+ </>
+ ) : null}
+ </span>
+ </div>
+ <div className="ml-auto">
+ <Button size="sm" onClick={() => onReview(r)}>
+ {t('vaults.requests.review')}
+ </Button>
+ </div>
+ </div>
+ );
+};
+
+/**
+ * Pending approvals strip for the hub: lists requests an agent is waiting on, polls for
+ * new ones, and opens the full {@link VaultApprovalCard} in a dialog to approve or deny.
+ * Best-effort — a requests fetch failure (e.g. an older backend without the route) must
+ * not surface an error or blank the rest of the hub.
+ */
+const PendingRequestsSection: React.FC<{ onResolved: () => void }> = ({ onResolved }) => {
+ const { t } = useTranslation();
+ const api = useApi();
+ const { showToast } = useToast();
+ const [requests, setRequests] = useState<VaultRequest[]>([]);
+ const [reviewing, setReviewing] = useState<VaultRequest | null>(null);
+
+ const load = useCallback(async () => {
+ try {
+ // Best-effort with suppressed errors so an older backend without the route doesn't
+ // spam global toasts on every 5s poll. Only approval (access/sign) requests render
+ // here — a provision request ($NAME secure-input) has no grant scope and would show
+ // a broken Review row, so filter it out.
+ const res = await api.getVaultRequests({ status: 'pending' }, { handleError: false });
+ const pending = (res.requests ?? []).filter((r) => {
+ const type = (r.card as { request_type?: string } | null)?.request_type ?? r.request_type;
+ return type === 'access' || type === 'sign';
+ });
+ setRequests(pending);
+ } catch {
+ setRequests([]);
+ }
+ }, [api]);
+
+ // Poll so a request an agent raises while the hub is open appears without a manual refresh.
+ useEffect(() => {
+ load();
+ const id = setInterval(load, 5000);
+ return () => clearInterval(id);
+ }, [load]);
+
+ const handleOutcome = useCallback(
+ (outcome: ApprovalOutcome) => {
+ // Drop the row immediately so it doesn't linger behind the poll; the next load
+ // reconciles against the server.
+ if (reviewing) setRequests((prev) => prev.filter((r) => r.id !== reviewing.id));
+ setReviewing(null);
+ const key =
+ outcome.kind === 'denied'
+ ? 'vaults.requests.denied'
+ : outcome.requestType === 'sign'
+ ? 'vaults.requests.signed'
+ : 'vaults.requests.approved';
+ showToast(t(key), outcome.kind === 'denied' ? 'warning' : 'success');
+ load();
+ onResolved();
+ },
+ [reviewing, showToast, t, load, onResolved],
+ );
+
+ if (requests.length === 0) return null;
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center gap-2 px-1">
+ <Inbox className="size-4 text-gold" />
+ <span className="text-sm font-semibold">{t('vaults.requests.title')}</span>
+ <Badge variant="warning">{requests.length}</Badge>
+ <span className="hidden text-xs text-muted sm:inline">{t('vaults.requests.subtitle')}</span>
+ </div>
+ {requests.map((r) => (
+ <RequestRow key={r.id} request={r} onReview={setReviewing} />
+ ))}
+ <Dialog
+ open={reviewing != null}
+ onOpenChange={(o) => {
+ if (!o) setReviewing(null);
+ }}
+ >
+ <DialogContent>
+ <DialogHeader>
+ <DialogTitle>{t('vaults.requests.reviewTitle')}</DialogTitle>
+ </DialogHeader>
+ {reviewing != null ? (
+ <VaultApprovalCard key={reviewing.id} request={reviewing} onResolved={handleOutcome} onCancel={() => setReviewing(null)} />
+ ) : null}
+ </DialogContent>
+ </Dialog>
+ </div>
+ );
+};
+
export const VaultsPage: React.FC = () => {
const { t } = useTranslation();
const api = useApi();
@@ -300,6 +427,7 @@ export const VaultsPage: React.FC = () => {
{error && (
<div className="rounded-xl border border-destructive/40 bg-destructive/10 px-4 py-3 text-sm text-destructive">{error}</div>
)}
+ <PendingRequestsSection onResolved={refresh} />
{grants.length > 0 && (
<div className="flex flex-col gap-2">
<div className="flex items-center gap-2 px-1">
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 464155ae0..694e8230f 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -79,6 +79,24 @@ type VaultBlindBox = {
ct: string;
};
+/**
+ * Browser-relayed protected access fulfillment. The browser releases each protected
+ * DEK as an opaque HPKE blind box addressed to the resident avault agent and submits
+ * ONLY `{name, dek_blindbox, approval}` per secret — never a raw DEK or plaintext.
+ * Mirrors the backend contract in PR #711 so the two additions dedupe cleanly on merge.
+ */
+export type VaultAccessFulfillmentPayload = {
+ scope_type?: 'secret' | 'skill' | 'group';
+ scope_ref?: string;
+ session_id?: string | null;
+ ttl_seconds?: number;
+ this_session_only?: boolean;
+ agent_pubkey?: { public_key?: string; fingerprint?: string };
+ deks?: Array<{ name: string; dek_blindbox: VaultBlindBox; approval: Record<string, unknown> }>;
+ agent_deks?: Array<{ name: string; dek_blindbox: VaultBlindBox; approval: Record<string, unknown> }>;
+ deks_by_secret?: Record<string, { dek_blindbox: VaultBlindBox; approval: Record<string, unknown> } | VaultBlindBox>;
+};
+
type VaultSealedEnvelope = {
ciphertext: string;
nonce: string;
@@ -329,7 +347,9 @@ export type ApiContextType = {
getVaultAgentPubkey: () => Promise<{ ok: boolean; public_key: string; fingerprint: string }>;
createVaultSecret: (payload: VaultCreatePayload, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; secret?: VaultSecret; code?: string; message?: string }>;
deleteVaultSecret: (name: string) => Promise<{ ok: boolean; removed?: boolean; code?: string; message?: string }>;
- getVaultRequests: (params?: { status?: string; type?: string; limit?: number }) => Promise<{ ok: boolean; requests: VaultRequest[] }>;
+ getVaultRequests: (params?: { status?: string; type?: string; limit?: number }, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; requests: VaultRequest[] }>;
+ denyVaultRequest: (requestId: string) => Promise<{ ok: boolean; request?: VaultRequest; code?: string; message?: string }>;
+ fulfillVaultAccessRequest: (requestId: string, payload: VaultAccessFulfillmentPayload) => Promise<{ ok: boolean; request_id?: string; grant?: VaultGrant; result?: { type: string; grant?: VaultGrant }; code?: string; message?: string }>;
getVaultGrants: (params?: { status?: string; sessionId?: string }, opts?: { handleError?: boolean }) => Promise<{ ok: boolean; grants: VaultGrant[] }>;
createVaultGrant: (payload: Record<string, unknown>) => Promise<{ ok: boolean; grant: VaultGrant; code?: string; message?: string }>;
fulfillVaultAccessRequest: (requestId: string, payload: VaultAccessFulfillmentPayload) => Promise<{ ok: boolean; request_id?: string; grant?: VaultGrant; result?: { type: string; grant?: VaultGrant }; code?: string; message?: string }>;
@@ -2040,14 +2060,17 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
getVaultAgentPubkey: () => getCachedJson('/api/vault/agent/pubkey', 1500),
createVaultSecret: (payload, opts) => postJson('/api/vault/secrets', payload, opts),
deleteVaultSecret: (name) => deleteJson(`/api/vault/secrets/${encodeURIComponent(name)}`),
- getVaultRequests: (params) => {
+ getVaultRequests: (params, opts) => {
const search = new URLSearchParams();
if (params?.status) search.set('status', params.status);
if (params?.type) search.set('type', params.type);
if (params?.limit) search.set('limit', String(params.limit));
const qs = search.toString();
- return getCachedJson(qs ? `/api/vault/requests?${qs}` : '/api/vault/requests', 1500);
+ return getCachedJson(qs ? `/api/vault/requests?${qs}` : '/api/vault/requests', 1500, opts);
},
+ denyVaultRequest: (requestId) => postJson(`/api/vault/requests/${encodeURIComponent(requestId)}/deny`, {}),
+ fulfillVaultAccessRequest: (requestId, payload) =>
+ postJson(`/api/vault/requests/${encodeURIComponent(requestId)}/fulfill-access`, payload),
getVaultGrants: (params, opts) => {
const search = new URLSearchParams();
if (params?.status) search.set('status', params.status);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c05b16ffe..cea533fa0 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2208,7 +2208,7 @@
"kindStaticHelp": "A token, password, or any text value.",
"kindKeypair": "Signing key",
"kindKeypairHelp": "A signing key generated in your browser.",
- "signingKeyHelp": "A new secp256k1 signing key is created in your browser. The private key is sealed like any other standard secret and avault signs with it locally; only the public key is stored in the clear.",
+ "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.",
"signingGenerate": "Generate",
"signingImport": "Import",
"signingGenerateCta": "Generate signing key",
@@ -2218,7 +2218,6 @@
"copyPublicKey": "Copy public key",
"signingPublicKeyHint": "Share this public key freely. The private key never leaves your vault, and the chain and signature scheme are chosen at signing time.",
"signingNeedsAvault": "Signing keys need avault {{version}} or newer installed.",
- "protectedKeypairNextVersion": "Protected signing keys arrive with the browser signing sandbox (next version).",
"checkingAvault": "Checking avault…",
"p2Unavailable": "Browser-side vault create requires avault {{version}} or newer. Installed: {{installed}}. Use the CLI stdin/file path until a compatible avault release is installed.",
"p2UnavailableStandardFallback": "Browser-side sealing requires avault {{version}} or newer. Installed: {{installed}}. Standard secrets can still be saved through the local avault seal fallback.",
@@ -2253,6 +2252,53 @@
"secretExists": "A secret with this name already exists."
}
},
+ "requests": {
+ "title": "Pending requests",
+ "subtitle": "An agent is waiting — approve or deny from this device.",
+ "reviewTitle": "Review request",
+ "review": "Review",
+ "waiting": "Waiting for approval",
+ "access": "Use secret",
+ "sign": "Sign",
+ "approved": "Access approved",
+ "signed": "Signature returned",
+ "denied": "Request denied"
+ },
+ "approval": {
+ "accessTitle": "Agent wants to use a secret",
+ "accessSubtitle": "The value is never shown to the agent or the chat.",
+ "signTitle": "Agent wants to sign",
+ "signSubtitle": "Signing is always per-use — it can't be pre-approved.",
+ "secret": "Secret",
+ "key": "Key",
+ "session": "Session",
+ "command": "Command",
+ "egress": "Egress",
+ "digest": "Digest",
+ "scopeTitle": "Approval scope",
+ "scopeMembers": "Covers {{count}} secrets",
+ "scope": {
+ "secret": "This secret only",
+ "skill": "Skill · {{ref}}",
+ "group": "Group · {{ref}}"
+ },
+ "thisSessionOnly": "This session only",
+ "approve": "Approve",
+ "sign": "Sign",
+ "deny": "Deny",
+ "close": "Close",
+ "ttlMinutes": "{{count}} min",
+ "ttlHours": "{{count}} h",
+ "accessNote": "The secret is unlocked in your browser and delivered inside avault — Python never sees it.",
+ "signNote": "The private key never leaves your browser — only the signature is returned.",
+ "errors": {
+ "failed": "Couldn't complete the approval. Please try again.",
+ "loadFailed": "Couldn't load this request. It may have been handled already.",
+ "noScope": "This request has no grantable scope.",
+ "missingDigest": "This sign request is missing its digest.",
+ "missingMaterial": "Protected key material wasn't available to sign. Reload and try again."
+ }
+ },
"request": {
"provide": "provide",
"fulfilled": "provided",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 01d9bdda4..c4c9a68a6 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2207,7 +2207,7 @@
"kindStaticHelp": "令牌、密码,或任意文本值。",
"kindKeypair": "签名密钥",
"kindKeypairHelp": "在你浏览器里生成的签名私钥。",
- "signingKeyHelp": "会在你的浏览器里新生成一把 secp256k1 签名密钥。私钥像其他标准密钥一样被封存、由本机 avault 签名;只有公钥明文保存。",
+ "signingKeyHelp": "会在你的浏览器里新生成一把 secp256k1 签名密钥。私钥在浏览器中封存——标准密钥由本机 avault 签名,保护层密钥在浏览器中签名——只有公钥明文保存。",
"signingGenerate": "生成",
"signingImport": "导入",
"signingGenerateCta": "生成签名密钥",
@@ -2217,7 +2217,6 @@
"copyPublicKey": "复制公钥",
"signingPublicKeyHint": "公钥可以放心分享。私钥始终留在你的保险库里;用哪条链、哪种签名方案,在签名时再定。",
"signingNeedsAvault": "签名密钥需要安装 avault {{version}} 或更新版本。",
- "protectedKeypairNextVersion": "保护层签名密钥将随浏览器签名沙箱在下个版本到来。",
"checkingAvault": "正在检查 avault…",
"p2Unavailable": "浏览器侧保险库创建需要 avault {{version}} 或更新版本。当前安装:{{installed}}。在兼容的 avault 发布版安装前,请使用 CLI stdin/file 路径。",
"p2UnavailableStandardFallback": "浏览器侧封装需要 avault {{version}} 或更新版本。当前安装:{{installed}}。标准密钥仍可通过本机 avault seal fallback 保存。",
@@ -2252,6 +2251,53 @@
"secretExists": "同名密钥已存在。"
}
},
+ "requests": {
+ "title": "待处理请求",
+ "subtitle": "有 Agent 正在等待——在本设备上批准或拒绝。",
+ "reviewTitle": "审阅请求",
+ "review": "审阅",
+ "waiting": "等待批准",
+ "access": "使用密钥",
+ "sign": "签名",
+ "approved": "已批准访问",
+ "signed": "已返回签名",
+ "denied": "已拒绝请求"
+ },
+ "approval": {
+ "accessTitle": "Agent 想使用一个密钥",
+ "accessSubtitle": "密钥值绝不会展示给 Agent 或聊天。",
+ "signTitle": "Agent 想要签名",
+ "signSubtitle": "签名始终按次进行——无法预先批准。",
+ "secret": "密钥",
+ "key": "密钥",
+ "session": "会话",
+ "command": "命令",
+ "egress": "出网",
+ "digest": "摘要",
+ "scopeTitle": "授权范围",
+ "scopeMembers": "覆盖 {{count}} 个密钥",
+ "scope": {
+ "secret": "仅此密钥",
+ "skill": "技能 · {{ref}}",
+ "group": "分组 · {{ref}}"
+ },
+ "thisSessionOnly": "仅限本会话",
+ "approve": "批准",
+ "sign": "签名",
+ "deny": "拒绝",
+ "close": "关闭",
+ "ttlMinutes": "{{count}} 分钟",
+ "ttlHours": "{{count}} 小时",
+ "accessNote": "密钥在你的浏览器中解锁、在 avault 内交付——Python 永远看不到它。",
+ "signNote": "私钥绝不会离开你的浏览器——只返回签名。",
+ "errors": {
+ "failed": "批准未能完成,请重试。",
+ "loadFailed": "无法加载该请求,它可能已被处理。",
+ "noScope": "该请求没有可授权的范围。",
+ "missingDigest": "该签名请求缺少摘要。",
+ "missingMaterial": "无法获取用于签名的保护层密钥材料,请重新加载后重试。"
+ }
+ },
"request": {
"provide": "填写",
"fulfilled": "已提供",
diff --git a/ui/src/lib/useProtectedVault.ts b/ui/src/lib/useProtectedVault.ts
index aa2ab3a80..31596071d 100644
--- a/ui/src/lib/useProtectedVault.ts
+++ b/ui/src/lib/useProtectedVault.ts
@@ -9,12 +9,31 @@ import {
newVmk,
packProtectedRecord,
passkeyPrfSaltEntries,
+ releaseProtectedDek,
sealProtected,
+ signProtectedDigest,
+ unpackProtectedRecord,
unwrapVmk,
webAuthnPrfExtensionInput,
+ type AvaultPublicKey,
+ type BlindBox,
+ type ProtectedDekDeliveryBlindBoxContext,
type ProtectedRecordEnvelope,
+ type SignatureResult,
+ type SignatureScheme,
} from './vaultCrypto';
+/**
+ * The protected envelope + name the daemon hydrates onto a UI-audience request card
+ * (`card.secret_unlock_material` / `scope_options[].unlock_material[]`). It is value-free
+ * metadata; the browser opens it locally with the unlocked VMK to sign or release a DEK.
+ */
+export type ProtectedUnlockMaterial = {
+ name: string;
+ kind?: string | null;
+ envelope: ProtectedRecordEnvelope;
+};
+
/**
* Protected-tier vault lifecycle for the Web UI.
*
@@ -222,12 +241,17 @@ export function useProtectedVault() {
commit(await unwrapVmk(wrapMeta, { kind: 'passkey', prfOutput, prfSalt }), wrapMeta, false);
}, []);
- /** Seal a value under the unlocked VMK into a stored protected envelope. */
+ /**
+ * Seal a value under the unlocked VMK into a stored protected envelope. Accepts a
+ * string (static secret) or raw bytes (a keypair's 32-byte private key), so protected
+ * signing keys seal the key material itself, not a UTF-8 string.
+ */
const sealValue = useCallback(
- async (name: string, value: string): Promise<{ envelope: ProtectedRecordEnvelope; establishingVmk: boolean }> => {
+ async (name: string, value: Uint8Array | string): Promise<{ envelope: ProtectedRecordEnvelope; establishingVmk: boolean }> => {
const { vmk, wrapMeta, freshSetup } = sessionVault;
if (!vmk || !wrapMeta) throw new Error('vault-locked');
- const sealed = await sealProtected(new TextEncoder().encode(value), vmk, { name });
+ const valueBytes = typeof value === 'string' ? new TextEncoder().encode(value) : value;
+ const sealed = await sealProtected(valueBytes, vmk, { name });
// `establishingVmk` lets the create transaction enforce the atomic single-init
// guard server-side (a UI re-check here can't be race-free); the daemon rejects a
// second VMK so concurrent first-time setups can't split the key history.
@@ -241,6 +265,42 @@ export function useProtectedVault() {
sessionVault.freshSetup = false;
}, []);
+ /**
+ * Sign a digest locally with a protected keypair, approving a per-use sign request.
+ * The private key is opened from the request's unlock material under the cached VMK,
+ * used, and zeroed inside {@link signProtectedDigest} — only the public signature
+ * leaves the browser. The VMK never escapes this module.
+ */
+ const signProtectedRequest = useCallback(
+ async (material: ProtectedUnlockMaterial, digest: string, scheme: SignatureScheme): Promise<SignatureResult> => {
+ const { vmk } = sessionVault;
+ if (!vmk) throw new Error('vault-locked');
+ const { sealed } = unpackProtectedRecord(material.envelope);
+ return signProtectedDigest(sealed, vmk, { name: material.name }, digest, scheme);
+ },
+ [],
+ );
+
+ /**
+ * Release a protected secret's DEK as an opaque HPKE blind box addressed to the
+ * resident avault agent, approving a protected value-access request. The released DEK
+ * is sealed to the agent's pinned public key inside {@link releaseProtectedDek}; the
+ * daemon only ever relays the resulting blind box, never a raw DEK or plaintext.
+ */
+ const releaseProtectedDelivery = useCallback(
+ async (
+ material: ProtectedUnlockMaterial,
+ publicKey: AvaultPublicKey,
+ context: ProtectedDekDeliveryBlindBoxContext,
+ ): Promise<BlindBox> => {
+ const { vmk } = sessionVault;
+ if (!vmk) throw new Error('vault-locked');
+ const { sealed } = unpackProtectedRecord(material.envelope);
+ return releaseProtectedDek(sealed, vmk, publicKey, { name: material.name }, context);
+ },
+ [],
+ );
+
const lock = useCallback(() => {
sessionVault.vmk?.fill(0);
sessionVault.vmk = null;
@@ -301,5 +361,5 @@ export function useProtectedVault() {
}
}, []);
- return { status, error, setError, refresh, setupPassword, setupPasskey, unlockPassword, unlockPasskey, sealValue, afterCreated, lock, discardAndRefresh, hasPasskey, hasPassword, passkeyUsableHere };
+ return { status, error, setError, refresh, setupPassword, setupPasskey, unlockPassword, unlockPasskey, sealValue, signProtectedRequest, releaseProtectedDelivery, afterCreated, lock, discardAndRefresh, hasPasskey, hasPassword, passkeyUsableHere };
}