password-service
v0.2.1
Published
password
Downloads
240
Readme
password-service
A lightweight, library-agnostic TypeScript library for password management.
This library provides a complete password lifecycle implementation, including password reset, password change, password history, password reuse prevention, optional two-factor verification, SQL repository support, and email integration.
It is designed around dependency injection and small interfaces, allowing it to work with virtually any database, hashing algorithm, or email provider.
Features
- 🔐 Password reset workflow
- 🔑 Password change workflow
- 📜 Password history
- 🚫 Prevent password reuse
- ⏱ Configurable passcode expiration
- ✉️ Email abstraction
- 🔒 Password hashing abstraction
- 🔄 Token revocation hook
- 📱 Optional two-factor verification
- 🗄 Generic SQL repository
- ⚙️ Configurable database schema
- 🧩 Framework independent
- 📝 Written in TypeScript
Password Flow
Forgot Password
User
│
▼
Generate Passcode
│
▼
Hash Passcode
│
▼
Store Passcode
│
▼
Send EmailReset Password
Verify User
│
▼
Verify Passcode
│
▼
Check Expiration
│
▼
Validate Password History
│
▼
Update Password
│
▼
Revoke TokensChange Password
Verify Current Password
│
▼
Password History Check
│
▼
Optional Two-Factor Verification
│
▼
Update Password
│
▼
Revoke TokensDesign
The library separates business logic from infrastructure.
PasswordService
│
┌───────────────┼────────────────┐
│ │ │
▼ ▼ ▼
PasswordRepository Comparator PasscodeRepository
│ │ │
▼ ▼ ▼
Database bcrypt/argon2 Redis/SQL/etc.The service itself has no dependency on:
- Express
- NestJS
- Fastify
- Koa
- Next.js
- MySQL
- PostgreSQL
- MongoDB
- bcrypt
- argon2
Everything is injected through interfaces.
Installation
npm install password-serviceor
yarn add password-serviceCore Interfaces
Comparator
Responsible for hashing and comparing passwords.
interface Comparator {
compare(data: string, encrypted: string): Promise<boolean>;
hash(password: string): Promise<string>;
}Example using bcrypt:
import bcrypt from "bcrypt";
const comparator = {
compare: bcrypt.compare,
hash: (password: string) => bcrypt.hash(password, 10)
};PasswordRepository
Responsible for loading users and updating passwords.
interface PasswordRepository<ID> {
getUser(usernameOrEmail: string): Promise<User<ID> | null>;
update(id: ID, password: string): Promise<number>;
getHistory(id: ID): Promise<string[]>;
}PasscodeRepository
Stores temporary reset codes.
interface PasscodeRepository<ID> {
save(id: ID, code: string, expireAt: Date): Promise<number>;
load(id: ID): Promise<Passcode | null>;
delete(id: ID): Promise<number>;
}Creating a Password Service
const service = new PasswordService(
comparator,
repository,
sendResetCode,
300,
passcodeRepository
);Forgot Password
await service.forgot("[email protected]");Reset Password
await service.reset({
username: "john",
passcode: "382194",
password: "NewPassword123!"
});Change Password
await service.change({
username: "john",
currentPassword: "OldPassword",
password: "NewPassword"
});Password History
The service can prevent users from reusing previous passwords.
const service = new PasswordService(
comparator,
repository,
sendResetCode,
300,
passcodeRepository,
5
);The example above prevents reuse of the previous five passwords.
Two-Factor Verification
Password changes can optionally require a second verification step.
const service = new PasswordService(
comparator,
repository,
sendResetCode,
300,
passcodeRepository,
5,
revokeTokens,
hasTwoFactors,
undefined,
sendPasscode
);If two-factor authentication is enabled for the user:
- A verification code is generated.
- The code is stored securely.
- The user receives the code.
- The password is updated only after successful verification.
SQL Repository
The package includes a generic SQL repository implementation.
Supported databases include any SQL database that can implement the DB interface.
interface DB {
param(i: number): string;
execute(sql: string, args?: any[]): Promise<number>;
executeBatch(statements: Statement[]): Promise<number>;
query<T>(sql: string, args?: any[]): Promise<T[]>;
}Typical adapters include:
- MySQL
- PostgreSQL
- SQL Server
- SQLite
- Oracle
Configurable Schema
Database table names are configurable.
useRepository(db, {
user: "users",
password: "user_passwords",
history: "password_history"
});Field names are also configurable.
useRepository(db, config, 5, {
id: "user_id",
username: "login_name",
contact: "email_address",
password: "password_hash"
});Mail Sender
A helper class is included for sending email notifications.
const sender = new MailSender(
sendMail,
"[email protected]",
emailTemplate,
"Password Reset"
);Utilities
The library also exports utility functions.
generate();
addSeconds(date, seconds);
after(date1, date2);
buildUpdate();
buildUpdateTable();Security Notes
This library is designed to work with secure password hashing algorithms such as:
- bcrypt
- Argon2
- PBKDF2
- scrypt
It is recommended to:
- Use HTTPS.
- Revoke authentication tokens after password changes.
- Enable password history.
- Enable two-factor verification for sensitive accounts.
- Apply rate limiting to password reset endpoints.
- Enforce password complexity rules.
Why This Library?
Unlike many password utilities that only hash passwords, this library provides a complete password management solution.
It includes:
- Password reset
- Password change
- Password history
- Duplicate password prevention
- Two-factor support
- SQL repository
- Email integration
- Framework independence
- Dependency injection
- Generic database abstraction
This makes it suitable for enterprise applications, REST APIs, microservices, and authentication servers.
Comparison with other libraries
License
MIT
