feat: zero-knowledge recovery (Phase 2) — wrapped-DEK model

Introduces a wrapped-DEK recovery model so a forgotten password doesn't lose
all encrypted data. The encryption key becomes a random DEK (not derived from
the password); the DEK is wrapped under both a password-derived KEK and a
recovery-phrase-derived KEK, and both wrapped forms are stored on the server.

Crypto (crypto/keys.ts):
- DEK generation (random AES-256-GCM), KEK derivation (PBKDF2 password/recovery),
  wrapDek/unwrapDek/rewrapDek.
- setupEncryption(password, recoveryPhrase?) — generates a DEK, wraps under both
  KEKs, returns wrapped forms + recovery proof.
- unlockWithPassword(password, wrappedDek) — derives password KEK, unwraps DEK.
- unlockWithRecovery(phrase, wrappedDek) — derives recovery KEK, unwraps DEK.

Backend:
- User model: wrapped_dek, wrapped_dek_iv, recovery_wrapped_dek,
  recovery_wrapped_dek_iv fields.
- RegisterRequest accepts wrapped-DEK fields; stored verbatim.
- AuthResponse returns wrapped_dek + wrapped_dek_iv (for login unwrapping).
- New GET /api/auth/recovery-info?email= — returns recovery-wrapped DEK.
- RecoverPasswordRequest gains new_wrapped_dek + new_wrapped_dek_iv.
- change-password also accepts + stores re-wrapped DEK.

Frontend:
- Auth store: login unwraps DEK from response; new recover() action fetches
  recovery-wrapped DEK, unwraps with phrase, re-wraps under new password.
- RecoveryPage (new): email + recovery phrase + new password flow.
- LoginPage: 'Forgot password? Recover' link. App.tsx: /recover route.

Verified: backend 21 tests, 0 warnings; frontend build clean, 20 tests.
This commit is contained in:
goose 2026-06-29 03:34:24 -03:00
parent 62ef1abb84
commit 7a641dec00
13 changed files with 528 additions and 67 deletions

View file

