@digitaldefiance/ecies-lib 4.1.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,1470 +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.1.0
717
-
718
- - ID Provider drives Member model as well
719
-
720
- ### v4.0.0 - ECIES Protocol v4.0: Enterprise-Grade Security & Efficiency
721
-
722
- #### 🛡️ Major Protocol Upgrade (Breaking Changes)
723
-
724
- 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.
725
-
726
- **Key Improvements:**
727
-
728
- - **Compressed Keys (33 bytes)**: Switched from uncompressed (65 bytes) to compressed public keys, reducing overhead and aligning with modern crypto standards.
729
- - **HKDF Key Derivation**: Replaced simple SHA-256 hashing with **HKDF-SHA256** (RFC 5869) for cryptographically robust key derivation.
730
- - **Shared Ephemeral Key**: Multi-recipient encryption now uses a **single ephemeral key pair** for all recipients, significantly reducing encryption time and message size.
731
- - **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.
732
- - **Sign-then-Encrypt**: Added native support for signing messages before encryption, ensuring sender authenticity.
733
-
734
- #### 💥 v4.0 Breaking Changes
735
-
736
- 1. **Message Format**: The version byte is now `0x04`. The internal structure of encrypted messages has changed completely.
737
- 2. **API Changes**:
738
- - `encryptMultiple` now takes a `SharedKeyMode` parameter (default: `Shared`).
739
- - `EciesRecipient` now expects compressed public keys (33 bytes).
740
- 3. **Key Management**:
741
- - `mnemonicToSimpleKeyPair` and other key utilities now return compressed public keys by default.
742
-
743
- #### 🔒 Security Enhancements
744
-
745
- - **Strict Header Validation**: Decryption now strictly validates all header fields against the AAD tag.
746
- - **Recipient ID Binding**: Recipient IDs are included in the AAD, preventing ID swapping attacks.
747
- - **Robust Signatures**: Improved signature handling with strict type checking for `@noble/curves` return values.
748
-
749
- #### 📚 Documentation
750
-
751
- - **Architecture**: See [ECIES_V4_ARCHITECTURE.md](./docs/ECIES_V4_ARCHITECTURE.md) for the full protocol specification.
752
- - **Migration**: See [NODE_ECIES_V4_MIGRATION_INSTRUCTIONS.md](./docs/NODE_ECIES_V4_MIGRATION_INSTRUCTIONS.md) for porting guidelines.
753
-
754
- ---
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.
755
14
 
756
- ### v3.8.0
757
-
758
- - Add recipient ID length to header
759
-
760
- ### v3.7.5
761
-
762
- - Fix export
763
-
764
- ### v3.7.4
765
-
766
- - Fix export
767
-
768
- ### v3.7.0-3.7.3 - Pluggable ID Provider System & Critical Bug Fixes
769
-
770
- #### 🎯 Overview
771
-
772
- 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.
773
-
774
- **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`).
775
-
776
- ---
777
-
778
- #### 🚀 Major Features
779
-
780
- **Pluggable ID Provider System**
781
-
782
- Introduced flexible ID provider architecture with multiple built-in implementations:
783
-
784
- - **ObjectIdProvider** (12 bytes) - MongoDB/BSON compatible IDs, **DEFAULT**
785
- - **GuidV4Provider** (16 bytes) - RFC 4122 compliant GUIDs without dashes
786
- - **UuidProvider** (16 bytes) - Standard UUIDs with dash separators
787
- - **CustomIdProvider** (1-255 bytes) - User-defined ID sizes and formats
788
-
789
- ```typescript
790
- // Example: Using GUID provider
791
- import { createRuntimeConfiguration, GuidV4Provider } from '@digitaldefiance/ecies-lib';
792
-
793
- const config = createRuntimeConfiguration({
794
- idProvider: new GuidV4Provider(), // 16-byte GUIDs
795
- });
796
-
797
- const id = config.idProvider.generate(); // Generates 16-byte GUID
798
- ```
799
-
800
- **Auto-Sync Configuration System**
801
-
802
- All ID-size-related constants now automatically synchronize when an ID provider is set:
803
-
804
- - `MEMBER_ID_LENGTH`
805
- - `ECIES.MULTIPLE.RECIPIENT_ID_SIZE`
806
- - `idProvider.byteLength`
807
-
808
- This prevents the 12 vs 32-byte misconfiguration that existed in v3.0.8.
15
+ ## Features
809
16
 
810
- **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).
811
50
 
812
- Added comprehensive validation to catch configuration mismatches at initialization:
51
+ ## Installation
813
52
 
814
- ```typescript
815
- // Automatic validation prevents mismatched configurations
816
- const config = createRuntimeConfiguration({
817
- idProvider: new GuidV4Provider(), // 16 bytes
818
- MEMBER_ID_LENGTH: 12, // ❌ Throws error - mismatch detected!
819
- });
53
+ ```bash
54
+ npm install @digitaldefiance/ecies-lib
55
+ # or
56
+ yarn add @digitaldefiance/ecies-lib
820
57
  ```
