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

@cauth/core

v0.2.5

Published

[![NPM Version](https://img.shields.io/npm/v/@cauth/core.svg)](https://www.npmjs.com/package/@cauth/core) [![License](https://img.shields.io/npm/l/@cauth/core.svg)](https://github.com/jonace-mpelule/cauth/blob/main/LICENSE)

Downloads

109

Readme

@cauth/core

NPM Version License

CAuth Core is a robust, type-safe authentication library for Node.js, built with TypeScript and Zod. It provides a modular foundation for building secure authentication systems with pluggable database and route handlers.

[!IMPORTANT] For more information and full documentation, visit cauth.dev.


✨ Features

  • 🛡️ Type-Safe: Comprehensive TypeScript support with Zod schema validation.
  • 🔑 JWT-Based: Industry-standard access and refresh token management.
  • 🎭 Role-Based Access Control (RBAC): Flexible, type-safe role management.
  • 📱 Multi-Factor Authentication: Secure OTP generation for 2FA, password resets, and more.
  • 📞 Phone & Email Support: E.164 phone validation and email support out of the box.
  • 🔒 Secure by Design:
    • Argon2id: State-of-the-art password hashing.
    • Hashed Refresh Tokens: Protection against database leaks.
    • CSPRNG OTPs: Cryptographically secure numeric codes.
  • 🧩 Modular Architecture: Decoupled core logic from database (Prisma) and framework (Express).

🚀 Installation

npm install @cauth/core
# or
yarn add @cauth/core
# or
pnpm add @cauth/core

🏁 Quick Start

Initialize CAuth by providing your database and route contractors, along with configuration for JWTs and roles.

import { CAuth } from '@cauth/core';
import { PrismaContractor } from '@cauth/prisma';
import { ExpressContractor } from '@cauth/express';
import { prisma } from './db';

const auth = CAuth({
  // Define your application roles
  roles: ['USER', 'ADMIN', 'EDITOR'] as const,
  
  // Pluggable contractors
  dbContractor: new PrismaContractor(prisma),
  routeContractor: new ExpressContractor(),

  jwtConfig: {
    accessTokenSecret: process.env.ACCESS_TOKEN_SECRET!,
    refreshTokenSecret: process.env.REFRESH_TOKEN_SECRET!,
    accessTokenLifeSpan: '15m',   // ms, string (ms format), or number
    refreshTokenLifeSpan: '7d',
  },

  otpConfig: {
    expiresIn: 300000, // 5 minutes in ms
    length: 6,         // 6-digit codes
  },
});

export default auth;

Basic Login Example

const result = await auth.FN.Login({
  email: '[email protected]',
  password: 'SecurePassword123!',
});

if (result.success) {
  console.log('Tokens:', result.value); // { accessToken, refreshToken, user }
} else {
  console.error('Errors:', result.errors); // Array of FNError objects
}

📖 Core Concepts

1. Functional Namespace (FN)

The FN namespace contains the core business logic functions. These are framework-agnostic and can be used in CLI tools, background jobs, or custom route handlers.

  • auth.FN.Register(data): Create new accounts.
  • auth.FN.Login(credentials): Authenticate and get tokens.
  • auth.FN.Logout({ refreshToken }): Revoke a session.
  • auth.FN.Refresh({ refreshToken }): Get a new access token.
  • auth.FN.ChangePassword(data): Update password with old password verification.
  • auth.FN.RequestOTPCode(data): Generate and send (via callback) an OTP.
  • auth.FN.LoginWithOTP(data): Passwordless login via code.

2. Routes Namespace (Routes)

The Routes namespace provides pre-built handlers for your chosen framework (e.g., Express). These wrap the FN logic and handle HTTP plumbing (status codes, body parsing).

// Express example
app.post('/auth/register', auth.Routes.Register());
app.post('/auth/login', auth.Routes.Login());

3. Middleware (Guard)

Protect your routes with type-safe RBAC.

// Only Admins can access this
app.get('/admin/stats', auth.Guard(['ADMIN']), (req, res) => {
  console.log('Admin ID:', req.cauth.id);
  res.send('Secret data');
});

🔒 Security Considerations

Password Hashing

CAuth uses Argon2id, the winner of the Password Hashing Competition. It provides excellent resistance against GPU/ASIC cracking and side-channel attacks.

Refresh Token Security

Refresh tokens are stored as HMAC hashes in your database. Even if your database is compromised, attackers cannot use the stored hashes to generate valid refresh tokens.

OTP Generation

OTPs are generated using node:crypto's randomInt, ensuring they are not predictable by attackers.


🛠️ API Reference

CAuthOptions

| Property | Type | Description | | :--- | :--- | :--- | | dbContractor | DatabaseContract | Implementation of database logic (e.g., PrismaContractor). | | routeContractor | RoutesContract | Implementation of framework logic (e.g., ExpressContractor). | | roles | string[] | Array of valid role strings. | | jwtConfig | JWTConfig | Secret keys and lifespans for tokens. | | otpConfig | OTPConfig | (Optional) Expiry and length for OTP codes. |


📄 License

MIT © Jonace Mpelule