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

octane-auth

v1.0.4

Published

OctaneAuth is a simple and customizable authentication module for JavaScript applications.

Downloads

14

Readme

Octane Auth Documentation

Octane Auth Logo

Simple and customizable authentication module for JavaScript applications.

Table of Contents

Installation

npm install octane-auth
# or
yarn add octane-auth

Quick Start

import OctaneAuth from "octane-auth";
import express from "express";

const app = express();
const auth = new OctaneAuth({
    jwtSecret: "your-secret-key",
    refreshSecret: "your-refresh-secret-key",
});

// Protected route example
app.get("/protected", auth.authenticate(), (req, res) => {
    res.json({ message: "Access granted", user: req.user });
});

Features

  • 🔐 JWT-based authentication with access and refresh tokens
  • 🔑 Secure password hashing with Argon2
  • 🚀 Express middleware support
  • ⚡ Simple and intuitive API
  • 🛡️ Built-in security best practices

API Reference

new OctaneAuth(options)

Creates a new instance of OctaneAuth.

Options

| Option | Type | Default | Description | | ---------------------- | ------ | ------------------------- | ------------------------------------ | | jwtSecret | string | 'your-secret-key' | Secret key for JWT signing | | refreshSecret | string | 'your-refresh-secret-key' | Secret key for refresh token signing | | tokenExpiration | string | '1h' | Access token expiration time | | refreshTokenExpiration | string | '7d' | Refresh token expiration time |

Methods

async hashPassword(password: string): Promise<string>

Hashes a password using Argon2.

const hashedPassword = await auth.hashPassword("userPassword123");

async verifyPassword(hash: string, password: string): Promise<boolean>

Verifies a password against a hash.

const isValid = await auth.verifyPassword(hashedPassword, "userPassword123");

generateTokens(payload: object): { accessToken: string, refreshToken: string }

Generates both access and refresh tokens.

const { accessToken, refreshToken } = auth.generateTokens({ userId: 123 });

verifyToken(token: string): object

Verifies an access token and returns the decoded payload.

try {
    const decoded = auth.verifyToken(accessToken);
    console.log(decoded.userId);
} catch (error) {
    console.error("Invalid token");
}

verifyRefreshToken(token: string): object

Verifies a refresh token and returns the decoded payload.

try {
    const decoded = auth.verifyRefreshToken(refreshToken);
    console.log(decoded.userId);
} catch (error) {
    console.error("Invalid refresh token");
}

refreshAccessToken(refreshToken: string): { tokens: { accessToken: string, refreshToken: string } }

Refreshes the access token using a valid refresh token.

try {
    const { tokens } = auth.refreshAccessToken(oldRefreshToken);
    // Use the new accessToken and refreshToken
} catch (error) {
    console.error("Failed to refresh token");
}

invalidateRefreshToken(refreshToken: string): void

Invalidates a refresh token.

auth.invalidateRefreshToken(refreshToken);

authenticate()

Express middleware for protecting routes using the access token.

app.get("/protected", auth.authenticate(), (req, res) => {
    res.json({ user: req.user });
});

Examples

User Registration

app.post("/register", async (req, res) => {
    const { username, password } = req.body;

    try {
        const hashedPassword = await auth.hashPassword(password);
        // Save user to database with hashedPassword
        const { accessToken, refreshToken } = auth.generateTokens({ username });
        res.json({ accessToken, refreshToken });
    } catch (error) {
        res.status(500).json({ error: "Registration failed" });
    }
});

User Login

app.post("/login", async (req, res) => {
    const { username, password } = req.body;

    try {
        // Fetch user from database
        const user = await User.findOne({ username });
        const isValid = await auth.verifyPassword(user.hashedPassword, password);

        if (!isValid) {
            return res.status(401).json({ error: "Invalid credentials" });
        }

        const { accessToken, refreshToken } = auth.generateTokens({ userId: user.id });
        res.json({ accessToken, refreshToken });
    } catch (error) {
        res.status(401).json({ error: "Login failed" });
    }
});

Refreshing Access Token

app.post("/refresh-token", (req, res) => {
    const { refreshToken } = req.body;

    try {
        const { tokens } = auth.refreshAccessToken(refreshToken);
        res.json(tokens);
    } catch (error) {
        res.status(401).json({ error: "Invalid refresh token" });
    }
});

Logout (Invalidating Refresh Token)

app.post("/logout", (req, res) => {
    const { refreshToken } = req.body;

    auth.invalidateRefreshToken(refreshToken);
    res.json({ message: "Logged out successfully" });
});

Security Considerations

  1. Environment Variables: Always use environment variables for sensitive data:
const auth = new OctaneAuth({
    jwtSecret: process.env.JWT_SECRET,
    refreshSecret: process.env.REFRESH_SECRET,
});
  1. HTTPS: Always use HTTPS in production environments.

  2. Token Storage: Store tokens securely:

    • Browser: Use HttpOnly cookies for refresh tokens, localStorage for access tokens
    • Mobile: Use secure storage solutions
  3. Password Requirements: Implement strong password requirements.

  4. Refresh Token Storage: In production, use a database instead of the in-memory Map for storing refresh tokens.

  5. Token Expiration: Adjust token expiration times based on your security requirements.


For more information or to contribute, please visit the OctaneAuth GitHub repository.