821
58
 
822
- Invariants include:
823
-
824
- - `RecipientIdConsistency` - Ensures all ID size constants match
825
- - `Pbkdf2ProfilesValidity` - Validates PBKDF2 profile configuration
826
- - `EncryptionAlgorithmConsistency` - Validates encryption algorithm settings
827
-
828
- **Configuration Provenance Tracking**
829
-
830
- Track configuration lineage for debugging and compliance:
831
-
832
- ```typescript
833
- import { ConstantsRegistry } from '@digitaldefiance/ecies-lib';
834
-
835
- const config = ConstantsRegistry.register('production', {
836
- idProvider: new ObjectIdProvider(),
837
- }, {
838
- description: 'Production configuration with ObjectID',
839
- });
59
+ ### Requirements
840
60
 
841
- // Later, retrieve provenance info
842
- const provenance = ConstantsRegistry.getProvenance('production');
843
- console.log(provenance.timestamp); // When created
844
- console.log(provenance.checksum); // Configuration hash
845
- ```
61
+ **Node.js**: 18+ (Web Crypto API built-in)
62
+ **Browsers**: Modern browsers with Web Crypto API support.
846
63
 
847
- ---
64
+ ## Architecture & Protocol
848
65
 
849
- #### 🐛 Critical Bug Fixes
66
+ ### ECIES v4.0 Protocol Flow
850
67
 
851
- **Fixed 12 vs 32-Byte ID Discrepancy**
68
+ The library implements a robust ECIES variant designed for security and efficiency.
852
69
 
853
- - **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
854
- - **Root Cause:** Two separate constant definitions that were never validated against each other
855
- - **Fix:**
856
- - All recipient ID sizes now derive from `idProvider.byteLength`
857
- - Automatic validation prevents mismatches
858
- - Integration tests added to catch regressions
859
- - `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.
860
72
 
861
- **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
+ ```
862
80
 
863
- - **Issue:** Attempting to modify frozen `ENCRYPTION` constant with `Object.assign()` caused runtime errors
864
- - **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.
865
86
 
866
- **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.
867
92
 
868
- - **Issue:** Invalid PBKDF2 profile configuration could pass validation
869
- - **Fix:** Added comprehensive PBKDF2 profile validation in invariant system
93
+ ### ID Provider System
870
94
 
871
- **Fixed Disposed Object Error Messages**
95
+ The library is agnostic to the format of unique identifiers. The `IdProvider` system drives the entire configuration:
872
96
 
873
- - **Issue:** `DisposedError` had incorrect i18n string keys
874
- - **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).
875
101
 
876
- ---
102
+ When you configure an ID provider, the library automatically:
877
103
 
878
- #### 💥 Breaking Changes
104
+ - Updates `MEMBER_ID_LENGTH`.
105
+ - Updates `ECIES.MULTIPLE.RECIPIENT_ID_SIZE`.
106
+ - Validates that all internal constants are consistent.
879
107
 
880
- **1. Direct Constant Assignments Removed**
108
+ ## Quick Start
881
109
 
882
- **Before (v3.0.8):**
110
+ ### 1. Basic Configuration & Usage
883
111
 
884
112
  ```typescript
885
- const config = createRuntimeConfiguration({
886
- MEMBER_ID_LENGTH: 16,
887
- ECIES: {
888
- MULTIPLE: {
889
- RECIPIENT_ID_SIZE: 16,
890
- },
891
- },
892
- });
893
- ```
113
+ import {
114
+ ECIESService,
115
+ getEciesI18nEngine,
116
+ createRuntimeConfiguration,
117
+ ObjectIdProvider
118
+ } from '@digitaldefiance/ecies-lib';
894
119
 
895
- **After (v3.7.x):**
120
+ // 1. Initialize i18n (required once)
121
+ getEciesI18nEngine();
896
122
 
