@digitaldefiance/node-ecies-lib 4.10.6 → 4.10.8

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,13 +2,13 @@
2
2
 
3
3
  [![npm version](https://badge.fury.io/js/%40digitaldefiance%2Fnode-ecies-lib.svg)](https://www.npmjs.com/package/@digitaldefiance/node-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-220%2B%20passing-brightgreen)](https://github.com/Digital-Defiance/ecies-lib)
5
+ [![Tests](https://img.shields.io/badge/tests-1100%2B%20passing-brightgreen)](https://github.com/Digital-Defiance/ecies-lib)
6
6
 
7
7
  A Node.js-specific implementation of the Digital Defiance ECIES (Elliptic Curve Integrated Encryption Scheme) library, providing secure encryption, decryption, and key management capabilities using Node.js crypto primitives. This package is designed to be binary compatible with similarly numbered releases of the browser-based `@digitaldefiance/ecies-lib`, enabling seamless cross-platform cryptographic operations.
8
8
 
9
9
  Part of [Express Suite](https://github.com/Digital-Defiance/express-suite)
10
10
 
11
- > Current Version: v4.7.14
11
+ > Current Version: v4.10.6
12
12
 
13
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.
14
14
 
@@ -52,8 +52,9 @@ This library implements a modern, enterprise-grade ECIES protocol (v4.0) featuri
52
52
 
53
53
  A comprehensive voting system built on homomorphic encryption with 17 voting methods and 1100+ test cases:
54
54
 
55
- - **Fully Secure Methods**: Plurality, Approval, Weighted, Borda Count, Score, Yes/No, Supermajority
56
- - **Multi-Round Methods**: Ranked Choice (IRV), Two-Round, STAR, STV
55
+ - **All 17 Methods Fully Implemented**: Plurality, Approval, Weighted, Borda Count, Score, Yes/No, Yes/No/Abstain, Supermajority, Ranked Choice (IRV), Two-Round, STAR, STV, Quadratic, Consensus, Consent-Based
56
+ - **Node.js Optimized**: Uses Buffer instead of Uint8Array for better Node.js performance
57
+ - **Extended PlatformID**: Supports Buffer and mongoose ObjectId in addition to base types
57
58
  - **Core Security Features**:
58
59
  - Homomorphic encryption (Paillier cryptosystem) - votes remain encrypted until tally
59
60
  - Verifiable receipts with ECDSA signatures
@@ -63,6 +64,7 @@ A comprehensive voting system built on homomorphic encryption with 17 voting met
63
64
  - Role separation (poll aggregator cannot decrypt votes)
64
65
  - Double-vote prevention
65
66
  - **Government Requirements (EARS)**: Audit Log, Bulletin Board, Event Logger
67
+ - **Cross-Platform Compatible**: 100% binary compatible with browser implementation
66
68
 
67
69
  See [Voting System Documentation](src/lib/voting/README.md) for complete details.
68
70
 
@@ -161,7 +163,89 @@ const decrypted = ecies.decryptSimpleOrSingleWithHeader(false, privateKey, encry
161
163
  console.log(decrypted.toString()); // "Hello, Secure World!"
162
164
  ```
163
165
 
164
- ### 2. Using Custom ID Providers (e.g., GUID)
166
+ ### 2. Strong Typing with ID Providers (New in v4.10.7)
167
+
168
+ The Node.js library now includes a comprehensive strong typing system for ID providers, eliminating the need for manual type casting and providing compile-time type safety.
169
+
170
+ #### The Problem (Before v4.10.7)
171
+
172
+ ```typescript
173
+ const Constants = getNodeRuntimeConfiguration();
174
+ const id = Constants.idProvider.generate(); // Returns Uint8Array (no strong typing)
175
+ const obj = Constants.idProvider.fromBytes(bytes); // Returns unknown (requires casting)
176
+ ```
177
+
178
+ #### The Solution (v4.10.7+)
179
+
180
+ **Enhanced Provider (Drop-in Replacement):**
181
+ ```typescript
182
+ import { getEnhancedNodeIdProvider } from '@digitaldefiance/node-ecies-lib';
183
+
184
+ const provider = getEnhancedNodeIdProvider<ObjectId>();
185
+ const id = provider.generateTyped(); // Returns ObjectId (strongly typed)
186
+ const obj = provider.fromBytesTyped(bytes); // Returns ObjectId (no casting needed)
187
+
188
+ // Original methods still work for backward compatibility
189
+ const rawBytes = provider.generate(); // Returns Uint8Array
190
+ ```
191
+
192
+ **Simple Typed Provider (Clean API):**
193
+ ```typescript
194
+ import { getTypedNodeIdProvider } from '@digitaldefiance/node-ecies-lib';
195
+
196
+ const provider = getTypedNodeIdProvider<ObjectId>();
197
+ const id = provider.generateTyped(); // Returns ObjectId
198
+ const bytes = provider.toBytesTyped(id); // Type-safe conversion
199
+ const restored = provider.fromBytesTyped(bytes); // Type-safe restoration
200
+ ```
201
+
202
+ **Complete Typed Configuration:**
203
+ ```typescript
204
+ import { createNodeObjectIdConfiguration } from '@digitaldefiance/node-ecies-lib';
205
+
206
+ const config = createNodeObjectIdConfiguration();
207
+ const objectId = config.generateId(); // Returns ObjectId (strongly typed)
208
+ const bytes = config.idToBytes(objectId); // Convert to bytes
209
+ const restored = config.idFromBytes(bytes); // Convert back to ObjectId
210
+
211
+ // Access full Node.js runtime configuration
212
+ const constants = config.constants; // Complete IConstants with ObjectIdProvider
213
+ ```
214
+
215
+ **Custom Provider Types:**
216
+ ```typescript
217
+ import {
218
+ createNodeTypedConfiguration,
219
+ GuidV4Provider,
220
+ UuidProvider
221
+ } from '@digitaldefiance/node-ecies-lib';
222
+
223
+ // GUID configuration
224
+ const guidConfig = createNodeTypedConfiguration<string>({
225
+ idProvider: new GuidV4Provider()
226
+ });
227
+ const guidId = guidConfig.generateId(); // Returns GUID object (strongly typed)
228
+
229
+ // UUID configuration
230
+ const uuidConfig = createNodeTypedConfiguration<string>({
231
+ idProvider: new UuidProvider()
232
+ });
233
+ const uuidId = uuidConfig.generateId(); // Returns UUID string (strongly typed)
234
+ ```
235
+
236
+ **Integration with ECIESService:**
237
+ ```typescript
238
+ import { ECIESService, createNodeObjectIdConfiguration } from '@digitaldefiance/node-ecies-lib';
239
+
240
+ const config = createNodeObjectIdConfiguration();
241
+ const service = new ECIESService(config.constants);
242
+
243
+ // Service uses the configured typed provider
244
+ console.log(service.idProvider.name); // "ObjectID"
245
+ console.log(service.idProvider.byteLength); // 12
246
+ ```
247
+
248
+ ### 3. Using Custom ID Providers (e.g., GUID)
165
249
 
166
250
  ```typescript
167
251
  import {
@@ -196,7 +280,7 @@ const ecies2 = new ECIESService({
196
280
  const ecies3 = new ECIESService();
197
281
  ```
198
282
 
199
- ### 3. Streaming Encryption (Large Files)
283
+ ### 4. Streaming Encryption (Large Files)
200
284
 
201
285
  Encrypt gigabytes of data with minimal memory footprint (<10MB).
202
286
 
@@ -221,7 +305,71 @@ async function processFile(filePath: string, publicKey: Buffer) {
221
305
  }
222
306
  ```
223
307
 
224
- ### 4. Member System
308
+ ### 5. Voting System (Node.js Optimized)
309
+
310
+ The Node.js voting system extends the browser implementation with Buffer support and mongoose integration:
311
+
312
+ ```typescript
313
+ import { Member, MemberType } from '@digitaldefiance/node-ecies-lib';
314
+ import { EmailString } from '@digitaldefiance/ecies-lib';
315
+ import {
316
+ PollFactory,
317
+ VoteEncoder,
318
+ PollTallier,
319
+ VotingMethod
320
+ } from '@digitaldefiance/node-ecies-lib';
321
+
322
+ const ecies = new ECIESService();
323
+
324
+ // Create authority with voting keys
325
+ const { member: authority, mnemonic } = Member.newMember(
326
+ ecies,
327
+ MemberType.System,
328
+ 'Election Authority',
329
+ new EmailString('authority@example.com')
330
+ );
331
+ await authority.deriveVotingKeys();
332
+
333
+ // Create poll (returns Node.js Poll with Buffer support)
334
+ const poll = PollFactory.createPlurality(
335
+ ['Alice', 'Bob', 'Charlie'],
336
+ authority
337
+ );
338
+
339
+ // Create voter and cast vote
340
+ const { member: voter } = Member.newMember(
341
+ ecies,
342
+ MemberType.User,
343
+ 'Voter',
344
+ new EmailString('voter@example.com')
345
+ );
346
+ await voter.deriveVotingKeys();
347
+
348
+ // Vote encoding uses Buffer internally
349
+ const encoder = new VoteEncoder(authority.votingPublicKey!);
350
+ const vote = encoder.encodePlurality(0, 3); // Vote for Alice
351
+ const receipt = poll.vote(voter, vote);
352
+
353
+ // Close and tally
354
+ poll.close();
355
+ const tallier = new PollTallier(
356
+ authority,
357
+ authority.votingPrivateKey!,
358
+ authority.votingPublicKey!
359
+ );
360
+ const results = tallier.tally(poll);
361
+
362
+ console.log('Winner:', results.choices[results.winner!]);
363
+ console.log('Tallies:', results.tallies);
364
+ ```
365
+
366
+ **Node.js Voting Features:**
367
+ - **All 17 Methods**: Complete implementation of all voting methods
368
+ - **Buffer Optimization**: Uses Node.js Buffer instead of Uint8Array for better performance
369
+ - **Mongoose Integration**: Extended PlatformID supports `Types.ObjectId`
370
+ - **Cross-Platform**: 100% binary compatible with browser voting system
371
+ - **File Persistence**: Can save/load encrypted votes to/from disk
372
+ - **Stream Processing**: Handle large voter datasets using Node.js streams
225
373
 
226
374
  The `Member` class provides a high-level user abstraction that integrates keys, IDs, and encryption.
227
375
 
@@ -245,7 +393,7 @@ console.log(member.id); // Buffer (size depends on provider)
245
393
  const encrypted = member.encryptData('My Secrets');
246
394
  ```
247
395
 
248
- ## API Reference
396
+ ### 6. Member System
249
397
 
250
398
  ### Core Services
251
399
 
@@ -274,17 +422,22 @@ const encrypted = member.encryptData('My Secrets');
274
422
 
275
423
  ### Voting System
276
424
 
277
- - **`Poll`**: Core poll with vote aggregation and receipt issuance.
425
+ - **`Poll`**: Core poll with vote aggregation and receipt issuance (generic over PlatformID, defaults to Buffer).
278
426
  - **`VotingPoll`**: High-level voting with encrypted receipts.
279
- - **`PollTallier`**: Decrypts and tallies votes (holds private key).
280
- - **`VoteEncoder`**: Encrypts votes using Paillier homomorphic encryption.
281
- - **`PollFactory`**: Convenient poll creation with method-specific configurations.
427
+ - **`PollTallier`**: Decrypts and tallies votes (holds private key, generic over PlatformID).
428
+ - **`VoteEncoder`**: Encrypts votes using Paillier homomorphic encryption (extends browser VoteEncoder with Buffer specialization).
429
+ - **`PollFactory`**: Convenient poll creation with method-specific configurations (extends browser PollFactory).
282
430
  - **`VotingSecurityValidator`**: Security level validation and enforcement.
283
431
  - **`ImmutableAuditLog`**: Hash-chained audit trail for compliance.
284
432
  - **`PublicBulletinBoard`**: Append-only vote publication with Merkle tree.
285
433
  - **`PollEventLogger`**: Event tracking with microsecond timestamps.
286
434
  - **`VotingMethod`**: Enum with all 17 voting methods.
287
435
  - **`SecurityLevel`**: Enum for security classifications (FullyHomomorphic, MultiRound, Insecure).
436
+ - **`EncryptedVote<TID extends PlatformID>`**: Encrypted vote structure with generic ID support (defaults to Buffer).
437
+ - **`PollResults<TID extends PlatformID>`**: Tally results with winner(s) and generic ID support (defaults to Buffer).
438
+ - **`VoteReceipt`**: Cryptographic vote receipt with signature verification.
439
+
440
+ ## API Reference
288
441
 
289
442
  ## Development
290
443
 
@@ -302,12 +455,13 @@ yarn format # Fix all (prettier + lint)
302
455
 
303
456
  ### Testing Approach
304
457
 
305
- The node-ecies-lib package uses comprehensive testing with 220+ tests covering all Node.js-specific cryptographic operations and binary compatibility with the browser-based ecies-lib.
458
+ The node-ecies-lib package uses comprehensive testing with 1100+ tests covering all Node.js-specific cryptographic operations, complete voting system functionality, and binary compatibility with the browser-based ecies-lib.
306
459
 
307
460
  **Test Framework**: Jest with TypeScript support
308
461
  **Property-Based Testing**: fast-check for cryptographic properties
309
462
  **Coverage Target**: 90%+ for all cryptographic operations
310
- **Binary Compatibility**: Verified with @digitaldefiance/ecies-lib
463
+ **Binary Compatibility**: Verified with @digitaldefiance/ecies-lib
464
+ **Voting System**: Complete test coverage for all 17 voting methods
311
465
 
312
466
  ### Test Structure
313
467
 
@@ -317,7 +471,19 @@ tests/
317
471
  ├── integration/ # Integration tests for protocol flows
318
472
  ├── e2e/ # End-to-end encryption/decryption tests
319
473
  ├── compatibility/ # Cross-platform compatibility with ecies-lib
320
- └── streaming/ # Streaming encryption tests
474
+ ├── streaming/ # Streaming encryption tests
475
+ └── voting/ # Voting system tests (Node.js specific)
476
+ ├── voting.spec.ts # Core voting functionality
477
+ ├── voting-stress.spec.ts # Stress tests with large datasets
478
+ ├── poll-core.spec.ts # Poll core functionality
479
+ ├── poll-audit.spec.ts # Audit log integration
480
+ ├── factory.spec.ts # Poll factory methods
481
+ ├── encoder.spec.ts # Vote encoding for all methods
482
+ ├── security.spec.ts # Security validation
483
+ ├── audit.spec.ts # Immutable audit log
484
+ ├── bulletin-board.spec.ts # Public bulletin board
485
+ ├── event-logger.spec.ts # Event logging system
486
+ └── cross-platform-encryption.pbt.spec.ts # Cross-platform voting compatibility
321
487
  ```
322
488
 
323
489
  ### Running Tests
@@ -487,6 +653,115 @@ describe('Integration with suite-core-lib', () => {
487
653
 
488
654
  ## ChangeLog
489
655
 
656
+ ### v4.10.7 - Strong Typing for ID Providers
657
+
658
+ **Major Features:**
659
+ - **Strong Typing System**: Added comprehensive strong typing for Node.js ID provider operations
660
+ - `getEnhancedNodeIdProvider<T>()`: Drop-in replacement with both original and typed methods
661
+ - `getTypedNodeIdProvider<T>()`: Simple typed provider with minimal API surface
662
+ - `createNodeTypedConfiguration<T>()`: Complete typed configuration wrapper
663
+ - `createNodeObjectIdConfiguration()`: Pre-configured ObjectId setup
664
+ - **Type Safety Benefits**: Eliminates manual casting and provides compile-time type safety
665
+ - `generateTyped()`: Returns strongly-typed IDs (ObjectId, string, etc.)
666
+ - `fromBytesTyped()`: Type-safe byte conversion without casting
667
+ - `toBytesTyped()`, `serializeTyped()`, `deserializeTyped()`: Complete typed API
668
+ - **Backward Compatibility**: Enhanced providers include original methods for seamless migration
669
+ - **Integration Ready**: Works seamlessly with ECIESService and Member system
670
+
671
+ **Usage Examples:**
672
+ ```typescript
673
+ // Enhanced provider (drop-in replacement)
674
+ const provider = getEnhancedNodeIdProvider<ObjectId>();
675
+ const id = provider.generateTyped(); // Returns ObjectId (strongly typed)
676
+
677
+ // Complete typed configuration
678
+ const config = createNodeObjectIdConfiguration();
679
+ const objectId = config.generateId(); // Returns ObjectId
680
+ const bytes = config.idToBytes(objectId); // Type-safe conversion
681
+
682
+ // Custom provider types
683
+ const guidConfig = createNodeTypedConfiguration<string>({
684
+ idProvider: new GuidV4Provider()
685
+ });
686
+ const guidId = guidConfig.generateId(); // Returns GUID object (strongly typed)
687
+ ```
688
+
689
+ **Breaking Changes:** None - fully backward compatible
690
+
691
+ **Files Added:**
692
+ - `src/typed-configuration.ts` - Main implementation
693
+ - `src/typed-configuration.spec.ts` - Comprehensive tests
694
+ - `src/examples/typed-configuration-usage.ts` - Usage examples
695
+
696
+ ### v4.10.6 - Voting System & PlatformID Integration
697
+
698
+ **Major Features:**
699
+ - **Complete Cryptographic Voting System**: Added comprehensive voting system with 17+ methods
700
+ - All methods fully implemented: Plurality, Approval, Weighted, Borda, Score, Yes/No, Yes/No/Abstain, Supermajority, Ranked Choice (IRV), Two-Round, STAR, STV, Quadratic, Consensus, Consent-Based
701
+ - Node.js optimized with Buffer instead of Uint8Array for better performance
702
+ - Government-grade security: Immutable audit logs, public bulletin board, event logging
703
+ - Role separation: Poll aggregators cannot decrypt votes until closure
704
+ - **Extended PlatformID Type System**: Enhanced ID provider system with Node.js-specific extensions
705
+ - `PlatformID = BasePlatformID | Buffer | Types.ObjectId`
706
+ - Seamless integration with mongoose and MongoDB applications
707
+ - Generic interfaces: `EncryptedVote<TID extends PlatformID>`, `PollResults<TID extends PlatformID>`
708
+ - **Enhanced Member System**: Added voting key derivation and management
709
+ - `deriveVotingKeys()`: Generate Paillier keypairs for homomorphic encryption
710
+ - `votingPublicKey` and `votingPrivateKey` properties for voting operations
711
+ - Full integration with voting system interfaces
712
+
713
+ **Node.js Voting System Components:**
714
+ - `Poll`: Core vote aggregation with receipt generation (extends browser Poll with Buffer support)
715
+ - `VotingPoll`: High-level voting with encrypted receipts
716
+ - `PollTallier`: Secure vote decryption and tallying (separate entity)
717
+ - `VoteEncoder`: Paillier homomorphic encryption for all voting methods (extends browser VoteEncoder)
718
+ - `PollFactory`: Convenient poll creation with method-specific configurations (extends browser PollFactory)
719
+ - `VotingSecurityValidator`: Security level validation and enforcement
720
+ - `ImmutableAuditLog`: Cryptographic hash chain for audit compliance
721
+ - `PublicBulletinBoard`: Transparent vote publication with Merkle tree integrity
722
+ - `PollEventLogger`: Comprehensive event tracking with microsecond timestamps
723
+
724
+ **Breaking Changes:**
725
+ - Voting interfaces now use generic `PlatformID` types with Buffer as default
726
+ - Member interface extended with voting key properties
727
+ - New voting system exports in main package
728
+
729
+ **Compatibility:**
730
+ - Fully backward compatible for existing ECIES operations
731
+ - New voting system is opt-in and doesn't affect existing functionality
732
+ - 100% binary compatible with `@digitaldefiance/ecies-lib` voting system
733
+ - Cross-platform vote encryption/decryption verified
734
+
735
+ ### v4.8.2 - Voting System Foundation
736
+
737
+ **Features:**
738
+ - Initial voting system architecture
739
+ - Core voting method implementations
740
+ - Basic showcase application structure
741
+
742
+ ### v4.8.1 - Voting System Initialization
743
+
744
+ **Features:**
745
+ - Foundation for cryptographic voting system
746
+ - Initial voting method definitions
747
+ - Enhanced Member system for voting key management
748
+
749
+ ### v4.8.0 - Voting System Introduction
750
+
751
+ **Major Features:**
752
+ - **Initial Voting System**: Introduced cryptographic voting system architecture
753
+ - **Voting Method Enumerations**: Defined all 17+ voting methods with security classifications
754
+ - **Enhanced Member System**: Added voting key derivation capabilities
755
+ - **Showcase Application**: Started development of interactive voting demos
756
+
757
+ ### v4.7.15 - Pre-Voting System Enhancements
758
+
759
+ **Improvements:**
760
+ - Enhanced core ECIES functionality
761
+ - Improved ID provider system
762
+ - Bug fixes and stability improvements
763
+ - Updated showcase components
764
+
490
765
  ### v4.7.14
491
766
 
492
767
  **Bug Fix: idProvider Configuration Now Respected by Member.newMember()**
@@ -1143,3 +1418,32 @@ Special thanks to the architecture improvements that enabled this clean migratio
1143
1418
  ### Version 1.0.3
1144
1419
 
1145
1420
  - Initial release.
1421
+
1422
+ ## Summary
1423
+
1424
+ The Node.js implementation of `@digitaldefiance/node-ecies-lib` provides a **complete, production-ready cryptographic library** with comprehensive voting system support:
1425
+
1426
+ ### ✅ Complete Implementation
1427
+ - **All 17 Voting Methods**: Every voting method from Plurality to Consent-Based is fully implemented and tested
1428
+ - **Node.js Optimized**: Uses Buffer instead of Uint8Array for optimal Node.js performance
1429
+ - **Extended PlatformID**: Supports Buffer and mongoose ObjectId for seamless database integration
1430
+ - **Cross-Platform**: 100% binary compatible with browser `@digitaldefiance/ecies-lib`
1431
+
1432
+ ### ✅ Government-Grade Security
1433
+ - **Homomorphic Encryption**: Paillier cryptosystem for privacy-preserving vote aggregation
1434
+ - **Immutable Audit Log**: Cryptographic hash chain for complete audit trail
1435
+ - **Public Bulletin Board**: Transparent, verifiable vote publication
1436
+ - **Event Logging**: Microsecond-precision event tracking
1437
+ - **Role Separation**: Poll aggregators cannot decrypt votes until closure
1438
+
1439
+ ### ✅ Production Ready
1440
+ - **1100+ Tests**: Comprehensive test coverage including all voting methods and cross-platform compatibility
1441
+ - **Stress Tested**: Handles 1000+ voters and complex elimination scenarios
1442
+ - **Attack Resistant**: Prevents double voting, vote manipulation, and unauthorized decryption
1443
+ - **Node.js Native**: Optimized for Node.js crypto module and Buffer operations
1444
+
1445
+ The system is ready for production use in government elections, corporate governance, and any application requiring secure, verifiable voting with Node.js backend systems.
1446
+
1447
+ ## License
1448
+
1449
+ MIT © Digital Defiance
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@digitaldefiance/node-ecies-lib",
3
- "version": "4.10.6",
3
+ "version": "4.10.8",
4
4
  "description": "Digital Defiance Node ECIES Library",
5
5
  "homepage": "https://github.com/Digital-Defiance/node-ecies-lib",
6
6
  "repository": {
@@ -62,7 +62,7 @@
62
62
  "license": "MIT",
63
63
  "packageManager": "yarn@4.10.3",
64
64
  "dependencies": {
65
- "@digitaldefiance/ecies-lib": "4.10.6",
65
+ "@digitaldefiance/ecies-lib": "4.10.8",
66
66
  "@digitaldefiance/express-suite-test-utils": "1.0.14",
67
67
  "@digitaldefiance/i18n-lib": "3.8.16",
68
68
  "@ethereumjs/wallet": "^10.0.0",
@@ -0,0 +1,54 @@
1
+ /**
2
+ * @fileoverview Usage examples for Node.js ECIES typed configuration system
3
+ *
4
+ * This file demonstrates how to use the strongly-typed ID provider system
5
+ * in Node.js applications for better type safety and developer experience.
6
+ *
7
+ * @version 4.10.7
8
+ * @since 4.10.7
9
+ */
10
+ /**
11
+ * Example 1: Enhanced ID Provider (Drop-in Replacement)
12
+ *
13
+ * The enhanced provider includes both original and typed methods,
14
+ * making it a perfect drop-in replacement for existing code.
15
+ */
16
+ declare function enhancedProviderExample(): void;
17
+ /**
18
+ * Example 2: Simple Typed Provider (Minimal API)
19
+ *
20
+ * The typed provider only exposes strongly-typed methods,
21
+ * providing a clean API surface for new code.
22
+ */
23
+ declare function typedProviderExample(): void;
24
+ /**
25
+ * Example 3: Complete Typed Configuration
26
+ *
27
+ * The typed configuration provides access to the full Node.js runtime
28
+ * configuration plus convenient typed ID helpers.
29
+ */
30
+ declare function typedConfigurationExample(): void;
31
+ /**
32
+ * Example 4: Custom Provider Configuration
33
+ *
34
+ * Demonstrates how to use different ID providers with strong typing.
35
+ */
36
+ declare function customProviderExample(): void;
37
+ /**
38
+ * Example 5: Type Safety Demonstration
39
+ *
40
+ * Shows how the typed system prevents common type-related errors.
41
+ */
42
+ declare function typeSafetyExample(): void;
43
+ /**
44
+ * Example 6: Integration with ECIESService
45
+ *
46
+ * Shows how to use typed configurations with the ECIES service.
47
+ */
48
+ declare function eciesIntegrationExample(): void;
49
+ /**
50
+ * Run all examples
51
+ */
52
+ declare function runAllExamples(): void;
53
+ export { enhancedProviderExample, typedProviderExample, typedConfigurationExample, customProviderExample, typeSafetyExample, eciesIntegrationExample, runAllExamples, };
54
+ //# sourceMappingURL=typed-configuration-usage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"typed-configuration-usage.d.ts","sourceRoot":"","sources":["../../../../../packages/digitaldefiance-node-ecies-lib/src/examples/typed-configuration-usage.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAYH;;;;;GAKG;AACH,iBAAS,uBAAuB,SAkB/B;AAED;;;;;GAKG;AACH,iBAAS,oBAAoB,SAqB5B;AAED;;;;;GAKG;AACH,iBAAS,yBAAyB,SAkBjC;AAED;;;;GAIG;AACH,iBAAS,qBAAqB,SAqB7B;AAED;;;;GAIG;AACH,iBAAS,iBAAiB,SAwBzB;AAED;;;;GAIG;AACH,iBAAS,uBAAuB,SAmB/B;AAED;;GAEG;AACH,iBAAS,cAAc,SAsBtB;AAGD,OAAO,EACL,uBAAuB,EACvB,oBAAoB,EACpB,yBAAyB,EACzB,qBAAqB,EACrB,iBAAiB,EACjB,uBAAuB,EACvB,cAAc,GACf,CAAC"}
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ /**
3
+ * @fileoverview Usage examples for Node.js ECIES typed configuration system
4
+ *
5
+ * This file demonstrates how to use the strongly-typed ID provider system
6
+ * in Node.js applications for better type safety and developer experience.
7
+ *
8
+ * @version 4.10.7
9
+ * @since 4.10.7
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.enhancedProviderExample = enhancedProviderExample;
13
+ exports.typedProviderExample = typedProviderExample;
14
+ exports.typedConfigurationExample = typedConfigurationExample;
15
+ exports.customProviderExample = customProviderExample;
16
+ exports.typeSafetyExample = typeSafetyExample;
17
+ exports.eciesIntegrationExample = eciesIntegrationExample;
18
+ exports.runAllExamples = runAllExamples;
19
+ const ecies_lib_1 = require("@digitaldefiance/ecies-lib");
20
+ const typed_configuration_1 = require("../typed-configuration");
21
+ /**
22
+ * Example 1: Enhanced ID Provider (Drop-in Replacement)
23
+ *
24
+ * The enhanced provider includes both original and typed methods,
25
+ * making it a perfect drop-in replacement for existing code.
26
+ */
27
+ function enhancedProviderExample() {
28
+ console.log('=== Enhanced Provider Example ===');
29
+ // Get enhanced provider with strong typing
30
+ const provider = (0, typed_configuration_1.getEnhancedNodeIdProvider)();
31
+ // Original methods still work (backward compatibility)
32
+ const rawBytes = provider.generate(); // Returns Uint8Array
33
+ // const _unknownObj = provider.fromBytes(rawBytes); // Returns unknown (requires casting)
34
+ // New typed methods provide type safety
35
+ const typedId = provider.generateTyped(); // Returns ObjectId (strongly typed)
36
+ const typedFromBytes = provider.fromBytesTyped(rawBytes); // Returns ObjectId (no casting needed)
37
+ console.log('Provider name:', provider.name);
38
+ console.log('Byte length:', provider.byteLength);
39
+ console.log('Typed ID generated:', typedId);
40
+ console.log('Round-trip successful:', typedFromBytes);
41
+ }
42
+ /**
43
+ * Example 2: Simple Typed Provider (Minimal API)
44
+ *
45
+ * The typed provider only exposes strongly-typed methods,
46
+ * providing a clean API surface for new code.
47
+ */
48
+ function typedProviderExample() {
49
+ console.log('=== Typed Provider Example ===');
50
+ // Get simple typed provider
51
+ const provider = (0, typed_configuration_1.getTypedNodeIdProvider)();
52
+ // Only typed methods available
53
+ const typedId = provider.generateTyped(); // Returns ObjectId
54
+ const bytes = provider.toBytesTyped(typedId); // Convert to bytes
55
+ const restored = provider.fromBytesTyped(bytes); // Convert back to ObjectId
56
+ // Serialization methods
57
+ const serialized = provider.serializeTyped(typedId);
58
+ const deserialized = provider.deserializeTyped(serialized);
59
+ console.log('Provider name:', provider.name);
60
+ console.log('Byte length:', provider.byteLength);
61
+ console.log('Original ID:', typedId);
62
+ console.log('Restored ID:', restored);
63
+ console.log('Serialized:', serialized);
64
+ console.log('Deserialized:', deserialized);
65
+ }
66
+ /**
67
+ * Example 3: Complete Typed Configuration
68
+ *
69
+ * The typed configuration provides access to the full Node.js runtime
70
+ * configuration plus convenient typed ID helpers.
71
+ */
72
+ function typedConfigurationExample() {
73
+ console.log('=== Typed Configuration Example ===');
74
+ // Create ObjectId configuration
75
+ const config = (0, typed_configuration_1.createNodeObjectIdConfiguration)();
76
+ // Access full Node.js runtime configuration
77
+ console.log('PBKDF2 algorithm:', config.constants.PBKDF2.ALGORITHM);
78
+ console.log('Member ID length:', config.constants.MEMBER_ID_LENGTH);
79
+ // Use convenient typed methods
80
+ const objectId = config.generateId(); // Returns ObjectId
81
+ const bytes = config.idToBytes(objectId);
82
+ const restored = config.idFromBytes(bytes);
83
+ console.log('Generated ObjectId:', objectId);
84
+ console.log('Byte length:', bytes.length);
85
+ console.log('Restored ObjectId:', restored);
86
+ }
87
+ /**
88
+ * Example 4: Custom Provider Configuration
89
+ *
90
+ * Demonstrates how to use different ID providers with strong typing.
91
+ */
92
+ function customProviderExample() {
93
+ console.log('=== Custom Provider Example ===');
94
+ // GUID configuration
95
+ const guidConfig = (0, typed_configuration_1.createNodeTypedConfiguration)({
96
+ idProvider: new ecies_lib_1.GuidV4Provider(),
97
+ });
98
+ // UUID configuration
99
+ const uuidConfig = (0, typed_configuration_1.createNodeTypedConfiguration)({
100
+ idProvider: new ecies_lib_1.UuidProvider(),
101
+ });
102
+ // Generate typed IDs
103
+ // const _guidId = guidConfig.generateId(); // Returns GUID object (strongly typed)
104
+ // const _uuidId = uuidConfig.generateId(); // Returns UUID string (strongly typed)
105
+ console.log('GUID provider name:', guidConfig.constants.idProvider.name);
106
+ console.log('GUID byte length:', guidConfig.constants.idProvider.byteLength);
107
+ console.log('UUID provider name:', uuidConfig.constants.idProvider.name);
108
+ console.log('UUID byte length:', uuidConfig.constants.idProvider.byteLength);
109
+ }
110
+ /**
111
+ * Example 5: Type Safety Demonstration
112
+ *
113
+ * Shows how the typed system prevents common type-related errors.
114
+ */
115
+ function typeSafetyExample() {
116
+ console.log('=== Type Safety Example ===');
117
+ const objectIdConfig = (0, typed_configuration_1.createNodeObjectIdConfiguration)();
118
+ const guidConfig = (0, typed_configuration_1.createNodeTypedConfiguration)({
119
+ idProvider: new ecies_lib_1.GuidV4Provider(),
120
+ });
121
+ // Generate strongly-typed IDs
122
+ const objectId = objectIdConfig.generateId(); // ObjectId type
123
+ const guidId = guidConfig.generateId(); // GUID object type
124
+ // Type-safe operations (no casting needed)
125
+ const objectIdBytes = objectIdConfig.idToBytes(objectId);
126
+ const guidBytes = guidConfig.idToBytes(guidId);
127
+ // Restore with type safety
128
+ const restoredObjectId = objectIdConfig.idFromBytes(objectIdBytes);
129
+ const restoredGuid = guidConfig.idFromBytes(guidBytes);
130
+ console.log('ObjectId bytes length:', objectIdBytes.length);
131
+ console.log('GUID bytes length:', guidBytes.length);
132
+ console.log('ObjectId restored:', restoredObjectId);
133
+ console.log('GUID restored:', restoredGuid);
134
+ }
135
+ /**
136
+ * Example 6: Integration with ECIESService
137
+ *
138
+ * Shows how to use typed configurations with the ECIES service.
139
+ */
140
+ function eciesIntegrationExample() {
141
+ console.log('=== ECIES Integration Example ===');
142
+ // Import ECIESService (commented out to avoid circular dependencies in examples)
143
+ // import { ECIESService } from '../services/ecies/service';
144
+ // Create typed configuration
145
+ const config = (0, typed_configuration_1.createNodeObjectIdConfiguration)();
146
+ // Use with ECIESService
147
+ // const service = new ECIESService(config.constants);
148
+ // The service will use the configured ID provider
149
+ // console.log('Service ID provider:', service.idProvider.name);
150
+ // console.log('Service ID byte length:', service.idProvider.byteLength);
151
+ console.log('Configuration ready for ECIESService');
152
+ console.log('ID provider:', config.constants.idProvider.name);
153
+ console.log('Byte length:', config.constants.idProvider.byteLength);
154
+ }
155
+ /**
156
+ * Run all examples
157
+ */
158
+ function runAllExamples() {
159
+ console.log('Node.js ECIES Typed Configuration Examples\n');
160
+ enhancedProviderExample();
161
+ console.log();
162
+ typedProviderExample();
163
+ console.log();
164
+ typedConfigurationExample();
165
+ console.log();
166
+ customProviderExample();
167
+ console.log();
168
+ typeSafetyExample();
169
+ console.log();
170
+ eciesIntegrationExample();
171
+ console.log();
172
+ console.log('All examples completed successfully!');
173
+ }
174
+ // Run examples if this file is executed directly
175
+ if (require.main === module) {
176
+ runAllExamples();
177
+ }
178
+ //# sourceMappingURL=typed-configuration-usage.js.map