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.

refactor(vault): passkey-only protected vaults — drop the password factor (frontend) (#822)

Call White76017d63dd38
diff --git a/ui/package-lock.json b/ui/package-lock.json
index a5cb47286..4e596f255 100644
--- a/ui/package-lock.json
+++ b/ui/package-lock.json
@@ -30,7 +30,6 @@
"cmdk": "^1.1.1",
"docx-preview": "^0.3.7",
"framer-motion": "^12.26.2",
- "hash-wasm": "^4.12.0",
"i18next": "^25.7.4",
"i18next-browser-languagedetector": "^8.2.0",
"lexical": "^0.45.0",
@@ -4073,12 +4072,6 @@
"node": ">=8"
}
},
- "node_modules/hash-wasm": {
- "version": "4.12.0",
- "resolved": "https://registry.npmjs.org/hash-wasm/-/hash-wasm-4.12.0.tgz",
- "integrity": "sha512-+/2B2rYLb48I/evdOIhP+K/DD2ca2fgBjp6O+GBEnCDk2e4rpeXIK8GvIyRPjTezgmWn9gmKwkQjjx6BtqDHVQ==",
- "license": "MIT"
- },
"node_modules/hast-util-to-html": {
"version": "9.0.5",
"resolved": "https://registry.npmjs.org/hast-util-to-html/-/hast-util-to-html-9.0.5.tgz",
diff --git a/ui/package.json b/ui/package.json
index aa6857df8..941113da5 100644
--- a/ui/package.json
+++ b/ui/package.json
@@ -37,7 +37,6 @@
"cmdk": "^1.1.1",
"docx-preview": "^0.3.7",
"framer-motion": "^12.26.2",
- "hash-wasm": "^4.12.0",
"i18next": "^25.7.4",
"i18next-browser-languagedetector": "^8.2.0",
"lexical": "^0.45.0",
diff --git a/ui/src/components/ui/vault-protected-unlock.tsx b/ui/src/components/ui/vault-protected-unlock.tsx
index 171666221..7a5b06787 100644
--- a/ui/src/components/ui/vault-protected-unlock.tsx
+++ b/ui/src/components/ui/vault-protected-unlock.tsx
@@ -1,5 +1,5 @@
import { useState } from 'react';
-import { KeyRound, Loader2, Lock, RefreshCw, ScanFace, ShieldCheck, Sparkles } from 'lucide-react';
+import { Loader2, Lock, RefreshCw, ScanFace, ShieldCheck, Sparkles } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import type { TFunction } from 'i18next';
@@ -7,7 +7,6 @@ import { webauthnAvailable } from '@/lib/useProtectedVault';
import type { useProtectedVault } from '@/lib/useProtectedVault';
import { Badge } from './badge';
import { Button } from './button';
-import { Input } from './input';
type Vault = ReturnType<typeof useProtectedVault>;
@@ -31,14 +30,10 @@ const PANEL = 'flex flex-col gap-4 rounded-2xl border border-border bg-surface p
/**
* Protected-tier setup / unlock panel — design.pen frames `kAmWj` (setup) and `g5Q7F`
- * (unlock). Setup leads with a single recommended passkey path and progressively reveals
- * the recoverable password fields behind a "Use a password instead" link; unlock leads
- * with passkey and reveals password the same way. Both are form-free: the panel often
- * lives inside the create dialog's own `<form>`, so a nested `<form>` here would be invalid
- * HTML and (in practice) trigger a full-page reload. Every action is a button `onClick`.
- *
- * Password is always the recovery root in the crypto layer; a passkey is the quick primary
- * unlock added on top. The unlocked VMK is cached for the session by {@link useProtectedVault}.
+ * (unlock). The panel is form-free: it often lives inside the create dialog's own `<form>`,
+ * so a nested `<form>` here would be invalid HTML and (in practice) trigger a full-page reload.
+ * Every action is a button `onClick`. The unlocked VMK is cached for the session by
+ * {@link useProtectedVault}.
*
* `secretName` is shown in the unlock subtitle ("<NAME> is protected …"); it is optional
* because the create-dialog gating step has no single secret name yet.
@@ -49,14 +44,9 @@ export const VaultProtectedUnlock: React.FC<{ vault: Vault; secretName?: string;
onDismiss,
}) => {
const { t } = useTranslation();
- const [password, setPassword] = useState('');
- const [confirm, setConfirm] = useState('');
const [busy, setBusy] = useState(false);
- // Progressive disclosure: password fields stay hidden until the user opts out of the
- // recommended passkey path. Resets whenever the panel re-mounts for a new state.
- const [showPassword, setShowPassword] = useState(false);
- // Passkey-only setup has no password/second-passkey/recovery fallback yet, so a lost
- // passkey is unrecoverable — gate the recommended action behind an explicit ack.
+ // Passkey-only setup has no recovery fallback yet, so a lost passkey is
+ // unrecoverable — gate the recommended action behind an explicit ack.
const [ackLoss, setAckLoss] = useState(false);
const run = async (fn: () => Promise<void>) => {
@@ -64,8 +54,6 @@ export const VaultProtectedUnlock: React.FC<{ vault: Vault; secretName?: string;
vault.setError(null);
try {
await fn();
- setPassword('');
- setConfirm('');
} catch (err) {
vault.setError(friendlyError(t, err instanceof Error ? err.message : String(err)));
} finally {
@@ -109,21 +97,9 @@ export const VaultProtectedUnlock: React.FC<{ vault: Vault; secretName?: string;
}
const canUsePasskey = webauthnAvailable();
- const passwordValid = password.trim().length > 0 && password === confirm;
// ---- Setup (needs-setup): design.pen `kAmWj` ---------------------------------------
if (vault.status === 'needs-setup') {
- const submitPassword = () => {
- if (password.trim().length === 0) return;
- if (password !== confirm) {
- vault.setError(t('vaults.protectedUnlock.errors.mismatch'));
- return;
- }
- void run(() => vault.setupPassword(password));
- };
- // Password is the only factor when WebAuthn isn't available here — surface the fields
- // immediately rather than hiding them behind a passkey card that can't be used.
- const passwordRevealed = showPassword || !canUsePasskey;
return (
<div className={PANEL}>
<div className="flex flex-col items-center gap-4">
@@ -138,8 +114,7 @@ export const VaultProtectedUnlock: React.FC<{ vault: Vault; secretName?: string;
</div>
</div>
- {/* Recommended: passkey — the single primary path (design leads with this). */}
- {canUsePasskey && (
+ {canUsePasskey ? (
<div className="flex flex-col items-center gap-2.5 rounded-xl border-[1.5px] border-mint bg-mint-soft p-4">
<Badge variant="success" className="border-transparent bg-mint uppercase tracking-wide text-background">
<Sparkles className="size-3" />
@@ -151,11 +126,12 @@ export const VaultProtectedUnlock: React.FC<{ vault: Vault; secretName?: string;
</Button>
<span className="text-center text-[11.5px] text-muted-foreground">{t('vaults.protectedUnlock.passkeyCaption')}</span>
</div>
+ ) : (
+ <div className="rounded-md border border-warning/40 bg-warning/10 px-3 py-2 text-xs leading-snug text-warning">
+ {t('vaults.protectedUnlock.unlockUnavailableHere')}
+ </div>
)}
- {/* Unrecoverable acknowledgement — a passkey-only vault has no password/second-passkey/
- recovery fallback yet, so a lost passkey means the protected secrets are gone. Gate
- the recommended action behind an explicit ack until a recovery flow exists. */}
{canUsePasskey && (
<div className="flex flex-col gap-2 rounded-xl border border-warning/40 bg-warning/10 p-3">
<span className="text-[11.5px] leading-snug text-warning">{t('vaults.protectedUnlock.passkeyUnrecoverableWarning')}</span>
@@ -166,61 +142,6 @@ export const VaultProtectedUnlock: React.FC<{ vault: Vault; secretName?: string;
</div>
)}
- {/* Progressive disclosure — password fields stay hidden until requested. */}
- {!passwordRevealed ? (
- <button
- type="button"
- onClick={() => setShowPassword(true)}
- className="flex items-center justify-center gap-2 text-[13px] font-medium text-muted-foreground transition-colors hover:text-foreground"
- >
- {t('vaults.protectedUnlock.usePasswordInstead')}
- <Badge variant="destructive">{t('vaults.protectedUnlock.lessSecure')}</Badge>
- </button>
- ) : (
- <div className="flex flex-col gap-2.5 rounded-xl border border-border bg-surface-2 p-3">
- <span className="flex items-center gap-1.5 text-xs font-semibold">
- <KeyRound className="size-3.5" />
- {t('vaults.protectedUnlock.passwordOptionTitle')}
- </span>
- <label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
- {t('vaults.protectedUnlock.setPasswordLabel')}
- <Input
- type="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- placeholder={t('vaults.protectedUnlock.passwordPlaceholder')}
- autoComplete="new-password"
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- submitPassword();
- }
- }}
- />
- </label>
- <label className="flex flex-col gap-1.5 text-xs text-muted-foreground">
- {t('vaults.protectedUnlock.confirmLabel')}
- <Input
- type="password"
- value={confirm}
- onChange={(e) => setConfirm(e.target.value)}
- placeholder={t('vaults.protectedUnlock.confirmPlaceholder')}
- autoComplete="new-password"
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- submitPassword();
- }
- }}
- />
- </label>
- <Button type="button" variant="secondary" onClick={submitPassword} disabled={busy || !passwordValid}>
- {busy && <Loader2 className="size-4 animate-spin" />}
- {t('vaults.protectedUnlock.createPassword')}
- </Button>
- </div>
- )}
-
{onDismiss && (
<button
type="button"
@@ -238,12 +159,6 @@ export const VaultProtectedUnlock: React.FC<{ vault: Vault; secretName?: string;
// ---- Unlock (locked): design.pen `g5Q7F` -------------------------------------------
const showUnlockPasskey = vault.hasPasskey() && canUsePasskey && vault.passkeyUsableHere();
- const showUnlockPassword = vault.hasPassword();
- // If the passkey can't be used here, the password is the only way in — reveal it up front.
- const passwordRevealed = showPassword || !showUnlockPasskey;
- const submitUnlock = () => {
- if (password.trim()) void run(() => vault.unlockPassword(password));
- };
return (
<div className={PANEL}>
<div className="flex flex-col items-center gap-4">
@@ -270,45 +185,7 @@ export const VaultProtectedUnlock: React.FC<{ vault: Vault; secretName?: string;
</div>
)}
- {showUnlockPassword &&
- (!passwordRevealed ? (
- <button
- type="button"
- onClick={() => setShowPassword(true)}
- className="flex items-center justify-center gap-2 text-[13px] font-medium text-muted-foreground transition-colors hover:text-foreground"
- >
- {t('vaults.protectedUnlock.usePasswordInline')}
- <Badge variant="destructive">{t('vaults.protectedUnlock.lessSecure')}</Badge>
- </button>
- ) : (
- <div className="flex items-end gap-2">
- <label className="flex flex-1 flex-col gap-1.5 text-xs font-medium text-muted-foreground">
- <span className="flex items-center gap-1.5">
- <KeyRound className="size-3.5" />
- {t('vaults.protectedUnlock.passwordLabel')}
- </span>
- <Input
- type="password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- placeholder={t('vaults.protectedUnlock.passwordPlaceholder')}
- autoComplete="current-password"
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- submitUnlock();
- }
- }}
- />
- </label>
- <Button type="button" onClick={submitUnlock} disabled={busy || !password.trim()}>
- {busy && <Loader2 className="size-4 animate-spin" />}
- {t('vaults.protectedUnlock.unlockCta')}
- </Button>
- </div>
- ))}
-
- {!showUnlockPasskey && !showUnlockPassword && (
+ {!showUnlockPasskey && (
<div className="rounded-md border border-warning/40 bg-warning/10 px-2.5 py-1.5 text-xs text-warning">
{t('vaults.protectedUnlock.unlockUnavailableHere')}
</div>
diff --git a/ui/src/components/workbench/VaultsPage.tsx b/ui/src/components/workbench/VaultsPage.tsx
index 40ba66c2b..e33ecbd2f 100644
--- a/ui/src/components/workbench/VaultsPage.tsx
+++ b/ui/src/components/workbench/VaultsPage.tsx
@@ -678,7 +678,7 @@ export const VaultsPage: React.FC = () => {
const protectedVault = useProtectedVault();
const [deleteTarget, setDeleteTarget] = useState<VaultSecret | null>(null);
const [editTarget, setEditTarget] = useState<VaultSecret | null>(null);
- // Deleting a protected secret requires the user present at an unlocked vault (a passkey/password
+ // Deleting a protected secret requires the user present at an unlocked vault (a passkey
// ceremony) — discover the current lock state when the delete dialog opens for one.
useEffect(() => {
if (deleteTarget?.protection !== 'protected') return;
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index b5624fa6d..7b9b95434 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2271,42 +2271,21 @@
"recommended": "Recommended",
"addPasskey": "Add a passkey",
"passkeyCaption": "Face ID · Touch ID · security key — the most secure option",
- "recoveryTip": "Add a second passkey (your phone) or save a recovery code, so a lost device never locks you out.",
- "usePasswordInstead": "Use a password instead",
- "lessSecure": "less secure",
"maybeLater": "Maybe later",
"unlockWithPasskey": "Unlock with passkey",
"unlockPasskeyCaption": "Face ID · Touch ID · security key",
- "usePasswordInline": "Use password instead",
- "factorNote": "Your factor never leaves the browser — the machine alone can't decrypt this",
+ "factorNote": "Your passkey proof never leaves the browser — the machine alone can't decrypt this",
"cancel": "Cancel",
- "createPassword": "Create password",
- "setupHelp": "Choose how to unlock protected secrets in the browser. The machine alone can never decrypt them.",
- "unlockHelp": "Confirm your unlock factor to seal this secret under your existing vault key.",
- "setPasswordLabel": "Recovery password",
- "passwordLabel": "Vault password",
- "passwordPlaceholder": "Enter a strong password",
- "confirmLabel": "Confirm password",
- "confirmPlaceholder": "Re-enter the password",
- "passkeyOptionTitle": "Passkey · most secure",
- "passkeyOptionHelp": "Unlock with Touch ID / Windows Hello. No password to phish or leak.",
- "passkeyUnrecoverableWarning": "If you lose this passkey — or open this vault from a different site/address than where you set it up — these protected secrets can't be recovered. There is no password to fall back on.",
+ "passkeyUnrecoverableWarning": "If you lose this passkey — or open this vault from a different site/address than where you set it up — these protected secrets can't be recovered. There is no recovery fallback.",
"passkeyAck": "I understand: if I lose this passkey or open this vault from a different site, these secrets can't be recovered.",
- "setupWithPasskey": "Set up with passkey",
- "passwordOptionTitle": "Password · recoverable",
- "passwordOptionHelp": "Recoverable as long as you remember it, but a password is weaker (can be phished or leaked).",
- "setupWithPassword": "Set up with password",
- "unlockPasskey": "Unlock with passkey",
- "unlockCta": "Unlock",
- "unlockUnavailableHere": "This vault is unlocked by a passkey set up on the site where you created it. Open Vaults from that site (Touch ID / Windows Hello) to unlock — this address can't.",
+ "unlockUnavailableHere": "Protected vaults need a passkey. Open Vaults from localhost or your avibe.bot address; raw IP addresses like 127.0.0.1 can't use WebAuthn.",
"errors": {
- "prfUnavailable": "This passkey/browser doesn't support the PRF extension needed for encryption. Try a platform passkey (Touch ID / Windows Hello) or use a password.",
+ "prfUnavailable": "This passkey/browser doesn't support the PRF extension needed for encryption. Try a platform passkey (Touch ID / Windows Hello).",
"cancelled": "Passkey prompt was cancelled.",
- "noPasskey": "No passkey is configured for this vault. Use your password.",
- "wrongFactor": "Couldn't unlock — wrong password or passkey.",
+ "noPasskey": "No passkey is configured for this protected vault.",
+ "wrongFactor": "Couldn't unlock with this passkey.",
"discoveryFailed": "Couldn't load your protected vault. Check your connection and retry — don't set up a new one, or you'll split your vault keys.",
- "mismatch": "The passwords don't match.",
- "alreadyInitialized": "This vault was just set up elsewhere. Reload and unlock with your existing password or passkey."
+ "alreadyInitialized": "This vault was just set up elsewhere. Reload and unlock with your existing passkey."
}
},
"dialog": {
@@ -2365,7 +2344,7 @@
"protection": "Who can unlock this secret?",
"protectedProtection": "Protected",
"standardProtection": "Standard",
- "protectedHelp": "The agent can't use it on its own. It's unlocked only after you decrypt it in your browser with your passkey or password (end-to-end encrypted). Safe even if this computer is stolen — good for crypto wallets and any important secret.",
+ "protectedHelp": "The agent can't use it on its own. It's unlocked only after you decrypt it in your browser with your passkey (end-to-end encrypted). Safe even if this computer is stolen — good for crypto wallets and any important secret.",
"standardHelp": "The agent can use it on its own. Good for API keys, environment variables, and most secrets.",
"alwaysAskSign": "Ask me before every signature",
"alwaysAskSignHelp": "Standard keys can sign on their own. For a high-value key, turn this on so every signature needs your approval in the browser.",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1fcaf0d05..82f0c690f 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2271,42 +2271,21 @@
"recommended": "推荐",
"addPasskey": "添加 passkey",
"passkeyCaption": "Face ID · Touch ID · 安全密钥——最安全的方式",
- "recoveryTip": "再加一把 passkey(你的手机)或保存一个恢复码,这样丢了设备也不会把你锁在门外。",
- "usePasswordInstead": "改用密码",
- "lessSecure": "较不安全",
"maybeLater": "以后再说",
"unlockWithPasskey": "用 passkey 解锁",
"unlockPasskeyCaption": "Face ID · Touch ID · 安全密钥",
- "usePasswordInline": "改用密码",
- "factorNote": "你的解锁因子绝不会离开浏览器——单凭这台机器无法解密",
+ "factorNote": "你的 passkey 证明绝不会离开浏览器——单凭这台机器无法解密",
"cancel": "取消",
- "createPassword": "创建密码",
- "setupHelp": "选择在浏览器里如何解锁保护层密钥。机器单独永远无法解密。",
- "unlockHelp": "确认你的解锁因子,用现有的保护层主密钥封装这条密钥。",
- "setPasswordLabel": "恢复密码",
- "passwordLabel": "保护层密码",
- "passwordPlaceholder": "输入一个强密码",
- "confirmLabel": "确认密码",
- "confirmPlaceholder": "再次输入密码",
- "passkeyOptionTitle": "Passkey · 最安全",
- "passkeyOptionHelp": "用 Touch ID / Windows Hello 解锁,没有可被钓鱼或泄露的密码。",
- "passkeyUnrecoverableWarning": "一旦丢失此 passkey、或从与设置时不同的站点/地址打开此保险库,这些保护层密钥将无法恢复(没有密码可兜底)。",
+ "passkeyUnrecoverableWarning": "一旦丢失此 passkey、或从与设置时不同的站点/地址打开此保险库,这些保护层密钥将无法恢复(没有恢复兜底)。",
"passkeyAck": "我明白:丢失此 passkey、或从其他站点打开此保险库后,这些密钥将无法恢复。",
- "setupWithPasskey": "用 passkey 设置",
- "passwordOptionTitle": "密码 · 可恢复",
- "passwordOptionHelp": "只要你记得就能恢复,但密码更弱(可能被钓鱼或泄露)。",
- "setupWithPassword": "用密码设置",
- "unlockPasskey": "用 passkey 解锁",
- "unlockCta": "解锁",
- "unlockUnavailableHere": "此保险库由设置时所在站点的 passkey 解锁。请从那个站点打开 Vaults(Touch ID / Windows Hello)来解锁——当前地址无法解锁。",
+ "unlockUnavailableHere": "保护层保险库需要 passkey。请从 localhost 或你的 avibe.bot 地址打开 Vaults;127.0.0.1 这类原始 IP 无法使用 WebAuthn。",
"errors": {
- "prfUnavailable": "这个 passkey/浏览器不支持加密所需的 PRF 扩展。请用平台 passkey(Touch ID / Windows Hello)或改用密码。",
+ "prfUnavailable": "这个 passkey/浏览器不支持加密所需的 PRF 扩展。请改用平台 passkey(Touch ID / Windows Hello)。",
"cancelled": "passkey 提示被取消了。",
- "noPasskey": "这个保护层没有配置 passkey。请用密码。",
- "wrongFactor": "无法解锁——密码或 passkey 不对。",
+ "noPasskey": "这个保护层保险库没有配置 passkey。",
+ "wrongFactor": "无法用这个 passkey 解锁。",
"discoveryFailed": "加载保护层失败。请检查网络后重试——不要重新设置,否则会把保护层主密钥分裂。",
- "mismatch": "两次输入的密码不一致。",
- "alreadyInitialized": "这个保护层刚在别处完成了设置。请刷新,用你已有的密码或 passkey 解锁。"
+ "alreadyInitialized": "这个保护层刚在别处完成了设置。请刷新,用你已有的 passkey 解锁。"
}
},
"dialog": {
@@ -2365,7 +2344,7 @@
"protection": "谁能解锁这条密钥?",
"protectedProtection": "保护档",
"standardProtection": "标准档",
- "protectedHelp": "AI 无法私自使用。只能在你的浏览器里用 Passkey 或密码解密后才能使用(端到端加密)。就算电脑被偷也打不开,适合加密钱包及一切重要密钥。",
+ "protectedHelp": "AI 无法私自使用。只能在你的浏览器里用 passkey 解密后才能使用(端到端加密)。就算电脑被偷也打不开,适合加密钱包及一切重要密钥。",
"standardHelp": "AI 可以自行使用。适合各类 API Key、环境变量和大多数密钥。",
"alwaysAskSign": "每次签名都要我确认",
"alwaysAskSignHelp": "标准档密钥默认可以自己签名。贵重密钥可以打开它——每次签名都要你在浏览器里亲自批准。",
diff --git a/ui/src/lib/useProtectedVault.ts b/ui/src/lib/useProtectedVault.ts
index 4b479c17b..0566c4e12 100644
--- a/ui/src/lib/useProtectedVault.ts
+++ b/ui/src/lib/useProtectedVault.ts
@@ -37,12 +37,11 @@ export type ProtectedUnlockMaterial = {
/**
* Protected-tier vault lifecycle for the Web UI.
*
- * The Vault Master Key (VMK) lives only in browser memory and is wrapped by user
- * factors into an opaque `wrap_meta` the daemon stores per protected secret. A
- * **password is always set as the recovery root**; a passkey (WebAuthn-PRF, Touch ID /
- * Windows Hello) can be added on top as the quick primary unlock — so losing a device
- * never makes protected secrets unrecoverable. The daemon never sees the VMK or
- * plaintext. No cross-origin sandbox yet — that hardening is a later version.
+ * The Vault Master Key (VMK) lives only in browser memory and is wrapped by a
+ * passkey (WebAuthn-PRF, Face ID / Touch ID / Windows Hello) into an opaque
+ * `wrap_meta` the daemon stores per protected secret. The daemon never sees
+ * the VMK or plaintext. No cross-origin sandbox yet — that hardening is a later
+ * version.
*
* The unlocked VMK is cached at module scope so it survives `VaultSecretForm`
* unmount/remount within one page session. A full reload re-initialises the module.
@@ -193,9 +192,8 @@ const WEBAUTHN_USER_HANDLE = new TextEncoder().encode('avibe-vault');
/**
* WebAuthn needs a secure context and a domain RP ID. Browsers reject raw IP RP IDs
- * (the default local `http://127.0.0.1:5123` workflow), so the passkey path is only
- * offered on `localhost` or an HTTPS domain (e.g. the tunnel); elsewhere we fall back
- * to the password, which is the recovery root anyway.
+ * (the default local `http://127.0.0.1:5123` workflow), so protected vault setup and
+ * unlock only work on `localhost` or an HTTPS domain (e.g. the tunnel).
*/
export function webauthnAvailable(): boolean {
if (typeof window === 'undefined' || typeof window.PublicKeyCredential === 'undefined') return false;
@@ -378,14 +376,8 @@ export function useProtectedVault() {
setError(null);
};
- // First-time setup uses ONE factor. Passkey-only is the most secure option (no
- // phishable/leakable password) but is unrecoverable if the device/passkey is lost —
- // the UI requires an explicit acknowledgement. Password is the recoverable alternative.
- const setupPassword = useCallback(async (password: string) => {
- const vmk = newVmk();
- commit(vmk, await buildWrapMeta(vmk, [{ kind: 'password', password }]), true);
- }, []);
-
+ // First-time setup is passkey-only. A lost passkey is unrecoverable for now, so the
+ // UI requires an explicit acknowledgement before calling this.
const setupPasskey = useCallback(async () => {
const prfSalt = newPasskeyPrfSalt();
const { prfOutput, credentialId } = await setupPasskeyFactor(prfSalt);
@@ -394,12 +386,6 @@ export function useProtectedVault() {
commit(vmk, withRpId(wrapMeta, window.location.hostname), true);
}, []);
- const unlockPassword = useCallback(async (password: string) => {
- const wrapMeta = sessionVault.wrapMeta;
- if (!wrapMeta) throw new Error('vault-not-setup');
- commit(await unwrapVmk(wrapMeta, { kind: 'password', password }), wrapMeta, false);
- }, []);
-
const unlockPasskey = useCallback(async () => {
const wrapMeta = sessionVault.wrapMeta;
if (!wrapMeta) throw new Error('vault-not-setup');
@@ -501,17 +487,6 @@ export function useProtectedVault() {
}
}, []);
- const hasPassword = useCallback(() => {
- const wrapMeta = sessionVault.wrapMeta;
- if (!wrapMeta) return false;
- try {
- const meta = JSON.parse(wrapMeta) as { copies?: Array<{ kind?: string }> };
- return Array.isArray(meta.copies) && meta.copies.some((copy) => copy.kind === 'password');
- } catch {
- return false;
- }
- }, []);
-
// A passkey can only be asserted on the host (RP ID) it was created on. Offer passkey
// unlock only when the current host matches the stored one (legacy vaults without a
// recorded rp_id are not blocked).
@@ -526,7 +501,22 @@ export function useProtectedVault() {
}
}, []);
- return { status, error, setError, refresh, setupPassword, setupPasskey, unlockPassword, unlockPasskey, sealValue, signProtectedRequest, releaseProtectedDelivery, afterCreated, lock, discardAndRefresh, hasPasskey, hasPassword, passkeyUsableHere };
+ return {
+ status,
+ error,
+ setError,
+ refresh,
+ setupPasskey,
+ unlockPasskey,
+ sealValue,
+ signProtectedRequest,
+ releaseProtectedDelivery,
+ afterCreated,
+ lock,
+ discardAndRefresh,
+ hasPasskey,
+ passkeyUsableHere,
+ };
}
/**
diff --git a/ui/src/lib/vaultCrypto.test.ts b/ui/src/lib/vaultCrypto.test.ts
index ec3d833a0..fa4c81321 100644
--- a/ui/src/lib/vaultCrypto.test.ts
+++ b/ui/src/lib/vaultCrypto.test.ts
@@ -1,13 +1,11 @@
import { describe, expect, it } from 'vitest';
import { Aes256Gcm, CipherSuite, HkdfSha256 } from '@hpke/core';
import { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';
-import { scrypt } from 'hash-wasm';
import vectors from './__fixtures__/p2_core_crypto.json';
import {
BLIND_BOX_AAD_DOMAIN,
BLIND_BOX_SCHEME,
- addPasswordCopy,
avaultPublicKeyFingerprint,
base64ToBytes,
blindBoxAad,
@@ -89,29 +87,21 @@ async function aesgcmEncryptForTest(key: Uint8Array, nonce: Uint8Array, plaintex
);
}
-async function malformedScryptVmkCopy(password: string, plaintext: Uint8Array) {
- const salt = new Uint8Array(16).fill(0xa5);
+async function malformedPasskeyVmkCopy(prfOutput: Uint8Array, prfSalt: Uint8Array, plaintext: Uint8Array) {
const nonce = new Uint8Array(12).fill(0x5a);
- const kek = (await scrypt({
- password: encoder.encode(password),
- salt,
- costFactor: 2 ** 15,
- blockSize: 8,
- parallelism: 1,
- hashLength: 32,
- outputType: 'binary',
- })) as Uint8Array;
- const wrapped = await aesgcmEncryptForTest(kek, nonce, plaintext);
- return {
- kind: 'password',
- kdf: 'scrypt',
- n: 2 ** 15,
- r: 8,
- p: 1,
- salt: bytesToBase64(salt),
- nonce: bytesToBase64(nonce),
- wrapped: bytesToBase64(wrapped),
- };
+ const kek = await derivePasskeyKek(prfOutput, prfSalt);
+ try {
+ const wrapped = await aesgcmEncryptForTest(kek, nonce, plaintext);
+ return {
+ kind: 'passkey',
+ kdf: 'webauthn-prf-hkdf-sha256',
+ prf_salt: bytesToBase64(prfSalt),
+ nonce: bytesToBase64(nonce),
+ wrapped: bytesToBase64(wrapped),
+ };
+ } finally {
+ kek.fill(0);
+ }
}
async function avaultVectorReceiverKey(): Promise<CryptoKeyPair> {
@@ -311,28 +301,22 @@ describe('vaultCrypto blind boxes', () => {
});
describe('vaultCrypto protected hierarchy', () => {
- it('unwraps the VMK with either passkey PRF or fallback password', async () => {
+ it('wraps and unwraps the VMK with a passkey PRF copy only', async () => {
const vmk = newVmk();
const prfSalt = new Uint8Array(32).fill(0x11);
const prfOutput = new Uint8Array(32).fill(0x22);
- const wrapMeta = await buildWrapMeta(vmk, [
- { kind: 'passkey', prfOutput, prfSalt, credentialId: 'cred-1' },
- { kind: 'password', password: 'less-secure-fallback' },
- ]);
+ const wrapMeta = await buildWrapMeta(vmk, [{ kind: 'passkey', prfOutput, prfSalt, credentialId: 'cred-1' }]);
await expect(unwrapVmk(wrapMeta, { kind: 'passkey', prfOutput })).resolves.toEqual(vmk);
- await expect(unwrapVmk(wrapMeta, 'less-secure-fallback')).resolves.toEqual(vmk);
- expect(JSON.parse(wrapMeta).copies.find((copy: { kind: string }) => copy.kind === 'password')?.kdf).toBe('scrypt');
+ await expect(
+ unwrapVmk(wrapMeta, { kind: 'passkey', prfOutput, prfSalt: new Uint8Array(32).fill(0x99) }),
+ ).rejects.toThrow(/unwrapped/);
+ const copies = JSON.parse(wrapMeta).copies as Array<{ kind: string; kdf?: string }>;
+ expect(copies).toHaveLength(1);
+ expect(copies[0]).toEqual(expect.objectContaining({ kind: 'passkey', kdf: 'webauthn-prf-hkdf-sha256' }));
expect(passkeyPrfSalts(wrapMeta)).toEqual([prfSalt]);
expect(passkeyPrfSaltEntries(wrapMeta)).toEqual([{ prfSalt, credentialId: 'cred-1' }]);
expect(webAuthnPrfExtensionInput(prfSalt).prf.eval.first.byteLength).toBe(32);
-
- const withArgon2id = await addPasswordCopy(wrapMeta, vmk, 'argon2id-fallback', {
- memorySize: 512,
- iterations: 2,
- });
- const copies = JSON.parse(withArgon2id).copies as Array<{ kind: string; kdf?: string }>;
- expect(copies.at(-1)?.kdf).toBe('argon2id');
});
it('keeps setup passkey PRF bytes and credential id intact through wrap_meta', async () => {
@@ -350,23 +334,30 @@ describe('vaultCrypto protected hierarchy', () => {
it('skips malformed authenticated VMK copies and tries the next valid copy', async () => {
const vmk = newVmk();
- const password = 'less-secure-fallback';
- const malformed = await malformedScryptVmkCopy(password, new Uint8Array(31).fill(0x44));
- const valid = await buildWrapMeta(vmk, [password]);
+ const prfSalt = new Uint8Array(32).fill(0x11);
+ const prfOutput = new Uint8Array(32).fill(0x22);
+ const malformed = await malformedPasskeyVmkCopy(prfOutput, prfSalt, new Uint8Array(31).fill(0x44));
+ const valid = await buildWrapMeta(vmk, [{ kind: 'passkey', prfOutput, prfSalt }]);
const combined = JSON.stringify({
v: 1,
copies: [malformed, ...JSON.parse(valid).copies],
});
- await expect(unwrapVmk(combined, password)).resolves.toEqual(vmk);
+ await expect(unwrapVmk(combined, { kind: 'passkey', prfOutput, prfSalt })).resolves.toEqual(vmk);
});
- it('rejects blank password wrap factors before deriving VMK copies', async () => {
+ it('rejects missing or malformed passkey wrap factors before deriving VMK copies', async () => {
const vmk = newVmk();
- await expect(buildWrapMeta(vmk, [''])).rejects.toThrow(/password/);
- await expect(buildWrapMeta(vmk, [{ kind: 'password', password: ' ' }])).rejects.toThrow(/password/);
- await expect(addPasswordCopy(JSON.stringify({ v: 1, copies: [] }), vmk, '')).rejects.toThrow(/password/);
+ await expect(buildWrapMeta(vmk, [])).rejects.toThrow(/factor/);
+ await expect(
+ buildWrapMeta(vmk, [{ kind: 'passkey', prfOutput: new Uint8Array(), prfSalt: new Uint8Array(32).fill(0x11) }]),
+ ).rejects.toThrow(/empty/);
+ await expect(
+ buildWrapMeta(vmk, [
+ { kind: 'passkey', prfOutput: new Uint8Array(32).fill(0x22), prfSalt: new Uint8Array(31).fill(0x11) },
+ ]),
+ ).rejects.toThrow(/PRF salt/);
});
it('wraps a protected value with a per-record DEK and releases only that DEK', async () => {
@@ -510,14 +501,16 @@ describe('vaultCrypto protected hierarchy', () => {
describe('protected record storage composition', () => {
it('packs a sealed record and unpacks it for a clean open round-trip', async () => {
const vmk = newVmk();
- const wrapMeta = await buildWrapMeta(vmk, ['vault-password']);
+ const prfSalt = new Uint8Array(32).fill(0x11);
+ const prfOutput = new Uint8Array(32).fill(0x22);
+ const wrapMeta = await buildWrapMeta(vmk, [{ kind: 'passkey', prfOutput, prfSalt }]);
const context = { name: 'OPENAI_API_KEY' };
const sealed = await sealProtected(new TextEncoder().encode('sk-secret-value'), vmk, context);
const envelope = packProtectedRecord(sealed, wrapMeta);
expect(JSON.parse(envelope.wrap_meta).scheme).toBe(WRAP_SCHEME);
const restored = unpackProtectedRecord(envelope);
- const vmkAgain = await unwrapVmk(restored.vmkWrapMeta, 'vault-password');
+ const vmkAgain = await unwrapVmk(restored.vmkWrapMeta, { kind: 'passkey', prfOutput, prfSalt });
const opened = await openProtected(restored.sealed, vmkAgain, context);
expect(new TextDecoder().decode(opened)).toBe('sk-secret-value');
@@ -525,7 +518,9 @@ describe('protected record storage composition', () => {
it('refuses to fold a DEK into a wrap_meta that already carries one', async () => {
const vmk = newVmk();
- const wrapMeta = await buildWrapMeta(vmk, ['pw']);
+ const wrapMeta = await buildWrapMeta(vmk, [
+ { kind: 'passkey', prfOutput: new Uint8Array(32).fill(0x22), prfSalt: new Uint8Array(32).fill(0x11) },
+ ]);
const sealed = await sealProtected(new TextEncoder().encode('v'), vmk, { name: 'NAME' });
const once = packProtectedRecord(sealed, wrapMeta);
expect(() => packProtectedRecord(sealed, once.wrap_meta)).toThrow();
diff --git a/ui/src/lib/vaultCrypto.ts b/ui/src/lib/vaultCrypto.ts
index 9f09e733b..b72036081 100644
--- a/ui/src/lib/vaultCrypto.ts
+++ b/ui/src/lib/vaultCrypto.ts
@@ -2,7 +2,6 @@ import { Aes256Gcm, CipherSuite, HkdfSha256 } from '@hpke/core';
import { DhkemX25519HkdfSha256 } from '@hpke/dhkem-x25519';
import { secp256k1, schnorr } from '@noble/curves/secp256k1.js';
import { bytesToHex, hexToBytes } from '@noble/curves/utils.js';
-import { argon2id, scrypt } from 'hash-wasm';
export const BLIND_BOX_SCHEME = 'hpke-x25519-hkdfsha256-aes256gcm-v1';
export const BLIND_BOX_HPKE_INFO = 'avault:blind-box:v1';
@@ -15,21 +14,9 @@ export const SIGN_SCHEME_SCHNORR_SECP256K1_BIP340 = 'schnorr-secp256k1-bip340';
const KEY_BYTES = 32;
const NONCE_BYTES = 12;
-const ARGON2_VERSION = 19;
const PASSKEY_PRF_SALT_BYTES = 32;
const PASSKEY_HKDF_INFO = 'avault:protected-vmk:kek-passkey:v1';
const SECRET_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
-const DEFAULT_SCRYPT = {
- n: 2 ** 15,
- r: 8,
- p: 1,
-} as const;
-
-const DEFAULT_ARGON2ID = {
- iterations: 3,
- memorySize: 64 * 1024,
- parallelism: 1,
-} as const;
const textEncoder = new TextEncoder();
@@ -60,27 +47,6 @@ export type ProtectedRecordContext = {
version?: typeof WRAP_META_VERSION;
};
-export type Argon2idParams = {
- iterations: number;
- memorySize: number;
- parallelism: number;
-};
-
-type PasswordScryptFactor = {
- kind: 'password';
- password: string;
- kdf?: 'scrypt';
-};
-
-type PasswordArgon2idFactor = {
- kind: 'password';
- password: string;
- kdf: 'argon2id';
- argon2id?: Partial<Argon2idParams>;
-};
-
-export type PasswordWrapFactor = PasswordScryptFactor | PasswordArgon2idFactor;
-
export type PasskeyWrapFactor = {
kind: 'passkey';
prfOutput: BytesLike;
@@ -88,21 +54,12 @@ export type PasskeyWrapFactor = {
credentialId?: string;
};
-export type VmkWrapFactor = PasswordWrapFactor | PasskeyWrapFactor;
-
-export type PasswordUnlockFactor = {
- kind: 'password';
- password: string;
-};
-
export type PasskeyUnlockFactor = {
kind: 'passkey';
prfOutput: BytesLike;
prfSalt?: BytesLike;
};
-export type VmkUnlockFactor = PasswordUnlockFactor | PasskeyUnlockFactor;
-
export type SignatureScheme =
| typeof SIGN_SCHEME_ECDSA_SECP256K1_RECOVERABLE
| typeof SIGN_SCHEME_ECDSA_SECP256K1_DER
@@ -177,30 +134,7 @@ export type ProtectedDekReleaseOperation =
type WrapMeta = {
v: 1;
- copies: WrapCopy[];
-};
-
-type PasswordArgon2idCopy = {
- kind: 'password';
- kdf: 'argon2id';
- version: 19;
- iterations: number;
- memorySize: number;
- parallelism: number;
- salt: string;
- nonce: string;
- wrapped: string;
-};
-
-type PasswordScryptCopy = {
- kind: 'password';
- kdf: 'scrypt';
- n: number;
- r: number;
- p: number;
- salt: string;
- nonce: string;
- wrapped: string;
+ copies: PasskeyPrfCopy[];
};
type PasskeyPrfCopy = {
@@ -212,8 +146,6 @@ type PasskeyPrfCopy = {
credential_id?: string;
};
-type WrapCopy = PasswordArgon2idCopy | PasswordScryptCopy | PasskeyPrfCopy;
-
export type WebAuthnPrfExtensionInput = {
prf: {
eval: {
@@ -291,32 +223,6 @@ function wipeArrayBuffer(buffer: ArrayBuffer | undefined): void {
}
}
-function normalizeArgon2idParams(params?: Partial<Argon2idParams>): Argon2idParams {
- const normalized = { ...DEFAULT_ARGON2ID, ...params };
- if (!Number.isInteger(normalized.iterations) || normalized.iterations < 1 || normalized.iterations > 10) {
- throw new Error('argon2id iterations out of bounds');
- }
- if (!Number.isInteger(normalized.memorySize) || normalized.memorySize < 8 || normalized.memorySize > 256 * 1024) {
- throw new Error('argon2id memorySize out of bounds');
- }
- if (!Number.isInteger(normalized.parallelism) || normalized.parallelism < 1 || normalized.parallelism > 8) {
- throw new Error('argon2id parallelism out of bounds');
- }
- return normalized;
-}
-
-function validateScryptParams(n: number, r: number, p: number): void {
- if (!Number.isInteger(n) || n < 2 || (n & (n - 1)) !== 0 || n > 2 ** 17) {
- throw new Error('scrypt N out of bounds');
- }
- if (!Number.isInteger(r) || r < 1 || r > 16) {
- throw new Error('scrypt r out of bounds');
- }
- if (!Number.isInteger(p) || p < 1 || p > 16) {
- throw new Error('scrypt p out of bounds');
- }
-}
-
async function aesgcmEncrypt(
key: BytesLike,
nonce: BytesLike,
@@ -412,32 +318,6 @@ async function hkdfSha256(ikm: BytesLike, salt: BytesLike, info: BytesLike, leng
}
}
-async function kekPasswordArgon2id(password: string, salt: BytesLike, params?: Partial<Argon2idParams>): Promise<Uint8Array> {
- const normalized = normalizeArgon2idParams(params);
- return (await argon2id({
- password: utf8(password),
- salt: toUint8Array(salt),
- iterations: normalized.iterations,
- memorySize: normalized.memorySize,
- parallelism: normalized.parallelism,
- hashLength: KEY_BYTES,
- outputType: 'binary',
- })) as Uint8Array;
-}
-
-async function kekPasswordScrypt(password: string, salt: BytesLike, n: number, r: number, p: number): Promise<Uint8Array> {
- validateScryptParams(n, r, p);
- return (await scrypt({
- password: utf8(password),
- salt: toUint8Array(salt),
- costFactor: n,
- blockSize: r,
- parallelism: p,
- hashLength: KEY_BYTES,
- outputType: 'binary',
- })) as Uint8Array;
-}
-
export async function derivePasskeyKek(prfOutput: BytesLike, prfSalt: BytesLike): Promise<Uint8Array> {
const output = toUint8Array(prfOutput, 'passkey PRF output');
try {
@@ -477,77 +357,6 @@ function parseWrapMeta(wrapMeta: string | WrapMeta): WrapMeta {
return parsed as WrapMeta;
}
-function normalizeWrapFactors(factors: VmkWrapFactor[] | string[]): VmkWrapFactor[] {
- return factors.map((factor): VmkWrapFactor => {
- if (typeof factor === 'string') {
- return { kind: 'password', password: requireNonBlankPassword(factor) };
- }
- if (factor.kind === 'password') {
- return { ...factor, password: requireNonBlankPassword(factor.password) };
- }
- return factor;
- });
-}
-
-async function passwordArgon2idCopy(vmk: BytesLike, factor: PasswordArgon2idFactor): Promise<PasswordArgon2idCopy> {
- const vmkBytes = toUint8Array(vmk, 'VMK');
- const salt = randomBytes(16);
- const nonce = randomBytes(NONCE_BYTES);
- let kek: Uint8Array | undefined;
- try {
- assertLength(vmkBytes, KEY_BYTES, 'VMK');
- const params = normalizeArgon2idParams(factor.argon2id);
- kek = await kekPasswordArgon2id(factor.password, salt, params);
- const wrapped = await aesgcmEncrypt(kek, nonce, vmkBytes);
- return {
- kind: 'password',
- kdf: 'argon2id',
- version: ARGON2_VERSION,
- iterations: params.iterations,
- memorySize: params.memorySize,
- parallelism: params.parallelism,
- salt: bytesToBase64(salt),
- nonce: bytesToBase64(nonce),
- wrapped: bytesToBase64(wrapped),
- };
- } finally {
- kek?.fill(0);
- vmkBytes.fill(0);
- }
-}
-
-async function passwordScryptCopy(vmk: BytesLike, password: string): Promise<PasswordScryptCopy> {
- const vmkBytes = toUint8Array(vmk, 'VMK');
- const salt = randomBytes(16);
- const nonce = randomBytes(NONCE_BYTES);
- let kek: Uint8Array | undefined;
- try {
- assertLength(vmkBytes, KEY_BYTES, 'VMK');
- kek = await kekPasswordScrypt(password, salt, DEFAULT_SCRYPT.n, DEFAULT_SCRYPT.r, DEFAULT_SCRYPT.p);
- const wrapped = await aesgcmEncrypt(kek, nonce, vmkBytes);
- return {
- kind: 'password',
- kdf: 'scrypt',
- n: DEFAULT_SCRYPT.n,
- r: DEFAULT_SCRYPT.r,
- p: DEFAULT_SCRYPT.p,
- salt: bytesToBase64(salt),
- nonce: bytesToBase64(nonce),
- wrapped: bytesToBase64(wrapped),
- };
- } finally {
- kek?.fill(0);
- vmkBytes.fill(0);
- }
-}
-
-async function passwordCopy(vmk: BytesLike, factor: PasswordWrapFactor): Promise<PasswordArgon2idCopy | PasswordScryptCopy> {
- const password = requireNonBlankPassword(factor.password);
- return factor.kdf === 'argon2id'
- ? passwordArgon2idCopy(vmk, { ...factor, password })
- : passwordScryptCopy(vmk, password);
-}
-
async function passkeyCopy(vmk: BytesLike, factor: PasskeyWrapFactor): Promise<PasskeyPrfCopy> {
const vmkBytes = toUint8Array(vmk, 'VMK');
const nonce = randomBytes(NONCE_BYTES);
@@ -574,17 +383,16 @@ async function passkeyCopy(vmk: BytesLike, factor: PasskeyWrapFactor): Promise<P
}
}
-export async function buildWrapMeta(vmk: BytesLike, factors: VmkWrapFactor[] | string[]): Promise<string> {
+export async function buildWrapMeta(vmk: BytesLike, factors: PasskeyWrapFactor[]): Promise<string> {
const vmkBytes = toUint8Array(vmk, 'VMK');
try {
assertLength(vmkBytes, KEY_BYTES, 'VMK');
- const normalized = normalizeWrapFactors(factors);
- if (normalized.length === 0) {
+ if (factors.length === 0) {
throw new Error('at least one protected unlock factor is required');
}
- const copies: WrapCopy[] = [];
- for (const factor of normalized) {
- copies.push(factor.kind === 'password' ? await passwordCopy(vmkBytes, factor) : await passkeyCopy(vmkBytes, factor));
+ const copies: PasskeyPrfCopy[] = [];
+ for (const factor of factors) {
+ copies.push(await passkeyCopy(vmkBytes, factor));
}
return JSON.stringify({ v: 1, copies } satisfies WrapMeta);
} finally {
@@ -592,23 +400,6 @@ export async function buildWrapMeta(vmk: BytesLike, factors: VmkWrapFactor[] | s
}
}
-export async function addPasswordCopy(
- wrapMeta: string,
- vmk: BytesLike,
- password: string,
- argon2idParams?: Partial<Argon2idParams>,
-): Promise<string> {
- const meta = parseWrapMeta(wrapMeta);
- meta.copies.push(
- await passwordCopy(vmk, {
- kind: 'password',
- password,
- ...(argon2idParams ? { kdf: 'argon2id', argon2id: argon2idParams } : {}),
- }),
- );
- return JSON.stringify(meta);
-}
-
export async function addPasskeyCopy(
wrapMeta: string,
vmk: BytesLike,
@@ -621,25 +412,6 @@ export async function addPasskeyCopy(
return JSON.stringify(meta);
}
-async function unwrapPasswordCopy(copy: PasswordArgon2idCopy | PasswordScryptCopy, password: string): Promise<Uint8Array> {
- const salt = base64ToBytes(copy.salt);
- const nonce = base64ToBytes(copy.nonce);
- const wrapped = base64ToBytes(copy.wrapped);
- const kek =
- copy.kdf === 'argon2id'
- ? await kekPasswordArgon2id(password, salt, {
- iterations: copy.iterations,
- memorySize: copy.memorySize,
- parallelism: copy.parallelism,
- })
- : await kekPasswordScrypt(password, salt, copy.n, copy.r, copy.p);
- try {
- return await aesgcmDecrypt(kek, nonce, wrapped);
- } finally {
- kek.fill(0);
- }
-}
-
async function unwrapPasskeyCopy(copy: PasskeyPrfCopy, factor: PasskeyUnlockFactor): Promise<Uint8Array> {
const prfSalt = base64ToBytes(copy.prf_salt);
if (factor.prfSalt && bytesToBase64(factor.prfSalt) !== copy.prf_salt) {
@@ -653,23 +425,12 @@ async function unwrapPasskeyCopy(copy: PasskeyPrfCopy, factor: PasskeyUnlockFact
}
}
-export async function unwrapVmk(wrapMeta: string | WrapMeta, factor: VmkUnlockFactor | string): Promise<Uint8Array> {
+export async function unwrapVmk(wrapMeta: string | WrapMeta, factor: PasskeyUnlockFactor): Promise<Uint8Array> {
const meta = parseWrapMeta(wrapMeta);
- const normalized: VmkUnlockFactor = typeof factor === 'string' ? { kind: 'password', password: factor } : factor;
for (const copy of meta.copies) {
try {
- if (normalized.kind === 'password' && copy.kind === 'password') {
- const vmk = await unwrapPasswordCopy(copy, normalized.password);
- try {
- assertLength(vmk, KEY_BYTES, 'VMK');
- return vmk;
- } catch (error) {
- vmk.fill(0);
- throw error;
- }
- }
- if (normalized.kind === 'passkey' && copy.kind === 'passkey') {
- const vmk = await unwrapPasskeyCopy(copy, normalized);
+ if (copy.kind === 'passkey') {
+ const vmk = await unwrapPasskeyCopy(copy, factor);
try {
assertLength(vmk, KEY_BYTES, 'VMK');
return vmk;
@@ -712,13 +473,6 @@ export function protectedRecordAadHex(context: ProtectedRecordContext): string {
return bytesToHex(protectedRecordAad(context));
}
-function requireNonBlankPassword(password: string): string {
- if (typeof password !== 'string' || password.trim() === '') {
- throw new Error('password must not be empty');
- }
- return password;
-}
-
function requirePinnedPublicKey(publicKey: AvaultPublicKey): AvaultPublicKey & { fingerprint: string } {
if (!publicKey.fingerprint) {
throw new Error('protected DEK release requires a pinned avault public key fingerprint');