897
- ```typescript
123
+ // 2. Configure (Optional - defaults to ObjectIdProvider)
898
124
  const config = createRuntimeConfiguration({
899
- idProvider: new GuidV4Provider(), // Auto-syncs all size constants
125
+ idProvider: new ObjectIdProvider()
900
126
  });
901
- ```
902
-
903
- **2. Recipient ID Generation Changes**
904
-
905
- **Before:**
906
-
907
- ```typescript
908
- const recipientId = crypto.getRandomValues(new Uint8Array(32)); // Hardcoded
909
- ```
910
-
911
- **After:**
912
-
913
- ```typescript
914
- const recipientId = config.idProvider.generate(); // Dynamic sizing
915
- ```
916
-
917
- **3. Multi-Recipient Constants Function Signature**
918
-
919
- **Before:**
920
-
921
- ```typescript
922
- const constants = getMultiRecipientConstants(); // Used hardcoded 32
923
- ```
924
-
925
- **After:**
926
-
927
- ```typescript
928
- const constants = getMultiRecipientConstants(config.idProvider.byteLength); // Dynamic
929
- ```
930
-
931
- ---
932
-
933
- #### 📚 New Documentation
934
-
935
- - **docs/MIGRATION_GUIDE_v3.7.md** - Complete migration guide from v3.6.x/v3.0.8 to v3.7.x
936
- - **docs/ID_PROVIDER_ARCHITECTURE.md** - Deep dive into the ID provider system (implied)
937
- - **docs/ENTERPRISE_ARCHITECTURE_ASSESSMENT.md** - Enterprise-grade architecture recommendations
938
- - **docs/ENTERPRISE_READINESS_CHECKLIST.md** - Production readiness assessment
939
- - **docs/EXECUTIVE_SUMMARY.md** - Executive overview of ID provider system
940
- - **docs/ID_PROVIDER_TESTING.md** - Comprehensive testing documentation
941
- - **docs/ID_SYSTEM_IMPLEMENTATION_STATUS.md** - Implementation status and roadmap
942
- - **docs/MIGRATION_CHECKLIST_NODE_LIB.md** - Node.js library migration checklist
943
-
944
- ---
945
-
946
- #### 🧪 Testing Improvements
947
-
948
- **New Test Suites**
949
-
950
- - `tests/lib/id-providers/id-providers.spec.ts` - Basic provider functionality (314 lines)
951
- - `tests/lib/id-providers/id-providers-comprehensive.spec.ts` - Comprehensive provider validation (913 lines)
952
- - `tests/lib/invariant-validator.spec.ts` - Invariant system validation (250 lines)
953
- - `tests/lib/configuration-provenance.spec.ts` - Provenance tracking tests (215 lines)
954
- - `tests/integration/recipient-id-consistency.spec.ts` - Cross-configuration ID consistency (319 lines)
955
- - `tests/integration/encrypted-message-structure.spec.ts` - Message structure validation (490 lines)
956
- - `tests/errors/ecies-error-context.spec.ts` - Enhanced error context testing (337 lines)
957
-
958
- **Test Statistics**
959
-
960
- - **Total Tests:** 1,200+ (up from ~1,100)
961
- - **Test Pass Rate:** 100% (1,200/1,200)
962
- - **Test Suites:** 61 suites
963
- - **New Test Files:** 7
964
- - **Test Execution Time:** ~77 seconds
965
-
966
- **Test Coverage**
967
-
968
- - All 4 ID providers have comprehensive test coverage
969
- - Cross-provider compatibility tests
970
- - Encrypted message structure validation with different ID sizes
971
- - Performance benchmarks (serialization/deserialization <50ms for 1000 operations)
972
- - Constant-time comparison validation (timing attack resistance)
973
- - Invariant validation edge cases
974
-
975
- ---
976
-
977
- #### ⚡ Performance
978
-
979
- **ID Provider Benchmarks**
980
-
981
- All providers meet performance requirements:
982
-
983
- - **ObjectIdProvider:** ~40ms per 1000 operations
984
- - **GuidV4Provider:** ~45ms per 1000 operations
985
- - **UuidProvider:** ~45ms per 1000 operations
986
- - **CustomIdProvider:** ~40ms per 1000 operations
987
-
988
- **Performance Baselines**
989
-
990
- - Serialization: 1000 IDs in <50ms (relaxed from 20ms for CI stability)
991
- - Deserialization: 1000 IDs in <50ms (relaxed from 25ms for CI stability)
992
- - Constant-time comparison ratio: <15.0x (relaxed from 5.0x for CI variance)
993
-
994
- ---
995
-
996
- #### 🔒 Security Enhancements
997
-
998
- **Constant-Time Operations**
999
-
1000
- - All ID providers use constant-time comparison to prevent timing attacks
1001
- - Validation timing tests ensure consistent execution time regardless of input
1002
-
1003
- **Immutable Configuration**
1004
-
1005
- - All constants are deeply frozen to prevent accidental modification
1006
- - Configuration provenance tracking provides audit trail
1007
-
1008
- **Validation at Initialization**
1009
-
1010
- - Invariant validation catches misconfigurations before runtime
1011
- - Comprehensive error context for debugging
1012
127
 
