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

mbkauthe

v5.10.2

Published

MBKTech's reusable authentication system for Node.js applications.

Readme

MBKAuthe - Node.js Authentication System

Website Version License Node.js Check npm version Downloads

MBKAuthe is an open source authentication package for Node.js and Express, backed by PostgreSQL or SQLite. It handles login, session validation, role/app access checks, optional TOTP 2FA, OAuth login, API token authentication, and multi-session management.

🌐 Official Website & Live Docs: https://mbkauthe.mbktech.org

Note: MBKAuthe is intentionally focused on authentication and session validation. The broader user, permission, and dashboard management system is a separate MBKTech product named MBKCore(closed source for now).

Features

  • Express middleware for session validation and role checks
  • PostgreSQL or SQLite storage for users, sessions, 2FA, trusted devices, and API tokens
  • Secure password authentication with PBKDF2
  • Optional TOTP 2FA with trusted devices
  • GitHub App and Google OAuth login flows
  • Optional browser-based CLI/device login flow for issuing API tokens
  • API token authentication with read-only/write scopes
  • Configurable multi-session support per user
  • CSRF protection, rate limiting, secure cookies, and session fixation prevention
  • Customizable Handlebars views
  • Vercel/serverless-friendly deployment support
  • Dev-only DB Query Monitor with callsite, timing, request context, and pool stats

Installation

npm install mbkauthe

Quick Start

  1. Copy the environment template.
Copy-Item .env.example .env
  1. Configure environment values.

See the configuration guide for mbkautheVar, mbkauthShared, OAuth settings, session settings, and deployment flags.

  1. Choose a database backend.

MBKAuthe supports two backends, selected with DB_TYPE in mbkautheVar:

  • PostgreSQL (default) - set LOGIN_DB to a connection string. Recommended for production and multi-instance deployments.
  • SQLite - set DB_TYPE to sqlite and SQLITE_PATH to a file path (created if missing). No database server required - convenient for development, tests, and small single-instance deployments. Uses better-sqlite3 with WAL mode; expect -wal/-shm side files next to the database file. See the SQLite backend notes in the database guide.
  1. Create database tables.
npm run create-tables

The script applies docs/schema/db.sql (PostgreSQL) or docs/schema/db.sqlite.sql (SQLite) to the configured backend. You can also run the matching SQL file yourself.

The schema includes a default superadmin user (support / 12345678). Change that password immediately. See the database guide.

  1. Mount MBKAuthe in Express.
import express from "express";
import dotenv from "dotenv";
import mbkauthe, { sessVal, roleChk, sessRole } from "mbkauthe";

dotenv.config();

const app = express();

app.use(mbkauthe);

app.get("/dashboard", sessVal, (req, res) => {
  res.send(`Welcome ${req.session.user.username}!`);
});

app.get("/admin", sessVal, roleChk("superadmin"), (req, res) => {
  res.send("Admin Panel");
});

// Or combine session and role checks into one middleware:
app.get("/admin", sessRole("superadmin"), (req, res) => {
  res.send("Admin Panel");
});

app.listen(3000);

Common Exports

  • sessVal / validateSession - require a valid session or API token.
  • roleChk / checkRolePermission - require a role after session validation.
  • sessRole / validateSessionAndRole - combine session and role checks.
  • sessPerm / permChk - dynamic permission middleware (app:service:action) using a session-cached, catalog-driven permission model. See the Permissions guide.
  • definePermissions / syncAppPermissions - declare an app's permission manifest and auto-sync it to the permission catalog.
  • strictValidateSession - require cookie session authentication only.
  • strictValidateSessionAndRole - strict cookie session plus role check.
  • authenticate(token) - protect server-to-server routes with a static bearer token.
  • dblogin - access the configured database pool (pg.Pool or the SQLite adapter, per DB_TYPE).
  • dbType - the active backend: "postgres" or "sqlite".
  • SqliteAdapter / SqlitePool - universal SQLite adapter wrapping better-sqlite3 with FIFO transaction mutex, type coercion, and row normalization.
  • PostgresAdapter - PostgreSQL database adapter wrapping pg.Pool with dialect binding.
  • translatePgToSqlite - runtime SQL translator for converting PostgreSQL queries ($1, ANY(), casts, ILIKE, NOW(), to_char, gen_random_uuid) to SQLite.
  • BaseRepository - extensible base repository with execute(), query(), withTransaction(), setDb(), and dialect query helpers.
  • postgresDialect / sqliteDialect - dialect SQL tokens for quoting, parameters, and pagination.
  • cliAuthRouter - the browser-based CLI/device-login routes, mounted automatically unless disabled.

