Security fixes: swarm signature verification and error handling

This commit is contained in:
Clawd Deploy Bot
2026-01-30 16:50:49 +01:00
parent 495a037eb1
commit 50355b740a
21 changed files with 850 additions and 467 deletions
+54 -64
View File
@@ -1,6 +1,6 @@
'use client';
import { createContext, useContext, useEffect, useState } from 'react';
import { createContext, useContext, useEffect, useState, useCallback } from 'react';
import { useUserIdentity } from '@/lib/hooks/useUserIdentity';
export interface User {
@@ -18,15 +18,18 @@ interface AuthContextType {
isAdmin: boolean;
loading: boolean;
isIdentityUnlocked: boolean;
isRestoring: boolean; // True while checking persistence
did: string | null;
handle: string | null;
checkAdmin: () => Promise<void>;
unlockIdentity: (password: string, explicitUser?: User) => Promise<void>;
login: (user: User) => void;
logout: () => Promise<void>;
showUnlockPrompt: boolean;
setShowUnlockPrompt: (show: boolean, onSuccess?: () => void) => void;
lockIdentity: () => Promise<void>; // New: manual lock
signUserAction: (action: string, data: any) => Promise<any>;
requiresUnlock: boolean; // True if user has encrypted key but not unlocked
showUnlockPrompt: boolean;
setShowUnlockPrompt: (show: boolean) => void;
}
const AuthContext = createContext<AuthContextType>({
@@ -34,33 +37,39 @@ const AuthContext = createContext<AuthContextType>({
isAdmin: false,
loading: true,
isIdentityUnlocked: false,
isRestoring: false,
did: null,
handle: null,
checkAdmin: async () => { },
unlockIdentity: async () => { },
login: () => { },
logout: async () => { },
lockIdentity: async () => { },
signUserAction: async () => Promise.reject('Not initialized'),
requiresUnlock: false,
showUnlockPrompt: false,
setShowUnlockPrompt: () => { },
signUserAction: async () => Promise.reject('Not initialized'),
});
export function AuthProvider({ children }: { children: React.ReactNode }) {
const [user, setUser] = useState<User | null>(null);
const [isAdmin, setIsAdmin] = useState(false);
const [loading, setLoading] = useState(true);
const [showUnlockPrompt, setShowUnlockPrompt] = useState(false);
// Integrate useUserIdentity hook
// Integrate useUserIdentity hook with persistence
const {
identity,
isUnlocked,
isRestoring,
initializeIdentity,
unlockIdentity: unlockIdentityHook,
lockIdentity: lockIdentityHook,
clearIdentity,
signUserAction,
} = useUserIdentity();
const checkAdmin = async () => {
const checkAdmin = useCallback(async () => {
try {
const res = await fetch('/api/admin/me');
const data = await res.json();
@@ -68,39 +77,13 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
} catch {
setIsAdmin(false);
}
};
const [showUnlockPrompt, _setShowUnlockPrompt] = useState(false);
const [onUnlockCallback, setOnUnlockCallback] = useState<(() => void) | null>(null);
const setShowUnlockPrompt = (show: boolean, onSuccess?: () => void) => {
_setShowUnlockPrompt(show);
if (show && onSuccess) {
setOnUnlockCallback(() => onSuccess);
} else if (!show) {
// If hiding without success (cancel), clear callback ???
// Actually unlockIdentity handles success case.
// If explicit hide (cancel), we should probably clear it.
// But unlockIdentity calls setShowUnlockPrompt(false) on success too.
// So we handle callback execution in unlockIdentity,
// and clearing in unlockIdentity OR here if it wasn't executed?
// Let's rely on unlockIdentity to execute and clear.
// If just closing dialog (cancel), we clear it.
// But we don't know if this call is from cancel or success?
// unlockIdentity calls this.
}
};
// Clear callback on close if it wasn't executed?
// It's safer to clear it when closing prompt to avoid stale callbacks.
// But unlockIdentity calls setShowUnlockPrompt(false) AFTER executing.
// So:
}, []);
/**
* Unlock the user's identity with their password
* Persists the key for auto-unlock on refresh
*/
const unlockIdentity = async (password: string, explicitUser?: User) => {
const unlockIdentity = useCallback(async (password: string, explicitUser?: User) => {
const targetUser = explicitUser || user;
if (!targetUser?.privateKeyEncrypted) {
@@ -115,50 +98,51 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
targetUser.publicKey
);
// Execute queued callback if exists
if (onUnlockCallback) {
try {
onUnlockCallback();
} catch (e) {
console.error('Error executing unlock callback:', e);
}
setOnUnlockCallback(null);
}
setShowUnlockPrompt(false); // Close prompt on success
};
}, [user, unlockIdentityHook]);
/**
* Manually lock the identity (user wants to secure their session)
*/
const lockIdentity = useCallback(async () => {
await lockIdentityHook();
}, [lockIdentityHook]);
/**
* Manually set the user state (called after successful login)
*/
const login = (userData: User) => {
const login = useCallback((userData: User) => {
setUser(userData);
// We re-check admin status just in case
checkAdmin();
};
// Initialize identity - will try to auto-restore if possible
if (userData.did && userData.publicKey) {
initializeIdentity({
did: userData.did,
handle: userData.handle,
publicKey: userData.publicKey,
privateKeyEncrypted: userData.privateKeyEncrypted,
});
}
}, [checkAdmin, initializeIdentity]);
/**
* Logout the user and clear their identity
*/
const logout = async () => {
const logout = useCallback(async () => {
try {
// Call the logout API endpoint
await fetch('/api/auth/logout', { method: 'POST' });
// Clear the user's identity (private key from localStorage)
clearIdentity();
await clearIdentity();
setShowUnlockPrompt(false);
setOnUnlockCallback(null);
// Clear the user state
setUser(null);
setIsAdmin(false);
} catch (error) {
console.error('[Auth] Logout failed:', error);
throw error;
}
};
}, [clearIdentity]);
// Load auth state on mount
useEffect(() => {
const loadAuth = async () => {
setLoading(true);
@@ -168,8 +152,8 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const data = await res.json();
setUser(data.user);
// Initialize identity if we have the required data
if (data.user?.did && data.user?.publicKey && data.user?.privateKeyEncrypted) {
// Initialize identity - will auto-restore if persisted
if (data.user?.did && data.user?.publicKey) {
await initializeIdentity({
did: data.user.did,
handle: data.user.handle,
@@ -183,18 +167,21 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
}
} else {
setUser(null);
clearIdentity();
await clearIdentity();
}
} catch {
setUser(null);
clearIdentity();
await clearIdentity();
} finally {
setLoading(false);
}
};
loadAuth();
}, []);
}, [checkAdmin, initializeIdentity, clearIdentity]);
// Determine if unlock is required (has encrypted key but not unlocked)
const requiresUnlock = !!user?.privateKeyEncrypted && !isUnlocked && !isRestoring;
return (
<AuthContext.Provider value={{
@@ -202,15 +189,18 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
isAdmin,
loading,
isIdentityUnlocked: isUnlocked,
isRestoring,
did: identity?.did || null,
handle: identity?.handle || null,
checkAdmin,
unlockIdentity,
login,
logout,
lockIdentity,
signUserAction,
requiresUnlock,
showUnlockPrompt,
setShowUnlockPrompt,
signUserAction,
}}>
{children}
</AuthContext.Provider>
+342
View File
@@ -0,0 +1,342 @@
/**
* Secure Key Persistence
*
* Stores the encrypted private key in IndexedDB so the user stays unlocked
* across page refreshes and tabs. The key is wrapped with a session key
* that's stored in localStorage (cleared on browser close/logout).
*
* Security model:
* - Private key is ALWAYS encrypted at rest (IndexedDB)
* - Session key in localStorage is needed to unwrap
* - XSS attacker needs BOTH storage access AND the session key
* - On logout, both are cleared
*/
import { deserializeEncryptedKey, type EncryptedPrivateKey } from './private-key-client';
const DB_NAME = 'synapsis-identity';
const DB_VERSION = 1;
const STORE_NAME = 'keys';
const SESSION_KEY_ITEM = 'synapsis_session_key';
const WRAPPED_KEY_ITEM = 'synapsis_wrapped_key';
interface WrappedKey {
wrapped: string; // Base64 of wrapped key
iv: string; // Base64 of IV
salt: string; // Base64 of salt
createdAt: number; // Timestamp for expiry
}
interface SessionData {
key: string; // Base64 of session encryption key
createdAt: number;
}
// ============================================
// IndexedDB Operations
// ============================================
async function openDB(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
request.onupgradeneeded = (event) => {
const db = (event.target as IDBOpenDBRequest).result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
db.createObjectStore(STORE_NAME);
}
};
});
}
async function storeInDB(key: string, value: any): Promise<void> {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
const request = store.put(value, key);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
}
async function getFromDB<T>(key: string): Promise<T | null> {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readonly');
const store = tx.objectStore(STORE_NAME);
const request = store.get(key);
request.onsuccess = () => resolve(request.result ?? null);
request.onerror = () => reject(request.error);
});
}
async function removeFromDB(key: string): Promise<void> {
const db = await openDB();
return new Promise((resolve, reject) => {
const tx = db.transaction(STORE_NAME, 'readwrite');
const store = tx.objectStore(STORE_NAME);
const request = store.delete(key);
request.onsuccess = () => resolve();
request.onerror = () => reject(request.error);
});
}
// ============================================
// Crypto Operations
// ============================================
/**
* Derive a session key from the user's password
* This is fast and deterministic - same password = same session key
*/
export async function deriveSessionKey(password: string): Promise<CryptoKey> {
const encoder = new TextEncoder();
const passwordData = encoder.encode(password);
// Import password as key material
const keyMaterial = await crypto.subtle.importKey(
'raw',
passwordData,
'PBKDF2',
false,
['deriveKey']
);
// Derive a session key - using a fixed salt since we want deterministic output
// The salt is public knowledge anyway (stored with wrapped key)
const fixedSalt = encoder.encode('synapsis-session-v1');
return crypto.subtle.deriveKey(
{
name: 'PBKDF2',
salt: fixedSalt,
iterations: 10000, // Lower than main encryption since this is session-only
hash: 'SHA-256',
},
keyMaterial,
{ name: 'AES-GCM', length: 256 },
true, // extractable so we can store it
['wrapKey', 'unwrapKey']
);
}
/**
* Generate a random session key (for when we already have the decrypted key)
*/
async function generateSessionKey(): Promise<CryptoKey> {
return crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true,
['wrapKey', 'unwrapKey']
);
}
async function exportSessionKey(key: CryptoKey): Promise<string> {
const exported = await crypto.subtle.exportKey('raw', key);
return arrayBufferToBase64(exported);
}
async function importSessionKey(keyData: string): Promise<CryptoKey> {
const buffer = base64ToArrayBuffer(keyData);
return crypto.subtle.importKey(
'raw',
buffer,
{ name: 'AES-GCM', length: 256 },
false, // not extractable after import
['wrapKey', 'unwrapKey']
);
}
// ============================================
// Key Wrapping / Unwrapping
// ============================================
/**
* Wrap the raw private key data with a session key for storage
* This works on the raw PKCS8 bytes, not the CryptoKey
*/
async function wrapRawPrivateKey(
privateKeyBase64: string,
sessionKey: CryptoKey
): Promise<WrappedKey> {
const iv = crypto.getRandomValues(new Uint8Array(12));
// Convert base64 private key to bytes
const privateKeyBytes = base64ToArrayBuffer(privateKeyBase64);
// Encrypt the raw key data using AES-GCM
const encrypted = await crypto.subtle.encrypt(
{ name: 'AES-GCM', iv },
sessionKey,
privateKeyBytes
);
return {
wrapped: arrayBufferToBase64(encrypted),
iv: arrayBufferToBase64(iv),
salt: arrayBufferToBase64(new Uint8Array(0)), // Not used but kept for structure
createdAt: Date.now(),
};
}
/**
* Unwrap the private key using the session key
* Returns the raw key bytes that can then be imported
*/
async function unwrapRawPrivateKey(
wrapped: WrappedKey,
sessionKey: CryptoKey
): Promise<ArrayBuffer> {
const wrappedBuffer = base64ToArrayBuffer(wrapped.wrapped);
const iv = base64ToArrayBuffer(wrapped.iv);
// Decrypt the raw key data
const decrypted = await crypto.subtle.decrypt(
{ name: 'AES-GCM', iv },
sessionKey,
wrappedBuffer
);
return decrypted;
}
// ============================================
// Public API
// ============================================
/**
* Save the unlocked private key for persistence
* Call this after the user unlocks with their password
*
* Note: We wrap the raw key data (not the CryptoKey) because the imported
* key is non-extractable for security. We have the raw PKCS8 data available
* right after decryption, before importing.
*/
export async function persistUnlockedKey(
privateKeyBase64: string,
password: string
): Promise<void> {
try {
// Derive session key from password
const sessionKey = await deriveSessionKey(password);
// Wrap the raw private key data (before importing as non-extractable)
const wrapped = await wrapRawPrivateKey(privateKeyBase64, sessionKey);
// Store wrapped key in IndexedDB
await storeInDB(WRAPPED_KEY_ITEM, wrapped);
// Store session key in localStorage (so it survives refreshes)
const sessionKeyData = await exportSessionKey(sessionKey);
const sessionData: SessionData = {
key: sessionKeyData,
createdAt: Date.now(),
};
localStorage.setItem(SESSION_KEY_ITEM, JSON.stringify(sessionData));
console.log('[KeyPersistence] Key persisted successfully');
} catch (error) {
console.error('[KeyPersistence] Failed to persist key:', error);
throw error;
}
}
/**
* Try to restore the private key from persistent storage
* Returns the raw key bytes if available, null otherwise
* The caller must then import these bytes as a non-extractable CryptoKey
*/
export async function tryRestoreKey(): Promise<ArrayBuffer | null> {
try {
// Get session key from localStorage
const sessionDataRaw = localStorage.getItem(SESSION_KEY_ITEM);
if (!sessionDataRaw) {
console.log('[KeyPersistence] No session key found');
return null;
}
const sessionData: SessionData = JSON.parse(sessionDataRaw);
// Check expiry (24 hours)
const MAX_AGE = 24 * 60 * 60 * 1000;
if (Date.now() - sessionData.createdAt > MAX_AGE) {
console.log('[KeyPersistence] Session expired');
await clearPersistentKey();
return null;
}
// Get wrapped key from IndexedDB
const wrapped = await getFromDB<WrappedKey>(WRAPPED_KEY_ITEM);
if (!wrapped) {
console.log('[KeyPersistence] No wrapped key found');
return null;
}
// Import session key
const sessionKey = await importSessionKey(sessionData.key);
// Unwrap to get raw key bytes
const privateKeyBytes = await unwrapRawPrivateKey(wrapped, sessionKey);
console.log('[KeyPersistence] Key restored successfully');
return privateKeyBytes;
} catch (error) {
console.error('[KeyPersistence] Failed to restore key:', error);
return null;
}
}
/**
* Clear the persisted key (logout)
*/
export async function clearPersistentKey(): Promise<void> {
try {
localStorage.removeItem(SESSION_KEY_ITEM);
await removeFromDB(WRAPPED_KEY_ITEM);
console.log('[KeyPersistence] Key cleared');
} catch (error) {
console.error('[KeyPersistence] Error clearing key:', error);
}
}
/**
* Check if a persisted key is available
*/
export async function hasPersistentKey(): Promise<boolean> {
const sessionData = localStorage.getItem(SESSION_KEY_ITEM);
if (!sessionData) return false;
try {
const parsed: SessionData = JSON.parse(sessionData);
const MAX_AGE = 24 * 60 * 60 * 1000;
return Date.now() - parsed.createdAt <= MAX_AGE;
} catch {
return false;
}
}
// ============================================
// Helpers
// ============================================
function arrayBufferToBase64(buffer: ArrayBuffer | Uint8Array): string {
const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);
let binary = '';
for (let i = 0; i < bytes.byteLength; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function base64ToArrayBuffer(base64: string): ArrayBuffer {
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer as ArrayBuffer;
}
+93 -111
View File
@@ -2,145 +2,127 @@
* User Signing Tests
*
* Tests for user-level cryptographic signing functionality
* Validates: Requirements US-1.2, US-1.4, US-6.3, US-6.4
* Validates: Key management, signing, and verification
*/
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { describe, it, expect, beforeEach } from 'vitest';
import {
getUserPrivateKey,
setUserPrivateKey,
keyStore,
hasUserPrivateKey,
clearUserPrivateKey,
hasUserPrivateKey
generateKeyPair,
exportPublicKey,
canonicalize
} from './user-signing';
// Mock localStorage for Node environment
const localStorageMock = (() => {
let store: Record<string, string> = {};
return {
getItem: (key: string) => store[key] || null,
setItem: (key: string, value: string) => {
store[key] = value;
},
removeItem: (key: string) => {
delete store[key];
},
clear: () => {
store = {};
},
};
})();
// Set up global mocks
global.localStorage = localStorageMock as any;
global.window = { localStorage: localStorageMock } as any;
describe('User Private Key Management', () => {
// Clean up localStorage before and after each test
describe('User Signing', () => {
beforeEach(() => {
localStorage.clear();
// Clear the key store before each test
keyStore.clear();
});
afterEach(() => {
localStorage.clear();
});
describe('setUserPrivateKey and getUserPrivateKey', () => {
it('should store and retrieve private key from localStorage', () => {
const testKey = '-----BEGIN PRIVATE KEY-----\ntest-key-content\n-----END PRIVATE KEY-----';
describe('keyStore', () => {
it('should store and retrieve identity', () => {
const identity = {
did: 'did:web:example.com:alice',
handle: 'alice',
publicKey: 'test-public-key'
};
// Store the key
setUserPrivateKey(testKey);
keyStore.setIdentity(identity);
const retrieved = keyStore.getIdentity();
// Retrieve the key
const retrievedKey = getUserPrivateKey();
// Verify it matches
expect(retrievedKey).toBe(testKey);
expect(retrieved).toEqual(identity);
});
it('should return null when no key is stored', () => {
const retrievedKey = getUserPrivateKey();
expect(retrievedKey).toBeNull();
});
it('should overwrite existing key when setting a new one', () => {
const firstKey = '-----BEGIN PRIVATE KEY-----\nfirst-key\n-----END PRIVATE KEY-----';
const secondKey = '-----BEGIN PRIVATE KEY-----\nsecond-key\n-----END PRIVATE KEY-----';
// Store first key
setUserPrivateKey(firstKey);
expect(getUserPrivateKey()).toBe(firstKey);
// Store second key
setUserPrivateKey(secondKey);
expect(getUserPrivateKey()).toBe(secondKey);
});
});
describe('clearUserPrivateKey', () => {
it('should remove private key from localStorage', () => {
const testKey = '-----BEGIN PRIVATE KEY-----\ntest-key-content\n-----END PRIVATE KEY-----';
// Store the key
setUserPrivateKey(testKey);
expect(getUserPrivateKey()).toBe(testKey);
// Clear the key
clearUserPrivateKey();
// Verify it's removed
expect(getUserPrivateKey()).toBeNull();
});
it('should be idempotent (safe to call multiple times)', () => {
const testKey = '-----BEGIN PRIVATE KEY-----\ntest-key-content\n-----END PRIVATE KEY-----';
// Store and clear
setUserPrivateKey(testKey);
clearUserPrivateKey();
// Clear again (should not throw)
expect(() => clearUserPrivateKey()).not.toThrow();
expect(getUserPrivateKey()).toBeNull();
});
it('should work when no key was stored', () => {
// Clear when nothing is stored (should not throw)
expect(() => clearUserPrivateKey()).not.toThrow();
expect(getUserPrivateKey()).toBeNull();
it('should return null when no identity is set', () => {
expect(keyStore.getIdentity()).toBeNull();
});
});
describe('hasUserPrivateKey', () => {
it('should return true when key is stored', () => {
const testKey = '-----BEGIN PRIVATE KEY-----\ntest-key-content\n-----END PRIVATE KEY-----';
setUserPrivateKey(testKey);
expect(hasUserPrivateKey()).toBe(true);
});
it('should return false when no key is stored', () => {
expect(hasUserPrivateKey()).toBe(false);
});
it('should return false after key is cleared', () => {
const testKey = '-----BEGIN PRIVATE KEY-----\ntest-key-content\n-----END PRIVATE KEY-----';
setUserPrivateKey(testKey);
expect(hasUserPrivateKey()).toBe(true);
clearUserPrivateKey();
expect(hasUserPrivateKey()).toBe(false);
});
});
describe('localStorage key name', () => {
it('should use the correct localStorage key', () => {
const testKey = '-----BEGIN PRIVATE KEY-----\ntest-key-content\n-----END PRIVATE KEY-----';
setUserPrivateKey(testKey);
describe('clearUserPrivateKey', () => {
it('should be idempotent (safe to call multiple times)', () => {
expect(() => clearUserPrivateKey()).not.toThrow();
expect(hasUserPrivateKey()).toBe(false);
});
});
describe('generateKeyPair', () => {
it('should generate a valid ECDSA P-256 key pair', async () => {
const keyPair = await generateKeyPair();
// Verify the key is stored with the correct name
const storedValue = localStorage.getItem('synapsis_user_private_key');
expect(storedValue).toBe(testKey);
expect(keyPair).toHaveProperty('privateKey');
expect(keyPair).toHaveProperty('publicKey');
expect(keyPair.privateKey.type).toBe('private');
expect(keyPair.publicKey.type).toBe('public');
expect(keyPair.privateKey.algorithm.name).toBe('ECDSA');
expect(keyPair.publicKey.algorithm.name).toBe('ECDSA');
});
});
describe('exportPublicKey', () => {
it('should export public key as base64', async () => {
const keyPair = await generateKeyPair();
const exported = await exportPublicKey(keyPair.publicKey);
expect(typeof exported).toBe('string');
expect(exported.length).toBeGreaterThan(0);
// Should be valid base64
expect(() => atob(exported)).not.toThrow();
});
});
describe('canonicalize', () => {
it('should canonicalize objects with sorted keys', () => {
const obj1 = { b: 1, a: 2 };
const obj2 = { a: 2, b: 1 };
expect(canonicalize(obj1)).toBe('{"a":2,"b":1}');
expect(canonicalize(obj2)).toBe('{"a":2,"b":1}');
expect(canonicalize(obj1)).toBe(canonicalize(obj2));
});
it('should handle nested objects', () => {
const obj = { z: { a: 1, b: 2 }, y: 'test' };
expect(canonicalize(obj)).toBe('{"y":"test","z":{"a":1,"b":2}}');
});
it('should handle arrays', () => {
const obj = { arr: [3, 1, 2] };
expect(canonicalize(obj)).toBe('{"arr":[3,1,2]}');
});
it('should throw on invalid types', () => {
expect(() => canonicalize({ d: new Date() })).toThrow(/Date objects not allowed/);
expect(() => canonicalize({ n: NaN })).toThrow(/Number is not finite/);
expect(() => canonicalize({ n: Infinity })).toThrow(/Number is not finite/);
});
it('should handle strings correctly', () => {
expect(canonicalize('hello')).toBe('"hello"');
expect(canonicalize('with"quotes')).toBe('"with\\"quotes"');
});
it('should handle numbers', () => {
expect(canonicalize(42)).toBe('42');
expect(canonicalize(3.14)).toBe('3.14');
});
it('should handle booleans and null', () => {
expect(canonicalize(true)).toBe('true');
expect(canonicalize(false)).toBe('false');
expect(canonicalize(null)).toBe('null');
});
});
});
+97 -73
View File
@@ -1,12 +1,19 @@
/**
* User Identity Hook
*
* Manages the user's cryptographic identity using in-memory storage.
* strict: NO localStorage for decrypted keys.
* Manages the user's cryptographic identity with persistent storage.
* Keys are encrypted at rest in IndexedDB and automatically restored
* across page refreshes and tabs.
*/
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { decryptPrivateKey } from '@/lib/crypto/private-key-client';
import {
persistUnlockedKey,
tryRestoreKey,
clearPersistentKey,
hasPersistentKey,
} from '@/lib/crypto/key-persistence';
import {
keyStore,
importPrivateKey,
@@ -27,89 +34,102 @@ export interface UserIdentity {
export function useUserIdentity() {
const [identity, setIdentity] = useState<UserIdentity | null>(null);
const [isUnlocked, setIsUnlocked] = useState(false);
const [isRestoring, setIsRestoring] = useState(true);
// Check status on mount / updates
// Check status on mount / updates and poll for changes in singleton
// Check status on mount and try to restore from persistence
useEffect(() => {
const check = () => {
const hasKey = !!keyStore.getPrivateKey();
setIsUnlocked(hasKey);
// Auto-sync identity if available in singleton but missing in local state
const globalIdentity = keyStore.getIdentity();
if (globalIdentity) {
setIdentity(prev => {
// Avoid rerenders if same
if (prev && prev.did === globalIdentity.did && prev.isUnlocked === hasKey) return prev;
return { ...globalIdentity, isUnlocked: hasKey };
});
} else {
// If global cleared, clear local
setIdentity(prev => prev ? null : null);
const checkAndRestore = async () => {
setIsRestoring(true);
try {
// First check if already in memory (hot reload scenario)
const hasKey = !!keyStore.getPrivateKey();
const globalIdentity = keyStore.getIdentity();
if (hasKey && globalIdentity) {
setIdentity({ ...globalIdentity, isUnlocked: true });
setIsUnlocked(true);
setIsRestoring(false);
return;
}
// Try to restore from persistent storage
const restoredKeyBytes = await tryRestoreKey();
if (restoredKeyBytes && globalIdentity) {
// Import the restored key as non-extractable
const cryptoKey = await importPrivateKey(restoredKeyBytes);
keyStore.setPrivateKey(cryptoKey);
setIdentity({ ...globalIdentity, isUnlocked: true });
setIsUnlocked(true);
console.log('[Identity] Auto-restored from persistent storage');
} else if (globalIdentity) {
// Have identity info but no key - locked state
setIdentity({ ...globalIdentity, isUnlocked: false });
setIsUnlocked(false);
}
} catch (error) {
console.error('[Identity] Error during restore:', error);
} finally {
setIsRestoring(false);
}
};
check();
// Poll fast to ensure UI updates are snappy
const interval = setInterval(check, 500);
return () => clearInterval(interval);
checkAndRestore();
}, []);
/**
* Initialize identity from user data & password
* Initialize identity from user data
* Call this when user data is loaded from the server
*/
const initializeIdentity = async (userData: {
const initializeIdentity = useCallback(async (userData: {
did: string;
handle: string;
publicKey: string;
privateKeyEncrypted: string;
}, password?: string) => {
// If password provided, attempt unlock
// Save to singleton
privateKeyEncrypted?: string;
}) => {
const coreIdentity = {
did: userData.did,
handle: userData.handle,
publicKey: userData.publicKey
};
keyStore.setIdentity(coreIdentity);
// If password provided, attempt unlock
if (password) {
await unlockIdentity(userData.privateKeyEncrypted, password);
// Try to auto-restore if we have persisted key
const restoredKeyBytes = await tryRestoreKey();
if (restoredKeyBytes) {
const cryptoKey = await importPrivateKey(restoredKeyBytes);
keyStore.setPrivateKey(cryptoKey);
setIdentity({ ...coreIdentity, isUnlocked: true });
setIsUnlocked(true);
} else {
// Just set public identity info if locked
setIdentity({
...coreIdentity,
isUnlocked: !!keyStore.getPrivateKey()
});
setIdentity({ ...coreIdentity, isUnlocked: false });
setIsUnlocked(false);
}
};
}, []);
/**
* Unlock the identity with a password
* Also persists the key for auto-unlock on refresh
*/
const unlockIdentity = async (privateKeyEncrypted: string, password: string, userDid?: string, userHandle?: string, userPublicKey?: string) => {
const unlockIdentity = useCallback(async (
privateKeyEncrypted: string,
password: string,
userDid?: string,
userHandle?: string,
userPublicKey?: string
) => {
try {
console.log('[Identity] Unlocking with DID:', userDid, 'Handle:', userHandle);
// Set identity first if provided (needed for storage key derivation)
// Set identity first if provided
if (userDid && userHandle && userPublicKey) {
keyStore.setIdentity({
did: userDid,
handle: userHandle,
publicKey: userPublicKey
});
console.log('[Identity] Identity set in keyStore');
} else {
console.warn('[Identity] Missing user info for identity setup');
}
// 1. Decrypt the PEM/String from server (which is actually a base64 encoded PKCS8 export usually?)
// Wait, existing implementation returns a string.
// We need to verify what `decryptPrivateKey` returns.
// Assuming it returns the decrypted string (Base64 of PKCS8)
// Decrypt the private key
const privateKeyPemOrBase64 = await decryptPrivateKey(privateKeyEncrypted, password);
// Clean up if it's PEM to get Base64
@@ -121,53 +141,56 @@ export function useUserIdentity() {
.replace(/\s/g, '');
}
// 2. Import into CryptoKey
// We need ArrayBuffer
// Import into CryptoKey (non-extractable for security)
const binaryDer = Buffer.from(privateKeyBase64, 'base64');
const cryptoKey = await importPrivateKey(binaryDer); // This is P-256 specific now
const cryptoKey = await importPrivateKey(binaryDer);
// 3. Store in Memory
// Store in memory
keyStore.setPrivateKey(cryptoKey);
console.log('[Identity] Private key stored in memory');
// PERSIST: Save raw key bytes for auto-restore on refresh
// We pass the raw bytes because the CryptoKey is non-extractable
await persistUnlockedKey(privateKeyBase64, password);
console.log('[Identity] Private key stored in memory and persisted');
// 4. Update State
setIdentity(prev => prev ? { ...prev, isUnlocked: true } : null); // We need the other data...
// Update State
const globalIdentity = keyStore.getIdentity();
if (globalIdentity) {
setIdentity({ ...globalIdentity, isUnlocked: true });
}
setIsUnlocked(true);
// If we didn't have identity wrapper set yet, we might need it.
// Usually initializeIdentity handles both.
} catch (error) {
console.error('[Identity] Failed to unlock identity:', error);
throw new Error('Failed to unlock identity. Incorrect password?');
}
};
}, []);
/**
* Lock the identity
* Lock the identity (manual lock, keeps identity info)
*/
const lockIdentity = () => {
const lockIdentity = useCallback(async () => {
keyStore.clear();
await clearPersistentKey();
setIsUnlocked(false);
setIdentity(prev => prev ? { ...prev, isUnlocked: false } : null);
};
}, []);
/**
* Clear the identity (logout)
*/
const clearIdentity = () => {
const clearIdentity = useCallback(async () => {
keyStore.clear();
await clearPersistentKey();
setIdentity(null);
setIsUnlocked(false);
};
}, []);
/**
* Sign a user action
*/
const signUserAction = async (action: string, data: any) => {
// Re-check global state directly to be safe
const signUserAction = useCallback(async (action: string, data: any) => {
const pk = keyStore.getPrivateKey();
const id = keyStore.getIdentity();
@@ -175,13 +198,14 @@ export function useUserIdentity() {
console.error('[Identity] Sign failed. Identity:', id, 'HasKey:', !!pk);
throw new Error('Identity locked');
}
// Use the fetched identity to ensure sync
return await createSignedAction(action, data, id.did, id.handle);
};
}, []);
return {
identity,
isUnlocked,
isRestoring, // New: lets UI know if we're checking persistence
initializeIdentity,
unlockIdentity,
lockIdentity,
+13 -1
View File
@@ -64,11 +64,23 @@ export async function buildAnnouncement(): Promise<SwarmAnnouncement> {
/**
* Announce this node to a remote node
*
* SECURITY: Signs the announcement with the node's private key
*/
export async function announceToNode(targetDomain: string): Promise<{ success: boolean; error?: string }> {
try {
const announcement = await buildAnnouncement();
// SECURITY: Sign the announcement with our private key
const { signPayload, getNodePrivateKey } = await import('./signature');
const privateKey = await getNodePrivateKey();
const signature = signPayload(announcement, privateKey);
const signedAnnouncement = {
...announcement,
signature,
};
const baseUrl = targetDomain.startsWith('http') ? targetDomain : `https://${targetDomain}`;
const url = `${baseUrl}/api/swarm/announce`;
@@ -78,7 +90,7 @@ export async function announceToNode(targetDomain: string): Promise<{ success: b
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(announcement),
body: JSON.stringify(signedAnnouncement),
});
if (!response.ok) {
+13 -1
View File
@@ -109,6 +109,8 @@ export async function processGossip(
/**
* Send gossip to a specific node
*
* SECURITY: Signs the gossip payload with the node's private key
*/
export async function gossipToNode(
targetDomain: string,
@@ -119,6 +121,16 @@ export async function gossipToNode(
try {
const payload = await buildGossipPayload(since);
// SECURITY: Sign the gossip payload with our private key
const { signPayload, getNodePrivateKey } = await import('./signature');
const privateKey = await getNodePrivateKey();
const signature = signPayload(payload, privateKey);
const signedPayload = {
...payload,
signature,
};
const baseUrl = targetDomain.startsWith('http') ? targetDomain : `https://${targetDomain}`;
const url = `${baseUrl}/api/swarm/gossip`;
@@ -128,7 +140,7 @@ export async function gossipToNode(
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify(payload),
body: JSON.stringify(signedPayload),
});
const durationMs = Date.now() - startTime;
+68 -47
View File
@@ -153,64 +153,80 @@ export async function getNodesSince(since: Date, limit = 100): Promise<SwarmNode
/**
* Mark a node as having failed contact
*
* @throws Error if database operation fails (after logging)
*/
export async function markNodeFailure(domain: string): Promise<void> {
if (!db) return;
const node = await db.query.swarmNodes.findFirst({
where: eq(swarmNodes.domain, domain),
});
try {
const node = await db.query.swarmNodes.findFirst({
where: eq(swarmNodes.domain, domain),
});
if (!node) return;
if (!node) return;
const newFailures = node.consecutiveFailures + 1;
const newTrust = Math.max(
SWARM_CONFIG.minTrustScore,
node.trustScore + SWARM_CONFIG.trustScoreOnFailure
);
const isActive = newFailures < SWARM_CONFIG.maxConsecutiveFailures;
const newFailures = node.consecutiveFailures + 1;
const newTrust = Math.max(
SWARM_CONFIG.minTrustScore,
node.trustScore + SWARM_CONFIG.trustScoreOnFailure
);
const isActive = newFailures < SWARM_CONFIG.maxConsecutiveFailures;
await db.update(swarmNodes)
.set({
consecutiveFailures: newFailures,
trustScore: newTrust,
isActive,
updatedAt: new Date(),
})
.where(eq(swarmNodes.domain, domain));
await db.update(swarmNodes)
.set({
consecutiveFailures: newFailures,
trustScore: newTrust,
isActive,
updatedAt: new Date(),
})
.where(eq(swarmNodes.domain, domain));
} catch (error) {
console.error(`[Swarm] Failed to mark node failure for ${domain}:`, error);
throw error;
}
}
/**
* Mark a node as successfully contacted
*
* @throws Error if database operation fails (after logging)
*/
export async function markNodeSuccess(domain: string): Promise<void> {
if (!db) return;
const node = await db.query.swarmNodes.findFirst({
where: eq(swarmNodes.domain, domain),
});
try {
const node = await db.query.swarmNodes.findFirst({
where: eq(swarmNodes.domain, domain),
});
if (!node) return;
if (!node) return;
const newTrust = Math.min(
SWARM_CONFIG.maxTrustScore,
node.trustScore + SWARM_CONFIG.trustScoreOnSuccess
);
const newTrust = Math.min(
SWARM_CONFIG.maxTrustScore,
node.trustScore + SWARM_CONFIG.trustScoreOnSuccess
);
await db.update(swarmNodes)
.set({
consecutiveFailures: 0,
trustScore: newTrust,
isActive: true,
lastSeenAt: new Date(),
lastSyncAt: new Date(),
updatedAt: new Date(),
})
.where(eq(swarmNodes.domain, domain));
await db.update(swarmNodes)
.set({
consecutiveFailures: 0,
trustScore: newTrust,
isActive: true,
lastSeenAt: new Date(),
lastSyncAt: new Date(),
updatedAt: new Date(),
})
.where(eq(swarmNodes.domain, domain));
} catch (error) {
console.error(`[Swarm] Failed to mark node success for ${domain}:`, error);
throw error;
}
}
/**
* Log a sync operation
*
* @throws Error if database operation fails (after logging)
*/
export async function logSync(
remoteDomain: string,
@@ -219,17 +235,22 @@ export async function logSync(
): Promise<void> {
if (!db) return;
await db.insert(swarmSyncLog).values({
remoteDomain,
direction,
nodesReceived: result.nodesReceived,
nodesSent: result.nodesSent,
handlesReceived: result.handlesReceived,
handlesSent: result.handlesSent,
success: result.success,
errorMessage: result.error,
durationMs: result.durationMs,
});
try {
await db.insert(swarmSyncLog).values({
remoteDomain,
direction,
nodesReceived: result.nodesReceived,
nodesSent: result.nodesSent,
handlesReceived: result.handlesReceived,
handlesSent: result.handlesSent,
success: result.success,
errorMessage: result.error,
durationMs: result.durationMs,
});
} catch (error) {
console.error(`[Swarm] Failed to log sync for ${remoteDomain}:`, error);
throw error;
}
}
/**
+6 -3
View File
@@ -12,11 +12,13 @@ export interface RemoteProfile {
/**
* Upsert a remote user into the local database for caching/display purposes.
*
* @throws Error if database operation fails (after logging)
*/
export async function upsertRemoteUser(profile: RemoteProfile) {
try {
if (!db) return;
export async function upsertRemoteUser(profile: RemoteProfile): Promise<void> {
if (!db) return;
try {
// Check if user already exists
const existing = await db.query.users.findFirst({
where: eq(users.did, profile.did),
@@ -50,5 +52,6 @@ export async function upsertRemoteUser(profile: RemoteProfile) {
}
} catch (error) {
console.error(`[User Cache] Failed to upsert ${profile.handle}:`, error);
throw error;
}
}