@digitaldefiance/ecies-lib 4.0.0 → 4.1.1

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.
package/README.md CHANGED
@@ -2,1466 +2,289 @@
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/%40digitaldefiance%2Fecies-lib.svg)](https://www.npmjs.com/package/@digitaldefiance/ecies-lib)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
- [![Tests](https://img.shields.io/badge/tests-646%20passing-brightgreen)](https://github.com/Digital-Defiance/ecies-lib)
5
+ [![Tests](https://img.shields.io/badge/tests-1200%2B%20passing-brightgreen)](https://github.com/Digital-Defiance/ecies-lib)
6
6
 
7
7
  Production-ready, browser-compatible ECIES (Elliptic Curve Integrated Encryption Scheme) library for TypeScript. Built on Web Crypto API and @noble/curves with comprehensive encryption, key management, and authentication services. Binary compatible with @digitaldefiance/node-ecies-lib for seamless cross-platform operations.
8
8
 
9
9
  Part of [Express Suite](https://github.com/Digital-Defiance/express-suite)
10
10
 
11
- **Version 2.0** features a modernized i18n architecture with automatic error translation in 8 languages and simplified service APIs.
11
+ **Current Version: v4.1.0**
12
12
 
13
- ## Features
14
-
15
- ### Core Cryptography
16
-
17
- - **ECIES Encryption** – Simple (98-byte overhead), Single (106-byte overhead), Multiple (multi-recipient) modes
18
- - **secp256k1 Curve** – ECDH key exchange and ECDSA signatures
19
- - **AES-256-GCM** – Authenticated symmetric encryption via Web Crypto API
20
- - **PBKDF2** – Configurable password-based key derivation profiles
21
-
22
- ### Key Management
23
-
24
- - **BIP39 Mnemonics** – 12/15/18/21/24-word phrase generation and key derivation
25
- - **HD Wallets** – BIP32/BIP44 hierarchical deterministic derivation
26
- - **Member System** – User abstraction with cryptographic operations
27
- - **Secure Storage** – Memory-safe SecureString/SecureBuffer with XOR obfuscation and auto-zeroing
28
-
29
- ### Advanced
30
-
31
- - **Streaming Encryption** – Memory-efficient encryption for large files (<10MB RAM for any size) ✨ NEW
32
- - **Multi-Recipient** – Encrypt for up to 65,535 recipients efficiently
33
- - **File Encryption** – Chunked 1MB segments for large files
34
- - **Password Login** – Complete authentication with encrypted key storage
35
- - **Signatures** – ECDSA message signing and verification
36
-
37
- ### Developer Experience
38
-
39
- - **TypeScript** – Full type definitions and interfaces
40
- - **i18n** – Error messages in 8 languages (en-US, en-GB, fr, es, de, zh-CN, ja, uk)
41
- - **Runtime Config** – Injectable configuration profiles via ConstantsRegistry
42
- - **Testing** – 40 test files with 480+ specs (unit, integration, e2e)
43
- - **Cross-Platform** – Node.js 18+ and modern browsers
44
-
45
- ## Installation
46
-
47
- ```bash
48
- npm install @digitaldefiance/ecies-lib
49
- # or
50
- yarn add @digitaldefiance/ecies-lib
51
- ```
52
-
53
- ### Requirements
54
-
55
- **Node.js**: 18+ (Web Crypto API built-in)
56
-
57
- - For Node < 18: `import { webcrypto } from 'crypto'; globalThis.crypto = webcrypto as unknown as Crypto;`
58
-
59
- **Browsers**: Chrome/Edge 60+, Firefox 60+, Safari 14+, Opera 47+
60
-
61
- **Dependencies**: `@digitaldefiance/i18n-lib`, `@noble/curves`, `@scure/bip32`, `@scure/bip39`, `@ethereumjs/wallet`, `bson`, `ts-brand`
62
-
63
- ## Quick Start
64
-
65
- ### Streaming Encryption (NEW)
66
-
67
- Memory-efficient encryption for large files:
68
-
69
- ```typescript
70
- import { ECIESService, EncryptionStream } from '@digitaldefiance/ecies-lib';
71
-
72
- const ecies = new ECIESService();
73
- const stream = new EncryptionStream(ecies);
74
- const mnemonic = ecies.generateNewMnemonic();
75
- const { publicKey, privateKey } = ecies.mnemonicToSimpleKeyPair(mnemonic);
76
-
77
- // Encrypt large file with <10MB RAM
78
- const file = document.querySelector('input[type="file"]').files[0];
79
- const encryptedChunks: Uint8Array[] = [];
80
-
81
- for await (const chunk of stream.encryptStream(file.stream(), publicKey)) {
82
- encryptedChunks.push(chunk.data);
83
- }
84
-
85
- // Decrypt
86
- const decryptedChunks: Uint8Array[] = [];
87
- for await (const chunk of stream.decryptStream(
88
- (async function* () {
89
- for (const encrypted of encryptedChunks) yield encrypted;
90
- })(),
91
- privateKey
92
- )) {
93
- decryptedChunks.push(chunk);
94
- }
95
- ```
96
-
97
- **Features:**
98
-
99
- - 99% memory reduction (1GB file: 1GB RAM → <10MB RAM)
100
- - Cancellation support via AbortSignal
101
- - AsyncGenerator API for flexibility
102
- - Works with ReadableStream and AsyncIterable
103
-
104
- See [Streaming API Quick Start](./docs/STREAMING_API_QUICKSTART.md) for more examples.
105
-
106
- ### Basic Encryption
107
-
108
- ```typescript
109
- import { ECIESService, getEciesI18nEngine } from '@digitaldefiance/ecies-lib';
110
-
111
- // Initialize i18n engine (required for error messages)
112
- getEciesI18nEngine();
113
-
114
- const ecies = new ECIESService();
115
- const mnemonic = ecies.generateNewMnemonic();
116
- const { privateKey, publicKey } = ecies.mnemonicToSimpleKeyPair(mnemonic);
117
-
118
- // Encrypt
119
- const message = new TextEncoder().encode('Hello, World!');
120
- const encrypted = await ecies.encryptSimpleOrSingle(false, publicKey, message);
121
-
122
- // Decrypt
123
- const decrypted = await ecies.decryptSimpleOrSingleWithHeader(false, privateKey, encrypted);
124
- console.log(new TextDecoder().decode(decrypted)); // "Hello, World!"
125
- ```
126
-
127
- ### Member System
128
-
129
- ```typescript
130
- import { ECIESService, Member, MemberType, EmailString } from '@digitaldefiance/ecies-lib';
131
-
132
- const ecies = new ECIESService();
133
- const { member, mnemonic } = Member.newMember(
134
- ecies,
135
- MemberType.User,
136
- 'Alice',
137
- new EmailString('alice@example.com')
138
- );
139
-
140
- // Encrypt/decrypt (up to 10MB)
141
- const encrypted = await member.encryptData('Sensitive data');
142
- const decrypted = await member.decryptData(encrypted);
143
-
144
- // Streaming encryption (any size)
145
- const file = document.querySelector('input[type="file"]').files[0];
146
- const chunks: Uint8Array[] = [];
147
- for await (const chunk of member.encryptDataStream(file.stream())) {
148
- chunks.push(chunk.data);
149
- }
150
-
151
- // Sign/verify
152
- const signature = member.sign(new TextEncoder().encode('Message'));
153
- const valid = member.verify(signature, new TextEncoder().encode('Message'));
154
- ```
155
-
156
- ## Core Services
157
-
158
- ### ECIESService
159
-
160
- Main encryption service with three modes:
161
-
162
- ```typescript
163
- import { ECIESService } from '@digitaldefiance/ecies-lib';
164
-
165
- const ecies = new ECIESService();
166
- const mnemonic = ecies.generateNewMnemonic();
167
- const { privateKey, publicKey } = ecies.mnemonicToSimpleKeyPair(mnemonic);
168
-
169
- // Simple mode (98-byte overhead, no length prefix)
170
- const simple = await ecies.encryptSimpleOrSingle(true, publicKey, message);
171
-
172
- // Single mode (106-byte overhead, 8-byte length prefix)
173
- const single = await ecies.encryptSimpleOrSingle(false, publicKey, message);
174
-
175
- // Decrypt with automatic header parsing
176
- const decrypted = await ecies.decryptSimpleOrSingleWithHeader(false, privateKey, single);
177
- ```
178
-
179
- ### EciesMultiRecipient
180
-
181
- Encrypt once for multiple recipients:
182
-
183
- ```typescript
184
- import { EciesMultiRecipient, EciesCryptoCore, Constants } from '@digitaldefiance/ecies-lib';
185
-
186
- const config = {
187
- curveName: Constants.ECIES.CURVE_NAME,
188
- primaryKeyDerivationPath: Constants.ECIES.PRIMARY_KEY_DERIVATION_PATH,
189
- mnemonicStrength: Constants.ECIES.MNEMONIC_STRENGTH,
190
- symmetricAlgorithm: Constants.ECIES.SYMMETRIC.ALGORITHM,
191
- symmetricKeyBits: Constants.ECIES.SYMMETRIC.KEY_BITS,
192
- symmetricKeyMode: Constants.ECIES.SYMMETRIC.MODE,
193
- };
194
-
195
- const multi = new EciesMultiRecipient(config);
196
- const core = new EciesCryptoCore(config);
197
-
198
- // Generate recipients
199
- const recipients = await Promise.all(
200
- [...Array(3)].map(async () => {
201
- const { privateKey, publicKey } = await core.generateEphemeralKeyPair();
202
- return {
203
- id: crypto.getRandomValues(new Uint8Array(Constants.ECIES.MULTIPLE.RECIPIENT_ID_SIZE)),
204
- privateKey,
205
- publicKey,
206
- };
207
- })
208
- );
209
-
210
- // Encrypt for all
211
- const encrypted = await multi.encryptMultiple(
212
- recipients.map(({ id, publicKey }) => ({ id, publicKey })),
213
- new TextEncoder().encode('Broadcast message')
214
- );
215
-
216
- // Any recipient can decrypt
217
- const decrypted = await multi.decryptMultipleForRecipient(
218
- multi.parseMessage(multi.buildHeader(encrypted) + encrypted.encryptedMessage),
219
- recipients[0].id,
220
- recipients[0].privateKey
221
- );
222
- ```
223
-
224
- ### EciesFileService
225
-
226
- Chunked file encryption:
227
-
228
- ```typescript
229
- import { ECIESService, EciesFileService } from '@digitaldefiance/ecies-lib';
230
-
231
- const ecies = new ECIESService();
232
- const { privateKey, publicKey } = ecies.mnemonicToSimpleKeyPair(ecies.generateNewMnemonic());
233
- const fileService = new EciesFileService(ecies, privateKey);
234
-
235
- // Encrypt file (1MB chunks)
236
- const encrypted = await fileService.encryptFile(file, publicKey);
237
-
238
- // Decrypt file
239
- const decrypted = await fileService.decryptFile(encrypted);
240
-
241
- // Download
242
- fileService.downloadEncryptedFile(encrypted, 'document.enc');
243
- fileService.downloadDecryptedFile(decrypted, 'document.pdf');
244
- ```
245
-
246
- ### PasswordLoginService
247
-
248
- Password-based authentication:
249
-
250
- ```typescript
251
- import {
252
- ECIESService,
253
- PasswordLoginService,
254
- Pbkdf2Service,
255
- Pbkdf2ProfileEnum,
256
- SecureString,
257
- getEciesI18nEngine,
258
- } from '@digitaldefiance/ecies-lib';
259
-
260
- // Initialize i18n (v2.0 - no longer passed to services)
261
- getEciesI18nEngine();
262
-
263
- const ecies = new ECIESService();
264
- const pbkdf2 = new Pbkdf2Service();
265
- const passwordLogin = new PasswordLoginService(ecies, pbkdf2);
266
-
267
- // Setup
268
- const mnemonic = ecies.generateNewMnemonic();
269
- const password = new SecureString('MySecurePassword123!');
270
- await passwordLogin.setupPasswordLoginLocalStorageBundle(
271
- mnemonic,
272
- password,
273
- Pbkdf2ProfileEnum.BROWSER_PASSWORD
274
- );
275
-
276
- // Login
277
- const { wallet, mnemonic: recovered } =
278
- await passwordLogin.getWalletAndMnemonicFromLocalStorageBundle(password);
279
-
280
- // Check setup
281
- if (PasswordLoginService.isPasswordLoginSetup()) {
282
- console.log('Ready');
283
- }
284
- ```
285
-
286
- ### Pbkdf2Service
287
-
288
- Key derivation with profiles:
289
-
290
- ```typescript
291
- import { Pbkdf2Service, Pbkdf2ProfileEnum, getEciesI18nEngine } from '@digitaldefiance/ecies-lib';
292
-
293
- // Initialize i18n
294
- getEciesI18nEngine();
295
-
296
- const pbkdf2 = new Pbkdf2Service();
297
-
298
- // Use built-in profile
299
- const result = await pbkdf2.deriveKeyFromPasswordWithProfileAsync(
300
- new TextEncoder().encode('password123'),
301
- Pbkdf2ProfileEnum.HIGH_SECURITY
302
- );
303
-
304
- console.log(result.hash); // Derived key
305
- console.log(result.salt); // Salt
306
- console.log(result.iterations); // 5,000,000
307
-
308
- // Custom profiles
309
- const custom = new Pbkdf2Service({
310
- ULTRA_SECURE: {
311
- hashBytes: 64,
312
- saltBytes: 32,
313
- iterations: 5000000,
314
- algorithm: 'SHA-512',
315
- },
316
- });
317
- ```
318
-
319
- **Built-in Profiles:**
320
-
321
- - `BROWSER_PASSWORD`: 2M iterations, SHA-512, 32-byte hash
322
- - `HIGH_SECURITY`: 5M iterations, SHA-256, 64-byte hash
323
- - `TEST_FAST`: 1K iterations, SHA-512, 32-byte hash
324
-
325
- ## Runtime Configuration
326
-
327
- Injectable configuration profiles via ConstantsRegistry:
328
-
329
- ```typescript
330
- import {
331
- ConstantsRegistry,
332
- registerRuntimeConfiguration,
333
- getRuntimeConfiguration,
334
- ECIESService,
335
- Pbkdf2Service,
336
- getEciesI18nEngine,
337
- } from '@digitaldefiance/ecies-lib';
338
-
339
- // Register profiles
340
- registerRuntimeConfiguration('security-first', {
341
- PBKDF2: { ITERATIONS_PER_SECOND: 3_000_000 },
342
- });
343
-
344
- registerRuntimeConfiguration('performance-first', {
345
- PBKDF2: { ITERATIONS_PER_SECOND: 250_000 },
346
- });
347
-
348
- // Use profiles
349
- getEciesI18nEngine(); // Initialize i18n
350
-
351
- const secureConfig = getRuntimeConfiguration('security-first');
352
- const secureEcies = new ECIESService(undefined, secureConfig.ECIES);
353
- const securePbkdf2 = new Pbkdf2Service(
354
- secureConfig.PBKDF2_PROFILES,
355
- secureConfig.ECIES,
356
- secureConfig.PBKDF2
357
- );
358
-
359
- // Cleanup
360
- unregisterRuntimeConfiguration('performance-first');
361
- ```
362
-
363
- **Registry API:**
364
-
365
- - `ConstantsRegistry.get(key)` – Retrieve configuration
366
- - `ConstantsRegistry.register(key, config)` – Register new profile
367
- - `ConstantsRegistry.create(overrides)` – Create without registering
368
- - `ConstantsRegistry.listKeys()` – List all keys
369
- - `ConstantsRegistry.has(key)` – Check existence
370
- - `ConstantsRegistry.unregister(key)` – Remove profile
371
- - `ConstantsRegistry.clear()` – Reset to defaults
372
-
373
- **Exports:**
374
-
375
- - `Constants` – Frozen default configuration
376
- - `createRuntimeConfiguration(overrides, base?)` – Deep merge and validate
377
- - `PASSWORD_REGEX`, `MNEMONIC_REGEX` – Validation patterns
378
-
379
- ## Secure Memory
380
-
381
- XOR-obfuscated storage with checksums:
382
-
383
- ```typescript
384
- import { SecureString, SecureBuffer } from '@digitaldefiance/ecies-lib';
385
-
386
- // SecureString for passwords/mnemonics
387
- const password = new SecureString('MyPassword123');
388
- console.log(password.value); // Access value
389
- console.log(password.valueAsHexString); // Hex format
390
- console.log(password.length); // Length
391
- password.dispose(); // Zero memory
392
-
393
- // SecureBuffer for binary secrets
394
- const key = new SecureBuffer(new Uint8Array(32));
395
- console.log(key.value); // Uint8Array
396
- console.log(key.valueAsString); // String
397
- console.log(key.valueAsBase64String); // Base64
398
- key.dispose(); // Zero memory
399
-
400
- // Features:
401
- // - XOR obfuscation in memory
402
- // - Checksum validation
403
- // - Disposal detection
404
- // - Stack traces for debugging
405
- ```
406
-
407
- ## Value Objects
408
-
409
- Type-safe wrapper:
410
-
411
- ```typescript
412
- import { EmailString } from '@digitaldefiance/ecies-lib';
413
-
414
- // Validated emails
415
- const email = new EmailString('user@example.com');
416
- // new EmailString('invalid'); // throws InvalidEmailError
417
- ```
418
-
419
- ## Error Handling
420
-
421
- Typed errors with i18n (8 languages):
422
-
423
- ```typescript
424
- import {
425
- ECIESError,
426
- ECIESErrorTypeEnum,
427
- MemberError,
428
- MemberErrorType,
429
- Pbkdf2Error,
430
- Pbkdf2ErrorType,
431
- } from '@digitaldefiance/ecies-lib';
432
-
433
- try {
434
- await ecies.decryptSimpleOrSingleWithHeader(false, privateKey, tamperedData);
435
- } catch (error) {
436
- if (error instanceof ECIESError) {
437
- switch (error.type) {
438
- case ECIESErrorTypeEnum.DecryptionFailed:
439
- console.error('Decryption failed');
440
- break;
441
- case ECIESErrorTypeEnum.InvalidEncryptionType:
442
- console.error('Invalid encryption type');
443
- break;
444
- }
445
- }
446
- }
447
-
448
- // Error categories:
449
- // - ECIESError: Encryption/decryption
450
- // - MemberError: Member operations
451
- // - Pbkdf2Error: Key derivation
452
- // - LengthError: Data length
453
- // - SecureStorageError: Memory operations
454
- // - InvalidEmailError: Email validation
455
- ```
456
-
457
- ## Architecture
458
-
459
- ### Structure
460
-
461
- ```
462
- src/
463
- ├── services/
464
- │ ├── ecies/
465
- │ │ ├── service.ts # ECIESService
466
- │ │ ├── crypto-core.ts # EciesCryptoCore
467
- │ │ ├── multi-recipient.ts # EciesMultiRecipient
468
- │ │ ├── single-recipient.ts # EciesSingleRecipient
469
- │ │ ├── file.ts # EciesFileService
470
- │ │ └── signature.ts # EciesSignature
471
- │ ├── aes-gcm.ts # AESGCMService
472
- │ ├── pbkdf2.ts # Pbkdf2Service
473
- │ ├── password-login.ts # PasswordLoginService
474
- │ └── xor.ts # XorService
475
- ├── enumerations/ # Type-safe enums
476
- ├── errors/ # Typed error classes
477
- ├── interfaces/ # TypeScript interfaces
478
- ├── types/ # Type definitions
479
- ├── constants.ts # Constants & ConstantsRegistry
480
- ├── member.ts # Member class
481
- ├── secure-string.ts # SecureString
482
- ├── secure-buffer.ts # SecureBuffer
483
- ├── email-string.ts # EmailString
484
- ├── utils.ts # Utilities
485
- ├── i18n-setup.ts # i18n configuration
486
- └── index.ts # Public API
487
-
488
- tests/ # 32 test files, 389+ specs
489
- ```
490
-
491
- ### Key Concepts
492
-
493
- **Encryption Modes:**
494
-
495
- - Simple: 98-byte overhead (type + pubkey + IV + tag)
496
- - Single: 106-byte overhead (Simple + 8-byte length)
497
- - Multiple: Shared symmetric key per recipient
498
-
499
- **Key Derivation:**
500
-
501
- - BIP39 mnemonic → BIP32 HD wallet → secp256k1 keypair
502
- - Deterministic generation
503
- - Custom derivation paths supported
504
-
505
- **Security:**
506
-
507
- - AES-256-GCM authenticated encryption
508
- - ECDH key agreement (secp256k1)
509
- - PBKDF2 with configurable iterations
510
- - Memory-safe storage with auto-zeroing
511
- - XOR obfuscation for in-memory secrets
512
-
513
- ## Development
514
-
515
- ### Commands
516
-
517
- ```bash
518
- yarn install # Install dependencies
519
- yarn build # Compile TypeScript
520
- yarn test # Run all tests (389+ specs)
521
- yarn test:stream # Stream test output
522
- yarn lint # ESLint check
523
- yarn lint:fix # Auto-fix issues
524
- yarn prettier:check # Format check
525
- yarn prettier:fix # Auto-format
526
- yarn format # Fix all (prettier + lint)
527
- ```
528
-
529
- ### Testing
530
-
531
- 32 test files covering:
532
-
533
- - Unit tests for all services
534
- - Integration tests for workflows
535
- - E2E tests for password login and file encryption
536
- - Cross-platform compatibility
537
- - Error handling and edge cases
538
-
539
- #### Test Utilities
540
-
541
- Test mocks are available via the `/testing` entry point:
542
-
543
- ```typescript
544
- import { mockFrontendMember } from '@digitaldefiance/ecies-lib/testing';
545
-
546
- // Use in your tests
547
- const member = mockFrontendMember();
548
- ```
549
-
550
- **Note:** The `/testing` entry point requires `@faker-js/faker` as a peer dependency:
551
-
552
- ```bash
553
- npm install -D @faker-js/faker
554
- # or
555
- yarn add -D @faker-js/faker
556
- ```
557
-
558
- ### Quality Gates
559
-
560
- CI enforces:
561
-
562
- - ESLint (no errors)
563
- - Prettier formatting
564
- - 389+ Jest specs passing
565
- - TypeScript compilation
566
-
567
- ## Platform Notes
568
-
569
- ### Node.js
570
-
571
- Node 18+ includes Web Crypto API. For older versions:
572
-
573
- ```typescript
574
- import { webcrypto } from 'crypto';
575
- globalThis.crypto = webcrypto as unknown as Crypto;
576
- ```
577
-
578
- ### Browser
579
-
580
- Works in all modern browsers:
581
-
582
- - Web Crypto API for cryptography
583
- - No polyfills needed
584
- - Tree-shakeable with Vite/Webpack/Rollup
585
- - ESM-compatible dependencies
586
-
587
- ### Bundler Config
588
-
589
- **Vite:**
590
-
591
- ```javascript
592
- export default {
593
- optimizeDeps: {
594
- include: ['@digitaldefiance/ecies-lib']
595
- }
596
- }
597
- ```
598
-
599
- **Webpack:**
600
-
601
- ```javascript
602
- module.exports = {
603
- resolve: {
604
- fallback: {
605
- crypto: false,
606
- stream: false
607
- }
608
- }
609
- }
610
- ```
611
-
612
- ### Memory Management
613
-
614
- Always dispose sensitive data:
615
-
616
- ```typescript
617
- const password = new SecureString('secret');
618
- try {
619
- // Use password
620
- } finally {
621
- password.dispose(); // Zeros memory
622
- }
623
- ```
624
-
625
- ## API Reference
626
-
627
- ### Main Exports
628
-
629
- ```typescript
630
- // Services
631
- export { ECIESService, EciesCryptoCore, EciesMultiRecipient, EciesFileService };
632
- export { AESGCMService, Pbkdf2Service, PasswordLoginService, XorService };
633
-
634
- // Member System
635
- export { Member, MemberType };
636
-
637
- // Secure Primitives
638
- export { SecureString, SecureBuffer, EmailString };
639
-
640
- // Configuration
641
- export { Constants, ConstantsRegistry, CHECKSUM, ECIES, PBKDF2 };
642
- export { createRuntimeConfiguration, getRuntimeConfiguration };
643
- export { registerRuntimeConfiguration, unregisterRuntimeConfiguration };
644
- export { PASSWORD_REGEX, MNEMONIC_REGEX };
645
-
646
- // Enumerations
647
- export { EciesEncryptionTypeEnum, Pbkdf2ProfileEnum };
648
- export { MemberErrorType, ECIESErrorTypeEnum };
649
-
650
- // Errors
651
- export { ECIESError, MemberError, Pbkdf2Error };
652
- export { LengthError, SecureStorageError, InvalidEmailError };
653
-
654
- // Utilities
655
- export { concatUint8Arrays, uint8ArrayToHex, hexToUint8Array };
656
- export { uint8ArrayToBase64, base64ToUint8Array };
657
-
658
- // i18n
659
- export { getEciesI18nEngine, EciesI18nEngine };
660
- ```
661
-
662
- ## Contributing
663
-
664
- 1. Fork & clone the repo.
665
- 2. Install dependencies with `yarn install` (Yarn 4 is already configured via `.yarnrc`).
666
- 3. Create a feature branch (`git checkout -b feature/awesome`).
667
- 4. Make changes and run `yarn format && yarn lint && yarn test`.
668
- 5. Submit a PR with a clear description and test evidence.
669
-
670
- Bug reports and feature requests are welcome—open an issue with reproduction steps and expected behavior.
671
-
672
- ## Security
673
-
674
- If you discover a vulnerability, please **do not** open a public issue. Email <security@digitaldefiance.org> with details so we can coordinate a fix and responsible disclosure timeline.
675
-
676
- ## License
677
-
678
- MIT © Digital Defiance
679
-
680
- ## Links
681
-
682
- - **Repository:** <https://github.com/Digital-Defiance/ecies-lib>
683
- - **npm:** <https://www.npmjs.com/package/@digitaldefiance/ecies-lib>
684
- - **Companion:** @digitaldefiance/node-ecies-lib (binary compatible)
685
-
686
- ## Migration from v1.x to v2.0
687
-
688
- **Breaking Changes**: Service constructors no longer accept i18n engine parameter.
689
-
690
- ### Quick Migration
691
-
692
- **Before (v1.x)**:
693
-
694
- ```typescript
695
- const engine = getEciesI18nEngine();
696
- const pbkdf2 = new Pbkdf2Service(engine);
697
- const passwordLogin = new PasswordLoginService(ecies, pbkdf2, engine);
698
- ```
699
-
700
- **After (v2.0)**:
701
-
702
- ```typescript
703
- getEciesI18nEngine(); // Just initialize once
704
- const pbkdf2 = new Pbkdf2Service();
705
- const passwordLogin = new PasswordLoginService(ecies, pbkdf2);
706
- ```
707
-
708
- ### Key Changes
709
-
710
- 1. **Automatic Engine Retrieval**: Errors now automatically retrieve the i18n engine from a singleton instance
711
- 2. **Simplified Constructors**: Services no longer require engine parameter
712
- 3. **Initialize Once**: Call `getEciesI18nEngine()` at app startup or in test setup
713
-
714
- ## ChangeLog
715
-
716
- ### v4.0.0 - ECIES Protocol v4.0: Enterprise-Grade Security & Efficiency
717
-
718
- #### 🛡️ Major Protocol Upgrade (Breaking Changes)
719
-
720
- Version 4.0 introduces a complete overhaul of the ECIES protocol to meet modern security standards and improve efficiency. This is a **breaking change**; messages encrypted with v4.0 cannot be decrypted by v3.x libraries, and vice versa.
721
-
722
- **Key Improvements:**
723
-
724
- - **Compressed Keys (33 bytes)**: Switched from uncompressed (65 bytes) to compressed public keys, reducing overhead and aligning with modern crypto standards.
725
- - **HKDF Key Derivation**: Replaced simple SHA-256 hashing with **HKDF-SHA256** (RFC 5869) for cryptographically robust key derivation.
726
- - **Shared Ephemeral Key**: Multi-recipient encryption now uses a **single ephemeral key pair** for all recipients, significantly reducing encryption time and message size.
727
- - **AAD Binding**: Header fields (version, algorithm, recipient IDs) are now bound to the encryption via **Additional Authenticated Data (AAD)**. This prevents header tampering and context manipulation attacks.
728
- - **Sign-then-Encrypt**: Added native support for signing messages before encryption, ensuring sender authenticity.
729
-
730
- #### 💥 v4.0 Breaking Changes
731
-
732
- 1. **Message Format**: The version byte is now `0x04`. The internal structure of encrypted messages has changed completely.
733
- 2. **API Changes**:
734
- - `encryptMultiple` now takes a `SharedKeyMode` parameter (default: `Shared`).
735
- - `EciesRecipient` now expects compressed public keys (33 bytes).
736
- 3. **Key Management**:
737
- - `mnemonicToSimpleKeyPair` and other key utilities now return compressed public keys by default.
738
-
739
- #### 🔒 Security Enhancements
740
-
741
- - **Strict Header Validation**: Decryption now strictly validates all header fields against the AAD tag.
742
- - **Recipient ID Binding**: Recipient IDs are included in the AAD, preventing ID swapping attacks.
743
- - **Robust Signatures**: Improved signature handling with strict type checking for `@noble/curves` return values.
744
-
745
- #### 📚 Documentation
746
-
747
- - **Architecture**: See [ECIES_V4_ARCHITECTURE.md](./docs/ECIES_V4_ARCHITECTURE.md) for the full protocol specification.
748
- - **Migration**: See [NODE_ECIES_V4_MIGRATION_INSTRUCTIONS.md](./docs/NODE_ECIES_V4_MIGRATION_INSTRUCTIONS.md) for porting guidelines.
13
+ This library implements a modern, enterprise-grade ECIES protocol (v4.0) featuring HKDF key derivation, AAD binding, and optimized multi-recipient encryption. It includes a pluggable ID provider system, memory-efficient streaming encryption, and comprehensive internationalization.
749
14
 
750
- ---
751
-
752
- ### v3.8.0
753
-
754
- - Add recipient ID length to header
755
-
756
- ### v3.7.5
757
-
758
- - Fix export
759
-
760
- ### v3.7.4
761
-
762
- - Fix export
763
-
764
- ### v3.7.0-3.7.3 - Pluggable ID Provider System & Critical Bug Fixes
765
-
766
- #### 🎯 Overview
767
-
768
- Version 3.7.0 introduces a **pluggable ID provider system** that replaces hardcoded recipient ID sizes with a flexible, extensible architecture. This release fixes a critical 12 vs 32-byte recipient ID discrepancy and adds enterprise-grade validation to prevent entire classes of configuration bugs.
769
-
770
- **Critical Fix:** Resolved silent encryption/decryption failures caused by mismatched recipient ID size constants (12 bytes in `ECIES.MULTIPLE.RECIPIENT_ID_SIZE` vs 32 bytes in `MULTI_RECIPIENT_CONSTANTS.RECIPIENT_ID_SIZE`).
771
-
772
- ---
773
-
774
- #### 🚀 Major Features
775
-
776
- **Pluggable ID Provider System**
777
-
778
- Introduced flexible ID provider architecture with multiple built-in implementations:
779
-
780
- - **ObjectIdProvider** (12 bytes) - MongoDB/BSON compatible IDs, **DEFAULT**
781
- - **GuidV4Provider** (16 bytes) - RFC 4122 compliant GUIDs without dashes
782
- - **UuidProvider** (16 bytes) - Standard UUIDs with dash separators
783
- - **CustomIdProvider** (1-255 bytes) - User-defined ID sizes and formats
784
-
785
- ```typescript
786
- // Example: Using GUID provider
787
- import { createRuntimeConfiguration, GuidV4Provider } from '@digitaldefiance/ecies-lib';
788
-
789
- const config = createRuntimeConfiguration({
790
- idProvider: new GuidV4Provider(), // 16-byte GUIDs
791
- });
792
-
793
- const id = config.idProvider.generate(); // Generates 16-byte GUID
794
- ```
795
-
796
- **Auto-Sync Configuration System**
797
-
798
- All ID-size-related constants now automatically synchronize when an ID provider is set:
799
-
800
- - `MEMBER_ID_LENGTH`
801
- - `ECIES.MULTIPLE.RECIPIENT_ID_SIZE`
802
- - `idProvider.byteLength`
803
-
804
- This prevents the 12 vs 32-byte misconfiguration that existed in v3.0.8.
15
+ ## Features
805
16
 
806
- **Invariant Validation System**
17
+ ### 🛡️ Core Cryptography (Protocol v4.0)
18
+
19
+ - **Advanced ECIES**:
20
+ - **HKDF-SHA256**: Cryptographically robust key derivation (RFC 5869).
21
+ - **AAD Binding**: Strict binding of header metadata and recipient IDs to the encryption context to prevent tampering.
22
+ - **Shared Ephemeral Key**: Optimized multi-recipient encryption using a single ephemeral key pair, reducing payload size.
23
+ - **Compressed Keys**: Uses 33-byte compressed public keys for efficiency.
24
+ - **Algorithms**:
25
+ - **Curve**: `secp256k1` for ECDH key exchange and ECDSA signatures.
26
+ - **Symmetric**: `AES-256-GCM` for authenticated symmetric encryption.
27
+ - **Hashing**: `SHA-256` and `SHA-512`.
28
+ - **Modes**:
29
+ - **Simple**: Minimal overhead (no length prefix).
30
+ - **Single**: Includes data length prefix.
31
+ - **Multiple**: Efficient encryption for up to 65,535 recipients.
32
+
33
+ ### 🆔 Identity & Management
34
+
35
+ - **Pluggable ID Providers**:
36
+ - **Flexible IDs**: Support for `ObjectId` (12 bytes), `GUID`/`UUID` (16 bytes), or custom formats (1-255 bytes).
37
+ - **Auto-Sync**: Configuration automatically adapts all cryptographic constants to the selected ID provider.
38
+ - **Member System**: User abstraction with cryptographic operations, fully integrated with the configured ID provider.
39
+ - **Key Management**:
40
+ - **BIP39**: Mnemonic phrase generation (12-24 words).
41
+ - **HD Wallets**: BIP32/BIP44 hierarchical deterministic derivation.
42
+ - **Secure Storage**: Memory-safe `SecureString` and `SecureBuffer` with XOR obfuscation and auto-zeroing.
43
+
44
+ ### 🚀 Advanced Capabilities
45
+
46
+ - **Streaming Encryption**: Memory-efficient processing for large files (<10MB RAM usage for any file size).
47
+ - **Internationalization (i18n)**: Automatic error translation in 8 languages (en-US, en-GB, fr, es, de, zh-CN, ja, uk).
48
+ - **Runtime Configuration**: Injectable configuration profiles via `ConstantsRegistry` for dependency injection and testing.
49
+ - **Cross-Platform**: Fully compatible with Node.js 18+ and modern browsers (Chrome, Edge, Firefox, Safari).
807
50
 
808
- Added comprehensive validation to catch configuration mismatches at initialization:
51
+ ## Installation
809
52
 
810
- ```typescript
811
- // Automatic validation prevents mismatched configurations
812
- const config = createRuntimeConfiguration({
813
- idProvider: new GuidV4Provider(), // 16 bytes
814
- MEMBER_ID_LENGTH: 12, // ❌ Throws error - mismatch detected!
815
- });
53
+ ```bash
54
+ npm install @digitaldefiance/ecies-lib
55
+ # or
56
+ yarn add @digitaldefiance/ecies-lib
816
57
  ```
817
58
 
818
- Invariants include:
819
-
820
- - `RecipientIdConsistency` - Ensures all ID size constants match
821
- - `Pbkdf2ProfilesValidity` - Validates PBKDF2 profile configuration
822
- - `EncryptionAlgorithmConsistency` - Validates encryption algorithm settings
823
-
824
- **Configuration Provenance Tracking**
825
-
826
- Track configuration lineage for debugging and compliance:
827
-
828
- ```typescript
829
- import { ConstantsRegistry } from '@digitaldefiance/ecies-lib';
830
-
831
- const config = ConstantsRegistry.register('production', {
832
- idProvider: new ObjectIdProvider(),
833
- }, {
834
- description: 'Production configuration with ObjectID',
835
- });
59
+ ### Requirements
836
60
 
837
- // Later, retrieve provenance info
838
- const provenance = ConstantsRegistry.getProvenance('production');
839
- console.log(provenance.timestamp); // When created
840
- console.log(provenance.checksum); // Configuration hash
841
- ```
61
+ **Node.js**: 18+ (Web Crypto API built-in)
62
+ **Browsers**: Modern browsers with Web Crypto API support.
842
63
 
843
- ---
64
+ ## Architecture & Protocol
844
65
 
845
- #### 🐛 Critical Bug Fixes
66
+ ### ECIES v4.0 Protocol Flow
846
67
 
847
- **Fixed 12 vs 32-Byte ID Discrepancy**
68
+ The library implements a robust ECIES variant designed for security and efficiency.
848
69
 
849
- - **Issue:** `ECIES.MULTIPLE.RECIPIENT_ID_SIZE` defaulted to 12 bytes while `MULTI_RECIPIENT_CONSTANTS.RECIPIENT_ID_SIZE` used 32 bytes, causing silent encryption/decryption failures
850
- - **Root Cause:** Two separate constant definitions that were never validated against each other
851
- - **Fix:**
852
- - All recipient ID sizes now derive from `idProvider.byteLength`
853
- - Automatic validation prevents mismatches
854
- - Integration tests added to catch regressions
855
- - `getMultiRecipientConstants()` now dynamically calculates sizes
70
+ 1. **Key Derivation (HKDF)**:
71
+ Shared secrets from ECDH are passed through **HKDF-SHA256** to derive the actual symmetric encryption keys. This ensures that the resulting keys have uniform distribution and are resistant to weak shared secrets.
856
72
 
857
- **Fixed Frozen Constant Mutation**
73
+ ```typescript
74
+ SymmetricKey = HKDF(
75
+ secret: ECDH(EphemeralPriv, RecipientPub),
76
+ salt: empty,
77
+ info: "ecies-v2-key-derivation"
78
+ )
79
+ ```
858
80
 
859
- - **Issue:** Attempting to modify frozen `ENCRYPTION` constant with `Object.assign()` caused runtime errors
860
- - **Fix:** Removed `Object.assign()` mutations, constants are now properly immutable
81
+ 2. **Authenticated Encryption (AAD)**:
82
+ All encryption operations use **AES-256-GCM** with Additional Authenticated Data (AAD).
83
+ - **Key Encryption**: The Recipient's ID is bound to the encrypted key.
84
+ - **Message Encryption**: The Message Header (containing version, algorithm, ephemeral key, etc.) is bound to the encrypted payload.
85
+ This prevents "context manipulation" attacks where an attacker might try to swap recipient IDs or modify header metadata.
861
86
 
862
- **Fixed PBKDF2 Profile Validation**
87
+ 3. **Multi-Recipient Optimization**:
88
+ Instead of generating a new ephemeral key pair for every recipient, the sender generates **one** ephemeral key pair for the message.
89
+ - The ephemeral public key is stored once in the header.
90
+ - A random "Message Key" is generated.
91
+ - This Message Key is encrypted individually for each recipient using the shared secret derived from the single ephemeral key and the recipient's public key.
863
92
 
864
- - **Issue:** Invalid PBKDF2 profile configuration could pass validation
865
- - **Fix:** Added comprehensive PBKDF2 profile validation in invariant system
93
+ ### ID Provider System
866
94
 
867
- **Fixed Disposed Object Error Messages**
95
+ The library is agnostic to the format of unique identifiers. The `IdProvider` system drives the entire configuration:
868
96
 
869
- - **Issue:** `DisposedError` had incorrect i18n string keys
870
- - **Fix:** Added proper error type enumeration and i18n translations
97
+ - **ObjectIdProvider** (Default): 12-byte MongoDB-style IDs.
98
+ - **GuidV4Provider**: 16-byte raw GUIDs.
99
+ - **UuidProvider**: 16-byte UUIDs (string representation handles dashes).
100
+ - **CustomIdProvider**: Define your own size (1-255 bytes).
871
101
 
872
- ---
102
+ When you configure an ID provider, the library automatically:
873
103
 
874
- #### 💥 Breaking Changes
104
+ - Updates `MEMBER_ID_LENGTH`.
105
+ - Updates `ECIES.MULTIPLE.RECIPIENT_ID_SIZE`.
106
+ - Validates that all internal constants are consistent.
875
107
 
876
- **1. Direct Constant Assignments Removed**
108
+ ## Quick Start
877
109
 
878
- **Before (v3.0.8):**
110
+ ### 1. Basic Configuration & Usage
879
111
 
880
112
  ```typescript
881
- const config = createRuntimeConfiguration({
882
- MEMBER_ID_LENGTH: 16,
883
- ECIES: {
884
- MULTIPLE: {
885
- RECIPIENT_ID_SIZE: 16,
886
- },
887
- },
888
- });
889
- ```
113
+ import {
114
+ ECIESService,
115
+ getEciesI18nEngine,
116
+ createRuntimeConfiguration,
117
+ ObjectIdProvider
118
+ } from '@digitaldefiance/ecies-lib';
890
119
 
891
- **After (v3.7.x):**
120
+ // 1. Initialize i18n (required once)
121
+ getEciesI18nEngine();
892
122
 
893
- ```typescript
123
+ // 2. Configure (Optional - defaults to ObjectIdProvider)
894
124
  const config = createRuntimeConfiguration({
895
- idProvider: new GuidV4Provider(), // Auto-syncs all size constants
125
+ idProvider: new ObjectIdProvider()
896
126
  });
897
- ```
898
-
899
- **2. Recipient ID Generation Changes**
900
-
901
- **Before:**
902
-
903
- ```typescript
904
- const recipientId = crypto.getRandomValues(new Uint8Array(32)); // Hardcoded
905
- ```
906
-
907
- **After:**
908
-
909
- ```typescript
910
- const recipientId = config.idProvider.generate(); // Dynamic sizing
911
- ```
912
-
913
- **3. Multi-Recipient Constants Function Signature**
914
-
915
- **Before:**
916
127
 
917
- ```typescript
918
- const constants = getMultiRecipientConstants(); // Used hardcoded 32
919
- ```
920
-
921
- **After:**
922
-
923
- ```typescript
924
- const constants = getMultiRecipientConstants(config.idProvider.byteLength); // Dynamic
925
- ```
926
-
927
- ---
928
-
929
- #### 📚 New Documentation
930
-
931
- - **docs/MIGRATION_GUIDE_v3.7.md** - Complete migration guide from v3.6.x/v3.0.8 to v3.7.x
932
- - **docs/ID_PROVIDER_ARCHITECTURE.md** - Deep dive into the ID provider system (implied)
933
- - **docs/ENTERPRISE_ARCHITECTURE_ASSESSMENT.md** - Enterprise-grade architecture recommendations
934
- - **docs/ENTERPRISE_READINESS_CHECKLIST.md** - Production readiness assessment
935
- - **docs/EXECUTIVE_SUMMARY.md** - Executive overview of ID provider system
936
- - **docs/ID_PROVIDER_TESTING.md** - Comprehensive testing documentation
937
- - **docs/ID_SYSTEM_IMPLEMENTATION_STATUS.md** - Implementation status and roadmap
938
- - **docs/MIGRATION_CHECKLIST_NODE_LIB.md** - Node.js library migration checklist
939
-
940
- ---
941
-
942
- #### 🧪 Testing Improvements
943
-
944
- **New Test Suites**
945
-
946
- - `tests/lib/id-providers/id-providers.spec.ts` - Basic provider functionality (314 lines)
947
- - `tests/lib/id-providers/id-providers-comprehensive.spec.ts` - Comprehensive provider validation (913 lines)
948
- - `tests/lib/invariant-validator.spec.ts` - Invariant system validation (250 lines)
949
- - `tests/lib/configuration-provenance.spec.ts` - Provenance tracking tests (215 lines)
950
- - `tests/integration/recipient-id-consistency.spec.ts` - Cross-configuration ID consistency (319 lines)
951
- - `tests/integration/encrypted-message-structure.spec.ts` - Message structure validation (490 lines)
952
- - `tests/errors/ecies-error-context.spec.ts` - Enhanced error context testing (337 lines)
953
-
954
- **Test Statistics**
955
-
956
- - **Total Tests:** 1,200+ (up from ~1,100)
957
- - **Test Pass Rate:** 100% (1,200/1,200)
958
- - **Test Suites:** 61 suites
959
- - **New Test Files:** 7
960
- - **Test Execution Time:** ~77 seconds
961
-
962
- **Test Coverage**
963
-
964
- - All 4 ID providers have comprehensive test coverage
965
- - Cross-provider compatibility tests
966
- - Encrypted message structure validation with different ID sizes
967
- - Performance benchmarks (serialization/deserialization <50ms for 1000 operations)
968
- - Constant-time comparison validation (timing attack resistance)
969
- - Invariant validation edge cases
970
-
971
- ---
972
-
973
- #### ⚡ Performance
974
-
975
- **ID Provider Benchmarks**
976
-
977
- All providers meet performance requirements:
978
-
979
- - **ObjectIdProvider:** ~40ms per 1000 operations
980
- - **GuidV4Provider:** ~45ms per 1000 operations
981
- - **UuidProvider:** ~45ms per 1000 operations
982
- - **CustomIdProvider:** ~40ms per 1000 operations
983
-
984
- **Performance Baselines**
985
-
986
- - Serialization: 1000 IDs in <50ms (relaxed from 20ms for CI stability)
987
- - Deserialization: 1000 IDs in <50ms (relaxed from 25ms for CI stability)
988
- - Constant-time comparison ratio: <15.0x (relaxed from 5.0x for CI variance)
989
-
990
- ---
991
-
992
- #### 🔒 Security Enhancements
993
-
994
- **Constant-Time Operations**
995
-
996
- - All ID providers use constant-time comparison to prevent timing attacks
997
- - Validation timing tests ensure consistent execution time regardless of input
998
-
999
- **Immutable Configuration**
1000
-
1001
- - All constants are deeply frozen to prevent accidental modification
1002
- - Configuration provenance tracking provides audit trail
1003
-
1004
- **Validation at Initialization**
1005
-
1006
- - Invariant validation catches misconfigurations before runtime
1007
- - Comprehensive error context for debugging
128
+ // 3. Initialize Service
129
+ const ecies = new ECIESService(config);
1008
130
 
1009
- ---
1010
-
1011
- #### 🌍 Internationalization
1012
-
1013
- **New Error Messages**
1014
-
1015
- Added i18n support for ID provider errors in 7 languages (en-US, fr, de, es, ja, uk, zh-cn):
1016
-
1017
- - `IdProviderInvalidByteLength` - Invalid byte length for ID provider
1018
- - `IdProviderInvalidIdFormat` - Invalid ID format
1019
- - `IdProviderIdValidationFailed` - ID validation failed
1020
- - `IdProviderSerializationFailed` - Serialization failed
1021
- - `IdProviderDeserializationFailed` - Deserialization failed
1022
- - `IdProviderInvalidStringLength` - Invalid string length
1023
- - `IdProviderInputMustBeUint8Array` - Input must be Uint8Array
1024
- - `IdProviderInputMustBeString` - Input must be string
1025
- - `IdProviderInvalidCharacters` - Invalid characters in input
1026
-
1027
- **Updated Error Messages**
1028
-
1029
- - Enhanced `DisposedError` with proper type enumeration
1030
- - Added context parameters to ECIES error messages
1031
- - Improved error message clarity across all services
1032
-
1033
- ---
1034
-
1035
- #### 📦 New Exports
1036
-
1037
- **ID Providers**
1038
-
1039
- ```typescript
1040
- export { ObjectIdProvider } from './lib/id-providers/objectid-provider';
1041
- export { GuidV4Provider } from './lib/id-providers/guidv4-provider';
1042
- export { UuidProvider } from './lib/id-providers/uuid-provider';
1043
- export { CustomIdProvider } from './lib/id-providers/custom-provider';
1044
- ```
131
+ // 4. Generate Keys
132
+ const mnemonic = ecies.generateNewMnemonic();
133
+ const { privateKey, publicKey } = ecies.mnemonicToSimpleKeyPair(mnemonic);
1045
134
 
1046
- **Interfaces**
135
+ // 5. Encrypt & Decrypt
136
+ const message = new TextEncoder().encode('Hello, Secure World!');
137
+ const encrypted = await ecies.encryptSimpleOrSingle(false, publicKey, message);
138
+ const decrypted = await ecies.decryptSimpleOrSingleWithHeader(false, privateKey, encrypted);
1047
139
 
1048
- ```typescript
1049
- export type { IIdProvider } from './interfaces/id-provider';
1050
- export { BaseIdProvider } from './interfaces/id-provider';
1051
- export type { IInvariant } from './interfaces/invariant';
1052
- export { BaseInvariant } from './interfaces/invariant';
1053
- export type { IConfigurationProvenance } from './interfaces/configuration-provenance';
140
+ console.log(new TextDecoder().decode(decrypted)); // "Hello, Secure World!"
1054
141
  ```
1055
142
 
1056
- **Validation**
143
+ ### 2. Using Custom ID Providers (e.g., GUID)
1057
144
 
1058
145
  ```typescript
1059
- export { InvariantValidator } from './lib/invariant-validator';
1060
- export { RecipientIdConsistencyInvariant } from './lib/invariants/recipient-id-consistency';
1061
- export { Pbkdf2ProfilesValidityInvariant } from './lib/invariants/pbkdf2-profiles-validity';
1062
- export { EncryptionAlgorithmConsistencyInvariant } from './lib/invariants/encryption-algorithm-consistency';
1063
- ```
146
+ import {
147
+ createRuntimeConfiguration,
148
+ GuidV4Provider,
149
+ ECIESService
150
+ } from '@digitaldefiance/ecies-lib';
1064
151
 
1065
- **Errors**
152
+ // Configure to use 16-byte GUIDs
153
+ const config = createRuntimeConfiguration({
154
+ idProvider: new GuidV4Provider()
155
+ });
1066
156
 
1067
- ```typescript
1068
- export { IdProviderError } from './errors/id-provider';
1069
- export { IdProviderErrorType } from './enumerations/id-provider-error-type';
1070
- export { DisposedErrorType } from './enumerations/disposed-error-type';
157
+ const ecies = new ECIESService(config);
158
+ const id = config.idProvider.generate(); // Returns 16-byte Uint8Array
1071
159
  ```
1072
160
 
1073
- ---
1074
-
1075
- #### 🔧 Code Structure Changes
1076
-
1077
- **New Files Added (7,611 insertions)**
1078
-
1079
- Core Implementation:
1080
-
1081
- - `src/lib/id-providers/objectid-provider.ts` (97 lines)
1082
- - `src/lib/id-providers/guidv4-provider.ts` (122 lines)
1083
- - `src/lib/id-providers/uuid-provider.ts` (117 lines)
1084
- - `src/lib/id-providers/custom-provider.ts` (165 lines)
1085
- - `src/lib/id-providers/index.ts` (31 lines)
1086
-
1087
- Validation System:
1088
-
1089
- - `src/lib/invariant-validator.ts` (133 lines)
1090
- - `src/lib/invariants/recipient-id-consistency.ts` (46 lines)
1091
- - `src/lib/invariants/pbkdf2-profiles-validity.ts` (78 lines)
1092
- - `src/lib/invariants/encryption-algorithm-consistency.ts` (73 lines)
1093
-
1094
- Interfaces:
1095
-
1096
- - `src/interfaces/id-provider.ts` (117 lines)
1097
- - `src/interfaces/invariant.ts` (60 lines)
1098
- - `src/interfaces/configuration-provenance.ts` (72 lines)
1099
-
1100
- Errors:
1101
-
1102
- - `src/errors/id-provider.ts` (40 lines)
1103
- - `src/enumerations/id-provider-error-type.ts` (50 lines)
1104
- - `src/enumerations/disposed-error-type.ts` (11 lines)
161
+ ### 3. Streaming Encryption (Large Files)
1105
162
 
1106
- **Major File Modifications**
1107
-
1108
- - `src/constants.ts` (+115 lines) - Added ID provider integration and auto-sync
1109
- - `src/interfaces/constants.ts` (+27 lines) - Extended with ID provider field
1110
- - `src/interfaces/multi-recipient-chunk.ts` (+69 lines) - Dynamic size calculation
1111
- - `src/services/multi-recipient-processor.ts` (+72 lines) - ID provider integration
1112
- - `src/services/encryption-stream.ts` (+18 lines) - Dynamic size support
1113
- - `src/secure-buffer.ts` (+28 lines) - Enhanced disposal handling
1114
- - `src/errors/ecies.ts` (+107 lines) - New error types with context
1115
-
1116
- **Translation Updates**
1117
-
1118
- Updated all 7 language files with new error messages:
1119
-
1120
- - `src/translations/en-US.ts` (+22 lines)
1121
- - `src/translations/fr.ts` (+26 lines)
1122
- - `src/translations/de.ts` (+22 lines)
1123
- - `src/translations/es.ts` (+28 lines)
1124
- - `src/translations/ja.ts` (+21 lines)
1125
- - `src/translations/uk.ts` (+24 lines)
1126
- - `src/translations/zh-cn.ts` (+27 lines)
1127
-
1128
- ---
1129
-
1130
- #### 🔄 Migration Guide
1131
-
1132
- **For Default Users (No Changes Needed)**
1133
-
1134
- If you're using the default ObjectID provider (12 bytes), **no code changes are required**:
163
+ Encrypt gigabytes of data with minimal memory footprint (<10MB).
1135
164
 
1136
165
  ```typescript
1137
- // v3.0.8 - Still works in v3.7.x!
1138
- import { ECIESService } from '@digitaldefiance/ecies-lib';
166
+ import { ECIESService, EncryptionStream } from '@digitaldefiance/ecies-lib';
1139
167
 
1140
168
  const ecies = new ECIESService();
1141
- const encrypted = await ecies.encrypt(data, publicKey);
1142
- ```
1143
-
1144
- **For Custom ID Size Users**
1145
-
1146
- If you were customizing ID sizes in v3.0.8:
1147
-
1148
- ```typescript
1149
- // v3.0.8 (OLD - BREAKS in v3.7.x)
1150
- const config = createRuntimeConfiguration({
1151
- MEMBER_ID_LENGTH: 16,
1152
- });
1153
-
1154
- // v3.7.x (NEW)
1155
- import { GuidV4Provider } from '@digitaldefiance/ecies-lib';
1156
-
1157
- const config = createRuntimeConfiguration({
1158
- idProvider: new GuidV4Provider(),
1159
- });
1160
- ```
1161
-
1162
- **Creating Custom ID Providers**
1163
-
1164
- ```typescript
1165
- import { BaseIdProvider } from '@digitaldefiance/ecies-lib';
169
+ const stream = new EncryptionStream(ecies);
1166
170
 
1167
- class MyCustomProvider extends BaseIdProvider {
1168
- constructor() {
1169
- super('MyCustom', 24, 'My 24-byte custom IDs');
1170
- }
1171
-
1172
- generate(): Uint8Array {
1173
- return crypto.getRandomValues(new Uint8Array(24));
1174
- }
171
+ // Assuming 'fileStream' is a ReadableStream from a File object
172
+ async function processFile(fileStream: ReadableStream, publicKey: Uint8Array) {
173
+ const encryptedChunks: Uint8Array[] = [];
1175
174
 
1176
- validate(id: Uint8Array): boolean {
1177
- return id.length === 24;
175
+ // Encrypt
176
+ for await (const chunk of stream.encryptStream(fileStream, publicKey)) {
177
+ encryptedChunks.push(chunk.data);
178
+ // In a real app, you'd write 'chunk.data' to disk or upload it immediately
1178
179
  }
1179
180
 
1180
- serialize(id: Uint8Array): string {
1181
- return Array.from(id).map(b => b.toString(16).padStart(2, '0')).join('');
1182
- }
1183
-
1184
- deserialize(str: string): Uint8Array {
1185
- const bytes = new Uint8Array(24);
1186
- for (let i = 0; i < 24; i++) {
1187
- bytes[i] = parseInt(str.substr(i * 2, 2), 16);
1188
- }
1189
- return bytes;
1190
- }
181
+ return encryptedChunks;
1191
182
  }
1192
183
  ```
1193
184
 
1194
- ---
1195
-
1196
- #### 📊 Version Details
1197
-
1198
- **v3.7.3**
1199
-
1200
- - Removed Legacy32ByteProvider from all code and documentation
1201
- - Fixed test failures from Legacy32ByteProvider removal
1202
- - Updated migration guides to only show supported providers
1203
- - Relaxed timing test thresholds for CI stability (15.0x ratio, 50ms thresholds)
1204
-
1205
- **v3.7.2**
1206
-
1207
- - Initial release of ID provider system
1208
- - Added comprehensive documentation
1209
- - Full test suite with 1,200+ tests
1210
-
1211
- ---
1212
-
1213
- #### 🙏 Contributors
1214
-
1215
- - Jessica Mulein (@JessicaMulein) - Lead developer
1216
- - GitHub Copilot - Architecture review and code assistance
1217
-
1218
- ---
1219
-
1220
- #### 📝 Release Statistics
1221
-
1222
- - **Lines of code changed:** ~7,600 additions, ~135 deletions
1223
- - **Files modified:** 61
1224
- - **New test files:** 7
1225
- - **New source files:** 14
1226
- - **Documentation added:** ~3,800 lines
1227
- - **Tests added:** 100+
1228
- - **Test pass rate:** 100% (1,200/1,200)
1229
-
1230
- ---
1231
-
1232
- ### v3.0.8
1233
-
1234
- - Update i18n
1235
-
1236
- ### v3.0.7
1237
-
1238
- - Update i18n
1239
-
1240
- ### v3.0.6
1241
-
1242
- - Update i18n
1243
-
1244
- ### v3.0.5
1245
-
1246
- - Update i18n
1247
-
1248
- ### v3.0.4
1249
-
1250
- - Fix EmailString usage of InvalidEmailError
1251
-
1252
- ### v3.0.3
1253
-
1254
- - Slight tweak to InvalidEmailError
1255
-
1256
- ### v3.0.2
1257
-
1258
- - Update test-utils
1259
-
1260
- ### v3.0.1
1261
-
1262
- - Fix strings mainly
1263
- - add service.encryptMultiple endpoint, clarify service.encrypt endpoint
1264
-
1265
- ### v3.0.0 - Streaming Encryption & Security Hardening
185
+ ### 4. Member System
1266
186
 
1267
- **Major Features**:
187
+ The `Member` class provides a high-level user abstraction that integrates keys, IDs, and encryption.
1268
188
 
1269
- - ✨ **Streaming Encryption**: Memory-efficient encryption for large files (<10MB RAM for any size)
1270
- - 🔐 **Multi-Recipient Streaming**: Encrypt once for up to 65,535 recipients with shared symmetric key
1271
- - 📊 **Progress Tracking**: Real-time throughput, ETA, and completion percentage
1272
- - 🔒 **Security Hardening**: 16 comprehensive security validations across all layers
1273
- - ✅ **AsyncGenerator API**: Flexible streaming with cancellation support
1274
- - 🎯 **100% Test Coverage**: 646/646 tests passing, 52/52 suites
1275
-
1276
- **New APIs**:
1277
-
1278
- **Single-Recipient Streaming**:
1279
-
1280
- - `EncryptionStream.encryptStream()` - Stream encryption with configurable chunks
1281
- - `EncryptionStream.decryptStream()` - Stream decryption with validation
1282
- - `Member.encryptDataStream()` - Member-level streaming encryption
1283
- - `Member.decryptDataStream()` - Member-level streaming decryption
1284
-
1285
- **Multi-Recipient Streaming**:
1286
-
1287
- - `EncryptionStream.encryptStreamMultiple()` - Encrypt for multiple recipients
1288
- - `EncryptionStream.decryptStreamMultiple()` - Decrypt as specific recipient
1289
- - `MultiRecipientProcessor.encryptChunk()` - Low-level multi-recipient encryption
1290
- - `MultiRecipientProcessor.decryptChunk()` - Low-level multi-recipient decryption
1291
-
1292
- **Progress Tracking**:
1293
-
1294
- - `ProgressTracker.update()` - Track bytes processed, throughput, ETA
1295
- - `IStreamProgress` interface with `throughputBytesPerSec` property
1296
- - Optional progress callbacks in all streaming operations
1297
-
1298
- **Security Enhancements (16 validations)**:
1299
-
1300
- **Base ECIES Layer (8 fixes)**:
1301
-
1302
- - Public key all-zeros validation
1303
- - Private key all-zeros validation
1304
- - Shared secret all-zeros validation
1305
- - Message size validation (max 2GB)
1306
- - Encrypted size bounds checking
1307
- - Minimum encrypted data size validation
1308
- - Component extraction validation
1309
- - Decrypted data validation
1310
-
1311
- **AES-GCM Layer (5 fixes)**:
1312
-
1313
- - Key length validation (16/24/32 bytes only)
1314
- - IV length validation (16 bytes)
1315
- - Null/undefined data rejection
1316
- - Data size validation (max 2GB)
1317
- - Comprehensive decrypt input validation
1318
-
1319
- **Multi-Recipient Layer (3 fixes)**:
1320
-
1321
- - Chunk index bounds checking (uint32 range)
1322
- - Data size validation (max 2GB)
1323
- - Safe accumulation with overflow detection
1324
-
1325
- **Performance**:
1326
-
1327
- - 99% memory reduction (1GB file: 1GB RAM → <10MB RAM)
1328
- - < 0.1% overhead from security validations
1329
- - Independent chunk encryption (resumability ready)
1330
- - Chunk sequence validation (prevents reordering attacks)
1331
- - Optional SHA-256 checksums (in addition to AES-GCM auth)
1332
- - Single symmetric key per stream (not per chunk)
1333
-
1334
- **Multi-Recipient Features**:
1335
-
1336
- - Maximum 65,535 recipients supported
1337
- - 32-byte recipient IDs required
1338
- - Shared symmetric key encrypted per recipient
1339
- - Efficient header format with recipient metadata
1340
- - Buffer overflow protection (100MB max per source chunk)
1341
-
1342
- **New Error Types**:
1343
-
1344
- - `InvalidAESKeyLength` - AES key must be 16/24/32 bytes
1345
- - `CannotEncryptEmptyData` - Empty/null data rejected
1346
- - `CannotDecryptEmptyData` - Empty/null encrypted data rejected
1347
- - `EncryptedSizeExceedsExpected` - Encrypted output too large
1348
- - `InvalidChunkIndex` - Chunk index out of uint32 range
1349
- - `HeaderSizeOverflow` - Recipient header size overflow
1350
-
1351
- **Documentation**:
1352
-
1353
- - Added `docs/STREAMING_ENCRYPTION_ARCHITECTURE.md`
1354
- - Added `docs/STREAMING_API_QUICKSTART.md`
1355
- - Added `docs/PHASE_1_COMPLETE.md`
1356
- - Added `ECIES_STREAMING_CHANGES_SUMMARY.md` (for node-ecies porting)
1357
- - Updated README with streaming and multi-recipient examples
1358
-
1359
- **Test Coverage**:
1360
-
1361
- - 646 tests passing (100%)
1362
- - 52 test suites passing (100%)
1363
- - 5 multi-recipient streaming tests
1364
- - 87+ streaming tests (unit + integration + e2e)
1365
- - All 16 security validations covered
1366
- - Error coverage validation updated
1367
-
1368
- ### v2.1.42
1369
-
1370
- - Fix Hmac constant
1371
-
1372
- ### v2.1.40
1373
-
1374
- - Alignment with Express Suite packages
1375
- - All packages updated to v2.1.40 (i18n, ecies-lib, node-ecies-lib, suite-core-lib, node-express-suite, express-suite-react-components)
1376
- - Test utilities remain at v1.0.7
1377
- - `/testing` entry point exports test mocks (mockFrontendMember)
1378
- - Requires `@faker-js/faker` as dev dependency for test utilities
1379
-
1380
- ## v2.1.39 - Update test-utils dep
1381
-
1382
- ## v2.1.38 - Export test mock for frontend member
1383
-
1384
- ## v2.1.32 - Config on i18n create
1385
-
1386
- ## v2.1.30 - Alignment bump
1387
-
1388
- ## v2.1.26 - use new express-suite-test-utils
1389
-
1390
- ## v2.1.25 - Upgrade i18n, mostly testing improvements
189
+ ```typescript
190
+ import { Member, MemberType, EmailString } from '@digitaldefiance/ecies-lib';
1391
191
 
1392
- ## v2.1.17 - Add frontend member mock
192
+ // Create a new member (ID generated automatically based on configured provider)
193
+ const { member, mnemonic } = Member.newMember(
194
+ ecies,
195
+ MemberType.User,
196
+ 'Alice',
197
+ new EmailString('alice@example.com')
198
+ );
1393
199
 
1394
- ## v2.1.16 - upgrade i18n
200
+ console.log(member.id); // Uint8Array (size depends on provider)
1395
201
 
1396
- ## v2.1.15 - upgrade i18n
202
+ // Encrypt data for this member
203
+ const encrypted = await member.encryptData('My Secrets');
204
+ ```
1397
205
 
1398
- ## v2.1.12 - upgrade i18n
206
+ ## API Reference
1399
207
 
1400
- ### v2.1.10 - Convergence bump
208
+ ### Core Services
1401
209
 
1402
- ### v2.1.7 - minor version bump to fix core component aliases
210
+ - **`ECIESService`**: The main entry point for encryption/decryption operations.
211
+ - **`EciesCryptoCore`**: Low-level cryptographic primitives (keys, signatures, ECDH).
212
+ - **`EciesMultiRecipient`**: Specialized service for handling multi-recipient messages.
213
+ - **`EciesFileService`**: Helper for chunked file encryption.
214
+ - **`PasswordLoginService`**: Secure authentication using PBKDF2 and encrypted key bundles.
1403
215
 
1404
- ### v2.1.6 - minor version bump from i18n lib
216
+ ### Configuration & Registry
1405
217
 
1406
- ### v2.1.5 - minor version bump from i18n lib
218
+ - **`Constants`**: The default, immutable configuration object.
219
+ - **`ConstantsRegistry`**: Manages runtime configurations.
220
+ - `register(key, config)`: Register a named configuration.
221
+ - `get(key)`: Retrieve a configuration.
222
+ - **`createRuntimeConfiguration(overrides)`**: Creates a validated configuration object with your overrides.
1407
223
 
1408
- ### v2.1.4 - minor version bump from i18n lib
224
+ ### Secure Primitives
1409
225
 
1410
- ### v2.1.3 - drop GUID altogether for ObjectID via BSON for better compatibility with node-ecies
226
+ - **`SecureString` / `SecureBuffer`**:
227
+ - Stores sensitive data in memory using XOR obfuscation.
228
+ - `dispose()` method to explicitly zero out memory.
229
+ - Prevents accidental leakage via `console.log` or serialization.
1411
230
 
1412
- ### v2.1.2 - add faux GUID support for MongoDB ObjectIds
231
+ ## Development
1413
232
 
1414
- ### v2.1.1 - upgrade to match i18n, upgrade error classes, deprecate Plu1inI8nEngine
233
+ ### Commands
1415
234
 
1416
- ### v2.0.3 - version bump/update i18n
235
+ ```bash
236
+ yarn install # Install dependencies
237
+ yarn build # Compile TypeScript
238
+ yarn test # Run all tests (1200+ specs)
239
+ yarn lint # ESLint check
240
+ yarn format # Fix all (prettier + lint)
241
+ ```
1417
242
 
1418
- ### v2.0.2 - version bump/update i18n
243
+ ### Testing
1419
244
 
1420
- ### v2.0.1 - Minor bump to remove generics on some error classes
245
+ The library maintains **100% test coverage** with over 1,200 tests, including:
1421
246
 
1422
- ### v2.0.0 - i18n Architecture Modernization
247
+ - **Unit Tests**: For all services and utilities.
248
+ - **Integration Tests**: Verifying protocol flows and message structures.
249
+ - **Vectors**: Validating against known test vectors.
250
+ - **Property-based Tests**: Fuzzing inputs for robustness.
1423
251
 
1424
- **Release Date**: January 2025
252
+ ## ChangeLog
1425
253
 
1426
- **Major Changes**:
254
+ ### v4.1.1
1427
255
 
1428
- - 🎉 **i18n v2.0**: Automatic error translation with singleton pattern
1429
- - ✨ **Simplified APIs**: Removed engine parameters from all service constructors
1430
- - 🔧 **Breaking**: `Pbkdf2Service`, `PasswordLoginService` constructors changed
1431
- - 📚 **Documentation**: Added comprehensive migration guides
1432
- - ✅ **Testing**: 393/393 tests passing (100%)
256
+ - Tweak to objectId provider to make generate() more robust
1433
257
 
1434
- **Migration Required**: See [Migration Guide](./docs/I18N_V2_MIGRATION_GUIDE.md)
258
+ ### v4.1.0
1435
259
 
1436
- **Services Updated**:
260
+ - **ID Provider Integration**: The `Member` model now fully utilizes the configured `IdProvider` for all ID operations, removing hard dependencies on specific ID formats.
261
+ - **Type Safety**: Enhanced type definitions for `Member` and `MemberBuilder` to support generic ID types (defaults to `Uint8Array`).
1437
262
 
1438
- - `Pbkdf2Service(profiles?, eciesParams?, pbkdf2Params?)` - removed engine parameter
1439
- - `PasswordLoginService(ecies, pbkdf2, eciesParams?)` - removed engine parameter
263
+ ### v4.0.0 - ECIES Protocol v4.0
1440
264
 
1441
- **New Features**:
265
+ #### Major Protocol Upgrade (Breaking Change)
1442
266
 
1443
- - Automatic i18n engine retrieval via singleton
1444
- - Unified index exports (v1 + v2 architecture)
1445
- - Enhanced error messages in 8 languages
267
+ - **HKDF Key Derivation**: Replaced simple hashing with HKDF-SHA256.
268
+ - **AAD Binding**: Enforced binding of header and recipient IDs to encryption.
269
+ - **Shared Ephemeral Key**: Optimized multi-recipient encryption.
270
+ - **Compressed Keys**: Standardized on 33-byte compressed public keys.
271
+ - **IV/Key Sizes**: Optimized constants (12-byte IV, 60-byte encrypted key blocks).
1446
272
 
1447
- **Bug Fixes**:
273
+ ### v3.7.0 - Pluggable ID Provider System
1448
274
 
1449
- - Fixed PBKDF2 profile lookup issues
1450
- - Resolved test initialization timing problems
1451
- - Corrected constructor parameter ordering
275
+ - **Flexible IDs**: Introduced `IdProvider` architecture.
276
+ - **Auto-Sync**: Configuration automatically adapts to ID size.
277
+ - **Invariant Validation**: Runtime checks for configuration consistency.
1452
278
 
1453
- **Documentation**:
279
+ ### v3.0.0 - Streaming Encryption
1454
280
 
1455
- - Added `docs/I18N_V2_MIGRATION_GUIDE.md`
1456
- - Added `docs/LESSONS_LEARNED.md`
1457
- - Added `docs/NODE_ECIES_MIGRATION_GUIDE.md`
1458
- - Updated README with v2.0 examples
281
+ - **Memory Efficiency**: Streaming support for large datasets.
282
+ - **Progress Tracking**: Real-time throughput and ETA monitoring.
1459
283
 
1460
- **Performance**:
284
+ ### v2.0.0 - i18n Architecture
1461
285
 
1462
- - No degradation: 44s test suite (vs 45s in v1.x)
1463
- - Reduced code complexity by 40%
1464
- - Eliminated parameter threading overhead
286
+ - **Singleton i18n**: Simplified service instantiation.
287
+ - **Translation**: Error messages in 8 languages.
1465
288
 
1466
289
  ### v1.3.27 and Earlier
1467
290
 
@@ -1687,3 +510,14 @@ class MyCustomProvider extends BaseIdProvider {
1687
510
  - Fri Sep 26 2025 10:21:00 GMT-0700 (Pacific Daylight Time)
1688
511
 
1689
512
  - Initial release of the ECIES library with multi-recipient support, AES-GCM helpers, PBKDF2 profiles, and password-login tooling
513
+
514
+ ## License
515
+
516
+ MIT © Digital Defiance
517
+
518
+ ## Links
519
+
520
+ - **Repository:** <https://github.com/Digital-Defiance/ecies-lib>
521
+ - **npm:** <https://www.npmjs.com/package/@digitaldefiance/ecies-lib>
522
+ - **Companion:** @digitaldefiance/node-ecies-lib (binary compatible)
523
+