1013
- ---
128
+ // 3. Initialize Service
129
+ const ecies = new ECIESService(config);
1014
130
 
1015
- #### 🌍 Internationalization
1016
-
1017
- **New Error Messages**
1018
-
1019
- Added i18n support for ID provider errors in 7 languages (en-US, fr, de, es, ja, uk, zh-cn):
1020
-
1021
- - `IdProviderInvalidByteLength` - Invalid byte length for ID provider
1022
- - `IdProviderInvalidIdFormat` - Invalid ID format
1023
- - `IdProviderIdValidationFailed` - ID validation failed
1024
- - `IdProviderSerializationFailed` - Serialization failed
1025
- - `IdProviderDeserializationFailed` - Deserialization failed
1026
- - `IdProviderInvalidStringLength` - Invalid string length
1027
- - `IdProviderInputMustBeUint8Array` - Input must be Uint8Array
1028
- - `IdProviderInputMustBeString` - Input must be string
1029
- - `IdProviderInvalidCharacters` - Invalid characters in input
1030
-
1031
- **Updated Error Messages**
1032
-
1033
- - Enhanced `DisposedError` with proper type enumeration
1034
- - Added context parameters to ECIES error messages
1035
- - Improved error message clarity across all services
1036
-
1037
- ---
1038
-
1039
- #### 📦 New Exports
1040
-
1041
- **ID Providers**
1042
-
1043
- ```typescript
1044
- export { ObjectIdProvider } from './lib/id-providers/objectid-provider';
1045
- export { GuidV4Provider } from './lib/id-providers/guidv4-provider';
1046
- export { UuidProvider } from './lib/id-providers/uuid-provider';
1047
- export { CustomIdProvider } from './lib/id-providers/custom-provider';
1048
- ```
131
+ // 4. Generate Keys
132
+ const mnemonic = ecies.generateNewMnemonic();
133
+ const { privateKey, publicKey } = ecies.mnemonicToSimpleKeyPair(mnemonic);
1049
134
 
1050
- **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);
1051
139
 
1052
- ```typescript
1053
- export type { IIdProvider } from './interfaces/id-provider';
1054
- export { BaseIdProvider } from './interfaces/id-provider';
1055
- export type { IInvariant } from './interfaces/invariant';
1056
- export { BaseInvariant } from './interfaces/invariant';
1057
- export type { IConfigurationProvenance } from './interfaces/configuration-provenance';
140
+ console.log(new TextDecoder().decode(decrypted)); // "Hello, Secure World!"
1058
141
  ```
1059
142
 
1060
- **Validation**
143
+ ### 2. Using Custom ID Providers (e.g., GUID)
1061
144
 
1062
145
  ```typescript
1063
- export { InvariantValidator } from './lib/invariant-validator';
1064
- export { RecipientIdConsistencyInvariant } from './lib/invariants/recipient-id-consistency';
1065
- export { Pbkdf2ProfilesValidityInvariant } from './lib/invariants/pbkdf2-profiles-validity';
1066
- export { EncryptionAlgorithmConsistencyInvariant } from './lib/invariants/encryption-algorithm-consistency';
1067
- ```
146
+ import {
147
+ createRuntimeConfiguration,
148
+ GuidV4Provider,
149
+ ECIESService
150
+ } from '@digitaldefiance/ecies-lib';
1068
151
 
1069
- **Errors**
152
+ // Configure to use 16-byte GUIDs
153
+ const config = createRuntimeConfiguration({
154
+ idProvider: new GuidV4Provider()
155
+ });
1070
156
 
1071
- ```typescript
1072
- export { IdProviderError } from './errors/id-provider';
1073
- export { IdProviderErrorType } from './enumerations/id-provider-error-type';
1074
- export { DisposedErrorType } from './enumerations/disposed-error-type';
157
+ const ecies = new ECIESService(config);
158
+ const id = config.idProvider.generate(); // Returns 16-byte Uint8Array
1075
159
  ```
1076
160
 
