npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

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 Email

Reset Password

Verify User
      │
      ▼
Verify Passcode
      │
      ▼
Check Expiration
      │
      ▼
Validate Password History
      │
      ▼
Update Password
      │
      ▼
Revoke Tokens

Change Password

Verify Current Password
          │
          ▼
Password History Check
          │
          ▼
Optional Two-Factor Verification
          │
          ▼
Update Password
          │
          ▼
Revoke Tokens

Design

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-service

or

yarn add password-service

Core 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:

  1. A verification code is generated.
  2. The code is stored securely.
  3. The user receives the code.
  4. 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