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

@kdsp/auth

v1.0.1

Published

Shared authentication middleware and models for Kernel services

Readme

@kdsp/auth

Shared authentication middleware, models, and services for Kernel microservices.

Installation

npm install @kdsp/auth

Peer Dependencies

This package requires the following peer dependencies:

npm install mongoose express

Features

  • JWT Token Service - Generate, verify, and manage JWT tokens
  • User Model - Complete user schema with roles, permissions, OAuth support
  • Session Model - Session management with device tracking and auto-expiry
  • Role Model - Flexible role-based access control with inheritance
  • Authentication Middleware - Ready-to-use Express middleware
  • Authorization Middleware - Role and permission-based access control
  • Error Classes - Comprehensive error types for auth flows

Quick Start

1. Initialize Models

import mongoose from 'mongoose';
import { getUserModel, getSessionModel, getRoleModel } from '@kdsp/auth';

// Connect to MongoDB
await mongoose.connect('mongodb://localhost:27017/myapp');

// Initialize models (creates them if not exists)
const User = getUserModel({ multiTenantEnabled: false });
const Session = getSessionModel({ multiTenantEnabled: false });
const Role = getRoleModel();

2. Configure Token Service

import { createTokenService } from '@kdsp/auth';

const tokenService = createTokenService({
  accessTokenSecret: process.env.JWT_SECRET!,
  accessTokenExpiry: '1h',
  refreshTokenExpiry: '7d',
  issuer: 'my-app',
  audience: 'my-api',
});

// Generate tokens for a user
const tokens = tokenService.generateTokenPair({
  userId: user._id.toString(),
  tenantId: user.tenantId?.toString(),
  roles: user.roles.map(r => r.name),
});

3. Setup Auth Middleware

import express from 'express';
import { createAuthMiddleware, getUserModel, getSessionModel } from '@kdsp/auth';

const app = express();

// Create middleware factory
const auth = createAuthMiddleware({
  tokenService,
  userModel: getUserModel(),
  sessionModel: getSessionModel(),
  validateSession: true, // Check session in DB (optional but recommended)
});

// Protected route
app.get('/api/profile', auth.authenticate, (req, res) => {
  res.json({ user: req.user });
});

// Optional auth (user attached if token valid, but not required)
app.get('/api/public', auth.optionalAuth, (req, res) => {
  res.json({ user: req.user || null });
});

// Role-based authorization
app.delete('/api/users/:id', 
  auth.authenticate, 
  auth.authorize('admin', 'superadmin'),
  (req, res) => {
    // Only admins can delete users
  }
);

// Permission-based authorization
app.post('/api/articles',
  auth.authenticate,
  auth.requirePermission('articles.create'),
  (req, res) => {
    // User must have 'articles.create' permission
  }
);

// Resource ownership (user can only access own resources)
app.get('/api/users/:userId/settings',
  auth.authenticate,
  auth.requireOwnership('userId'),
  (req, res) => {
    // User can only access their own settings (admins bypass)
  }
);

4. Custom Logger

import winston from 'winston';

const logger = winston.createLogger({ /* ... */ });

const auth = createAuthMiddleware({
  tokenService,
  userModel: getUserModel(),
  sessionModel: getSessionModel(),
  logger: {
    debug: (msg, ...args) => logger.debug(msg, ...args),
    info: (msg, ...args) => logger.info(msg, ...args),
    warn: (msg, ...args) => logger.warn(msg, ...args),
    error: (msg, ...args) => logger.error(msg, ...args),
  },
});

API Reference

Models

User Model

import { getUserModel, createUserModel, UserSchemaOptions } from '@kdsp/auth';

// Get existing model or create new one
const User = getUserModel(options?: UserSchemaOptions);

// Force create new model (useful in tests)
const User = createUserModel(options?: UserSchemaOptions);

interface UserSchemaOptions {
  multiTenantEnabled?: boolean;  // Default: false
  maxLoginAttempts?: number;     // Default: 5
  lockoutDurationMs?: number;    // Default: 15 minutes
}

Session Model

import { getSessionModel, createSessionModel, SessionSchemaOptions } from '@kdsp/auth';

const Session = getSessionModel(options?: SessionSchemaOptions);

interface SessionSchemaOptions {
  multiTenantEnabled?: boolean;  // Default: false
}

Role Model

import { getRoleModel, createRoleModel } from '@kdsp/auth';

const Role = getRoleModel();

Token Service

import { createTokenService, TokenServiceConfig } from '@kdsp/auth';

const tokenService = createTokenService(config: TokenServiceConfig);

interface TokenServiceConfig {
  accessTokenSecret: string;      // Required
  accessTokenExpiry?: string;     // Default: '1h'
  refreshTokenExpiry?: string;    // Default: '7d'
  issuer?: string;                // Default: 'kernel-auth'
  audience?: string;              // Default: 'kernel-api'
}

// Methods
tokenService.generateAccessToken(payload);
tokenService.generateRefreshToken();
tokenService.generateTokenPair(user);
tokenService.verifyAccessToken(token);
tokenService.decodeToken(token);
tokenService.generateVerificationToken();
tokenService.generatePasswordResetToken();
tokenService.hashToken(token);

Middleware

import { createAuthMiddleware, AuthMiddlewareConfig } from '@kdsp/auth';

const auth = createAuthMiddleware(config: AuthMiddlewareConfig);

interface AuthMiddlewareConfig {
  tokenService: TokenService;
  userModel: IUserModel;
  sessionModel: ISessionModel;
  logger?: Logger;
  validateSession?: boolean;  // Default: true
}

// Available middleware
auth.authenticate;              // Require valid token
auth.optionalAuth;              // Attach user if token present
auth.authorize(...roles);       // Require specific roles
auth.requirePermission(...perms); // Require specific permissions
auth.requireOwnership(field);   // Ensure resource ownership

Error Classes

import {
  AppError,
  BadRequestError,
  UnauthorizedError,
  ForbiddenError,
  NotFoundError,
  ConflictError,
  ValidationError,
  TooManyRequestsError,
  InternalServerError,
  ServiceUnavailableError,
  AuthenticationError,
  TokenExpiredError,
  InvalidTokenError,
  AccountLockedError,
  EmailNotVerifiedError,
  InsufficientPermissionsError,
} from '@kdsp/auth';

Multi-Tenancy

Enable multi-tenant support:

const User = getUserModel({ multiTenantEnabled: true });
const Session = getSessionModel({ multiTenantEnabled: true });

// Now tenantId is required on User and Session documents

TypeScript Support

Full TypeScript support with exported types:

import type {
  IUser,
  IUserModel,
  ISession,
  ISessionModel,
  IRole,
  IRoleModel,
  TokenPayload,
  TokenPair,
  AuthenticatedRequest,
  AuthenticatedUser,
} from '@kdsp/auth';

Migration from Existing Code

If migrating from existing user-management code:

  1. Install the package
  2. Replace model imports with getUserModel(), etc.
  3. Replace middleware imports with createAuthMiddleware()
  4. Update config to match the new interface

License

MIT