@zkim-platform/file-format 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1985 @@
1
+ /**
2
+ * Singleton Pattern Base Classes for @zkim-platform/file-format
3
+ * Lightweight singleton implementation without platform dependencies
4
+ */
5
+ /**
6
+ * Base Singleton Class
7
+ * Use this for simple singletons that don't require initialization
8
+ */
9
+ declare abstract class SingletonBase {
10
+ protected static instances: Map<new () => unknown, unknown>;
11
+ /**
12
+ * Protected constructor to prevent direct instantiation
13
+ */
14
+ protected constructor();
15
+ /**
16
+ * Get or create the singleton instance
17
+ */
18
+ static getInstance<T>(this: new () => T): T;
19
+ /**
20
+ * Clear all singleton instances (useful for testing)
21
+ * For ServiceBase instances, cleanup() is called before clearing
22
+ */
23
+ static clearInstances(): Promise<void>;
24
+ /**
25
+ * Check if an instance exists
26
+ */
27
+ static hasInstance<T>(this: new () => T): boolean;
28
+ }
29
+ /**
30
+ * Service Base Class
31
+ * Use this for services that require initialization and cleanup
32
+ */
33
+ declare abstract class ServiceBase extends SingletonBase {
34
+ protected initialized: boolean;
35
+ protected initializing: boolean;
36
+ /**
37
+ * Public constructor for ServiceBase extensions
38
+ * Required because getServiceInstance() calls new this() internally
39
+ */
40
+ constructor();
41
+ /**
42
+ * Initialize the service
43
+ * Must be async and return Promise<void>
44
+ */
45
+ abstract initialize(): Promise<void>;
46
+ /**
47
+ * Cleanup the service
48
+ * Must be async and return Promise<void>
49
+ */
50
+ abstract cleanup(): Promise<void>;
51
+ /**
52
+ * Check if the service is ready
53
+ */
54
+ isReady(): boolean;
55
+ /**
56
+ * Get service status
57
+ */
58
+ getStatus(): {
59
+ initialized: boolean;
60
+ [key: string]: unknown;
61
+ };
62
+ /**
63
+ * Ensure service is initialized before use
64
+ */
65
+ protected ensureInitialized(): Promise<void>;
66
+ /**
67
+ * Get or create and initialize the singleton instance
68
+ * This is the ONLY way to get ServiceBase instances
69
+ */
70
+ static getServiceInstance<T extends ServiceBase>(this: new () => T): Promise<T>;
71
+ }
72
+
73
+ /**
74
+ * Logger Interface and Console Implementation
75
+ * Lightweight logging adapter for @zkim-platform/file-format package
76
+ *
77
+ * Note: Console usage is required for this logger implementation in a standalone package.
78
+ * Users can provide their own ILogger implementation to avoid console usage if needed.
79
+ */
80
+ declare enum LogLevel {
81
+ DEBUG = "debug",
82
+ INFO = "info",
83
+ WARN = "warn",
84
+ ERROR = "error"
85
+ }
86
+ interface ILogger {
87
+ debug(message: string, context?: Record<string, unknown>): void;
88
+ info(message: string, context?: Record<string, unknown>): void;
89
+ warn(message: string, context?: Record<string, unknown>): void;
90
+ error(message: string, error?: unknown, context?: Record<string, unknown>): void;
91
+ }
92
+ /**
93
+ * Console Logger Implementation
94
+ * Simple console-based logger for standalone package usage
95
+ */
96
+ declare class ConsoleLogger implements ILogger {
97
+ private logLevel;
98
+ constructor(logLevel?: LogLevel);
99
+ setLogLevel(level: LogLevel): void;
100
+ debug(message: string, context?: Record<string, unknown>): void;
101
+ info(message: string, context?: Record<string, unknown>): void;
102
+ warn(message: string, context?: Record<string, unknown>): void;
103
+ error(message: string, error?: unknown, context?: Record<string, unknown>): void;
104
+ private shouldLog;
105
+ private formatMessage;
106
+ }
107
+ /**
108
+ * Default logger instance
109
+ */
110
+ declare const defaultLogger: ILogger;
111
+
112
+ /**
113
+ * ZKIM File Format Types - Single Source of Truth
114
+ *
115
+ * This file contains all ZKIM file format-related types including core file format,
116
+ * archive format, message format, and service configuration types.
117
+ */
118
+ /**
119
+ * ZKIM Magic Bytes Type
120
+ * - "ZKIM": Magic bytes identifier using ML-DSA-65 (FIPS 204)
121
+ */
122
+ type ZKIMMagicBytes = "ZKIM";
123
+ /**
124
+ * ZKIM File Header Interface
125
+ */
126
+ interface ZkimFileHeader {
127
+ /**
128
+ * Magic bytes: "ZKIM" (using ML-DSA-65, FIPS 204)
129
+ */
130
+ magic: ZKIMMagicBytes;
131
+ version: number;
132
+ flags: number;
133
+ platformKeyId: string;
134
+ userId: string;
135
+ fileId: string;
136
+ createdAt: number;
137
+ chunkCount: number;
138
+ totalSize: number;
139
+ compressionType: number;
140
+ encryptionType: number;
141
+ hashType: number;
142
+ /**
143
+ * Signature type: 1 (ML-DSA-65, 3,309 bytes, FIPS 204)
144
+ */
145
+ signatureType: number;
146
+ }
147
+ /**
148
+ * ZKIM File Chunk Interface
149
+ */
150
+ interface ZkimFileChunk {
151
+ chunkIndex: number;
152
+ chunkSize: number;
153
+ compressedSize: number;
154
+ encryptedSize: number;
155
+ nonce: Uint8Array;
156
+ encryptedData: Uint8Array;
157
+ integrityHash: Uint8Array;
158
+ padding: Uint8Array;
159
+ }
160
+ /**
161
+ * Base File Metadata Interface
162
+ * Used as base for ZKIM file metadata
163
+ */
164
+ interface FileMetadata {
165
+ id: string;
166
+ name: string;
167
+ size: number;
168
+ mimeType: string;
169
+ hash: string;
170
+ createdAt: number;
171
+ updatedAt: number;
172
+ tags?: string[];
173
+ metadata?: Record<string, unknown>;
174
+ accessControl?: {
175
+ readAccess: string[];
176
+ writeAccess: string[];
177
+ deleteAccess: string[];
178
+ };
179
+ retentionPolicy?: {
180
+ expiresAt?: number;
181
+ maxAccessCount?: number;
182
+ autoDelete?: boolean;
183
+ };
184
+ }
185
+ /**
186
+ * ZKIM File Metadata Interface
187
+ * Extends base FileMetadata with ZKIM-specific fields
188
+ */
189
+ interface ZkimFileMetadata extends Omit<FileMetadata, "id" | "name" | "size" | "hash" | "updatedAt"> {
190
+ fileName: string;
191
+ customFields?: Record<string, unknown>;
192
+ userId?: string;
193
+ createdAt: number;
194
+ /**
195
+ * ML-KEM-768 public key (1,184 bytes, base64 encoded)
196
+ * Used for post-quantum key derivation during decryption
197
+ */
198
+ kemPublicKey?: string;
199
+ }
200
+ /**
201
+ * ZKIM File Interface
202
+ */
203
+ interface ZkimFile {
204
+ header: ZkimFileHeader;
205
+ chunks: ZkimFileChunk[];
206
+ metadata: ZkimFileMetadata;
207
+ platformSignature: Uint8Array;
208
+ userSignature: Uint8Array;
209
+ contentSignature: Uint8Array;
210
+ }
211
+ /**
212
+ * ZKIM File Result Interface
213
+ */
214
+ interface ZkimFileResult {
215
+ success: boolean;
216
+ file: ZkimFile;
217
+ zkimFile: ZkimFile;
218
+ objectId: string;
219
+ size: number;
220
+ chunks: number;
221
+ processingTime: number;
222
+ compressionRatio: number;
223
+ encryptionOverhead: number;
224
+ }
225
+ /**
226
+ * ZKIM File Search Result Interface
227
+ */
228
+ interface ZkimFileSearchResult {
229
+ fileId: string;
230
+ objectId: string;
231
+ relevance: number;
232
+ metadata: Partial<ZkimFileMetadata>;
233
+ accessLevel: "full" | "metadata" | "none";
234
+ lastAccessed: number;
235
+ }
236
+ /**
237
+ * ZKIM File Service Configuration Interface
238
+ */
239
+ interface ZKIMFileServiceConfig {
240
+ enableCompression: boolean;
241
+ enableDeduplication: boolean;
242
+ chunkSize: number;
243
+ compressionLevel: number;
244
+ compressionAlgorithm: "brotli" | "gzip";
245
+ enableSearchableEncryption: boolean;
246
+ enableIntegrityValidation: boolean;
247
+ enableMetadataIndexing: boolean;
248
+ maxFileSize: number;
249
+ enableStreaming: boolean;
250
+ }
251
+ /**
252
+ * ZKIM Encryption Configuration Interface
253
+ */
254
+ interface ZkimEncryptionConfig {
255
+ enableThreeLayerEncryption: boolean;
256
+ enableKeyRotation: boolean;
257
+ enablePerfectForwardSecrecy: boolean;
258
+ enableCompromiseDetection: boolean;
259
+ defaultAlgorithm: "xchacha20-poly1305" | "aes-256-gcm";
260
+ keySize: number;
261
+ nonceSize: number;
262
+ compressionEnabled: boolean;
263
+ compressionAlgorithm: "brotli" | "gzip";
264
+ compressionLevel: number;
265
+ algorithm?: string;
266
+ keyRotationInterval?: number;
267
+ maxKeyAge?: number;
268
+ enableKeyValidation?: boolean;
269
+ enablePerformanceOptimization?: boolean;
270
+ }
271
+ /**
272
+ * ZKIM Integrity Configuration Interface
273
+ */
274
+ interface ZkimIntegrityConfig {
275
+ enableHeaderValidation: boolean;
276
+ enableChunkValidation: boolean;
277
+ enableSignatureValidation: boolean;
278
+ enableMetadataValidation: boolean;
279
+ enableTamperDetection: boolean;
280
+ validationThreshold: number;
281
+ enableAuditLogging: boolean;
282
+ enablePerformanceMetrics: boolean;
283
+ hashAlgorithm: "blake3" | "sha256" | "sha512";
284
+ signatureAlgorithm: "ml-dsa-65";
285
+ }
286
+ /**
287
+ * Compression Configuration Interface
288
+ */
289
+ interface CompressionConfig {
290
+ algorithm: "lz4" | "zstd" | "brotli" | "gzip";
291
+ level: number;
292
+ enableDictionary: boolean;
293
+ enableStreaming: boolean;
294
+ maxDictionarySize: number;
295
+ enableAdaptiveCompression: boolean;
296
+ }
297
+ /**
298
+ * Compression Result Interface
299
+ */
300
+ interface CompressionResult {
301
+ originalSize: number;
302
+ compressedSize: number;
303
+ compressedData: Uint8Array;
304
+ compressionRatio: number;
305
+ compressionTime: number;
306
+ decompressionTime: number;
307
+ algorithm: string;
308
+ level: number;
309
+ }
310
+ /**
311
+ * Integrity Validation Result Interface
312
+ */
313
+ interface IntegrityValidationResult {
314
+ isValid: boolean;
315
+ validationLevel: "none" | "basic" | "full";
316
+ headerValid: boolean;
317
+ chunksValid: boolean;
318
+ signaturesValid: boolean;
319
+ metadataValid: boolean;
320
+ errors: string[];
321
+ warnings: string[];
322
+ validationTime: number;
323
+ }
324
+ /**
325
+ * Searchable Encryption Configuration Interface
326
+ */
327
+ interface SearchableEncryptionConfig {
328
+ enableOPRF: boolean;
329
+ enableRateLimiting: boolean;
330
+ enableQueryBatching: boolean;
331
+ enableTrapdoorRotation: boolean;
332
+ epochDuration: number;
333
+ maxQueriesPerEpoch: number;
334
+ bucketSizes: number[];
335
+ minCoverage: number;
336
+ enablePrivacyEnhancement: boolean;
337
+ enableResultPadding: boolean;
338
+ enableQueryLogging: boolean;
339
+ }
340
+ /**
341
+ * Indexed File Interface
342
+ */
343
+ interface IndexedFile {
344
+ fileId: string;
345
+ objectId: string;
346
+ userId: string;
347
+ metadata: ZkimFileMetadata;
348
+ trapdoors: string[];
349
+ indexedAt: number;
350
+ lastAccessed: number;
351
+ accessCount: number;
352
+ privacyLevel: "high" | "medium" | "low";
353
+ }
354
+ /**
355
+ * Query History Entry Interface
356
+ */
357
+ interface QueryHistoryEntry {
358
+ queryId: string;
359
+ query: string;
360
+ userId: string;
361
+ timestamp: number;
362
+ resultsCount: number;
363
+ processingTime: number;
364
+ privacyLevel: "high" | "medium" | "low";
365
+ trapdoorId?: string;
366
+ metadata?: Record<string, unknown>;
367
+ }
368
+ /**
369
+ * Search Query Interface
370
+ */
371
+ interface SearchQuery {
372
+ queryId: string;
373
+ query: string;
374
+ userId: string;
375
+ timestamp: number;
376
+ priority: "high" | "medium" | "low";
377
+ metadata?: Record<string, unknown>;
378
+ }
379
+ /**
380
+ * Search Result Interface
381
+ */
382
+ interface SearchResult {
383
+ queryId: string;
384
+ results: ZkimFileSearchResult[];
385
+ totalResults: number;
386
+ processingTime: number;
387
+ privacyLevel: "high" | "medium" | "low";
388
+ metadata?: Record<string, unknown>;
389
+ }
390
+ /**
391
+ * Trapdoor Interface
392
+ */
393
+ interface Trapdoor {
394
+ trapdoorId: string;
395
+ userId: string;
396
+ query: string;
397
+ epoch: number;
398
+ expiresAt: number;
399
+ usageCount: number;
400
+ maxUsage: number;
401
+ isRevoked: boolean;
402
+ }
403
+ /**
404
+ * Query Batch Configuration Interface
405
+ */
406
+ interface QueryBatchConfig {
407
+ enableBatching: boolean;
408
+ batchSize: number;
409
+ batchTimeout: number;
410
+ maxConcurrentBatches: number;
411
+ enableLoadBalancing: boolean;
412
+ enableQueryOptimization: boolean;
413
+ }
414
+ /**
415
+ * Query Batch Interface
416
+ */
417
+ interface QueryBatch {
418
+ batchId: string;
419
+ queries: SearchQuery[];
420
+ createdAt: number;
421
+ status: "pending" | "processing" | "completed" | "failed";
422
+ results: SearchResult[];
423
+ processingTime: number;
424
+ errorCount: number;
425
+ }
426
+ /**
427
+ * Trapdoor Rotation Configuration Interface
428
+ */
429
+ interface TrapdoorRotationConfig {
430
+ enableRotation: boolean;
431
+ rotationInterval: number;
432
+ gracePeriod: number;
433
+ enableRevocation: boolean;
434
+ maxActiveTrapdoors: number;
435
+ enableUsageTracking: boolean;
436
+ }
437
+ /**
438
+ * Trapdoor Rotation Event Interface
439
+ */
440
+ interface TrapdoorRotationEvent {
441
+ eventId: string;
442
+ userId: string;
443
+ trapdoorId: string;
444
+ eventType: "created" | "rotated" | "revoked" | "expired";
445
+ timestamp: number;
446
+ metadata?: Record<string, unknown>;
447
+ }
448
+ /**
449
+ * Usage Pattern Interface
450
+ */
451
+ interface UsagePattern {
452
+ userId: string;
453
+ queryPatterns: string[];
454
+ usageFrequency: number;
455
+ lastUsed: number;
456
+ totalUsage: number;
457
+ anomalyScore: number;
458
+ }
459
+ /**
460
+ * Anomaly Detector Class
461
+ */
462
+ declare class AnomalyDetector {
463
+ detectAnomaly(usagePattern: UsagePattern, currentUsage: number): {
464
+ isAnomaly: boolean;
465
+ score: number;
466
+ reason: string;
467
+ };
468
+ }
469
+ /**
470
+ * Cached Result Interface
471
+ */
472
+ interface CachedResult {
473
+ result: SearchResult;
474
+ timestamp: number;
475
+ accessCount: number;
476
+ }
477
+ /**
478
+ * Query Batcher Performance Metrics Interface
479
+ */
480
+ interface QueryBatcherPerformanceMetrics {
481
+ totalBatches: number;
482
+ totalQueries: number;
483
+ totalProcessingTime: number;
484
+ successfulQueries: number;
485
+ failedQueries: number;
486
+ averageProcessingTime: number;
487
+ successRate: number;
488
+ averageBatchTime: number;
489
+ averageQueryTime: number;
490
+ cacheHitRate: number;
491
+ loadBalancingEfficiency: number;
492
+ updateBatchMetrics(batchTime: number): void;
493
+ updateQueryMetrics(queryTime: number, success: boolean): void;
494
+ reset(): void;
495
+ }
496
+ /**
497
+ * Metadata With Access Level Interface
498
+ */
499
+ interface MetadataWithAccessLevel {
500
+ fileName?: string;
501
+ accessLevel?: string;
502
+ [key: string]: unknown;
503
+ }
504
+
505
+ /**
506
+ * Storage Interface for @zkim-platform/file-format
507
+ * Abstract storage backend for different storage implementations
508
+ */
509
+ /**
510
+ * Storage backend interface
511
+ * Implement this interface to provide custom storage backends
512
+ */
513
+ interface IStorageBackend {
514
+ /**
515
+ * Store data with the given key
516
+ */
517
+ set(key: string, value: Uint8Array): Promise<void>;
518
+ /**
519
+ * Retrieve data by key
520
+ */
521
+ get(key: string): Promise<Uint8Array | null>;
522
+ /**
523
+ * Check if key exists
524
+ */
525
+ has(key: string): Promise<boolean>;
526
+ /**
527
+ * Delete data by key
528
+ */
529
+ delete(key: string): Promise<void>;
530
+ /**
531
+ * Clear all data
532
+ */
533
+ clear(): Promise<void>;
534
+ /**
535
+ * Get all keys
536
+ */
537
+ keys(): Promise<string[]>;
538
+ }
539
+ /**
540
+ * In-memory storage implementation
541
+ * Useful for testing or temporary storage
542
+ */
543
+ declare class InMemoryStorage implements IStorageBackend {
544
+ private storage;
545
+ set(key: string, value: Uint8Array): Promise<void>;
546
+ get(key: string): Promise<Uint8Array | null>;
547
+ has(key: string): Promise<boolean>;
548
+ delete(key: string): Promise<void>;
549
+ clear(): Promise<void>;
550
+ keys(): Promise<string[]>;
551
+ }
552
+ /**
553
+ * LocalStorage-based storage implementation
554
+ * For browser environments
555
+ */
556
+ declare class LocalStorageBackend implements IStorageBackend {
557
+ private prefix;
558
+ constructor(prefix?: string);
559
+ private getKey;
560
+ set(key: string, value: Uint8Array): Promise<void>;
561
+ get(key: string): Promise<Uint8Array | null>;
562
+ has(key: string): Promise<boolean>;
563
+ delete(key: string): Promise<void>;
564
+ clear(): Promise<void>;
565
+ keys(): Promise<string[]>;
566
+ }
567
+
568
+ /**
569
+ * ZKIM File Service - Core File Format Implementation
570
+ * Handles ZKIM file creation, management, and operations
571
+ *
572
+ * Service Flow:
573
+ * 1. Create ZKIM files with three-layer encryption (Platform/User/Content)
574
+ * 2. Manage file lifecycle and metadata
575
+ * 3. Provide searchable encryption capabilities
576
+ * 4. Ensure integrity validation and tamper detection
577
+ */
578
+
579
+ declare class ZKIMFileService extends ServiceBase {
580
+ private readonly defaultConfig;
581
+ private config;
582
+ private storageService;
583
+ private logger;
584
+ constructor(config?: Partial<ZKIMFileServiceConfig>, logger?: ILogger, storageService?: IStorageBackend);
585
+ initialize(): Promise<void>;
586
+ /**
587
+ * Create a new ZKIM file with three-layer encryption
588
+ * @param skipCasStorage - If true, skip storing to CAS (prevents circular dependency when persisting to filesystem)
589
+ */
590
+ createZkimFile(data: Uint8Array | string, userId: string, platformKey: Uint8Array, userKey: Uint8Array, metadata?: Partial<ZkimFileMetadata>, skipCasStorage?: boolean): Promise<ZkimFileResult>;
591
+ /**
592
+ * Decrypt and retrieve a ZKIM file
593
+ */
594
+ decryptZkimFile(zkimFile: ZkimFile, userId: string, userKey: Uint8Array): Promise<Uint8Array>;
595
+ /**
596
+ * Get a ZKIM file by object ID
597
+ */
598
+ getZkimFile(objectId: string): Promise<{
599
+ success: boolean;
600
+ data?: ZkimFile;
601
+ error?: string;
602
+ }>;
603
+ /**
604
+ * Search through encrypted files using searchable encryption
605
+ */
606
+ searchFiles(query: string, userId: string, limit?: number): Promise<SearchResult>;
607
+ /**
608
+ * Validate file integrity
609
+ */
610
+ validateFileIntegrity(zkimFile: ZkimFile): Promise<IntegrityValidationResult>;
611
+ /**
612
+ * Update file metadata
613
+ */
614
+ updateFileMetadata(zkimFile: ZkimFile, userId: string, updates: Partial<ZkimFileMetadata>): Promise<ZkimFile>;
615
+ /**
616
+ * Derive ML-DSA-65 signing key from encryption key
617
+ * Uses deterministic key generation with BLAKE3 seed derivation
618
+ * ML-DSA-65 secret key is 4,032 bytes (FIPS 204)
619
+ *
620
+ * Matches infrastructure implementation for consistency
621
+ */
622
+ private deriveMLDSA65SigningKeyFromEncryptionKey;
623
+ /**
624
+ * Decode base64 signing key with error handling
625
+ */
626
+ private decodeBase64SigningKey;
627
+ /**
628
+ * Validate ML-DSA-65 signing key length
629
+ * ML-DSA-65 secret key must be exactly 4,032 bytes (FIPS 204)
630
+ */
631
+ private validateMLDSA65KeyLength;
632
+ /**
633
+ * Get or derive ML-DSA-65 signing key from metadata or encryption key
634
+ * ML-DSA-65 secret key must be 4,032 bytes (FIPS 204)
635
+ * If not provided in metadata, generates a key pair (non-deterministic)
636
+ * For production use, signing keys should be provided in metadata
637
+ */
638
+ private getOrDeriveSigningKey;
639
+ private generateFileId;
640
+ private createFileHeader;
641
+ private processData;
642
+ /**
643
+ * Map 3-layer encrypted content to ZKIM chunks
644
+ * This method chunks the contentEncrypted data (already encrypted by 3-layer encryption)
645
+ */
646
+ private mapEncryptedContentToChunks;
647
+ /**
648
+ * Generate cryptographically random nonce for chunk storage
649
+ *
650
+ * Security Critical: Nonces MUST be random and unique for each chunk.
651
+ * Deterministic nonce generation breaks XChaCha20-Poly1305 security guarantees.
652
+ *
653
+ * Note: Chunks are storage chunks of already-encrypted content data.
654
+ * These nonces are stored in wire format for metadata purposes.
655
+ * Even though chunks are not re-encrypted, we use random nonces for security best practices.
656
+ */
657
+ private generateChunkNonce;
658
+ private generateIntegrityHash;
659
+ private generatePadding;
660
+ private createFileMetadata;
661
+ private generateSignatures;
662
+ private signData;
663
+ private verifyUserAccess;
664
+ private decompressData;
665
+ private reconstructData;
666
+ private generateQueryId;
667
+ /**
668
+ * Store ML-KEM-768 secret key encrypted with user key
669
+ */
670
+ private storeKemSecretKey;
671
+ /**
672
+ * Retrieve and decrypt ML-KEM-768 secret key
673
+ */
674
+ private getKemSecretKey;
675
+ /**
676
+ * Cleanup method required by ServiceBase
677
+ */
678
+ cleanup(): Promise<void>;
679
+ /**
680
+ * Download a ZKIM file by object ID
681
+ *
682
+ * ⚠️ SECURITY: Requires explicit userKey and platformKey parameters.
683
+ * Keys must be derived from actual user authentication, not generated deterministically.
684
+ * See Authentication Integration guide for proper key derivation.
685
+ */
686
+ downloadFile(objectId: string, userId: string, platformKey: Uint8Array, userKey: Uint8Array): Promise<{
687
+ success: boolean;
688
+ data?: Uint8Array;
689
+ error?: string;
690
+ }>;
691
+ }
692
+
693
+ /**
694
+ * Encryption Service Interface
695
+ * Abstract interface for encryption operations used by wire format utilities
696
+ */
697
+ interface IEncryptionService {
698
+ /**
699
+ * Decrypt user layer encryption
700
+ * Returns file metadata and content key
701
+ */
702
+ decryptUserLayer(userEncrypted: Uint8Array, userKey: Uint8Array, nonce: Uint8Array): Promise<{
703
+ fileId: string;
704
+ contentKey: Uint8Array;
705
+ metadata: Record<string, unknown>;
706
+ }>;
707
+ /**
708
+ * Decrypt platform layer encryption (optional)
709
+ * Returns search metadata
710
+ */
711
+ decryptPlatformLayer(platformEncrypted: Uint8Array, platformKey: Uint8Array, nonce: Uint8Array): Promise<Record<string, unknown>>;
712
+ }
713
+
714
+ /**
715
+ * ZKIM Encryption Service - Three-Layer Encryption Implementation
716
+ * Handles encryption/decryption for Platform, User, and Content layers
717
+ *
718
+ * Service Flow:
719
+ * 1. Platform layer encryption (search-only, never decrypts)
720
+ * 2. User layer encryption (full decryption authority)
721
+ * 3. Content layer encryption (per-file random keys)
722
+ * 4. Key management and rotation
723
+ */
724
+
725
+ declare class ZkimEncryption extends ServiceBase implements IEncryptionService {
726
+ private static readonly THREE_LAYER_COUNT;
727
+ private static readonly COMPRESSION_LEVEL_DEFAULT;
728
+ private readonly defaultConfig;
729
+ private config;
730
+ private keyStore;
731
+ private sessionKeys;
732
+ private logger;
733
+ constructor(config?: Partial<ZkimEncryptionConfig>, logger?: ILogger);
734
+ initialize(): Promise<void>;
735
+ /**
736
+ * Encrypt data with three-layer encryption
737
+ *
738
+ * Three-Layer Encryption Architecture:
739
+ * 1. Platform Layer: Search-only encryption (never decrypts user data)
740
+ * - Uses platform key for searchable encryption
741
+ * - Enables privacy-preserving search without data access
742
+ * - Encrypts searchable metadata and indexes
743
+ *
744
+ * 2. User Layer: Full decryption authority
745
+ * - Uses user-specific key for complete data access
746
+ * - Enables user to decrypt all their content
747
+ * - Provides user-level access control
748
+ *
749
+ * 3. Content Layer: Per-file random keys
750
+ * - Uses unique random key for each file
751
+ * - Provides perfect forward secrecy
752
+ * - Prevents cross-file key compromise
753
+ *
754
+ * Security Properties:
755
+ * - Authenticated encryption with associated data (AEAD)
756
+ * - 256-bit security level with XChaCha20-Poly1305
757
+ * - Nonce reuse protection with unique nonces per layer
758
+ * - Integrity validation with authentication tags
759
+ * - Perfect forward secrecy with per-file keys
760
+ *
761
+ * @param data - Plaintext data to encrypt
762
+ * @param platformKey - 32-byte platform encryption key
763
+ * @param userKey - 32-byte user-specific encryption key
764
+ * @param fileId - Unique file identifier for key derivation
765
+ * @param metadata - Optional metadata for encryption context
766
+ * @returns Object containing encrypted data for each layer, content key, and nonces
767
+ */
768
+ encryptData(data: Uint8Array, platformKey: Uint8Array, userKey: Uint8Array, fileId: string, metadata?: Record<string, unknown>): Promise<{
769
+ platformEncrypted: Uint8Array;
770
+ userEncrypted: Uint8Array;
771
+ contentEncrypted: Uint8Array;
772
+ contentKey: Uint8Array;
773
+ nonces: Uint8Array[];
774
+ }>;
775
+ /**
776
+ * Decrypt chunk data
777
+ */
778
+ decryptChunk(chunk: ZkimFileChunk, userKey: Uint8Array, fileId: string, chunkIndex: number): Promise<Uint8Array>;
779
+ /**
780
+ * Decrypt user layer to get content key
781
+ */
782
+ decryptUserLayer(userEncrypted: Uint8Array, userKey: Uint8Array, nonce: Uint8Array): Promise<{
783
+ fileId: string;
784
+ contentKey: Uint8Array;
785
+ metadata: Record<string, unknown>;
786
+ }>;
787
+ /**
788
+ * Decrypt platform layer (search-only metadata)
789
+ */
790
+ decryptPlatformLayer(platformEncrypted: Uint8Array, platformKey: Uint8Array, nonce: Uint8Array): Promise<Record<string, unknown>>;
791
+ /**
792
+ * Simple decrypt method for general use
793
+ */
794
+ decrypt(encryptedData: Uint8Array, key: Uint8Array, nonce: Uint8Array): Promise<Uint8Array>;
795
+ /**
796
+ * Compress data using configured algorithm
797
+ */
798
+ compressData(data: Uint8Array, config?: Partial<CompressionConfig>): Promise<CompressionResult>;
799
+ /**
800
+ * Decompress data using configured algorithm
801
+ */
802
+ decompressData(data: Uint8Array, originalSize: number, config?: Partial<CompressionConfig>): Promise<Uint8Array>;
803
+ /**
804
+ * Generate session key for secure communication
805
+ */
806
+ generateSessionKey(peerId: string, ephemeralKey: Uint8Array): Promise<Uint8Array>;
807
+ /**
808
+ * Rotate keys for enhanced security
809
+ */
810
+ rotateKeys(fileId: string): Promise<Uint8Array>;
811
+ /**
812
+ * Check for compromised keys
813
+ */
814
+ checkKeyCompromise(fileId: string): Promise<boolean>;
815
+ protected ensureInitialized(): Promise<void>;
816
+ private initializeKeyManagement;
817
+ /**
818
+ * Extract searchable text from content data
819
+ * Tokenizes content into searchable words for privacy-preserving search
820
+ */
821
+ private extractSearchableText;
822
+ /**
823
+ * Generate cryptographically secure random nonces for encryption
824
+ *
825
+ * Security Critical: Nonces MUST be random and unique for each encryption operation.
826
+ * This method uses sodium.randombytes_buf() for cryptographically random nonce generation.
827
+ * Deterministic nonce generation (e.g., hash-based) breaks XChaCha20-Poly1305 security guarantees.
828
+ *
829
+ * Nonce Requirements:
830
+ * - Must be unique for each encryption operation
831
+ * - Must be cryptographically random (not deterministic)
832
+ * - Must be 24 bytes for XChaCha20-Poly1305
833
+ * - Never reuse nonces with the same key
834
+ *
835
+ * Implementation: Uses sodium.randombytes_buf() for true cryptographic randomness.
836
+ * The fileId parameter is used ONLY for logging/tracking, NOT for nonce generation.
837
+ *
838
+ * @param fileId - File identifier (used for logging only, NOT for nonce generation)
839
+ * @param count - Number of nonces to generate (typically 3 for three-layer encryption)
840
+ * @returns Array of cryptographically random nonces generated via sodium.randombytes_buf()
841
+ */
842
+ private generateNonces;
843
+ /**
844
+ * Core encryption method using XChaCha20-Poly1305 AEAD
845
+ *
846
+ * Cryptographic Implementation:
847
+ * - Uses XChaCha20-Poly1305 for authenticated encryption with associated data
848
+ * - Provides 256-bit security level with 24-byte nonce and 32-byte key
849
+ * - Implements AEAD (Authenticated Encryption with Associated Data)
850
+ * - Returns separate encrypted data and authentication tag
851
+ *
852
+ * Security Properties:
853
+ * - Authenticated encryption prevents tampering
854
+ * - Nonce reuse protection (each encryption uses unique nonce)
855
+ * - Integrity validation through authentication tag
856
+ * - Constant-time operations to prevent timing attacks
857
+ * - Forward secrecy with unique keys per operation
858
+ *
859
+ * Performance Characteristics:
860
+ * - Fast encryption/decryption for large data
861
+ * - Minimal memory overhead
862
+ * - Optimized for streaming operations
863
+ * - Hardware acceleration support where available
864
+ *
865
+ * @param data - Plaintext data to encrypt
866
+ * @param key - 32-byte encryption key (must be cryptographically random)
867
+ * @param nonce - 24-byte nonce (must be unique for each encryption)
868
+ * @param layer - Layer identifier for logging (platform/user/content)
869
+ * @returns EncryptionResult with encrypted data, tag, and metadata
870
+ */
871
+ private encryptLayer;
872
+ private decryptLayer;
873
+ /**
874
+ * Create no compression result for disabled compression
875
+ */
876
+ private createNoCompressionResult;
877
+ /**
878
+ * Compress data using Brotli algorithm
879
+ * Uses browser's native CompressionStream API (backendless-compatible)
880
+ */
881
+ private compressBrotli;
882
+ /**
883
+ * Decompress data using Brotli algorithm
884
+ * Uses browser's native DecompressionStream API (backendless-compatible)
885
+ */
886
+ private decompressBrotli;
887
+ /**
888
+ * Compress data using GZIP algorithm
889
+ * Delegates to compression-utils for mockability in tests
890
+ */
891
+ private compressGZIP;
892
+ /**
893
+ * Decompress data using GZIP algorithm
894
+ * Delegates to compression-utils for mockability in tests
895
+ */
896
+ private decompressGZIP;
897
+ /**
898
+ * Clean up resources
899
+ */
900
+ cleanup(): Promise<void>;
901
+ }
902
+
903
+ /**
904
+ * ZKIM Integrity Service - File Validation and Tamper Detection
905
+ * Handles integrity validation using BLAKE3 + ML-DSA-65 signatures (FIPS 204)
906
+ *
907
+ * Service Flow:
908
+ * 1. Validate file header integrity
909
+ * 2. Verify chunk integrity with BLAKE3 hashes
910
+ * 3. Validate signatures (Platform, User, Content)
911
+ * 4. Detect tampering and provide detailed validation results
912
+ */
913
+
914
+ declare class ZkimIntegrity extends ServiceBase {
915
+ private readonly defaultConfig;
916
+ private config;
917
+ private isInitialized;
918
+ private validationCache;
919
+ private auditLog;
920
+ private logger;
921
+ constructor(config?: Partial<ZkimIntegrityConfig>, logger?: ILogger);
922
+ initialize(): Promise<void>;
923
+ /**
924
+ * Validate complete ZKIM file integrity
925
+ *
926
+ * @param zkimFile - The ZKIM file to validate
927
+ * @param platformKey - Optional platform encryption key (required for signature verification)
928
+ * @param userKey - Optional user encryption key (required for signature verification)
929
+ */
930
+ validateFile(zkimFile: ZkimFile, platformKey?: Uint8Array, userKey?: Uint8Array): Promise<IntegrityValidationResult>;
931
+ /**
932
+ * Validate specific file header
933
+ */
934
+ validateHeader(header: ZkimFileHeader): Promise<boolean>;
935
+ /**
936
+ * Validate file chunks integrity
937
+ */
938
+ validateChunks(chunks: ZkimFileChunk[], header: ZkimFileHeader): Promise<boolean>;
939
+ /**
940
+ * Validate file signatures
941
+ *
942
+ * @param zkimFile - The ZKIM file to validate
943
+ * @param platformKey - Optional platform encryption key (used to derive public key for verification)
944
+ * @param userKey - Optional user encryption key (used to derive public key for verification)
945
+ * @returns true if signatures are valid or if keys are not provided (signature verification skipped)
946
+ */
947
+ validateSignatures(zkimFile: ZkimFile, platformKey?: Uint8Array, userKey?: Uint8Array): Promise<boolean>;
948
+ /**
949
+ * Validate file metadata
950
+ */
951
+ validateMetadata(metadata: ZkimFileMetadata): Promise<boolean>;
952
+ /**
953
+ * Detect tampering in file
954
+ */
955
+ detectTampering(zkimFile: ZkimFile): Promise<{
956
+ isTampered: boolean;
957
+ tamperType: string[];
958
+ evidence: string[];
959
+ }>;
960
+ private initializeValidationSystems;
961
+ private isCacheValid;
962
+ private calculateValidationScore;
963
+ private determineValidationLevel;
964
+ private isValidAlgorithmId;
965
+ private verifySignature;
966
+ private logAuditEntry;
967
+ /**
968
+ * Get audit log entries
969
+ */
970
+ getAuditLog(limit?: number): Array<{
971
+ timestamp: number;
972
+ fileId: string;
973
+ operation: string;
974
+ result: boolean;
975
+ details: string;
976
+ }>;
977
+ /**
978
+ * Clear validation cache
979
+ */
980
+ clearCache(): void;
981
+ /**
982
+ * Clean up resources
983
+ */
984
+ cleanup(): Promise<void>;
985
+ }
986
+
987
+ /**
988
+ * ZKIM Searchable Encryption Service - OPRF-based Privacy-Preserving Search
989
+ * Implements searchable encryption using OPRF on ristretto255 curve
990
+ *
991
+ * Service Flow:
992
+ * 1. Index files with OPRF-based searchable encryption
993
+ * 2. Process search queries with privacy enhancement
994
+ * 3. Return results with rate limiting and padding
995
+ * 4. Manage trapdoor rotation and revocation
996
+ */
997
+
998
+ declare class SearchableEncryption extends ServiceBase {
999
+ private readonly defaultConfig;
1000
+ static search(query: SearchQuery, limit?: number): Promise<SearchResult>;
1001
+ private config;
1002
+ private isInitialized;
1003
+ private fileIndex;
1004
+ private trapdoors;
1005
+ private queryHistory;
1006
+ private currentEpoch;
1007
+ private epochStartTime;
1008
+ private oprfSecretKey;
1009
+ private zkimFileService;
1010
+ private saveIndexTimer;
1011
+ private epochTimer;
1012
+ private logger;
1013
+ private createIndexedFile;
1014
+ private createQueryHistoryEntry;
1015
+ constructor(config?: Partial<SearchableEncryptionConfig>, logger?: ILogger);
1016
+ initialize(): Promise<void>;
1017
+ /**
1018
+ * Index a file for searchable encryption
1019
+ */
1020
+ indexFile(zkimFile: ZkimFile, userId: string): Promise<void>;
1021
+ /**
1022
+ * Search through encrypted files
1023
+ */
1024
+ search(query: SearchQuery, limit?: number): Promise<SearchResult>;
1025
+ /**
1026
+ * Update file index when metadata changes
1027
+ */
1028
+ updateFileIndex(zkimFile: ZkimFile, userId: string): Promise<void>;
1029
+ /**
1030
+ * Remove file from search index
1031
+ */
1032
+ removeFileFromIndex(fileId: string): Promise<void>;
1033
+ /**
1034
+ * Rotate trapdoors for enhanced privacy
1035
+ */
1036
+ rotateTrapdoors(): Promise<void>;
1037
+ /**
1038
+ * Generate OPRF token for a word (public API for indexing)
1039
+ * Used by message indexing service to generate privacy-preserving tokens
1040
+ */
1041
+ generateOPRFToken(word: string): Promise<string>;
1042
+ /**
1043
+ * Get search statistics
1044
+ */
1045
+ getSearchStats(): Promise<{
1046
+ totalIndexedFiles: number;
1047
+ totalTrapdoors: number;
1048
+ activeTrapdoors: number;
1049
+ queriesThisEpoch: number;
1050
+ averageQueryTime: number;
1051
+ privacyLevels: Record<string, number>;
1052
+ }>;
1053
+ protected ensureInitialized(): Promise<void>;
1054
+ private initializeOPRF;
1055
+ private startEpochManagement;
1056
+ private advanceEpoch;
1057
+ private generateObjectId;
1058
+ private generateSearchTokens;
1059
+ /**
1060
+ * Generate OPRF token using Ristretto255 curve
1061
+ * OPRF evaluation: F(k, x) = H(x) * k
1062
+ * 1. Hash input to uniform distribution (BLAKE3)
1063
+ * 2. Map hash to Ristretto255 point (hash as scalar × base point)
1064
+ * 3. Multiply by secret key scalar
1065
+ * 4. Return base64-encoded result
1066
+ */
1067
+ private generateToken;
1068
+ /**
1069
+ * Convert bytes to scalar for Ristretto255
1070
+ * Clamps bytes to valid scalar range (mod curve order)
1071
+ */
1072
+ private bytesToScalar;
1073
+ /**
1074
+ * Generate OPRF trapdoor for search query
1075
+ * Same OPRF evaluation as generateToken, returns raw bytes instead of base64
1076
+ */
1077
+ private generateOPRFTrapdoor;
1078
+ private determineAccessLevel;
1079
+ private checkRateLimit;
1080
+ private generateTrapdoor;
1081
+ private generateTrapdoorId;
1082
+ private performOPRFSearch;
1083
+ /**
1084
+ * Match OPRF trapdoor against indexed trapdoors using constant-time comparison
1085
+ * Prevents timing attacks by using sodium.memcmp for all comparisons
1086
+ */
1087
+ private matchesOPRFQuery;
1088
+ private calculateRelevance;
1089
+ private applyPrivacyEnhancement;
1090
+ private addResultPadding;
1091
+ private selectTargetBucket;
1092
+ private generatePaddingResults;
1093
+ private generateRandomFloat;
1094
+ private shuffleArray;
1095
+ private determinePrivacyLevel;
1096
+ private rotateTrapdoor;
1097
+ private cleanupExpiredTrapdoors;
1098
+ private logQueryHistory;
1099
+ private calculatePrivacyLevels;
1100
+ cleanup(): Promise<void>;
1101
+ /**
1102
+ * Load file index from persistence (browser: localStorage, Node.js: in-memory only)
1103
+ */
1104
+ private loadFileIndex;
1105
+ /**
1106
+ * Save file index to persistence (browser: localStorage as ZKIM file, Node.js: in-memory only)
1107
+ */
1108
+ private saveFileIndex;
1109
+ private startAutoSave;
1110
+ }
1111
+
1112
+ /**
1113
+ * Error Types and Classes for @zkim-platform/file-format
1114
+ * Lightweight error handling without platform dependencies
1115
+ */
1116
+ interface ErrorContext {
1117
+ message: string;
1118
+ type: string;
1119
+ source: string;
1120
+ operation: string;
1121
+ timestamp: number;
1122
+ severity: "low" | "medium" | "high" | "critical";
1123
+ metadata?: Record<string, unknown>;
1124
+ service?: string;
1125
+ userId?: string;
1126
+ sessionId?: string;
1127
+ requestId?: string;
1128
+ [key: string]: unknown;
1129
+ }
1130
+ interface ServiceResult<T = unknown> {
1131
+ success: boolean;
1132
+ data?: T;
1133
+ error?: string;
1134
+ errorCode?: string;
1135
+ context?: ErrorContext;
1136
+ metadata?: Record<string, unknown>;
1137
+ }
1138
+ /**
1139
+ * Base Service Error Class
1140
+ */
1141
+ declare class ServiceError extends Error {
1142
+ readonly code?: string;
1143
+ readonly details?: Record<string, unknown>;
1144
+ constructor(message: string, options?: {
1145
+ code?: string;
1146
+ details?: Record<string, unknown>;
1147
+ });
1148
+ }
1149
+ /**
1150
+ * ZKIM File Format Specific Errors
1151
+ */
1152
+ declare class ZKIMFileError extends ServiceError {
1153
+ constructor(message: string, options?: {
1154
+ code?: string;
1155
+ details?: Record<string, unknown>;
1156
+ });
1157
+ }
1158
+ declare class ZKIMEncryptionError extends ServiceError {
1159
+ constructor(message: string, options?: {
1160
+ code?: string;
1161
+ details?: Record<string, unknown>;
1162
+ });
1163
+ }
1164
+ declare class ZKIMIntegrityError extends ServiceError {
1165
+ constructor(message: string, options?: {
1166
+ code?: string;
1167
+ details?: Record<string, unknown>;
1168
+ });
1169
+ }
1170
+ declare class ZKIMStorageError extends ServiceError {
1171
+ constructor(message: string, options?: {
1172
+ code?: string;
1173
+ details?: Record<string, unknown>;
1174
+ });
1175
+ }
1176
+
1177
+ /**
1178
+ * ZKIM Trapdoor Rotator Service - Privacy Enhancement and Key Rotation
1179
+ * Handles trapdoor rotation, revocation, and usage tracking for enhanced privacy
1180
+ *
1181
+ * Service Flow:
1182
+ * 1. Manage trapdoor lifecycle and rotation schedules
1183
+ * 2. Implement automatic revocation and expiration
1184
+ * 3. Track usage patterns and detect anomalies
1185
+ * 4. Provide privacy metrics and audit logging
1186
+ */
1187
+
1188
+ interface TrapdoorRotatorServiceConfig extends TrapdoorRotationConfig {
1189
+ enableAnomalyDetection: boolean;
1190
+ enableAuditLogging: boolean;
1191
+ rotationThreshold: number;
1192
+ revocationThreshold: number;
1193
+ }
1194
+ declare class TrapdoorRotator extends ServiceBase {
1195
+ private readonly defaultConfig;
1196
+ private config;
1197
+ private trapdoors;
1198
+ private rotationEvents;
1199
+ private usagePatterns;
1200
+ private rotationTimer?;
1201
+ private anomalyDetector;
1202
+ private logger;
1203
+ constructor(config?: Partial<TrapdoorRotatorServiceConfig>, logger?: ILogger);
1204
+ initialize(): Promise<void>;
1205
+ /**
1206
+ * Create a new trapdoor
1207
+ */
1208
+ createTrapdoor(userId: string, query: string, maxUsage?: number): Promise<ServiceResult<Trapdoor>>;
1209
+ /**
1210
+ * Rotate an existing trapdoor
1211
+ */
1212
+ rotateTrapdoor(trapdoorId: string): Promise<ServiceResult<Trapdoor>>;
1213
+ /**
1214
+ * Revoke a trapdoor
1215
+ */
1216
+ revokeTrapdoor(trapdoorId: string, reason?: string): Promise<void>;
1217
+ /**
1218
+ * Update trapdoor usage
1219
+ */
1220
+ updateTrapdoorUsage(trapdoorId: string): Promise<ServiceResult<{
1221
+ shouldRotate: boolean;
1222
+ shouldRevoke: boolean;
1223
+ anomalyDetected: boolean;
1224
+ }>>;
1225
+ /**
1226
+ * Get trapdoor information
1227
+ */
1228
+ getTrapdoorInfo(trapdoorId: string): ServiceResult<Trapdoor | null>;
1229
+ /**
1230
+ * Get user's active trapdoors
1231
+ */
1232
+ getUserTrapdoors(userId: string): ServiceResult<Trapdoor[]>;
1233
+ /**
1234
+ * Get rotation events
1235
+ */
1236
+ getRotationEvents(limit?: number): ServiceResult<TrapdoorRotationEvent[]>;
1237
+ /**
1238
+ * Get usage statistics
1239
+ */
1240
+ getUsageStats(): ServiceResult<{
1241
+ totalTrapdoors: number;
1242
+ activeTrapdoors: number;
1243
+ revokedTrapdoors: number;
1244
+ averageUsagePerTrapdoor: number;
1245
+ totalRotations: number;
1246
+ totalRevocations: number;
1247
+ anomalyCount: number;
1248
+ }>;
1249
+ private initializeRotationSystem;
1250
+ private startRotationTimer;
1251
+ private performScheduledRotations;
1252
+ private generateTrapdoorId;
1253
+ private getActiveTrapdoorCount;
1254
+ private updateUsagePattern;
1255
+ private logRotationEvent;
1256
+ /**
1257
+ * Clean up resources
1258
+ */
1259
+ cleanup(): Promise<void>;
1260
+ }
1261
+
1262
+ /**
1263
+ * ZKIM Query Batcher Service - Query Optimization and Batching
1264
+ * Handles query batching, load balancing, and optimization for searchable encryption
1265
+ *
1266
+ * Service Flow:
1267
+ * 1. Batch multiple queries for efficient processing
1268
+ * 2. Implement load balancing across search nodes
1269
+ * 3. Optimize query execution and caching
1270
+ * 4. Provide query analytics and performance metrics
1271
+ */
1272
+
1273
+ interface QueryBatcherServiceConfig extends QueryBatchConfig {
1274
+ maxResultsPerQuery: number;
1275
+ enableQueryCaching: boolean;
1276
+ cacheSize: number;
1277
+ cacheTTL: number;
1278
+ enablePerformanceMetrics: boolean;
1279
+ }
1280
+ declare class QueryBatcher extends ServiceBase {
1281
+ private readonly defaultConfig;
1282
+ private config;
1283
+ private isInitialized;
1284
+ private pendingQueries;
1285
+ private activeBatches;
1286
+ private queryCache;
1287
+ private batchTimer;
1288
+ private logger;
1289
+ private performanceMetrics;
1290
+ private createPerformanceMetrics;
1291
+ private batchCounter;
1292
+ constructor(config?: Partial<QueryBatcherServiceConfig>, logger?: ILogger);
1293
+ initialize(): Promise<void>;
1294
+ /**
1295
+ * Add query to batch processing
1296
+ */
1297
+ addQuery(query: SearchQuery): Promise<string>;
1298
+ /**
1299
+ * Process queries in batches
1300
+ */
1301
+ processBatch(): Promise<void>;
1302
+ /**
1303
+ * Get batch status and results
1304
+ */
1305
+ getBatchStatus(batchId: string): Promise<QueryBatch | null>;
1306
+ /**
1307
+ * Get query results from batch
1308
+ */
1309
+ getQueryResults(queryId: string): Promise<SearchResult | null>;
1310
+ /**
1311
+ * Get performance metrics
1312
+ */
1313
+ getPerformanceMetrics(): Promise<{
1314
+ totalBatches: number;
1315
+ totalQueries: number;
1316
+ averageBatchTime: number;
1317
+ averageQueryTime: number;
1318
+ cacheHitRate: number;
1319
+ loadBalancingEfficiency: number;
1320
+ pendingQueries: number;
1321
+ activeBatches: number;
1322
+ cacheSize: number;
1323
+ }>;
1324
+ /**
1325
+ * Clear cache and reset metrics
1326
+ */
1327
+ reset(): Promise<void>;
1328
+ protected ensureInitialized(): Promise<void>;
1329
+ private initializeBatchingSystem;
1330
+ private startBatchProcessing;
1331
+ private shouldStartNewBatch;
1332
+ private generateBatchId;
1333
+ private processBatchAsync;
1334
+ private processQuery;
1335
+ private getCachedResult;
1336
+ /**
1337
+ * Update query performance metrics
1338
+ */
1339
+ private updateQueryMetrics;
1340
+ /**
1341
+ * Calculate performance score based on processing time
1342
+ */
1343
+ private calculatePerformanceScore;
1344
+ private cacheResult;
1345
+ private generateCacheKey;
1346
+ private isCacheValid;
1347
+ /**
1348
+ * Clean up resources
1349
+ */
1350
+ cleanup(): Promise<void>;
1351
+ }
1352
+
1353
+ /**
1354
+ * ZKIM Error Recovery Service
1355
+ *
1356
+ * Comprehensive error recovery strategies for ZKIM operations
1357
+ * including corruption recovery, validation, and repair mechanisms.
1358
+ *
1359
+ * @fileoverview Error recovery and repair strategies
1360
+ */
1361
+
1362
+ /**
1363
+ * Recovery result interface
1364
+ */
1365
+ interface ZkimRecoveryResult {
1366
+ success: boolean;
1367
+ recoveredData?: Uint8Array;
1368
+ repairActions: string[];
1369
+ warnings: string[];
1370
+ errors: string[];
1371
+ metadata?: Record<string, unknown>;
1372
+ }
1373
+ /**
1374
+ * Corruption detection result
1375
+ */
1376
+ interface ZkimCorruptionDetection {
1377
+ isCorrupted: boolean;
1378
+ corruptionType: "header" | "chunk" | "signature" | "metadata" | "unknown";
1379
+ severity: "low" | "medium" | "high" | "critical";
1380
+ affectedChunks: number[];
1381
+ description: string;
1382
+ }
1383
+ /**
1384
+ * Repair strategy
1385
+ */
1386
+ interface ZkimRepairStrategy {
1387
+ strategy: "skip" | "reconstruct" | "recover" | "fail";
1388
+ confidence: number;
1389
+ description: string;
1390
+ actions: string[];
1391
+ }
1392
+ declare class ZkimErrorRecovery extends ServiceBase {
1393
+ private readonly context;
1394
+ private recoveryAttempts;
1395
+ private logger;
1396
+ constructor(logger?: ILogger);
1397
+ /**
1398
+ * Initialize error recovery service
1399
+ */
1400
+ initialize(): Promise<void>;
1401
+ /**
1402
+ * Cleanup error recovery service
1403
+ */
1404
+ cleanup(): Promise<void>;
1405
+ /**
1406
+ * Recover from file corruption
1407
+ */
1408
+ recoverFromCorruption(corruptedData: Uint8Array, fileId: string, options?: {
1409
+ maxRepairAttempts?: number;
1410
+ enableReconstruction?: boolean;
1411
+ strictValidation?: boolean;
1412
+ }): Promise<ZkimRecoveryResult>;
1413
+ /**
1414
+ * Validate and repair file integrity
1415
+ */
1416
+ validateAndRepair(data: Uint8Array, fileId: string, options?: {
1417
+ enableRepair?: boolean;
1418
+ strictMode?: boolean;
1419
+ }): Promise<ZkimRecoveryResult>;
1420
+ /**
1421
+ * Detect corruption in file data
1422
+ */
1423
+ private detectCorruption;
1424
+ /**
1425
+ * Determine repair strategy based on corruption type
1426
+ */
1427
+ private determineRepairStrategy;
1428
+ /**
1429
+ * Execute recovery based on strategy
1430
+ */
1431
+ private executeRecovery;
1432
+ /**
1433
+ * Execute skip strategy
1434
+ */
1435
+ private executeSkipStrategy;
1436
+ /**
1437
+ * Execute reconstruct strategy
1438
+ */
1439
+ private executeReconstructStrategy;
1440
+ /**
1441
+ * Execute recover strategy
1442
+ */
1443
+ private executeRecoverStrategy;
1444
+ /**
1445
+ * Validate file structure
1446
+ */
1447
+ private validateFileStructure;
1448
+ /**
1449
+ * Repair file structure
1450
+ */
1451
+ private repairFileStructure;
1452
+ }
1453
+
1454
+ /**
1455
+ * ZKIM Performance Monitor
1456
+ *
1457
+ * Comprehensive performance monitoring and metrics collection for ZKIM operations
1458
+ * including encryption, decryption, serialization, and parsing performance.
1459
+ *
1460
+ * @fileoverview Performance monitoring and metrics collection
1461
+ */
1462
+
1463
+ /**
1464
+ * Performance metrics interface
1465
+ */
1466
+ interface ZkimPerformanceMetrics {
1467
+ operation: string;
1468
+ duration: number;
1469
+ dataSize: number;
1470
+ throughput: number;
1471
+ memoryUsage: number;
1472
+ timestamp: number;
1473
+ success: boolean;
1474
+ error?: string;
1475
+ }
1476
+ /**
1477
+ * Performance statistics
1478
+ */
1479
+ interface ZkimPerformanceStats {
1480
+ totalOperations: number;
1481
+ successfulOperations: number;
1482
+ failedOperations: number;
1483
+ averageDuration: number;
1484
+ averageThroughput: number;
1485
+ averageMemoryUsage: number;
1486
+ successRate: number;
1487
+ p95Duration: number;
1488
+ p99Duration: number;
1489
+ maxDuration: number;
1490
+ minDuration: number;
1491
+ }
1492
+ /**
1493
+ * Performance thresholds
1494
+ */
1495
+ interface ZkimPerformanceThresholds {
1496
+ maxDuration: number;
1497
+ minThroughput: number;
1498
+ maxMemoryUsage: number;
1499
+ minSuccessRate: number;
1500
+ }
1501
+ /**
1502
+ * ZKIM Performance Monitor
1503
+ */
1504
+ declare class ZkimPerformanceMonitor extends ServiceBase {
1505
+ private readonly context;
1506
+ private metrics;
1507
+ private thresholds;
1508
+ private monitoringInterval;
1509
+ private logger;
1510
+ constructor(thresholds?: Partial<ZkimPerformanceThresholds>, logger?: ILogger);
1511
+ /**
1512
+ * Initialize performance monitoring
1513
+ */
1514
+ initialize(): Promise<void>;
1515
+ /**
1516
+ * Get memory usage from browser performance API
1517
+ * Falls back to 0 if performance.memory is not available
1518
+ */
1519
+ private getMemoryUsage;
1520
+ /**
1521
+ * Record performance metrics for an operation
1522
+ */
1523
+ recordOperation(operation: string, duration: number, dataSize: number, success: boolean, error?: string): void;
1524
+ /**
1525
+ * Get performance statistics
1526
+ */
1527
+ getPerformanceStats(): ZkimPerformanceStats;
1528
+ /**
1529
+ * Get performance metrics for a specific operation
1530
+ */
1531
+ getOperationMetrics(operation: string): ZkimPerformanceMetrics[];
1532
+ /**
1533
+ * Get recent performance metrics
1534
+ */
1535
+ getRecentMetrics(limit?: number): ZkimPerformanceMetrics[];
1536
+ /**
1537
+ * Clear performance metrics
1538
+ */
1539
+ clearMetrics(): void;
1540
+ /**
1541
+ * Update performance thresholds
1542
+ */
1543
+ updateThresholds(thresholds: Partial<ZkimPerformanceThresholds>): void;
1544
+ /**
1545
+ * Check if a metric value violates thresholds
1546
+ */
1547
+ private checkMetricThreshold;
1548
+ /**
1549
+ * Generate alert message for threshold violation
1550
+ */
1551
+ private generateAlertMessage;
1552
+ /**
1553
+ * Get performance alerts based on statistics
1554
+ */
1555
+ getPerformanceAlerts(): string[];
1556
+ /**
1557
+ * Start performance monitoring
1558
+ */
1559
+ private startMonitoring;
1560
+ /**
1561
+ * Perform health check
1562
+ */
1563
+ private performHealthCheck;
1564
+ /**
1565
+ * Check performance thresholds for a single metric
1566
+ */
1567
+ private checkThresholds;
1568
+ /**
1569
+ * Stop performance monitoring
1570
+ */
1571
+ stopMonitoring(): void;
1572
+ /**
1573
+ * Cleanup resources
1574
+ */
1575
+ cleanup(): Promise<void>;
1576
+ }
1577
+
1578
+ /**
1579
+ * ZKIM File Wire Format Utilities
1580
+ *
1581
+ * Contains all wire format I/O operations for ZKIM files.
1582
+ * Wire Format: MAGIC + VERSION + FLAGS + KEM_CIPHERTEXT(1,088 bytes ML-KEM-768) + EH_PLATFORM + EH_USER + CHUNKS + MERKLE_ROOT + SIG
1583
+ *
1584
+ * Part of ZKIM's Level 3+ security implementation.
1585
+ * Uses NIST-standardized ML-KEM-768 (FIPS 203) and ML-DSA-65 (FIPS 204).
1586
+ * NOT FIPS 140-3 validated by an accredited laboratory.
1587
+ *
1588
+ * This module exports pure functions (not class methods) for wire format operations.
1589
+ */
1590
+
1591
+ /**
1592
+ * Write little-endian u16
1593
+ */
1594
+ declare function writeU16(value: number): Uint8Array;
1595
+ /**
1596
+ * Read little-endian u16
1597
+ */
1598
+ declare function readU16(buffer: Uint8Array, offset: number): number;
1599
+ /**
1600
+ * Format EH header: nonce24 || tag16 (40 bytes fixed)
1601
+ * Ciphertext is stored in chunks, not in EH header
1602
+ */
1603
+ declare function formatEhHeader(nonce: Uint8Array, data: {
1604
+ ciphertext: Uint8Array;
1605
+ tag: Uint8Array;
1606
+ } | Uint8Array): Uint8Array;
1607
+ /**
1608
+ * Calculate Merkle root from chunk integrity hashes using BLAKE3
1609
+ */
1610
+ declare function calculateMerkleRoot(chunks: ZkimFileChunk[]): Uint8Array;
1611
+ /**
1612
+ * Generate file signature: ML-DSA-65(BLAKE3("zkim/root" || root || manifestHash || algSuiteId || version))
1613
+ * Format uses ML-DSA-65 (FIPS 204)
1614
+ * Derives signing key from userKey using deterministic key generation with context "zkim/ml-dsa-65/file"
1615
+ * Matches infrastructure implementation for consistency
1616
+ */
1617
+ declare function generateFileSignature(merkleRoot: Uint8Array, manifestHash: Uint8Array, algSuiteId: number, version: number, userKey: Uint8Array): Promise<Uint8Array>;
1618
+ /**
1619
+ * Calculate manifest hash (BLAKE3 of EH_USER header)
1620
+ */
1621
+ declare function calculateManifestHash(ehUser: Uint8Array): Uint8Array;
1622
+ /**
1623
+ * Write ZKIM file in wire format according to spec
1624
+ * Wire Format: MAGIC + VERSION + FLAGS + KEM_CIPHERTEXT + EH_PLATFORM + EH_USER + CHUNKS + MERKLE_ROOT + SIG
1625
+ */
1626
+ declare function writeWireFormat(header: ZkimFileHeader, kemCipherText: Uint8Array, ehPlatform: Uint8Array, ehUser: Uint8Array, chunks: ZkimFileChunk[], merkleRoot: Uint8Array, signature: Uint8Array, logger?: ILogger): Uint8Array;
1627
+ /**
1628
+ * Parse ZKIM file from bytes (wire format only)
1629
+ */
1630
+ declare function parseZkimFile(data: Uint8Array, userKey: Uint8Array, platformKey: Uint8Array, encryptionService: IEncryptionService, logger?: ILogger, kemSecretKey?: Uint8Array): Promise<ZkimFile>;
1631
+
1632
+ /**
1633
+ * Error Handling Utilities for @zkim-platform/file-format
1634
+ * Lightweight error handling without platform dependencies
1635
+ */
1636
+
1637
+ /**
1638
+ * Error handling utilities for services
1639
+ */
1640
+ declare class ErrorUtils {
1641
+ private static logger;
1642
+ /**
1643
+ * Set custom logger instance
1644
+ */
1645
+ static setLogger(logger: ILogger): void;
1646
+ /**
1647
+ * Create error context for consistent error handling
1648
+ */
1649
+ static createContext(service: string, operation: string, additionalContext?: Record<string, unknown>): ErrorContext;
1650
+ /**
1651
+ * Extract error message from unknown error type
1652
+ */
1653
+ static getErrorMessage(error: unknown): string;
1654
+ /**
1655
+ * Create a successful service result
1656
+ */
1657
+ static createSuccessResult<T>(data: T): ServiceResult<T>;
1658
+ /**
1659
+ * Create a failed service result
1660
+ */
1661
+ static createErrorResult<T>(error: string | Error): ServiceResult<T>;
1662
+ /**
1663
+ * Wrap async operations with error handling
1664
+ */
1665
+ static withErrorHandling<T>(operation: () => Promise<T>, context: ErrorContext, fallback?: T): Promise<ServiceResult<T>>;
1666
+ /**
1667
+ * Handle errors with context and logging
1668
+ */
1669
+ static handleError(error: unknown, context: ErrorContext): void;
1670
+ }
1671
+
1672
+ /**
1673
+ * Environment-Agnostic Crypto Utilities for @zkim-platform/file-format
1674
+ * Provides crypto operations that work in both browser and Node.js environments
1675
+ */
1676
+ /**
1677
+ * Generate random bytes using libsodium
1678
+ */
1679
+ declare function generateRandomBytes(length: number): Promise<Uint8Array>;
1680
+ /**
1681
+ * Generate random hex string
1682
+ */
1683
+ declare function generateRandomHex(length: number): Promise<string>;
1684
+ /**
1685
+ * Hash data using BLAKE3
1686
+ */
1687
+ declare function hashData(data: Uint8Array, outputLength?: number): Uint8Array;
1688
+ /**
1689
+ * Hash data to hex string
1690
+ */
1691
+ declare function hashDataToHex(data: Uint8Array, outputLength?: number): string;
1692
+ /**
1693
+ * Generate key pair using X25519 (for encryption)
1694
+ */
1695
+ declare function generateKeyPair(): Promise<{
1696
+ publicKey: Uint8Array;
1697
+ privateKey: Uint8Array;
1698
+ }>;
1699
+ /**
1700
+ * Generate ML-DSA-65 signing key pair (FIPS 204)
1701
+ * Returns public key (1,952 bytes) and secret key (4,032 bytes)
1702
+ */
1703
+ declare function generateSigningKeyPair(): Promise<{
1704
+ publicKey: Uint8Array;
1705
+ privateKey: Uint8Array;
1706
+ }>;
1707
+ /**
1708
+ * Encrypt data using XChaCha20-Poly1305
1709
+ */
1710
+ declare function encryptData(data: Uint8Array, key: Uint8Array, nonce?: Uint8Array): Promise<{
1711
+ ciphertext: Uint8Array;
1712
+ nonce: Uint8Array;
1713
+ }>;
1714
+ /**
1715
+ * Decrypt data using XChaCha20-Poly1305
1716
+ */
1717
+ declare function decryptData(ciphertext: Uint8Array, key: Uint8Array, nonce: Uint8Array): Promise<Uint8Array>;
1718
+ /**
1719
+ * Convert Uint8Array to base64 string
1720
+ */
1721
+ declare function toBase64(data: Uint8Array): Promise<string>;
1722
+ /**
1723
+ * Convert base64 string to Uint8Array
1724
+ */
1725
+ declare function fromBase64(data: string): Promise<Uint8Array>;
1726
+ /**
1727
+ * Convert Uint8Array to hex string
1728
+ */
1729
+ declare function toHex(data: Uint8Array): Promise<string>;
1730
+ /**
1731
+ * Convert hex string to Uint8Array
1732
+ */
1733
+ declare function fromHex(data: string): Promise<Uint8Array>;
1734
+
1735
+ /**
1736
+ * ZKIM Compression Utilities
1737
+ *
1738
+ * Abstraction layer for compression operations
1739
+ * Uses pako for browser compatibility, with Node.js zlib fallback for Node.js environments
1740
+ *
1741
+ * Note: Node.js zlib is only used as a fallback in Node.js runtime environments (e.g., Jest tests).
1742
+ * In browser environments, pako is used exclusively. The dynamic import of zlib will fail
1743
+ * gracefully in browsers and fall back to pako.
1744
+ */
1745
+
1746
+ /**
1747
+ * Compress data using GZIP algorithm
1748
+ * Uses pako for browser compatibility, with Node.js zlib fallback
1749
+ */
1750
+ declare function compressGzip(data: Uint8Array, level?: number, logger?: ILogger): Promise<Uint8Array>;
1751
+ /**
1752
+ * Decompress data using GZIP algorithm
1753
+ * Uses pako for browser compatibility, with Node.js zlib fallback
1754
+ */
1755
+ declare function decompressGzip(data: Uint8Array, originalSize?: number, logger?: ILogger): Promise<Uint8Array>;
1756
+
1757
+ /**
1758
+ * Constant-Time Security Utilities
1759
+ *
1760
+ * Provides constant-time implementations of common operations to prevent
1761
+ * timing attacks in cryptographic applications.
1762
+ *
1763
+ * Security Features:
1764
+ * - Constant-time string comparison
1765
+ * - Constant-time array operations
1766
+ * - Timing attack prevention
1767
+ * - Secure random delays
1768
+ * - Memory-safe operations
1769
+ */
1770
+ declare class ConstantTimeSecurity {
1771
+ private static readonly MIN_OPERATION_TIME;
1772
+ private static readonly MAX_OPERATION_TIME;
1773
+ private static readonly RANDOM_DELAY_FACTOR;
1774
+ /**
1775
+ * Constant-time string comparison
1776
+ *
1777
+ * Prevents timing attacks by ensuring comparison always takes the same time
1778
+ * regardless of where the strings differ.
1779
+ */
1780
+ static constantTimeStringCompare(a: string, b: string): boolean;
1781
+ /**
1782
+ * Constant-time byte array comparison
1783
+ *
1784
+ * Prevents timing attacks on binary data comparisons.
1785
+ */
1786
+ static constantTimeByteCompare(a: Uint8Array, b: Uint8Array): boolean;
1787
+ /**
1788
+ * Constant-time array search
1789
+ *
1790
+ * Prevents timing attacks on array search operations by always
1791
+ * checking all elements regardless of early matches.
1792
+ */
1793
+ static constantTimeArrayIncludes<T>(array: T[], target: T, compareFn?: (a: T, b: T) => boolean): boolean;
1794
+ /**
1795
+ * Constant-time string array search
1796
+ *
1797
+ * Specialized version for string arrays using constant-time comparison.
1798
+ */
1799
+ static constantTimeStringArrayIncludes(array: string[], target: string): boolean;
1800
+ /**
1801
+ * Constant-time length validation
1802
+ *
1803
+ * Validates array/string length without revealing the actual length
1804
+ * through timing differences.
1805
+ */
1806
+ static constantTimeLengthCheck(data: string | Uint8Array, expectedLength: number): boolean;
1807
+ /**
1808
+ * Secure random delay
1809
+ *
1810
+ * Adds a random delay to prevent timing analysis attacks.
1811
+ */
1812
+ static addSecureDelay(baseTime?: number): Promise<void>;
1813
+ /**
1814
+ * Timing attack prevention wrapper
1815
+ *
1816
+ * Wraps any operation with timing attack prevention measures.
1817
+ */
1818
+ static withTimingProtection<T>(operation: () => T | Promise<T>, minTime?: number, maxTime?: number): Promise<T>;
1819
+ /**
1820
+ * Constant-time magic number validation
1821
+ *
1822
+ * Validates magic numbers without timing leaks.
1823
+ */
1824
+ static validateMagicNumber(actual: string, expected?: string): boolean;
1825
+ /**
1826
+ * Constant-time version validation
1827
+ *
1828
+ * Validates version numbers without timing leaks.
1829
+ */
1830
+ static validateVersion(actual: number, expected: number, minVersion?: number, maxVersion?: number): boolean;
1831
+ /**
1832
+ * Constant-time size validation
1833
+ *
1834
+ * Validates data sizes without timing leaks.
1835
+ */
1836
+ static validateSize(actualSize: number, expectedSize: number, tolerance?: number): boolean;
1837
+ /**
1838
+ * Secure comparison with logging
1839
+ *
1840
+ * Performs constant-time comparison with security logging.
1841
+ */
1842
+ static secureCompare<T>(actual: T, expected: T, context: string, compareFn?: (a: T, b: T) => boolean): boolean;
1843
+ /**
1844
+ * Memory-safe string operations
1845
+ *
1846
+ * Performs string operations without memory leaks.
1847
+ */
1848
+ static memorySafeStringOperation(operation: (str: string) => string): (str: string) => string;
1849
+ /**
1850
+ * Secure array operations
1851
+ *
1852
+ * Performs array operations with timing attack prevention.
1853
+ */
1854
+ static secureArrayOperation<T>(array: T[], operation: (arr: T[]) => boolean): boolean;
1855
+ /**
1856
+ * Timing attack detection
1857
+ *
1858
+ * Detects potential timing attacks by monitoring operation times.
1859
+ */
1860
+ static detectTimingAttack(operationTimes: number[], threshold?: number): boolean;
1861
+ }
1862
+
1863
+ /**
1864
+ * ZKIM File Format Constants
1865
+ * Single source of truth for all file format-related constants
1866
+ *
1867
+ * Uses NIST-standardized post-quantum algorithms (FIPS 203/204).
1868
+ * NOT FIPS 140-3 validated by an accredited laboratory.
1869
+ */
1870
+ /**
1871
+ * ZKIM Encryption Constants
1872
+ */
1873
+ declare const ZKIM_ENCRYPTION_CONSTANTS: {
1874
+ readonly DEFAULT_ALGORITHM: "xchacha20-poly1305";
1875
+ readonly KEY_SIZE: 32;
1876
+ readonly NONCE_SIZE: 24;
1877
+ readonly TAG_SIZE: 16;
1878
+ readonly SALT_LENGTH: 32;
1879
+ readonly ITERATIONS: 100000;
1880
+ readonly KEY_ROTATION_INTERVAL: number;
1881
+ readonly MAX_KEY_AGE: number;
1882
+ readonly ML_DSA_65_PUBLIC_KEY_SIZE: 1952;
1883
+ readonly ML_DSA_65_SECRET_KEY_SIZE: 4032;
1884
+ readonly ML_DSA_65_SIGNATURE_SIZE: 3309;
1885
+ readonly ML_KEM_768_PUBLIC_KEY_SIZE: 1184;
1886
+ readonly ML_KEM_768_SECRET_KEY_SIZE: 2400;
1887
+ readonly ML_KEM_768_CIPHERTEXT_SIZE: 1088;
1888
+ readonly EH_HEADER_SIZE: 40;
1889
+ readonly MAGIC_BYTES_SIZE: 4;
1890
+ readonly VERSION_BYTES_SIZE: 2;
1891
+ readonly FLAGS_BYTES_SIZE: 2;
1892
+ readonly MERKLE_ROOT_SIZE: 32;
1893
+ readonly SIGNATURE_SIZE: 3309;
1894
+ readonly VERSION: 1;
1895
+ readonly MAGIC: "ZKIM";
1896
+ readonly ALG_SUITE_ID: 1;
1897
+ readonly WORKER_BATCH_SIZE: 25;
1898
+ readonly WORKER_BATCH_INTERVAL_MS: 25;
1899
+ };
1900
+ /**
1901
+ * ZKIM File Service Constants
1902
+ */
1903
+ declare const ZKIM_FILE_SERVICE_CONSTANTS: {
1904
+ readonly COMPRESSION_TYPE_MAP: {
1905
+ readonly brotli: 1;
1906
+ readonly gzip: 2;
1907
+ };
1908
+ readonly COMPRESSION_TYPE_REVERSE_MAP: {
1909
+ readonly 1: "brotli";
1910
+ readonly 2: "gzip";
1911
+ };
1912
+ readonly DEFAULT_MAGIC: "ZKIM";
1913
+ readonly DEFAULT_VERSION: 1;
1914
+ readonly NONCE_PREFIX: "zkim/nonce";
1915
+ readonly KEY_PREFIX: "zkim/key";
1916
+ readonly USER_KEY_PREFIX: "zkim/userkey";
1917
+ };
1918
+ /**
1919
+ * File Processing Constants
1920
+ */
1921
+ declare const FILE_PROCESSING_CONSTANTS: {
1922
+ readonly DEFAULT_CHUNK_SIZE: number;
1923
+ readonly MAX_CHUNK_SIZE: number;
1924
+ readonly MIN_CHUNK_SIZE: 1024;
1925
+ readonly DEFAULT_MAX_FILE_SIZE: number;
1926
+ readonly COMPRESSION_LEVEL: 6;
1927
+ readonly DEFAULT_COMPRESSION_ALGORITHM: "gzip";
1928
+ readonly MAX_METADATA_SIZE: number;
1929
+ };
1930
+ /**
1931
+ * Service Lifecycle Constants
1932
+ */
1933
+ declare const ZKIM_SERVICE_LIFECYCLE_CONSTANTS: {
1934
+ readonly INITIALIZATION_TIMEOUT: 30000;
1935
+ readonly CLEANUP_TIMEOUT: 10000;
1936
+ readonly MAX_INITIALIZATION_RETRIES: 3;
1937
+ readonly HEALTH_CHECK_INTERVAL: 60000;
1938
+ };
1939
+ /**
1940
+ * ZKIM Binary Format Constants
1941
+ *
1942
+ * v1 Magic bytes: "ZKIM" (Z=0x5a, K=0x4b, I=0x49, M=0x4d)
1943
+ */
1944
+ declare const ZKIM_BINARY_CONSTANTS: {
1945
+ readonly MAGIC_BYTE_Z: 90;
1946
+ readonly MAGIC_BYTE_K: 75;
1947
+ readonly MAGIC_BYTE_I: 73;
1948
+ readonly MAGIC_BYTE_M: 77;
1949
+ readonly MAGIC_BYTES: Uint8Array<ArrayBuffer>;
1950
+ readonly VERSION: 1;
1951
+ readonly HEADER_SIZE: 16;
1952
+ readonly MAX_FILE_SIZE: number;
1953
+ readonly CHUNK_SIZE: number;
1954
+ };
1955
+ /**
1956
+ * ZKIM Post-Quantum Constants
1957
+ * NIST-standardized algorithms: FIPS 203 (ML-KEM-768), FIPS 204 (ML-DSA-65)
1958
+ */
1959
+ declare const ZKIM_POST_QUANTUM_CONSTANTS: {
1960
+ readonly KEM_ALGORITHM: "ML-KEM-768";
1961
+ readonly DSA_ALGORITHM: "ML-DSA-65";
1962
+ readonly HASH_ALGORITHM: "BLAKE3";
1963
+ readonly KEM_STANDARD: "FIPS-203";
1964
+ readonly DSA_STANDARD: "FIPS-204";
1965
+ readonly ML_KEM_768_PUBLIC_KEY: 1184;
1966
+ readonly ML_KEM_768_SECRET_KEY: 2400;
1967
+ readonly ML_KEM_768_CIPHERTEXT: 1088;
1968
+ readonly ML_KEM_768_SHARED_SECRET: 32;
1969
+ readonly ML_DSA_65_PUBLIC_KEY: 1952;
1970
+ readonly ML_DSA_65_SECRET_KEY: 4032;
1971
+ readonly ML_DSA_65_SIGNATURE: 3309;
1972
+ };
1973
+
1974
+ /**
1975
+ * @zkim-platform/file-format - ZKIM Secure File Format
1976
+ *
1977
+ * A secure, encrypted file format with three-layer encryption,
1978
+ * integrity validation, and privacy-preserving search capabilities.
1979
+ *
1980
+ * @packageDocumentation
1981
+ */
1982
+
1983
+ declare const VERSION = "1.0.0";
1984
+
1985
+ export { AnomalyDetector, type CachedResult, ConsoleLogger, ConstantTimeSecurity, type ErrorContext, ErrorUtils, FILE_PROCESSING_CONSTANTS, type IEncryptionService, type ILogger, type IStorageBackend, InMemoryStorage, type IndexedFile, type IntegrityValidationResult, LocalStorageBackend, type MetadataWithAccessLevel, type QueryBatch, type QueryBatchConfig, QueryBatcher, type QueryBatcherPerformanceMetrics, type QueryHistoryEntry, type SearchQuery, type SearchResult, SearchableEncryption, type SearchableEncryptionConfig, ServiceBase, ServiceError, type ServiceResult, SingletonBase, type Trapdoor, type TrapdoorRotationConfig, type TrapdoorRotationEvent, TrapdoorRotator, type UsagePattern, VERSION, ZKIMEncryptionError, ZKIMFileError, ZKIMFileService, type ZKIMFileServiceConfig, ZKIMIntegrityError, ZKIMStorageError, ZKIM_BINARY_CONSTANTS, ZKIM_ENCRYPTION_CONSTANTS, ZKIM_FILE_SERVICE_CONSTANTS, ZKIM_POST_QUANTUM_CONSTANTS, ZKIM_SERVICE_LIFECYCLE_CONSTANTS, type ZkimCorruptionDetection, ZkimEncryption, type ZkimEncryptionConfig, ZkimErrorRecovery, type ZkimFile, type ZkimFileChunk, type ZkimFileHeader, type ZkimFileMetadata, type ZkimFileResult, type ZkimFileSearchResult, ZkimIntegrity, type ZkimIntegrityConfig, type ZkimPerformanceMetrics, ZkimPerformanceMonitor, type ZkimPerformanceStats, type ZkimPerformanceThresholds, type ZkimRecoveryResult, type ZkimRepairStrategy, calculateManifestHash, calculateMerkleRoot, compressGzip, decompressGzip, decryptData, defaultLogger, encryptData, formatEhHeader, fromBase64, fromHex, generateFileSignature, generateKeyPair, generateRandomBytes, generateRandomHex, generateSigningKeyPair, hashData, hashDataToHex, parseZkimFile, readU16, toBase64, toHex, writeU16, writeWireFormat };