A comprehensive library providing higher-level primitives and foundational building blocks for creating a cryptographically-secure user management system and Node.js Express server framework. Built on top of @digitaldefiance/ecies-lib and @digitaldefiance/node-ecies-lib, this package serves as the core foundation for the node-ecies and node-express-suite projects, which together form a complete full-stack security and user management ecosystem.
Part of Express Suite
@digitaldefiance/suite-core-lib offers the essential core primitives and abstractions that power:
- Secure user accounts and authentication mechanisms
- End-to-end encryption between users and servers
- Zero-knowledge proof based authentication flows
- Role-based access control (RBAC) with fine-grained permissions
- Multi-language internationalization (i18n) with plugin-based architecture
npm install @digitaldefiance/suite-core-lib
# or
yarn add @digitaldefiance/suite-core-libThis library includes built-in support for five major languages using a modern plugin-based i18n architecture:
- English (US and UK variants)
- French
- Spanish
- Mandarin Chinese
- Ukrainian
All error messages, validation texts, and user-facing strings are fully localized and designed to be extensible for additional languages.
import {
IUserBase,
IRoleBase,
IUserRoleBase,
AccountStatus,
Role,
CoreLanguage
} from '@digitaldefiance/suite-core-lib';
// Create a user interface with string IDs for frontend applications
interface FrontendUser extends IUserBase<string, Date, 'en', AccountStatus> {
// Additional app-specific fields
}
// Create a user interface with ObjectId for MongoDB backend
import { Types } from 'mongoose';
interface BackendUser extends IUserBase<Types.ObjectId, Date, 'en', AccountStatus> {
// Additional app-specific fields
}
// Create a user interface with UUID strings for SQL databases
interface SqlUser extends IUserBase<string, Date, 'en', AccountStatus> {
// Additional app-specific fields
}
// Create custom role interfaces
interface AppRole extends IRoleBase<string, Date, Role> {
// Additional app-specific fields
}import { BackupCodeString, Constants } from '@digitaldefiance/suite-core-lib';
// Generate cryptographically secure backup codes
const backupCodes = BackupCodeString.generateBackupCodes();
console.log(backupCodes.length); // Default is 10, configurable via Constants.BACKUP_CODES.Count
// Format a backup code for user display
const code = new BackupCodeString('deadbeefcafebabefeedface01234567');
console.log(code.value); // Outputs: "dead-beef-cafe-babe-feed-face-0123-4567"
// Access multiple secure encoding formats
console.log(code.valueAsHexString); // Hex-encoded UTF-8 bytes
console.log(code.valueAsBase64String); // Base64-encoded string
console.log(code.valueAsUint8Array); // Raw Uint8Array byte arrayimport {
UserNotFoundError,
UsernameInUseError,
AccountLockedError,
CoreLanguage
} from '@digitaldefiance/suite-core-lib';
// Throw errors with automatic localization support
throw new UserNotFoundError(CoreLanguage.French);
// Output: "Compte utilisateur introuvable"
throw new UsernameInUseError(CoreLanguage.Spanish);
// Output: "El nombre de usuario ya está en uso"
throw new AccountLockedError(CoreLanguage.German);
// Output: "Konto ist von einem Administrator gesperrt"The @digitaldefiance/node-express-suite package builds upon these primitives to create full-featured framework components:
// Usage of suite-core-lib primitives in Express applications
import {
IUserBase,
AccountStatus,
BackupCodeString,
UserNotFoundError,
InvalidBackupCodeError,
CoreLanguage
} from '@digitaldefiance/suite-core-lib';
interface BackupCode {
encrypted: string;
used: boolean;
}
// Middleware example: validate backup code input
function validateBackupCode(userInput: string, storedCodes: BackupCode[]): boolean {
try {
const inputCode = new BackupCodeString(userInput);
return storedCodes.some(stored =>
BackupCodeString.normalizeCode(inputCode.value) === stored.encrypted
);
} catch (error) {
if (error instanceof InvalidBackupCodeError) {
// Handle localized error response gracefully
return false;
}
throw error;
}
}// Frontend frameworks consume type-safe base interfaces
import { IUserBase, AccountStatus } from '@digitaldefiance/suite-core-lib';
// Define a frontend user type with string IDs and Date objects
type FrontendUser = IUserBase<string, Date, 'en' | 'fr' | 'es', AccountStatus>;
// React/Vue/Angular component props example
interface UserProfileProps {
user: FrontendUser;
onStatusChange: (status: AccountStatus) => void;
}
// Function to update user status with type safety
function updateUserStatus(user: FrontendUser, status: AccountStatus): FrontendUser {
return {
...user,
accountStatus: status,
updatedAt: new Date()
};
}// Database schemas implementing suite-core-lib base interfaces
import { IUserBase, IUserRoleBase, AccountStatus } from '@digitaldefiance/suite-core-lib';
import { Types } from 'mongoose';
// Define a MongoDB user type using ObjectId
type MongoUser = IUserBase<Types.ObjectId, Date, 'en', AccountStatus>;
const userSchema = new mongoose.Schema<MongoUser>({
_id: { type: Types.ObjectId, required: true },
username: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
accountStatus: {
type: String,
enum: Object.values(AccountStatus),
default: AccountStatus.PendingEmailVerification
},
// Additional schema fields matching the interface
});
// SQL database example with UUID strings
type SqlUser = IUserBase<string, Date, 'en', AccountStatus> & {
customField: string;
};Note: The static
ModelNameandBaseModelNameenums are deprecated. For extensibility, use dynamic model registration available inModelRegistryfromnode-express-suite.
You can register and extend models dynamically at runtime:
import { ModelRegistry } from '@digitaldefiance/node-express-suite';
// Register a custom model, e.g., Organization
ModelRegistry.instance.register({
modelName: 'Organization',
schema: organizationSchema,
model: OrganizationModel,
collection: 'organizations',
});
// Retrieve the model anywhere in your application
const orgModel = ModelRegistry.instance.get('Organization')?.model;This dynamic approach supports advanced use cases such as multi-tenancy and plugin-based architectures.
import { EmailTokenType } from '@digitaldefiance/suite-core-lib';
// Common built-in email token types
const tokenTypes = [
EmailTokenType.AccountVerification, // Email confirmation
EmailTokenType.PasswordReset, // Password reset flow
EmailTokenType.LoginRequest, // Passwordless login
EmailTokenType.PrivateKeyRequest, // Key recovery
EmailTokenType.MnemonicRecoveryRequest // Mnemonic recovery
];import { AccountStatus } from '@digitaldefiance/suite-core-lib';
// Manage user account states with fine granularity
switch (user.accountStatus) {
case AccountStatus.PendingEmailVerification:
// Trigger email verification workflow
break;
case AccountStatus.Active:
// Grant full access
break;
case AccountStatus.AdminLock:
// Restrict access pending admin intervention
break;
}The @digitaldefiance/node-ecies and @digitaldefiance/node-express-suite packages leverage these primitives to build:
- A complete Express.js framework with middleware, routing, and database integration
- Frontend adapters for React, Vue, Angular, and Svelte
- Mobile and desktop SDKs for React Native, Flutter, Electron, and Tauri
- DevOps and deployment tooling including Docker, Kubernetes, and CI/CD pipelines
Core base interfaces (IUserBase, IRoleBase, IUserRoleBase, etc.) now support generic ID types. This enables seamless integration with any database system using the Pluggable ID Providers (ObjectId, UUID, GUID) introduced in @digitaldefiance/ecies-lib v4.1.0.
import { IUserBase, AccountStatus } from '@digitaldefiance/suite-core-lib';
import { Types } from 'mongoose';
// MongoDB with ObjectId
type MongoUser = IUserBase<Types.ObjectId, Date, 'en', AccountStatus>;
// SQL database with UUID strings
type SqlUser = IUserBase<string, Date, 'en', AccountStatus>;
// PostgreSQL with numeric IDs
type PostgresUser = IUserBase<number, Date, 'en', AccountStatus>;
// Frontend with string IDs and ISO date strings
type FrontendUser = IUserBase<string, string, 'en', AccountStatus>;import { UserBuilder, RoleBuilder } from '@digitaldefiance/suite-core-lib';
const user = UserBuilder.create()
.withUsername('admin')
.withEmail('admin@example.com')
.withEmailVerified(true)
.build();
const role = RoleBuilder.create()
.withName(Role.Admin)
.asAdmin()
.build();import { Result, success, failure, isSuccess } from '@digitaldefiance/suite-core-lib';
function processUser(id: string): Result<User, UserNotFoundError> {
const user = findUser(id);
return user ? success(user) : failure(new UserNotFoundError(id));
}
if (isSuccess(result)) {
console.log('User:', result.data);
} else {
console.error('Error:', result.error);
}import {
isValidUsername,
isValidEmail,
isValidPassword,
createValidators,
createConstants
} from '@digitaldefiance/suite-core-lib';
// Use default validators with built-in constants
if (!isValidUsername('test123')) {
throw new InvalidUsernameError('test123');
}
// Create validators with custom constants
const myConstants = createConstants('myapp.com', {
UsernameRegex: /^[a-z0-9_]{4,20}$/,
UsernameMinLength: 4,
UsernameMaxLength: 20,
});
const validators = createValidators(myConstants);
if (!validators.isValidUsername('user_name')) {
throw new Error('Invalid username');
}- 70% Code Reduction:
TranslatableSuiteHandleableErrornow extends i18n-lib base classes - Organized Structure: New
builders/,core/,lib/folders - Custom Constants: Validators accept custom
IConstantsfor flexibility - Better Type Safety: Enhanced TypeScript types throughout
This package uses a runtime configuration registry for all constants and cryptographic parameters. You can override defaults at runtime for advanced use cases:
import {
getSuiteCoreRuntimeConfiguration,
registerSuiteCoreRuntimeConfiguration,
} from '@digitaldefiance/suite-core-lib';
// Retrieve current configuration
const config = getSuiteCoreRuntimeConfiguration();
// Register a custom configuration with overrides
const customKey = Symbol('custom-suite-core-config');
registerSuiteCoreRuntimeConfiguration(customKey, 'example.com', { BcryptRounds: 12 });
const customConfig = getSuiteCoreRuntimeConfiguration(customKey);All constants are immutable and accessible via the registry/config API. See src/constants.ts and src/defaults.ts for more information.
- Centralized constants file for configuration
- Immutability enforced via Object.freeze
- Registry/config pattern for runtime overrides
- Type-safe interfaces for all configuration objects
# Run the comprehensive test suite
yarn test
# 409 tests covering:
# âś… Type safety and interface validation
# âś… Cryptographic security functions
# âś… Multi-language localization
# âś… Error handling and edge cases
# âś… Integration scenarios
# âś… Builders and fluent APIs
# âś… Result pattern and core utilities
# âś… Validators with custom constants- Statements: 98.47%
- Branches: 94.56%
- Functions: 88.09%
- Lines: 98.63%
We welcome contributions to help build the future of secure user management! Areas where contributions are especially appreciated:
- Frontend component libraries for popular frameworks
- Additional language translations and localization
- Performance optimizations and benchmarking
- Documentation and example applications
- Security auditing and penetration testing
MIT © Digital Defiance
@digitaldefiance/ecies-lib- ECIES encryption foundation@digitaldefiance/i18n-lib- Plugin-based internationalization@digitaldefiance/node-ecies-lib- Node.js crypto utilities
- i18n-lib - Internationalization framework with plugin support
- node-ecies - Cryptographic framework and security protocols
- node-express-suite - Complete Express.js framework with authentication, database integration, and API generation
Building user management primitives? Start with @digitaldefiance/suite-core-lib for type-safe, secure, and internationalized user system foundations. For complete frameworks, check out the node-ecies and node-express-suite projects! 🚀
The suite-core-lib package uses comprehensive testing with 409 tests covering all user management primitives, validation logic, and error handling.
Test Framework: Jest with TypeScript support
Property-Based Testing: fast-check for validation properties
Coverage: 98.47% statements, 94.56% branches, 88.09% functions
# Run all tests
npm test
# Run with coverage
npm test -- --coverage
# Run specific test suite
npm test -- user-builder.spec.tsimport { UserBuilder, RoleBuilder, Role } from '@digitaldefiance/suite-core-lib';
describe('User Builder', () => {
it('should build user with fluent API', () => {
const user = UserBuilder.create()
.withUsername('alice')
.withEmail('alice@example.com')
.withEmailVerified(true)
.build();
expect(user.username).toBe('alice');
expect(user.emailVerified).toBe(true);
});
});import { isValidUsername, isValidEmail, isValidPassword } from '@digitaldefiance/suite-core-lib';
describe('Validators', () => {
it('should validate usernames', () => {
expect(isValidUsername('alice123')).toBe(true);
expect(isValidUsername('ab')).toBe(false); // too short
});
it('should validate emails', () => {
expect(isValidEmail('alice@example.com')).toBe(true);
expect(isValidEmail('invalid')).toBe(false);
});
});import { UserNotFoundError, UsernameInUseError, CoreLanguage } from '@digitaldefiance/suite-core-lib';
describe('Error Handling', () => {
it('should throw localized errors', () => {
const error = new UserNotFoundError(CoreLanguage.French);
expect(error.message).toContain('utilisateur');
});
});Testing with base interfaces:
import { IUserBase, AccountStatus } from '@digitaldefiance/suite-core-lib';
import { Types } from 'mongoose';
// Define your user type
type TestUser = IUserBase<Types.ObjectId, Date, 'en', AccountStatus>;
describe('User Management', () => {
it('should create user with correct status', () => {
const user: TestUser = {
_id: new Types.ObjectId(),
username: 'alice',
email: 'alice@example.com',
accountStatus: AccountStatus.Active,
emailVerified: true,
siteLanguage: 'en',
createdAt: new Date(),
updatedAt: new Date(),
// ... other required fields
};
expect(user.accountStatus).toBe(AccountStatus.Active);
expect(user.emailVerified).toBe(true);
});
});- Breaking Change: Move
IFrontend*andIBackend*type aliases to@digitaldefiance/node-express-suite- Base interfaces (
IUserBase,IRoleBase,IUserRoleBase, etc.) remain insuite-core-libas the core primitives - Framework-specific type aliases moved to
node-express-suitefor better separation of concerns - Migration: Use base interfaces directly (e.g.,
IUserBase<string, Date, 'en', AccountStatus>) or import pre-configured types from@digitaldefiance/node-express-suite
- Base interfaces (
- Update testing
- Update ecies
- Update testing
- Upgrade ecies to 4.4.0
- Upgrade ECIES to 4.3.0
- Bump versions to 4.2.7 ECIES
- Bump versions to 4.2.6 ECIES / i18n 3.7.5
This release focuses on improving type safety by removing unsafe type casts and implementing proper type constraints.
-
Deep Clone Improvements
- Added
Cloneabletype union to constrain deep clone operations - Removed
as unknown as Tcasts from array and object cloning - Improved type safety for RegExp and Date cloning
- Added
-
Dynamic Property Access
- Removed
(obj as any)[prop]cast fromdeepFreezefunction - Added proper type handling for object property access
- Removed
(result as any)[key]cast fromapplyOverridesfunction
- Removed
-
Translation Error Handling
- Removed unnecessary
language as anycast inTranslatableSuiteError - The i18n engine's
translatemethod already acceptslanguage?: string
- Removed unnecessary
- Before: 5 instances of unsafe type casts
- After: 2 controlled type conversions in well-defined functions
- Improvement: 60% reduction in type safety escape hatches
None. This is a backward-compatible release focused on internal type safety improvements.
- Update ECIES to 4.2.0
- Update ECIES to 4.1.1
- Upgrade ECIES to 4.1.0
- Update base interfaces (
IUserBase,IUserRoleBase,ITokenRole, etc.) to support generic ID types. This enables support for pluggable ID providers (e.g. ObjectId, UUID, GUID, numbers) introduced in@digitaldefiance/ecies-libv4.1.0.
- Add CSS warning logo constants
- Add CSS warning color constant
- Add CSS constants
- Add new role interface
- Update libs
- Add strings
- Add IUserSettings/IUserSettingsDTO and hydrate/dehydrate methods
- Update i18n/ecies
- Update i18n/ecies
- Add strings
- Add string
- Add string
- Add string
- Update ecies, i18n
- Add currency,directChallenge to IRequestUserDTO
- Add strings
- Add strings
- Update string
- Reorganize strings
- Add strings
- Add string
- Add this.name to errors
- Add DirectChallengeNotEnabled error
- Add user DarkMode preference
- Add strings
- Fix BackupCodeString
- Fix InvalidEmailError
- Update ecies
- Update ecies
- Update ecies
- Builders Module: UserBuilder, RoleBuilder with fluent APIs
- Core Module: Result<T,E> pattern, type exports, error exports
- Lib Module: Validators, formatters, custom constants support
- Custom Constants:
createValidators(constants)for flexible validation rules
- TranslatableSuiteHandleableError extends i18n-lib base (70% code reduction)
- Organized folder structure: builders/, core/, lib/
- Enhanced type safety throughout
- 409 tests (was 313)
- 94.56% branch coverage (was 59.3%)
- 98.47% statement coverage (was 92.86%)
- 88.09% function coverage (was 67.53%)
- Complete migration guide in MIGRATION_V2.md
- Comprehensive examples in V2_IMPROVEMENTS_COMPLETE.md
- Final metrics in V2_FINAL_SUMMARY.md
- None - 100% backwards compatible
- Upgraded all @digitaldefiance dependencies to v2.0
- @digitaldefiance/ecies-lib: 2.0.1
- @digitaldefiance/i18n-lib: 2.0.0
- @digitaldefiance/node-ecies-lib: 2.0.0
- No breaking API changes
- See MIGRATION_V2.md for upgrade guide
- Upgrade i18n, ecies, version bump
- Add a few strings, but mainly version bump/alignment
- Skip 1.3.16 for homogenization
- Upgrade i18n with aliases for t() function
- Homogenize versions
- Update i18n/ecies
- Re-release with js
- Upgrade to es2022/nx monorepo
- Upgrade libs
- Add strings
- Bugfixes on i18n registration
- Improve i18n plugin registration
- Update i18n/ecies
- Add string
- Export LocalStorageManager
- Use typed/handleable from i18n
- Update ecies
- Update ecies
- Add numerous error classes
- Add local storage manager
- Update ecies libs
- Add npmignore
- Add strings
- Add strings
- Add strings
- Add string
- Add string
- CommonJS
- Update libs
- Update libs
- Add frontend-objects
- Update libs
- Update libs
- Update libs
- Mon Oct 27 2025 15:15:00 GMT-0700 (Pacific Daylight Time)
- Add string
- Sun Oct 26 2025 22:31:00 GMT-0700 (Pacific Daylight Time)
- Update readme
- Sun Oct 26 2025 20:33:00 GMT-0700 (Pacific Daylight Time)
- Update libraries
- Update error classes to not use CoreLanguageCode (use string instead)
- Sun Oct 26 2025 13:46:00 GMT-0700 (Pacific Daylight Time)
- Add some string keys
- Sat Oct 25 2025 16:19:00 GMT-0700 (Pacific Daylight Time)
- Bump versions of libs
- Fri Oct 24 2025 17:27:00 GMT-0700 (Pacific Daylight Time)
- Add string key
- Fri Oct 24 2025 13:40:00 GMT-0700 (Pacific Daylight Time)
- Version bump
- Thu Oct 23 2025 20:34:00 GMT-0700 (Pacific Daylight Time)
- add InvalidChallengeResponseError/LoginChallengeExpiredError
- Thu Oct 23 2025 20:20:00 GMT-0700 (Pacific Daylight Time)
- export PrivateKeyRequiredError
- Thu Oct 23 2025 20:19:00 GMT-0700 (Pacific Daylight Time)
- Add PrivateKeyRequiredError
- Thu Oct 23 2025 17:58:00 GMT-0700 (Pacific Daylight Time)
- Add EmailTokenFailedToSendError and supporting strings
- Thu Oct 23 2025 16:12:00 GMT-0700 (Pacific Daylight Time)
- Add string key/string for EmailService
- Thu Oct 23 2025 14:53:00 GMT-0700 (Pacific Daylight Time)
- Update for i18n and ecies libs
- Wed Oct 22 2025 16:40:00 GMT-0700 (Pacific Daylight Time)
- Renamed SuiteCoreStringKey.Validation_MissingValidatedDataForField to SuiteCoreStringKey.Validation_MissingValidatedDataForFieldTemplate so that it would be processed as a template
- Wed Oct 22 2025 15:06:00 GMT-0700 (Pacific Daylight Time)
- coreLanguageToDefaultLanguage and DefaultLanguage helpers
- Tue Oct 21 2025 16:07:00 GMT-0700 (Pacific Daylight Time)
-
Updated
@digitaldefiance/ecies-libfrom 1.0.31 to 1.0.32
-
Updated
@digitaldefiance/node-ecies-libfrom 1.0.12 to 1.0.13
-
Added site configuration constants:
SiteSiteTaglineSiteDescriptionto core constants
-
Added new error type enumerations:
FecErrorType- Forward Error Correction error types (13 error cases)
Pbkdf2ErrorType- PBKDF2 validation error types (2 error cases)
- Removed unused common string keys (UnexpectedError, Ready, Connecting, Disconnected, MongoDB, Unauthorized, NoActiveRequest, NoUserOnRequest, NoActiveResponse)
- Removed unused validation string keys (UsernameInUse, EmailInUse, InvalidEmail, InvalidCredentials, UsernameOrEmailRequired, TokenExpired, InvalidToken, ValidationError, MissingValidatedData, MissingValidatedDataForField, MnemonicRegex)
- Removed unused error string keys (LengthExceedsMaximum, LengthIsInvalidType, FailedToCreateRoleTemplate)
- Added extensive admin/system string keys (30+ new keys for database initialization, environment setup, error handling, and system operations)
-
Updated enumeration index to export new
FecErrorTypeand
Pbkdf2ErrorTypeenumerations
- Fri Oct 17 2025 14:18:00 GMT-0700 (Pacific Daylight Time)
- Add string keys
- Wed Oct 15 2025 16:53:00 GMT-0700 (Pacific Daylight Time)
- Version bump of ecies/i18n libs
- Wed Oct 15 2025 16:30:00 GMT-0700 (Pacific Daylight Time)
- Version bump ecies/i18n libs
- Add TranslatableSuiteError
- Wed Oct 15 2025 15:34:00 GMT-0700 (Pacific Daylight Time)
- Add missing Validation_InvalidToken
- Wed Oct 15 2025 15:23:00 GMT-0700 (Pacific Daylight Time)
- Include additional suite internationalization strings from express suite
- Wed Oct 15 2025 14:26:00 GMT-0700 (Pacific Daylight Time)
- Export ITokenUser
- Wed Oct 15 2025 14:22:00 GMT-0700 (Pacific Daylight Time)
- Add missing ITokenUser
- Sun Oct 12 2025 17:52:00 GMT-0700 (Pacific Daylight Time)
- Actually include failable result
- Version bump of libraries
- Sun Oct 12 2025 15:48:00 GMT-0700 (Pacific Daylight Time)
- Added IFailableResult class
- Sun Oct 12 2025 14:13:00 GMT-0700 (Pacific Daylight Time)
- Added missing export for IConstants in src/interfaces/index.ts
- Sun Oct 12 2025 13:34:00 GMT-0700 (Pacific Daylight Time)
- Added more constants and changed to a function to create the constants object
- Sun Oct 12 2025 13:26:37 GMT-0700 (Pacific Daylight Time)
- Initial release of
@digitaldefiance/suite-core-libwith core user management primitives, type-safe interfaces, secure backup code system, localized error handling, and multi-language support.
- Initial release of