1077
- ---
1078
-
1079
- #### 🔧 Code Structure Changes
1080
-
1081
- **New Files Added (7,611 insertions)**
1082
-
1083
- Core Implementation:
1084
-
1085
- - `src/lib/id-providers/objectid-provider.ts` (97 lines)
1086
- - `src/lib/id-providers/guidv4-provider.ts` (122 lines)
1087
- - `src/lib/id-providers/uuid-provider.ts` (117 lines)
1088
- - `src/lib/id-providers/custom-provider.ts` (165 lines)
1089
- - `src/lib/id-providers/index.ts` (31 lines)
1090
-
1091
- Validation System:
1092
-
1093
- - `src/lib/invariant-validator.ts` (133 lines)
1094
- - `src/lib/invariants/recipient-id-consistency.ts` (46 lines)
1095
- - `src/lib/invariants/pbkdf2-profiles-validity.ts` (78 lines)
1096
- - `src/lib/invariants/encryption-algorithm-consistency.ts` (73 lines)
1097
-
1098
- Interfaces:
1099
-
1100
- - `src/interfaces/id-provider.ts` (117 lines)
1101
- - `src/interfaces/invariant.ts` (60 lines)
1102
- - `src/interfaces/configuration-provenance.ts` (72 lines)
1103
-
1104
- Errors:
1105
-
1106
- - `src/errors/id-provider.ts` (40 lines)
1107
- - `src/enumerations/id-provider-error-type.ts` (50 lines)
1108
- - `src/enumerations/disposed-error-type.ts` (11 lines)
1109
-
1110
- **Major File Modifications**
161
+ ### 3. Streaming Encryption (Large Files)
1111
162
 
1112
- - `src/constants.ts` (+115 lines) - Added ID provider integration and auto-sync
1113
- - `src/interfaces/constants.ts` (+27 lines) - Extended with ID provider field
1114
- - `src/interfaces/multi-recipient-chunk.ts` (+69 lines) - Dynamic size calculation
1115
- - `src/services/multi-recipient-processor.ts` (+72 lines) - ID provider integration
1116
- - `src/services/encryption-stream.ts` (+18 lines) - Dynamic size support
1117
- - `src/secure-buffer.ts` (+28 lines) - Enhanced disposal handling
1118
- - `src/errors/ecies.ts` (+107 lines) - New error types with context
1119
-
1120
- **Translation Updates**
1121
-
1122
- Updated all 7 language files with new error messages:
1123
-
1124
- - `src/translations/en-US.ts` (+22 lines)
1125
- - `src/translations/fr.ts` (+26 lines)
1126
- - `src/translations/de.ts` (+22 lines)
1127
- - `src/translations/es.ts` (+28 lines)
1128
- - `src/translations/ja.ts` (+21 lines)
1129
- - `src/translations/uk.ts` (+24 lines)
1130
- - `src/translations/zh-cn.ts` (+27 lines)
1131
-
1132
- ---
1133
-
1134
- #### 🔄 Migration Guide
1135
-
1136
- **For Default Users (No Changes Needed)**
1137
-
1138
- 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).
1139
164
 
1140
165
  ```typescript
1141
- // v3.0.8 - Still works in v3.7.x!
1142
- import { ECIESService } from '@digitaldefiance/ecies-lib';
166
+ import { ECIESService, EncryptionStream } from '@digitaldefiance/ecies-lib';
1143
167
 
1144
168
  const ecies = new ECIESService();
1145
- const encrypted = await ecies.encrypt(data, publicKey);
1146
- ```
1147
-
1148
- **For Custom ID Size Users**
1149
-
1150
- If you were customizing ID sizes in v3.0.8:
1151
-
1152
- ```typescript
1153
- // v3.0.8 (OLD - BREAKS in v3.7.x)
1154
- const config = createRuntimeConfiguration({
1155
- MEMBER_ID_LENGTH: 16,
1156
- });
1157
-
1158
- // v3.7.x (NEW)
1159
- import { GuidV4Provider } from '@digitaldefiance/ecies-lib';
1160
-
1161
- const config = createRuntimeConfiguration({
1162
- idProvider: new GuidV4Provider(),
1163
- });
1164
- ```
1165
-
1166
- **Creating Custom ID Providers**
1167
-
1168
- ```typescript
1169
- import { BaseIdProvider } from '@digitaldefiance/ecies-lib';
169
+ const stream = new EncryptionStream(ecies);
1170
170
 
1171
- class MyCustomProvider extends BaseIdProvider {
1172
- constructor() {
1173
- super('MyCustom', 24, 'My 24-byte custom IDs');
1174
- }
1175
-
1176
- generate(): Uint8Array {
1177
- return crypto.getRandomValues(new Uint8Array(24));
1178
- }
1179
-
1180
- validate(id: Uint8Array): boolean {
1181
- return id.length === 24;
1182
- }
171
+ // Assuming 'fileStream' is a ReadableStream from a File object
172
+ async function processFile(fileStream: ReadableStream, publicKey: Uint8Array) {
173
+ const encryptedChunks: Uint8Array[] = [];
1183
174
 
1184
- serialize(id: Uint8Array): string {
1185
- return Array.from(id).map(b => b.toString(16).padStart(2, '0')).join('');
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
1186
179
  }
1187
180
 
1188
- deserialize(str: string): Uint8Array {
1189
- const bytes = new Uint8Array(24);
1190
- for (let i = 0; i < 24; i++) {
1191
- bytes[i] = parseInt(str.substr(i * 2, 2), 16);
1192
- }
1193
- return bytes;
1194
- }
181
+ return encryptedChunks;
1195
182
  }
1196
183
  ```
