@clplab/clp-typescript
Version:
Crystalline Lattice Protocol - Next-generation post-quantum cryptography library with comprehensive multi-layer security (TypeScript)
640 lines (621 loc) • 17.1 kB
TypeScript
/**
* CLP Types
*/
type SecurityProfile = 'ULTIMATE' | 'HIGH' | 'STANDARD';
interface SecurityConfig {
lattice_dimension: number;
polynomial_degree: number;
graph_size: number;
prime_bits: number;
key_derivation_rounds: number;
growth_trigger_threshold: number;
}
interface PerformanceConfig {
enable_parallel_processing: boolean;
use_web_workers: boolean;
cache_size: number;
batch_size: number;
compression_enabled: boolean;
}
interface FeatureConfig {
auto_growth: boolean;
authenticated_encryption: boolean;
streaming_support: boolean;
debug_mode: boolean;
strict_validation: boolean;
}
interface CLPConfig {
security: SecurityConfig;
performance: PerformanceConfig;
features: FeatureConfig;
}
interface ConfigOverrides {
security?: Partial<SecurityConfig>;
performance?: Partial<PerformanceConfig>;
features?: Partial<FeatureConfig>;
}
interface EncryptionOptions {
withAuthentication?: boolean;
withCompression?: boolean;
useParallel?: boolean;
}
interface DecryptionOptions {
verifyAuthentication?: boolean;
strict?: boolean;
}
interface EncryptedPayload {
version: string;
blocks: EncryptedBlock[];
metadata: PayloadMetadata;
auth?: string;
}
interface EncryptedBlock {
lattice: SerializedBigInt;
growthCycle: number;
entropy: number;
}
interface PayloadMetadata {
timestamp: number;
blockCount: number;
algorithm: string;
profile: SecurityProfile;
compressed: boolean;
authenticated: boolean;
originalLength?: number;
growthCycle?: number;
}
interface SerializedBigInt {
_bigint: string;
}
type LatticeMatrix = bigint[][];
type LatticeVector = bigint[];
interface LatticeConfig {
dimension: number;
prime: bigint;
config: CLPConfig;
}
interface EncodedValue {
value: bigint;
checksum?: number;
}
type CLPErrorCode = 'CONFIG_ERROR' | 'CRYPTO_ERROR' | 'WORKER_ERROR' | 'VALIDATION_ERROR' | 'PERFORMANCE_ERROR' | 'UNKNOWN_ERROR';
interface CLPErrorDetails {
originalError?: Error;
messageLength?: number;
blockCount?: number;
[key: string]: any;
}
interface ErrorRecoveryHints {
[code: string]: string;
}
interface SystemCapabilities {
webWorkers: boolean;
standaloneRandom: boolean;
streams: boolean;
bigInt: boolean;
nodeEnvironment: boolean;
browserEnvironment: boolean;
}
interface ValidationResult {
valid: boolean;
error?: string;
recoveryHints?: string;
}
interface BenchmarkResult {
profile: SecurityProfile;
opsPerSec: number;
avgTime: string;
minTime: number;
maxTime: number;
}
interface BenchmarkResults {
results: Record<SecurityProfile, BenchmarkResult>;
systemInfo: SystemCapabilities;
timestamp: number;
}
type StreamChunk = string | Uint8Array | Buffer;
interface StreamOptions {
authentication?: boolean;
compression?: boolean;
chunkSize?: number;
encoding?: 'utf8' | 'binary';
}
interface CLPStream {
write(chunk: string): Promise<void>;
flush(): Promise<EncryptedPayload>;
encrypt(chunk: StreamChunk): Promise<EncryptedPayload>;
decrypt(payload: EncryptedPayload): Promise<StreamChunk>;
close(): void;
destroy(): void;
}
interface FluentEncryption {
withAuthentication(): FluentEncryption;
withCompression(): FluentEncryption;
withParallel(): FluentEncryption;
execute(): Promise<EncryptedPayload>;
}
interface FluentDecryption {
withVerification(): FluentDecryption;
withStrict(): FluentDecryption;
execute(): Promise<string>;
}
type CLPEventType = 'encrypt' | 'decrypt' | 'evolve' | 'error';
interface CLPEvent {
type: CLPEventType;
timestamp: number;
data: any;
}
type CLPEventListener = (event: CLPEvent) => void;
interface CLPInfo {
version: string;
securityLevel: string;
configuration: CLPConfig;
currentState: {
growthCycle: number;
operationCount: number;
cacheSize: number;
};
performance: {
workerPoolActive: boolean;
cacheHitRatio: number;
};
complexity: number;
}
interface CLP {
encrypt(message: string, options?: EncryptionOptions): FluentEncryption;
decrypt(payload: EncryptedPayload, options?: DecryptionOptions): Promise<string>;
evolve(): Promise<void>;
getInfo(): CLPInfo;
createStream(options?: StreamOptions): CLPStream;
on(event: CLPEventType, listener: CLPEventListener): void;
off(event: CLPEventType, listener: CLPEventListener): void;
destroy(): void;
}
interface TestCase {
name: string;
message: string;
expectedBlocks?: number;
profile?: SecurityProfile;
}
interface TestResult {
passed: number;
failed: number;
total: number;
duration: number;
details: Array<{
name: string;
passed: boolean;
error?: string;
duration: number;
}>;
}
interface CLPFactory {
create(profile?: SecurityProfile, overrides?: ConfigOverrides): CLP;
ultimate(overrides?: ConfigOverrides): CLP;
high(overrides?: ConfigOverrides): CLP;
standard(overrides?: ConfigOverrides): CLP;
utils: {
getCapabilities(): SystemCapabilities;
validateConfig(config: CLPConfig): ValidationResult;
benchmark(iterations?: number): Promise<BenchmarkResults>;
test(profile?: SecurityProfile): Promise<TestResult>;
};
}
/**
* Core CLP (Cryptographic Layered Protocol) implementation
*/
declare class CLPCore implements CLP {
private config;
private hybridLayer;
private growthCounter;
private operationCount;
private eventListeners;
private errorHandler;
private isDestroyed;
private growthStates;
constructor(config: CLPConfig);
/**
* Fluent encryption interface
*/
encrypt(message: string, options?: EncryptionOptions): FluentEncryption;
/**
* Direct decryption
*/
decrypt(payload: EncryptedPayload, options?: DecryptionOptions): Promise<string>;
/**
* Internal encryption implementation
*/
performEncryption(message: string, options: EncryptionOptions): Promise<EncryptedPayload>;
/**
* Encrypt a single block using a hybrid multi-layer approach
*/
private encryptBlock;
/**
* Decrypt a single block using a hybrid multi-layer approach
*/
private decryptBlock;
/**
* Protocol evolution for enhanced security across all layers
*/
evolve(): Promise<void>;
/**
* Get comprehensive protocol information including all layers
*/
getInfo(): CLPInfo;
/**
* Create a streaming interface
*/
createStream(options?: StreamOptions): CLPStream;
/**
* Event system
*/
on(event: CLPEventType, listener: CLPEventListener): void;
off(event: CLPEventType, listener: CLPEventListener): void;
private emit;
/**
* Clean up resources across all layers
*/
destroy(): void;
private validateNotDestroyed;
private validateInput;
private validatePayload;
private shouldTriggerGrowth;
private getSecurityLevel;
private calculateCacheHitRatio;
private bytesToBlock;
private blockToBytes;
private generateAuthTag;
private verifyAuthTag;
private serializeBigInt;
private deserializeBigInt;
private saveCurrentState;
private restoreGrowthState;
}
/**
* Configuration Manager for CLP (Cryptographic Lattice Protocol)
*/
declare class CLPConfigManager {
private static readonly PROFILES;
/**
* Create configuration from a profile with optional overrides
*/
static create(profile?: SecurityProfile, overrides?: ConfigOverrides): CLPConfig;
/**
* Get available security profiles
*/
static getProfiles(): SecurityProfile[];
/**
* Get the default configuration for a profile
*/
static getProfile(profile: SecurityProfile): CLPConfig;
/**
* Validate configuration object
*/
static validate(config: CLPConfig): void;
private static validateSecurity;
private static validatePerformance;
private static validateFeatures;
/**
* Deep merge two configuration objects
*/
private static deepMerge;
/**
* Create configuration with security level recommendations
*/
static recommendProfile(requirements: {
securityLevel?: 'maximum' | 'high' | 'standard';
performance?: 'fast' | 'balanced' | 'secure';
environment?: 'browser' | 'node' | 'worker';
}): SecurityProfile;
}
/**
* Custom error handling for CLP (Crypto Library Protocol)
*/
declare class CLPError extends Error {
readonly code: CLPErrorCode;
readonly details: CLPErrorDetails;
readonly timestamp: number;
readonly recoveryHints: string;
constructor(message: string, code?: CLPErrorCode, details?: CLPErrorDetails);
private generateRecoveryHints;
/**
* Convert error to JSON for logging/serialization
*/
toJSON(): object;
/**
* Check if the error is recoverable
*/
isRecoverable(): boolean;
/**
* Get error severity level
*/
getSeverity(): 'low' | 'medium' | 'high' | 'critical';
}
/**
* Error handler with proper memory management
*/
declare class CLPErrorHandler {
private static instance;
private errorLog;
private maxLogSize;
private listeners;
private constructor();
static getInstance(): CLPErrorHandler;
/**
* Handle error with proper logging and cleanup
*/
handle(error: CLPError): void;
/**
* Add error listener
*/
addListener(listener: (error: CLPError) => void): void;
/**
* Remove error listener
*/
removeListener(listener: (error: CLPError) => void): void;
/**
* Get recent errors
*/
getRecentErrors(count?: number): CLPError[];
/**
* Clear error log to free memory
*/
clearLog(): void;
/**
* Destroy handler and clean up memory
*/
destroy(): void;
}
/**
* HybridLayer class for encoding and decoding data using a multi-layer approach
*/
declare class HybridLayer {
private config;
private latticeLayer;
private polynomialLayer;
private graphLayer;
private isDestroyed;
constructor(config: CLPConfig);
/**
* Encode data using a hybrid multi-layer approach
*/
encode(data: number, useAuth?: boolean): any;
/**
* Decode data using a hybrid multi-layer approach
*/
decode(encodedData: any): number;
/**
* Evolve all layers for enhanced security
*/
evolve(): Promise<void>;
/**
* Get complexity metrics for all layers
*/
getComplexity(): any;
/**
* Get the current state of all layers for state management
*/
getState(): any;
/**
* Set the state of all layers for state management
*/
setState(state: any): void;
/**
* Clean up all layers and prevent memory leaks
*/
destroy(): void;
}
/**
* GraphLayer class for secure data encoding/decoding
*/
declare class GraphLayer {
private config;
private size;
private nodes;
private isDestroyed;
constructor(config: CLPConfig);
/**
* Initialize graph structure
*/
private initializeGraph;
/**
* Encode data using graph traversal
*/
encode(data: bigint): bigint;
/**
* Decode data using reverse graph traversal
*/
decode(encodedData: bigint): bigint;
/**
* Evolve graph structure for enhanced security
*/
evolve(): Promise<void>;
/**
* Get graph complexity metric
*/
getComplexity(): number;
/**
* Get current state for state management
*/
getState(): any;
/**
* Set state for state management
*/
setState(state: any): void;
/**
* Clean up graph data to prevent memory leaks
*/
destroy(): void;
}
/**
* PolynomialLayer class for encoding and decoding data using polynomial evaluation.
*/
declare class PolynomialLayer {
private config;
private degree;
private coefficients;
private modulus;
private isDestroyed;
constructor(config: CLPConfig);
/**
* Initialize polynomial coefficients
*/
private initializeCoefficients;
/**
* Encode data using polynomial evaluation
*/
encode(data: bigint): bigint;
/**
* Decode data using polynomial interpolation (simplified)
*/
decode(encodedData: bigint): bigint;
/**
* Evolve polynomial for enhanced security
*/
evolve(): Promise<void>;
/**
* Get polynomial complexity metric
*/
getComplexity(): number;
/**
* Get current state for state management
*/
getState(): any;
/**
* Set state for state management
*/
setState(state: any): void;
/**
* Clean up polynomial data to prevent memory leaks
*/
destroy(): void;
/**
* Calculate modular inverse
*/
private modularInverse;
}
/**
* LatticeLayer class for lattice-based encryption and decryption
*/
declare class LatticeLayer {
private config;
private dimension;
private basis;
private privateKey;
private isDestroyed;
constructor(config: CLPConfig);
/**
* Initialize a lattice basis and private key
*/
private initializeLattice;
/**
* Encode data using lattice-based encryption
*/
encode(data: number): bigint;
/**
* Decode data using lattice-based decryption
*/
decode(encodedData: bigint): number;
/**
* Evolve the lattice for enhanced security
*/
evolve(): Promise<void>;
/**
* Get lattice complexity metric
*/
getComplexity(): number;
/**
* Get current state for state management
*/
getState(): any;
/**
* Set state for state management
*/
setState(state: any): void;
/**
* Clean up lattice data to prevent memory leaks
*/
destroy(): void;
}
/**
* CLPMath - Cryptographic Math Utilities
*/
declare class CLPMath {
private static entropy;
private static initialized;
/**
* Initialize an entropy pool with multiple sources
*/
static initializeEntropy(): void;
/**
* Secure random number generation using multiple entropy sources
*/
static secureRandom(max?: number): number;
/**
* Generate cryptographically strong random bytes
*/
static randomBytes(length: number): Uint8Array;
/**
* Generate safe prime numbers for cryptographic use
*/
static generatePrime(bits?: number): bigint;
/**
* Modular exponentiation for large numbers
*/
static modPow(base: bigint, exponent: bigint, modulus: bigint): bigint;
/**
* Greatest common divisor
*/
static gcd(a: bigint, b: bigint): bigint;
/**
* Clean up static resources to prevent memory leaks
*/
static cleanup(): void;
/**
* Validate number range to prevent overflow
*/
static validateRange(value: number, min?: number, max?: number): boolean;
}
/**
* CLP Utils - Utility functions for CLP operations
*/
declare class CLPUtils {
/**
* Get system capabilities for environment detection
*/
static getCapabilities(): SystemCapabilities;
/**
* Validate configuration with detailed error reporting
*/
static validateConfig(config: CLPConfig): ValidationResult;
/**
* Comprehensive benchmark across all security profiles
*/
static benchmark(iterations?: number): Promise<BenchmarkResults>;
/**
* Comprehensive test suite
*/
static test(profile?: SecurityProfile): Promise<TestResult>;
private static testBasicEncryption;
private static testEmptyString;
private static testLargeMessage;
private static testUnicodeSupport;
private static testAuthentication;
private static testEvolution;
private static testErrorHandling;
private static testConfigValidation;
/**
* Generate performance report
*/
static generatePerformanceReport(benchmarkResults: BenchmarkResults): string;
/**
* Memory usage estimation
*/
static estimateMemoryUsage(config: CLPConfig): {
latticeSize: string;
cacheSize: string;
totalEstimate: string;
};
}
export { CLPConfigManager, CLPCore, CLPError, CLPErrorHandler, CLPMath, CLPUtils, GraphLayer, HybridLayer, LatticeLayer, PolynomialLayer, CLPCore as default };
export type { BenchmarkResult, BenchmarkResults, CLP, CLPConfig, CLPErrorCode, CLPErrorDetails, CLPEvent, CLPEventListener, CLPEventType, CLPFactory, CLPInfo, CLPStream, ConfigOverrides, DecryptionOptions, EncodedValue, EncryptedBlock, EncryptedPayload, EncryptionOptions, ErrorRecoveryHints, FeatureConfig, FluentDecryption, FluentEncryption, LatticeConfig, LatticeMatrix, LatticeVector, PayloadMetadata, PerformanceConfig, SecurityConfig, SecurityProfile, SerializedBigInt, StreamChunk, StreamOptions, SystemCapabilities, TestCase, TestResult, ValidationResult };