See the Dual-Database & Repository Architecture Guide for integrating the standardized database layer and PostgreSQL + SQLite in host apps.

API Token Management

MBKAuthe provides both sides of the API token lifecycle:

  • Authentication (built-in): Bearer tokens prefixed with mbk_ are validated on every request (sessVal / sessRole accept them), and each token carries an explicit permission allow-list enforced by permChk / sessPerm. See the API reference and docs/schema/ for the ApiTokens table.
  • Management backend (mounted by the host app): the CRUD repository, user-facing routes, and admin routes. The page views (settings/api-tokens.handlebars, dashboard/admin/api-tokens.handlebars) are provided by the host application — only the backend ships here.

Exports:

  • apiTokenRepository / ApiTokenRepository - repository with listForUser, countForUser, insert, deleteByIdAndUsername, findByTokenHash, updateLastUsedByHash, plus admin helpers (listAll, stats, listForUserAdmin, findInfoById, deleteById, deleteAllByUsername, listForUserDetail).
  • apiTokensRouter - user-facing routes: GET /user/api-tokens, POST /api/token, DELETE /api/tokens/:id, POST /api/tokens/verify.
  • adminApiTokensRouter - admin routes: GET /dashboard/admin/api-tokens, GET /api/admin/api-tokens/stats, GET /api/admin/api-tokens/:username, DELETE /api/admin/api-tokens/:id, DELETE /api/admin/api-tokens/user/:username.
  • hashApiToken(token) - SHA-256 hash for storage/comparison.
  • generatePrefixedToken(prefix = "mbk_") / generateRandomHex(bytes = 32) - token generation helpers.

Mount the routers wherever you want the endpoints to live (they use root-relative paths):

import express from "express";
import mbkauthe, { apiTokensRouter, adminApiTokensRouter } from "mbkauthe";

const app = express();
app.use(mbkauthe);
app.use(apiTokensRouter);        // /user/api-tokens, /api/token, ...
app.use(adminApiTokensRouter);   // /dashboard/admin/api-tokens, /api/admin/api-tokens/*

See the API reference for endpoints, middleware, examples, security notes, and rate limits.

JSON Error Responses

Browser page routes usually render HTML errors, while API/AJAX-style requests receive JSON. MBKAuthe treats a request as JSON when any of these are true:

  • The path starts with /mbkauthe/api/ or /api/
  • X-Requested-With: XMLHttpRequest
  • Accept prefers JSON and does not explicitly prefer text/html
  • User-Agent looks like a non-browser client such as curl, wget, or Postman
  • User-Agent: json
curl -i -H "User-Agent: json" http://localhost:3000/mbkauthe/test

Development

npm test
npm run test:watch
npm run dev

Development-only diagnostics are mounted when process.env.env === "dev":

  • /mbkauthe/db - DB Query Monitor UI
  • /mbkauthe/db.json - DB Query Monitor JSON
  • /mbkauthe/db/reset - reset diagnostic query logs
  • /mbkauthe/validate-superadmin - superadmin validation check

Documentation

Deployment Checklist

  • Set IS_DEPLOYED=true
  • Use strong SESSION_SECRET_KEY and MAIN_SECRET_TOKEN values
  • Enable HTTPS
  • Set the correct DOMAIN
  • Set an appropriate COOKIE_EXPIRE_TIME
  • Store secrets in environment variables
  • Configure OAuth credentials only when the matching provider is enabled
  • If using the SQLite backend, put SQLITE_PATH on persistent disk (not ephemeral/serverless storage) and back up the database together with its -wal/-shm side files

Vercel deployments can use shared OAuth credentials through mbkauthShared.

License

MIT - see LICENSE.

Author

Muhammad Bin Khalid
[email protected] | [email protected]
GitHub @MIbnEKhalid

Links