1197
184
 
1198
- ---
1199
-
1200
- #### 📊 Version Details
1201
-
1202
- **v3.7.3**
1203
-
1204
- - Removed Legacy32ByteProvider from all code and documentation
1205
- - Fixed test failures from Legacy32ByteProvider removal
1206
- - Updated migration guides to only show supported providers
1207
- - Relaxed timing test thresholds for CI stability (15.0x ratio, 50ms thresholds)
1208
-
1209
- **v3.7.2**
1210
-
1211
- - Initial release of ID provider system
1212
- - Added comprehensive documentation
1213
- - Full test suite with 1,200+ tests
1214
-
1215
- ---
1216
-
1217
- #### 🙏 Contributors
1218
-
1219
- - Jessica Mulein (@JessicaMulein) - Lead developer
1220
- - GitHub Copilot - Architecture review and code assistance
1221
-
1222
- ---
1223
-
1224
- #### 📝 Release Statistics
1225
-
1226
- - **Lines of code changed:** ~7,600 additions, ~135 deletions
1227
- - **Files modified:** 61
1228
- - **New test files:** 7
1229
- - **New source files:** 14
1230
- - **Documentation added:** ~3,800 lines
1231
- - **Tests added:** 100+
1232
- - **Test pass rate:** 100% (1,200/1,200)
1233
-
1234
- ---
1235
-
1236
- ### v3.0.8
1237
-
1238
- - Update i18n
1239
-
1240
- ### v3.0.7
1241
-
1242
- - Update i18n
1243
-
1244
- ### v3.0.6
1245
-
1246
- - Update i18n
1247
-
1248
- ### v3.0.5
1249
-
1250
- - Update i18n
1251
-
1252
- ### v3.0.4
1253
-
1254
- - Fix EmailString usage of InvalidEmailError
1255
-
1256
- ### v3.0.3
1257
-
1258
- - Slight tweak to InvalidEmailError
1259
-
1260
- ### v3.0.2
1261
-
1262
- - Update test-utils
1263
-
1264
- ### v3.0.1
1265
-
1266
- - Fix strings mainly
1267
- - add service.encryptMultiple endpoint, clarify service.encrypt endpoint
1268
-
1269
- ### v3.0.0 - Streaming Encryption & Security Hardening
1270
-
1271
- **Major Features**:
185
+ ### 4. Member System
1272
186
 
1273
- - **Streaming Encryption**: Memory-efficient encryption for large files (<10MB RAM for any size)
1274
- - 🔐 **Multi-Recipient Streaming**: Encrypt once for up to 65,535 recipients with shared symmetric key
1275
- - 📊 **Progress Tracking**: Real-time throughput, ETA, and completion percentage
1276
- - 🔒 **Security Hardening**: 16 comprehensive security validations across all layers
1277
- - ✅ **AsyncGenerator API**: Flexible streaming with cancellation support
1278
- - 🎯 **100% Test Coverage**: 646/646 tests passing, 52/52 suites
187
+ The `Member` class provides a high-level user abstraction that integrates keys, IDs, and encryption.
1279
188
 