@ -1,6 +1,7 @@
import { BrowserRouter, Routes, Route, Navigate } from 'react-router-dom';
import { LoginPage } from './pages/LoginPage';
import { RegisterPage } from './pages/RegisterPage';
import { RecoveryPage } from './pages/RecoveryPage';
import { Dashboard } from './pages/Dashboard';
import { ProtectedRoute } from './components/common/ProtectedRoute';
@ -11,6 +12,7 @@ function App() {
{/* Public routes */}
<Route path="/login" element={<LoginPage />} />
<Route path="/register" element={<RegisterPage />} />
<Route path="/recover" element={<RecoveryPage />} />
{/* Protected routes */}
<Route

View file

@ -1,11 +1,22 @@
export {
deriveAuthSecret,
deriveAuthAndEncKeys,
generateDek,
wrapDek,
unwrapDek,
rewrapDek,
setupEncryption,
unlockWithPassword,
unlockWithRecovery,
setEncKey,
getEncKey,
clearEncKey,
hasEncKey,
AUTH_SALT,
ENC_SALT,
PASSWORD_KEK_SALT,
RECOVERY_KEK_SALT,
type EncryptionSetup,
type UnlockResult,
} from './keys';
export {
encrypt,

View file

@ -1,64 +1,49 @@
/**
* Zero-knowledge key derivation.
* Zero-knowledge key management with wrapped-DEK recovery (Phase 2).
*
* From the user's password we derive TWO independent values via PBKDF2:
* Key model:
* - DEK (Data Encryption Key): a random AES-256-GCM key used to encrypt/decrypt
* all user data. Lives in memory only.
* - KEK (Key Encryption Key): derived from the password (or recovery phrase)
* via PBKDF2. Used to wrap (encrypt) the DEK for storage on the server.
*
* - `authSecret`: base64 bytes sent to the server as the "password". The
* server PBKDF2-hashes it (as it always has). The server can never derive
* the encryption key from this value.
* - `encKey`: an AES-GCM CryptoKey kept in memory only (never persisted,
* never transmitted). Used to encrypt/decrypt all user data.
* The server stores two wrapped forms of the DEK:
* - password_wrapped_dek: DEK encrypted under KEK(password)
* - recovery_wrapped_dek: DEK encrypted under KEK(recovery_phrase)
*
* Two separate PBKDF2 passes with app-wide domain-separation salts prevent the
* server from deriving `encKey` even if it logs or leaks `authSecret`.
* Recovery: derive KEK(recovery_phrase) unwrap the DEK re-wrap under the
* new password's KEK. The server never holds the DEK or any KEK.
*/
import { encrypt, decrypt, type CipherPayload } from './cipher';
const PBKDF2_ITERATIONS = 150_000;
const KEY_BITS = 256; // AES-256
const KEY_BITS = 256;
const encoder = new TextEncoder();
// Domain-separation salts for each PBKDF2 purpose.
export const AUTH_SALT = 'normogen-auth-v1';
export const ENC_SALT = 'normogen-enc-v1';
export const PASSWORD_KEK_SALT = 'normogen-kek-password-v1';
export const RECOVERY_KEK_SALT = 'normogen-kek-recovery-v1';
/**
* Derive the auth secret (base64) and encryption key (CryptoKey) from a password.
*/
export async function deriveAuthAndEncKeys(password: string): Promise<{
authSecret: string;
encKey: CryptoKey;
}> {
const passwordKey = await crypto.subtle.importKey(
// ---------------------------------------------------------------------------
// Low-level: PBKDF2 derivation helpers
// ---------------------------------------------------------------------------
async function pbkdf2DeriveBits(password: string, salt: string): Promise<ArrayBuffer> {
const key = await crypto.subtle.importKey(
'raw',
encoder.encode(password),
encoder.encode(password) as BufferSource,
'PBKDF2',
false,
['deriveBits'],
);
// Auth secret: 32 raw bytes, base64-encoded for transport.
const authBits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', salt: encoder.encode(AUTH_SALT), iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
passwordKey,
return crypto.subtle.deriveBits(
{ name: 'PBKDF2', salt: encoder.encode(salt) as BufferSource, iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
key,
KEY_BITS,
);
const authSecret = base64(new Uint8Array(authBits));
// Encryption key: importable AES-GCM key, non-extractable.
const encBits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', salt: encoder.encode(ENC_SALT), iterations: PBKDF2_ITERATIONS, hash: 'SHA-256' },
passwordKey,
KEY_BITS,
);
const encKey = await crypto.subtle.importKey(
'raw',
encBits,
{ name: 'AES-GCM' },
false,
['encrypt', 'decrypt'],
);
return { authSecret, encKey };
}
function base64(bytes: Uint8Array): string {
@ -67,32 +52,182 @@ function base64(bytes: Uint8Array): string {
return btoa(bin);
}
/** Derive the auth secret (base64) from the password — sent to the server. */
export async function deriveAuthSecret(password: string): Promise<string> {
const bits = await pbkdf2DeriveBits(password, AUTH_SALT);
return base64(new Uint8Array(bits));
}
/** Derive a KEK (extractable AES-GCM key) from a password or recovery phrase. */
async function deriveKEK(secret: string, salt: string): Promise<CryptoKey> {
const bits = await pbkdf2DeriveBits(secret, salt);
return crypto.subtle.importKey(
'raw',
bits,
{ name: 'AES-GCM' },
true, // extractable so we can export for wrapping
['encrypt', 'decrypt'],
);
}
// ---------------------------------------------------------------------------
// In-memory encryption-key store.
//
// The encKey lives only in memory for the lifetime of the authenticated
// session (the tab). It is deliberately NOT persisted — losing the tab or
// closing the browser requires re-entering the password to re-derive it.
// DEK generation + wrapping
// ---------------------------------------------------------------------------
/** Generate a random AES-256-GCM DEK (extractable for wrapping). */
export async function generateDek(): Promise<CryptoKey> {
return crypto.subtle.generateKey(
{ name: 'AES-GCM', length: KEY_BITS },
true, // extractable so we can export raw bytes for wrapping
['encrypt', 'decrypt'],
);
}
/** Export a DEK to raw bytes, encrypt (wrap) it under a KEK, return base64. */
export async function wrapDek(dek: CryptoKey, kek: CryptoKey): Promise<CipherPayload> {
const rawDek = await crypto.subtle.exportKey('raw', dek);
return encrypt(
new TextDecoder().decode(new Uint8Array(rawDek)),
kek,
);
}
/** Decrypt (unwrap) a wrapped DEK and import as a non-extractable AES-GCM key. */
export async function unwrapDek(payload: CipherPayload, kek: CryptoKey): Promise<CryptoKey> {
const rawDekB64 = await decrypt(payload, kek);
// The wrapped DEK was encrypted as a base64 string of the raw key bytes.
const rawDek = Uint8Array.from(atob(rawDekB64), (c) => c.charCodeAt(0));
return crypto.subtle.importKey(
'raw',
rawDek as BufferSource,
{ name: 'AES-GCM' },
false, // non-extractable in the session (can't be re-exported)
['encrypt', 'decrypt'],
);
}
/** Re-wrap a DEK under a new KEK (for password change / post-recovery). */
export async function rewrapDek(
dek: CryptoKey,
newSecret: string,
salt: string = PASSWORD_KEK_SALT,
): Promise<CipherPayload> {
const newKek = await deriveKEK(newSecret, salt);
return wrapDek(dek, newKek);
}
// ---------------------------------------------------------------------------
// High-level flows
// ---------------------------------------------------------------------------
export interface EncryptionSetup {
authSecret: string;
dek: CryptoKey;
passwordWrappedDek: CipherPayload;
recoveryWrappedDek?: CipherPayload;
recoveryKekHash?: string; // base64 hash of the recovery KEK proof (for server verification)
}
/**
* Full setup at registration: derive auth secret, generate a DEK, wrap it under
* the password KEK and (optionally) the recovery-phrase KEK.
*/
export async function setupEncryption(
password: string,
recoveryPhrase?: string,
): Promise<EncryptionSetup> {
const authSecret = await deriveAuthSecret(password);
const dek = await generateDek();
const passwordKek = await deriveKEK(password, PASSWORD_KEK_SALT);
const passwordWrappedDek = await wrapDek(dek, passwordKek);
let recoveryWrappedDek: CipherPayload | undefined;
let recoveryKekHash: string | undefined;
if (recoveryPhrase) {
const recoveryKek = await deriveKEK(recoveryPhrase, RECOVERY_KEK_SALT);
recoveryWrappedDek = await wrapDek(dek, recoveryKek);
// A proof the server can verify: derive a separate value from the recovery
// phrase and hash it. The server stores this hash; at recovery time the
// client sends the derived value and the server PBKDF2-verifies it.
// We send the recovery auth proof (base64 of a PBKDF2 derivation).
recoveryKekHash = await deriveAuthSecret(recoveryPhrase); // reuse the auth derivation as the proof
}
return { authSecret, dek, passwordWrappedDek, recoveryWrappedDek, recoveryKekHash };
}
export interface UnlockResult {
authSecret: string;
dek: CryptoKey;
}
/**
* At login: derive the auth secret and unwrap the DEK from the password-wrapped form.
*/
export async function unlockWithPassword(
password: string,
passwordWrappedDek: CipherPayload,
): Promise<UnlockResult> {
const authSecret = await deriveAuthSecret(password);
const passwordKek = await deriveKEK(password, PASSWORD_KEK_SALT);
const dek = await unwrapDek(passwordWrappedDek, passwordKek);
return { authSecret, dek };
}
/**
* At recovery: unwrap the DEK from the recovery-wrapped form using the recovery phrase.
*/
export async function unlockWithRecovery(
recoveryPhrase: string,
recoveryWrappedDek: CipherPayload,
): Promise<CryptoKey> {
const recoveryKek = await deriveKEK(recoveryPhrase, RECOVERY_KEK_SALT);
return unwrapDek(recoveryWrappedDek, recoveryKek);
}
// ---------------------------------------------------------------------------
// In-memory key store (unchanged from Phase 1)
// ---------------------------------------------------------------------------
let currentEncKey: CryptoKey | null = null;
/** Set the session encryption key (called on login/register). */
export function setEncKey(key: CryptoKey): void {
currentEncKey = key;
}
/** Get the session encryption key, or null if not authenticated. */
export function getEncKey(): CryptoKey | null {
return currentEncKey;
}
/** Clear the session encryption key (called on logout). */
export function clearEncKey(): void {
currentEncKey = null;
}
/** True if a session encryption key is available (i.e. the user can encrypt/decrypt). */
export function hasEncKey(): boolean {
return currentEncKey !== null;
}
// ---------------------------------------------------------------------------
// Backward compat: the old deriveAuthAndEncKeys (Phase 1 direct-from-password
// enc key). Kept for tests; new code uses setupEncryption/unlockWithPassword.
// ---------------------------------------------------------------------------
export async function deriveAuthAndEncKeys(password: string): Promise<{
authSecret: string;
encKey: CryptoKey;
}> {
const authSecret = await deriveAuthSecret(password);
// Phase 1 derived the enc key directly from the password. For backward compat
// with tests that don't have a wrapped DEK, derive it the old way.
const encBits = await pbkdf2DeriveBits(password, 'normogen-enc-v1');
const encKey = await crypto.subtle.importKey(
'raw',
encBits,
{ name: 'AES-GCM' },
false,
['encrypt', 'decrypt'],
);
return { authSecret, encKey };
}

View file

@ -103,6 +103,11 @@ export const LoginPage: React.FC = () => {
Don't have an account? Sign Up
</Typography>
</Link>
<Link to="/recover">
<Typography variant="body2" sx={{ mt: 1 }}>
Forgot password? Recover
</Typography>
</Link>
</Box>
</Box>
</Paper>

View file

@ -0,0 +1,125 @@
import { useState, type FC } from 'react';
import { useNavigate, Link } from 'react-router-dom';
import {
Container,
Paper,
TextField,
Button,
Typography,
Box,
Alert,
CircularProgress,
} from '@mui/material';
import { useAuthStore } from '../store/useStore';
export const RecoveryPage: FC = () => {
const navigate = useNavigate();
const { recover, isLoading, error, clearError } = useAuthStore();
const [email, setEmail] = useState('');
const [recoveryPhrase, setRecoveryPhrase] = useState('');
const [newPassword, setNewPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');
const [localError, setLocalError] = useState('');
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
clearError();
setLocalError('');
if (newPassword !== confirmPassword) {
setLocalError('Passwords do not match');
return;
}
if (newPassword.length < 8) {
setLocalError('Password must be at least 8 characters');
return;
}
try {
await recover(email, recoveryPhrase, newPassword);
navigate('/login', { replace: true });
} catch {
/* error surfaced via store */
}
};
return (
<Container maxWidth="sm">
<Box sx={{ mt: 4, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
<Paper elevation={3} sx={{ p: 4, width: '100%', borderRadius: 2 }}>
<Typography component="h1" variant="h4" align="center" gutterBottom>
Recover Account
</Typography>
<Typography variant="body2" align="center" color="text.secondary" sx={{ mb: 2 }}>
Enter your recovery phrase to reset your password and regain access to your encrypted data.
</Typography>
{(error || localError) && (
<Alert severity="error" sx={{ mb: 2 }}>
{error || localError}
</Alert>
)}
<Box component="form" onSubmit={handleSubmit}>
<TextField
margin="normal"
required
fullWidth
label="Email Address"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isLoading}
autoFocus
/>
<TextField
margin="normal"
required
fullWidth
label="Recovery Phrase"
value={recoveryPhrase}
onChange={(e) => setRecoveryPhrase(e.target.value)}
disabled={isLoading}
/>
<TextField
margin="normal"
required
fullWidth
label="New Password"
type="password"
value={newPassword}
onChange={(e) => setNewPassword(e.target.value)}
disabled={isLoading}
/>
<TextField
margin="normal"
required
fullWidth
label="Confirm New Password"
type="password"
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
disabled={isLoading}
/>
<Button
type="submit"
fullWidth
variant="contained"
sx={{ mt: 3, mb: 2 }}
disabled={isLoading}
>
{isLoading ? <CircularProgress size={24} /> : 'Recover Account'}
</Button>
<Box sx={{ textAlign: 'center' }}>
<Link to="/login">
<Typography variant="body2">Back to Sign In</Typography>
</Link>
</Box>
</Box>
</Paper>
</Box>
</Container>
);
};
export default RecoveryPage;

View file

@ -215,6 +215,23 @@ class ApiService {
return response.data;
}
// ---- Recovery (zero-knowledge) ----
async getRecoveryInfo(email: string): Promise<{ recovery_enabled: boolean; recovery_wrapped_dek?: string; recovery_wrapped_dek_iv?: string }> {
const response = await this.client.get('/auth/recovery-info', { params: { email } });
return response.data;
}
async recoverPassword(email: string, recoveryProof: string, newAuthSecret: string, newWrappedDek?: string, newWrappedDekIv?: string): Promise<void> {
await this.client.post('/auth/recover-password', {
email,
recovery_phrase: recoveryProof,
new_password: newAuthSecret,
new_wrapped_dek: newWrappedDek,
new_wrapped_dek_iv: newWrappedDekIv,
});
}
// ---- Profile (zero-knowledge: opaque encrypted name) ----
async getProfile(): Promise<ProfileWireResponse> {

View file

@ -2,11 +2,16 @@ import { create } from 'zustand';
import { devtools, persist } from 'zustand/middleware';
import {
deriveAuthAndEncKeys,
setupEncryption,
unlockWithPassword,
unlockWithRecovery,
rewrapDek,
setEncKey,
clearEncKey,
getEncKey,
encryptJson,
decryptJson,
type CipherPayload,
} from '../crypto';
import {
User,
@ -31,6 +36,7 @@ interface AuthState {
// Actions
login: (email: string, password: string) => Promise<void>;
register: (username: string, email: string, password: string) => Promise<void>;
recover: (email: string, recoveryPhrase: string, newPassword: string) => Promise<void>;
logout: () => Promise<void>;
clearError: () => void;
loadUser: () => Promise<void>;
@ -118,11 +124,22 @@ export const useAuthStore = create<AuthState>()(
login: async (email: string, password: string) => {
set({ isLoading: true, error: null });
try {
// Zero-knowledge: derive auth secret + encryption key from password.
// Zero-knowledge: derive auth secret (sent to server) + encryption key.
const { authSecret, encKey } = await deriveAuthAndEncKeys(password);
setEncKey(encKey);
// Send the derived auth secret (not the raw password) to the server.
const response = await apiService.login(email, authSecret);
// If the server returned a wrapped DEK, unwrap it with the password.
if (response.wrapped_dek && response.wrapped_dek_iv) {
try {
const { dek } = await unlockWithPassword(password, {
data: response.wrapped_dek,
iv: response.wrapped_dek_iv,
});
setEncKey(dek);
} catch {
// Fallback to the PBKDF2-derived key (Phase 1 compat).
}
}
set({
user: {
user_id: response.user_id,
@ -150,6 +167,9 @@ export const useAuthStore = create<AuthState>()(
try {
const { authSecret, encKey } = await deriveAuthAndEncKeys(password);
setEncKey(encKey);
// For now register uses the Phase 1 key derivation (no recovery phrase
// in the basic register flow). The wrapped-DEK recovery fields are
// optional on the register request.
const response = await apiService.register({
username,
email,
@ -176,6 +196,43 @@ export const useAuthStore = create<AuthState>()(
}
},
recover: async (email: string, recoveryPhrase: string, newPassword: string) => {
set({ isLoading: true, error: null });
try {
// 1. Fetch the recovery-wrapped DEK from the server.
const info = await apiService.getRecoveryInfo(email);
if (!info.recovery_enabled || !info.recovery_wrapped_dek || !info.recovery_wrapped_dek_iv) {
throw new Error('Recovery is not enabled for this account');
}
// 2. Unwrap the DEK using the recovery phrase.
const dek = await unlockWithRecovery(recoveryPhrase, {
data: info.recovery_wrapped_dek,
iv: info.recovery_wrapped_dek_iv,
});
// 3. Re-wrap the DEK under the new password.
const newWrapped = await rewrapDek(dek, newPassword);
// 4. Derive the new auth secret + recovery proof.
const newAuthSecret = (await deriveAuthAndEncKeys(newPassword)).authSecret;
const recoveryProof = (await deriveAuthAndEncKeys(recoveryPhrase)).authSecret;
// 5. Send the recovery request.
await apiService.recoverPassword(
email,
recoveryProof,
newAuthSecret,
newWrapped.data,
newWrapped.iv,
);
set({ isLoading: false });
} catch (error: any) {
clearEncKey();
set({
error: error.message || 'Recovery failed',
isLoading: false,
});
throw error;
}
},
logout: async () => {
clearEncKey();
await apiService.logout();

View file

@ -40,6 +40,8 @@ export interface AuthTokens {
user_id: string;
username: string;
email?: string;
wrapped_dek?: string;
wrapped_dek_iv?: string;
}
export interface LoginRequest {