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 🙏

© 2024 – Pkg Stats / Ryan Hefner

auth-guardian

v2.1.2

Published

auth-guardian a library for enhancing application security

Downloads

15

Readme


Guardian - Secure Your Applications with Confidence

Description

Guardian is a powerful JavaScript library designed to fortify your application's security with essential features for password management, authentication, and rate limiting. Whether you're developing user authentication, safeguarding against brute-force attacks, or enforcing password policies, Guardian has got you covered.

This library is easy to integrate into your project and offers a comprehensive set of features, making it a reliable choice for enhancing the security of your application.

you can run it with TypeScript or JavaScript.

Installation

To install Guardian, simply run the following command using npm:

npm i auth-guardian

Features

JSON Web Token (JWT) Generation and Verification

Guardian simplifies the generation and verification of JSON Web Tokens (JWTs) with its JwtAuth class. JWTs are widely used for user authentication, single sign-on, and session management. Guardian streamlines JWT handling to ensure a secure authentication process in your application.

Password Validation and Complexity Checks

With Guardian's PassPolicy class, you can enforce strong password complexity rules. Define minimum length, character requirements, and other policy settings to ensure that your users' passwords meet stringent security standards. Guardian helps protect your users' accounts by enforcing robust password policies.

Password Hashing and Verification

Guardian simplifies the secure hashing and verification of passwords using the bcrypt algorithm through its PassCheck class. Bcrypt is a well-established and trusted password hashing algorithm. Guardian ensures that your password management is secure, enhancing the overall safety of your user data.

Rate Limiting for Enhanced Security

Guardian offers a RateLimiter class to implement rate limits on actions like login attempts. Protect your application from brute-force attacks and excessive usage by controlling the rate at which users can perform specific actions. Guardian adds an extra layer of security to your application by preventing abuse.

Secure Password Generation

Guardian's PasswordGenerator class allows you to generate strong, random passwords based on your specified criteria. This feature is invaluable when creating secure user accounts, managing password resets, or enhancing password security in your application.

Usage/Examples

for imports

import only jwtAuth

const { JwtAuth } = require('guardian');

import only passPolicy

const { PassPolicy } = require('guardian');

import only passCheck

const { PassCheck } = require('guardian');

import only rateLimiter

const { RateLimiter } = require('guardian');

import only passwordGenerator

const { PasswordGenerator } = require('guardian');

import all

const { JwtAuth, PassPolicy, PassCheck, RateLimiter, PasswordGenerator } = require('guardian');

JSON Web Token (JWT) Management - JwtAuth

Initialize JwtAuth

const jwtAuth = new JwtAuth('mySecretKey');

Generate a JWT

const token = await jwtAuth.generateJWT({ userId: 123 }, { expiresIn: '1h' });

Verify a JWT

const result = await jwtAuth.verifyJWT(token);

Decode a JWT

const payload = await jwtAuth.decodeJWT(token);

Get JWT Expiration Date

const expirationDate = await jwtAuth.getJWTExpirationDate(token);

Check JWT Expiration

const isExpired = await jwtAuth.isJWTExpired(token);

Refresh a JWT

const refreshedToken = await jwtAuth.refreshJWT(token, { expiresIn: '1h' });

Blacklist a JWT

const result = await jwtAuth.blacklistJWT(token);

Password Policy Validation - PassPolicy

Initialize PassPolicy

const passPolicy = new PassPolicy({
  minLength: 8,
  minUpper: 1,
  minLower: 1,
  minNum: 1,
  minSpecial: 1,
  specialChars: "!@#$%^&*()_+~`|}{[]:;?><,./-=",
});

Validate a Password

const validation = passPolicy.validate('Strong1@Password');

Check Password Difference

const differenceValidation = passPolicy.checkDifference('NewPassword123', 'OldPassword123', 5);

Password Hashing and Verification - PassCheck

Initialize PassCheck

const passCheck = new PassCheck(10, { minLength: 8, requireDigits: true });

Verify a Password

const isMatch = await passCheck.verifyPassword('myPassword', 'hashedPassword');

Hash a Password

const hashedPassword = await passCheck.hashPassword('myPassword');

Rate Limiting for Enhanced Security - RateLimiter

Initialize RateLimiter

const rateLimiter = new RateLimiter({
  login: { max: 5, timespan: 60000 },
  signup: { max: 3, timespan: 3600000 },
});

Add a User

const userLimits = rateLimiter.addUser('user123');

Add an Event

const eventLimits = rateLimiter.addEvent('login', 5, 60000);

Remove a User

rateLimiter.removeUser('user123');

Attempt an Event

const result = rateLimiter.attemptEvent('user123', 'login');

Reset an Event for a User

rateLimiter.resetEventUser('user123', 'login');

Reset an Event

rateLimiter.resetEvent('login');

Reset a User

rateLimiter.resetUser('user123');

Reset All

rateLimiter.resetAll();

Get Last Attempt Time

const lastAttemptTime = rateLimiter.lastAttempt('user123', 'login');

Get User Attempts

const allAttempts = rateLimiter.userAttempts('user123', 'login');

Get Remaining Attempts

const remaining = rateLimiter.remainingAttempts('user123', 'login');

Password Generation - PasswordGenerator

Initialize PasswordGenerator

const options = {
    minLength: 8,
    maxLength: 16,
    minLower: 2,
    minUpper: 2,
    minNum: 2,
    minSpecial: 2,
    specialChars: "!@#$%^&*()_+~`|}{[]:;?><,./-="
};

const passwordGenerator = new PasswordGenerator(options);

Generate a Random Password

const randomPassword = passwordGenerator.Generate();

Notes

  • Guardian offers a comprehensive set of features for enhancing the security of your applications, including JWT handling, password validation, hashing, rate limiting, and password generation.

  • Each feature is encapsulated within its respective class, making it easy to integrate into your project.

  • These classes provide asynchronous methods that return promises, making them suitable for use in asynchronous code.

  • Ensure that you handle errors appropriately, especially when working with rate limiting to account for cases where users or events are not found or other errors occur.

  • The PassPolicy class provides methods for validating passwords based on complexity rules and checking the difference between old and new passwords.

  • The PassCheck class securely hashes passwords using bcrypt for storage and verification.

  • The RateLimiter class manages rate limits for events, useful for protecting against abuse or overuse of specific functionality.

  • The JwtAuth class simplifies JWT generation, verification, and management, including a token blacklist.

  • The PasswordGenerator class creates random passwords based on specified criteria.

Authors

License

MIT License

Guardian - Secure your applications with confidence!