fortifyjs-react
Version:
React integration for Nehonix FortifyJS - Secure state management with enhanced object operations
339 lines (325 loc) • 10.3 kB
TypeScript
import { SecureObject } from 'fortify2-js';
export { SecureObject } from 'fortify2-js';
import React, { ReactNode } from 'react';
/**
* FortifyJS React Hooks - Type Definitions
*/
/**
* Configuration options for useSecureState hook
*/
interface UseSecureStateOptions {
/** Keys that should be treated as sensitive */
sensitiveKeys?: string[];
/** Enable automatic encryption for sensitive data */
autoEncrypt?: boolean;
/** Encryption algorithm to use */
encryptionAlgorithm?: "AES-256-GCM" | "ChaCha20-Poly1305";
/** Enable performance monitoring */
enableMonitoring?: boolean;
/** Custom validation function */
validator?: (value: any) => boolean;
/** Debounce updates (ms) */
debounceMs?: number;
}
/**
* Configuration options for useSecureObject hook
*/
interface UseSecureObjectOptions {
/** Enable automatic cleanup on unmount */
autoCleanup?: boolean;
/** Enable event tracking */
enableEvents?: boolean;
/** Performance optimization level */
optimizationLevel?: "basic" | "enhanced" | "maximum";
/** Memory management strategy */
memoryStrategy?: "conservative" | "balanced" | "aggressive";
}
/**
* Return type for useSecureState hook
*/
interface UseSecureStateReturn<T extends Record<string, any>> {
/** The secure object containing the state */
state: SecureObject<T>;
/** Function to update the state */
setState: (value: T | ((prev: T) => T)) => void;
/** Get a specific value from state */
getValue: <K extends keyof T>(key: K) => T[K];
/** Set a specific value in state */
setValue: <K extends keyof T>(key: K, value: T[K]) => void;
/** Check if state is encrypted */
isEncrypted: boolean;
/** Performance metrics */
metrics: {
updateCount: number;
lastUpdateTime: number;
averageUpdateTime: number;
};
}
/**
* Return type for useSecureObject hook
*/
interface UseSecureObjectReturn<T extends Record<string, any>> {
/** The secure object */
object: SecureObject<T>;
/** Refresh the object from source */
refresh: () => void;
/** Check if object is ready */
isReady: boolean;
/** Loading state */
isLoading: boolean;
/** Error state */
error: Error | null;
/** Object metadata */
metadata: {
size: number;
sensitiveKeyCount: number;
lastModified: Date;
};
}
/**
* FortifyJS React Components - Type Definitions
*/
/**
* Security configuration for the application
*/
interface SecurityConfig {
/** Default encryption level */
encryptionLevel?: "basic" | "enhanced" | "military";
/** Default sensitive key patterns */
defaultSensitiveKeys?: string[];
/** Enable automatic security monitoring */
enableMonitoring?: boolean;
/** Performance optimization settings */
performance?: {
enableCaching?: boolean;
cacheSize?: number;
enableLazyLoading?: boolean;
};
/** Memory management settings */
memory?: {
autoCleanup?: boolean;
cleanupInterval?: number;
maxMemoryUsage?: number;
};
/** Development settings */
development?: {
enableDebugMode?: boolean;
logLevel?: "none" | "error" | "warn" | "info" | "debug";
enablePerformanceMetrics?: boolean;
};
}
/**
* Props for SecureProvider component
*/
interface SecureProviderProps {
/** Security configuration */
config: SecurityConfig;
/** Child components */
children: ReactNode;
/** Optional fallback component for loading */
fallback?: ReactNode;
/** Optional error boundary */
onError?: (error: Error, errorInfo: any) => void;
}
/**
* Context value type for SecurityContext
*/
interface SecurityContextValue {
/** Current security configuration */
config: SecurityConfig;
/** Update security configuration */
updateConfig: (config: Partial<SecurityConfig>) => void;
/** Get security metrics */
getMetrics: () => {
totalOperations: number;
encryptedOperations: number;
averageOperationTime: number;
memoryUsage: number;
};
/** Enable/disable debug mode */
setDebugMode: (enabled: boolean) => void;
/** Current debug mode state */
debugMode: boolean;
/** Register a secure component */
registerComponent: (componentId: string, metadata: any) => void;
/** Unregister a secure component */
unregisterComponent: (componentId: string) => void;
/** Get registered components */
getRegisteredComponents: () => Record<string, any>;
}
/**
* FortifyJS React useSecureState Hook
* Secure state management with automatic encryption and enhanced operations
*/
/**
* Hook for secure state management with enhanced object operations
*
* @param initialValue - Initial state value
* @param options - Configuration options
* @returns Secure state management object
*
* @example
* ```tsx
* function UserProfile() {
* const [user, setUser] = useSecureState({
* name: "John",
* email: "john@example.com",
* password: "secret123"
* }, {
* sensitiveKeys: ["password"],
* autoEncrypt: true
* });
*
* return (
* <div>
* <p>Name: {user.get("name")}</p>
* <p>Email: {user.get("email")}</p>
* // Password is automatically encrypted
* </div>
* );
* }
* ```
*/
declare function useSecureState<T extends Record<string, any>>(initialValue: T, options?: UseSecureStateOptions): UseSecureStateReturn<T>;
/**
* FortifyJS React useSecureObject Hook
* Enhanced object operations with React integration
*/
/**
* Hook for enhanced object operations with React integration
*
* @param initialData - Initial object data or data source
* @param options - Configuration options
* @returns Enhanced object management
*
* @example
* ```tsx
* function DataProcessor() {
* const data = useSecureObject(rawData, {
* autoCleanup: true,
* enableEvents: true
* });
*
* const processedData = data.object
* .filterNonSensitive()
* .transform(value => value.toUpperCase())
* .compact();
*
* return (
* <div>
* <p>Processed {processedData.size} items</p>
* <p>Ready: {data.isReady ? "Yes" : "No"}</p>
* </div>
* );
* }
* ```
*/
declare function useSecureObject<T extends Record<string, any>>(initialData: T | (() => T) | (() => Promise<T>), options?: UseSecureObjectOptions): UseSecureObjectReturn<T>;
/**
* Hook for creating a secure object from static data
* Simplified version of useSecureObject for static data
*
* @param data - Static object data
* @param options - Configuration options
* @returns Secure object
*/
declare function useStaticSecureObject<T extends Record<string, any>>(data: T, options?: Omit<UseSecureObjectOptions, "autoCleanup">): UseSecureObjectReturn<T>;
/**
* Hook for creating a secure object from async data source
* Specialized version for async data loading
*
* @param dataLoader - Async function that returns data
* @param dependencies - Dependencies that trigger reload
* @param options - Configuration options
* @returns Secure object with loading states
*/
declare function useAsyncSecureObject<T extends Record<string, any>>(dataLoader: () => Promise<T>, dependencies?: React.DependencyList, options?: UseSecureObjectOptions): UseSecureObjectReturn<Promise<T>>;
/**
* FortifyJS React SecureProvider Component
* Global security context provider for React applications
*/
/**
* Global security provider component
* Provides security context to all child components
*
* @example
* ```tsx
* function App() {
* return (
* <SecureProvider
* config={{
* encryptionLevel: "military",
* enableMonitoring: true
* }}
* >
* <UserProfile />
* <DataProcessor />
* </SecureProvider>
* );
* }
* ```
*/
declare const SecureProvider: React.FC<SecureProviderProps>;
/**
* Nehonix FortifyJS React Security Context
* Modular security context for React applications
*/
/**
* Default security configuration
*/
declare const DEFAULT_SECURITY_CONFIG: SecurityConfig;
/**
* Hook to access security context
* @returns Security context value
* @throws Error if used outside SecurityProvider
*/
declare function useSecurityContext(): SecurityContextValue;
/**
* Hook to access security configuration
* @returns Current security configuration
*/
declare function useSecurityConfig(): SecurityConfig;
/**
* Hook to check if a key should be treated as sensitive
* @param key - The key to check
* @returns Whether the key is sensitive
*/
declare function useIsSensitiveKey(key: string): boolean;
/**
* Hook to access security metrics
* @returns Current security metrics
*/
declare function useSecurityMetrics(): {
totalOperations: number;
encryptedOperations: number;
averageOperationTime: number;
memoryUsage: number;
};
/**
* Hook to control debug mode
* @returns Debug mode controls
*/
declare function useDebugMode(): {
enabled: boolean;
enable: () => void;
disable: () => void;
toggle: () => void;
};
/**
* Hook to register/unregister components for monitoring
* @param componentId - Unique component identifier
* @param metadata - Component metadata
*/
declare function useComponentRegistration(componentId: string, metadata?: any): void;
/**
* Hook to get performance metrics for the current component
* @param componentId - Component identifier
* @returns Performance metrics
*/
declare function useComponentMetrics(componentId: string): {
renderCount: number;
averageRenderTime: number;
lastRenderTime: number;
};
export { DEFAULT_SECURITY_CONFIG, SecureProvider, useAsyncSecureObject, useComponentMetrics, useComponentRegistration, useDebugMode, useIsSensitiveKey, useSecureObject, useSecureState, useSecurityConfig, useSecurityContext, useSecurityMetrics, useStaticSecureObject };
export type { SecureProviderProps, SecurityConfig, SecurityContextValue, UseSecureObjectOptions, UseSecureObjectReturn, UseSecureStateOptions, UseSecureStateReturn };