1280
- **New APIs**:
1281
-
1282
- **Single-Recipient Streaming**:
1283
-
1284
- - `EncryptionStream.encryptStream()` - Stream encryption with configurable chunks
1285
- - `EncryptionStream.decryptStream()` - Stream decryption with validation
1286
- - `Member.encryptDataStream()` - Member-level streaming encryption
1287
- - `Member.decryptDataStream()` - Member-level streaming decryption
1288
-
1289
- **Multi-Recipient Streaming**:
1290
-
1291
- - `EncryptionStream.encryptStreamMultiple()` - Encrypt for multiple recipients
1292
- - `EncryptionStream.decryptStreamMultiple()` - Decrypt as specific recipient
1293
- - `MultiRecipientProcessor.encryptChunk()` - Low-level multi-recipient encryption
1294
- - `MultiRecipientProcessor.decryptChunk()` - Low-level multi-recipient decryption
1295
-
1296
- **Progress Tracking**:
1297
-
1298
- - `ProgressTracker.update()` - Track bytes processed, throughput, ETA
1299
- - `IStreamProgress` interface with `throughputBytesPerSec` property
1300
- - Optional progress callbacks in all streaming operations
1301
-
1302
- **Security Enhancements (16 validations)**:
1303
-
1304
- **Base ECIES Layer (8 fixes)**:
1305
-
1306
- - Public key all-zeros validation
1307
- - Private key all-zeros validation
1308
- - Shared secret all-zeros validation
1309
- - Message size validation (max 2GB)
1310
- - Encrypted size bounds checking
1311
- - Minimum encrypted data size validation
1312
- - Component extraction validation
1313
- - Decrypted data validation
1314
-
1315
- **AES-GCM Layer (5 fixes)**:
1316
-
1317
- - Key length validation (16/24/32 bytes only)
1318
- - IV length validation (16 bytes)
1319
- - Null/undefined data rejection
1320
- - Data size validation (max 2GB)
1321
- - Comprehensive decrypt input validation
1322
-
1323
- **Multi-Recipient Layer (3 fixes)**:
1324
-
1325
- - Chunk index bounds checking (uint32 range)
1326
- - Data size validation (max 2GB)
1327
- - Safe accumulation with overflow detection
1328
-
1329
- **Performance**:
1330
-
1331
- - 99% memory reduction (1GB file: 1GB RAM → <10MB RAM)
1332
- - < 0.1% overhead from security validations
1333
- - Independent chunk encryption (resumability ready)
1334
- - Chunk sequence validation (prevents reordering attacks)
1335
- - Optional SHA-256 checksums (in addition to AES-GCM auth)
1336
- - Single symmetric key per stream (not per chunk)
1337
-
1338
- **Multi-Recipient Features**:
1339
-
1340
- - Maximum 65,535 recipients supported
1341
- - 32-byte recipient IDs required
1342
- - Shared symmetric key encrypted per recipient
1343
- - Efficient header format with recipient metadata
1344
- - Buffer overflow protection (100MB max per source chunk)
1345
-
1346
- **New Error Types**:
1347
-
1348
- - `InvalidAESKeyLength` - AES key must be 16/24/32 bytes
1349
- - `CannotEncryptEmptyData` - Empty/null data rejected
1350
- - `CannotDecryptEmptyData` - Empty/null encrypted data rejected
1351
- - `EncryptedSizeExceedsExpected` - Encrypted output too large
1352
- - `InvalidChunkIndex` - Chunk index out of uint32 range
1353
- - `HeaderSizeOverflow` - Recipient header size overflow
1354
-
1355
- **Documentation**:
1356
-
1357
- - Added `docs/STREAMING_ENCRYPTION_ARCHITECTURE.md`
1358
- - Added `docs/STREAMING_API_QUICKSTART.md`
1359
- - Added `docs/PHASE_1_COMPLETE.md`
1360
- - Added `ECIES_STREAMING_CHANGES_SUMMARY.md` (for node-ecies porting)
1361
- - Updated README with streaming and multi-recipient examples
1362
-
1363
- **Test Coverage**:
1364
-
1365
- - 646 tests passing (100%)
1366
- - 52 test suites passing (100%)
1367
- - 5 multi-recipient streaming tests
1368
- - 87+ streaming tests (unit + integration + e2e)
1369
- - All 16 security validations covered
1370
- - Error coverage validation updated
1371
-
1372
- ### v2.1.42
1373
-
1374
- - Fix Hmac constant
1375
-
1376
- ### v2.1.40
1377
-
1378
- - Alignment with Express Suite packages
1379
- - All packages updated to v2.1.40 (i18n, ecies-lib, node-ecies-lib, suite-core-lib, node-express-suite, express-suite-react-components)
1380
- - Test utilities remain at v1.0.7
1381
- - `/testing` entry point exports test mocks (mockFrontendMember)
1382
- - Requires `@faker-js/faker` as dev dependency for test utilities
1383
-
1384
- ## v2.1.39 - Update test-utils dep
1385
-
1386
- ## v2.1.38 - Export test mock for frontend member
1387
-
1388
- ## v2.1.32 - Config on i18n create
1389
-
1390
- ## v2.1.30 - Alignment bump
1391
-
1392
- ## v2.1.26 - use new express-suite-test-utils
1393
-
1394
- ## v2.1.25 - Upgrade i18n, mostly testing improvements
189
+ ```typescript
190
+ import { Member, MemberType, EmailString } from '@digitaldefiance/ecies-lib';
1395
191
 
1396
- ## 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
+ );
1397
199
 
1398
- ## v2.1.16 - upgrade i18n
200
+ console.log(member.id); // Uint8Array (size depends on provider)
1399
201
 
1400
- ## v2.1.15 - upgrade i18n
202
+ // Encrypt data for this member
203
+ const encrypted = await member.encryptData('My Secrets');
204
+ ```
1401
205
 
1402
- ## v2.1.12 - upgrade i18n
206
+ ## API Reference
1403
207
 
1404
- ### v2.1.10 - Convergence bump
208
+ ### Core Services
1405
209
 
1406
- ### 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.
1407
215
 
1408
- ### v2.1.6 - minor version bump from i18n lib
216
+ ### Configuration & Registry
1409
217
 
1410
- ### 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.
1411
223
 
1412
- ### v2.1.4 - minor version bump from i18n lib
224
+ ### Secure Primitives
1413
225
 
1414
- ### 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.
1415
230
 
1416
- ### v2.1.2 - add faux GUID support for MongoDB ObjectIds
231
+ ## Development
1417
232
 
1418
- ### v2.1.1 - upgrade to match i18n, upgrade error classes, deprecate Plu1inI8nEngine
233
+ ### Commands
1419
234
 
1420
- ### 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
+ ```
1421
242
 
1422
- ### v2.0.2 - version bump/update i18n
243
+ ### Testing
1423
244
 
1424
- ### 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:
1425
246
 
1426
- ### 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.
1427
251
 
1428
- **Release Date**: January 2025
252
+ ## ChangeLog
1429
253
 
1430
- **Major Changes**:
254
+ ### v4.1.1
1431
255
 
1432
- - 🎉 **i18n v2.0**: Automatic error translation with singleton pattern
1433
- - ✨ **Simplified APIs**: Removed engine parameters from all service constructors
1434
- - 🔧 **Breaking**: `Pbkdf2Service`, `PasswordLoginService` constructors changed
1435
- - 📚 **Documentation**: Added comprehensive migration guides
1436
- - ✅ **Testing**: 393/393 tests passing (100%)
256
+ - Tweak to objectId provider to make generate() more robust
1437
257
 
1438
- **Migration Required**: See [Migration Guide](./docs/I18N_V2_MIGRATION_GUIDE.md)
258
+ ### v4.1.0
1439
259
 
1440
- **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`).
1441
262
 
1442
- - `Pbkdf2Service(profiles?, eciesParams?, pbkdf2Params?)` - removed engine parameter
1443
- - `PasswordLoginService(ecies, pbkdf2, eciesParams?)` - removed engine parameter
263
+ ### v4.0.0 - ECIES Protocol v4.0
1444
264
 
1445
- **New Features**:
265
+ #### Major Protocol Upgrade (Breaking Change)
1446
266
 
1447
- - Automatic i18n engine retrieval via singleton
1448
- - Unified index exports (v1 + v2 architecture)
1449
- - 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).
1450
272
 
1451
- **Bug Fixes**:
273
+ ### v3.7.0 - Pluggable ID Provider System
1452
274
 
1453
- - Fixed PBKDF2 profile lookup issues
1454
- - Resolved test initialization timing problems
1455
- - 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.
1456
278
 
1457
- **Documentation**:
279
+ ### v3.0.0 - Streaming Encryption
1458
280
 
1459
- - Added `docs/I18N_V2_MIGRATION_GUIDE.md`
1460
- - Added `docs/LESSONS_LEARNED.md`
1461
- - Added `docs/NODE_ECIES_MIGRATION_GUIDE.md`
1462
- - Updated README with v2.0 examples
281
+ - **Memory Efficiency**: Streaming support for large datasets.
282
+ - **Progress Tracking**: Real-time throughput and ETA monitoring.
1463
283
 
1464
- **Performance**:
284
+ ### v2.0.0 - i18n Architecture
1465
285
 
1466
- - No degradation: 44s test suite (vs 45s in v1.x)
1467
- - Reduced code complexity by 40%
1468
- - Eliminated parameter threading overhead
286
+ - **Singleton i18n**: Simplified service instantiation.
287
+ - **Translation**: Error messages in 8 languages.
1469
288
 
1470
289
  ### v1.3.27 and Earlier
1471
290
 
@@ -1691,3 +510,14 @@ class MyCustomProvider extends BaseIdProvider {
1691
510
  - Fri Sep 26 2025 10:21:00 GMT-0700 (Pacific Daylight Time)
1692
511
 
1693
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
+