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

@verb-js/allow

v0.0.1

Published

Authentication library for Verb framework

Readme

Allow

Authentication library for Verb. Sessions, JWT, OAuth, and account linking.

Part of the Verb Ecosystem

| Package | Description | |---------|-------------| | Verb | Fast web framework for Bun | | Hull | Ecto-inspired database toolkit | | Allow | Authentication library (this repo) | | Hoist | Deployment platform |

Features

  • 🔐 Multiple Authentication Strategies: Local (email/password), OAuth (GitHub, Google, Discord), JWT, and custom strategies
  • 🔗 Account Linking: Users can link multiple authentication methods to a single account
  • 🗄️ Database Integration: Optional SQLite/PostgreSQL storage for user data and sessions
  • 🧩 TypeScript First: Full type safety and excellent developer experience
  • 🚀 Bun Optimized: Built specifically for Bun runtime with native crypto and password hashing
  • 🌐 Verb Integration: Seamless integration with Verb's request/response handling
  • 🔧 Flexible Configuration: Configure strategies via TypeScript or store in database
  • 🧪 Testing Ready: Comprehensive test suite with Bun test

Installation

bun add @verb-js/allow

Quick Start

import { createServer } from "verb";
import { createAllow, getSessionMiddleware, getMiddleware, getHandlers } from "@verb-js/allow";

const allow = createAllow({
  secret: "your-secret-key",
  sessionDuration: 86400000, // 24 hours
  database: {
    type: "sqlite",
    connection: "auth.db",
    migrate: true
  },
  strategies: [
    {
      name: "local",
      type: "local",
      config: {
        usernameField: "email",
        passwordField: "password"
      }
    },
    {
      name: "github",
      type: "oauth",
      config: {
        clientId: process.env.GITHUB_CLIENT_ID!,
        clientSecret: process.env.GITHUB_CLIENT_SECRET!,
        callbackURL: "http://localhost:3000/auth/github/callback",
        scope: ["user:email"]
      }
    }
  ]
});

const app = createServer();

// Get middleware and handlers
const sessionMw = getSessionMiddleware(allow);
const middleware = getMiddleware(allow);
const handlers = getHandlers(allow);

// Add session middleware
app.use(sessionMw);

// Authentication routes
app.get("/auth/github", handlers.login("github"));
app.get("/auth/github/callback", handlers.callback("github"));

// Protected routes
app.get("/profile", middleware.requireAuth, handlers.profile);
app.get("/admin", middleware.requireRole("admin"), (req, res) => {
  res.json({ message: "Admin area", user: req.user });
});

// Account linking
app.get("/link/github", middleware.requireAuth, handlers.link("github"));
app.post("/unlink/github", middleware.requireAuth, handlers.unlink("github"));

// Logout
app.post("/logout", handlers.logout);

app.listen(3000);

Configuration

Basic Configuration

interface AuthConfig {
  secret: string;                    // JWT secret key
  sessionDuration?: number;          // Session duration in milliseconds
  database?: DatabaseConfig;         // Optional database configuration
  strategies: StrategyConfig[];      // Authentication strategies
}

Database Configuration

interface DatabaseConfig {
  type: "sqlite" | "postgres";
  connection: string;                // Database connection string
  migrate?: boolean;                 // Run migrations on startup
}

Strategy Configuration

interface StrategyConfig {
  name: string;                      // Strategy name
  type: "local" | "oauth" | "jwt";   // Strategy type
  config: Record<string, any>;       // Strategy-specific configuration
  enabled?: boolean;                 // Enable/disable strategy
}

Authentication Strategies

Local Strategy (Email/Password)

{
  name: "local",
  type: "local",
  config: {
    usernameField: "email",          // Field name for username
    passwordField: "password",       // Field name for password
    hashRounds: 12                   // Bcrypt hash rounds
  }
}

OAuth Strategy

{
  name: "github",
  type: "oauth",
  config: {
    clientId: "your-client-id",
    clientSecret: "your-client-secret",
    callbackURL: "http://localhost:3000/auth/github/callback",
    scope: ["user:email"]
  }
}

Built-in OAuth Providers

import { useStrategy, githubStrategy, googleStrategy, discordStrategy } from "@verb-js/allow";

// GitHub
useStrategy(allow, githubStrategy({
  clientId: process.env.GITHUB_CLIENT_ID!,
  clientSecret: process.env.GITHUB_CLIENT_SECRET!,
  callbackURL: "http://localhost:3000/auth/github/callback"
}));

// Google
useStrategy(allow, googleStrategy({
  clientId: process.env.GOOGLE_CLIENT_ID!,
  clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
  callbackURL: "http://localhost:3000/auth/google/callback"
}));

// Discord
useStrategy(allow, discordStrategy({
  clientId: process.env.DISCORD_CLIENT_ID!,
  clientSecret: process.env.DISCORD_CLIENT_SECRET!,
  callbackURL: "http://localhost:3000/auth/discord/callback"
}));

JWT Strategy

{
  name: "jwt",
  type: "jwt",
  config: {
    secret: "jwt-secret",
    algorithm: "HS256",
    expiresIn: "1h"
  }
}

Custom Strategies

Create custom authentication strategies as functions:

import { useStrategy, generateError, generateSuccess } from "@verb-js/allow";
import type { VerbRequest, AuthResult, AuthStrategy } from "@verb-js/allow";

function createAPIKeyStrategy(): AuthStrategy {
  return {
    name: "apikey",
    
    async authenticate(req: VerbRequest): Promise<AuthResult> {
      const apiKey = req.headers.get("X-API-Key");
      
      if (!apiKey) {
        return generateError("Missing API key");
      }

      const user = await validateAPIKey(apiKey);
      if (!user) {
        return generateError("Invalid API key");
      }

      return generateSuccess(user);
    }
  };
}

async function validateAPIKey(apiKey: string) {
  // Your validation logic here
  return null;
}

// Register custom strategy
useStrategy(allow, createAPIKeyStrategy());

Middleware

Authentication Middleware

import { getMiddleware } from "@verb-js/allow";

const middleware = getMiddleware(allow);

// Require authentication
app.get("/protected", middleware.requireAuth, (req, res) => {
  res.json({ user: req.user });
});

// Optional authentication
app.get("/mixed", middleware.optionalAuth, (req, res) => {
  if (req.isAuthenticated()) {
    res.json({ user: req.user });
  } else {
    res.json({ message: "Public content" });
  }
});

// Require specific role
app.get("/admin", middleware.requireRole("admin"), (req, res) => {
  res.json({ message: "Admin area" });
});

Session Middleware

import { getSessionMiddleware } from "@verb-js/allow";

// Add session support
const sessionMw = getSessionMiddleware(allow);
app.use(sessionMw);

Account Linking

Allow users to link multiple authentication methods to a single account:

import { getMiddleware, getHandlers, getUserStrategies } from "@verb-js/allow";

const middleware = getMiddleware(allow);
const handlers = getHandlers(allow);

// Link GitHub account to current user
app.get("/link/github", middleware.requireAuth, handlers.link("github"));

// Unlink GitHub account
app.post("/unlink/github", middleware.requireAuth, handlers.unlink("github"));

// Get user's linked strategies
const strategies = await getUserStrategies(allow, userId);

Database Migrations

Run database migrations to set up the required tables:

import { runMigrations } from "@verb-js/allow";

await runMigrations({
  database: {
    type: "sqlite",
    connection: "auth.db"
  }
});

Or run migrations via CLI:

bun run migrate

Password Hashing

Use Bun's built-in password hashing for local authentication:

import { hashPassword, verifyPassword } from "@verb-js/allow";

// Hash password
const hash = await hashPassword("password123");

// Verify password
const isValid = await verifyPassword("password123", hash);

Testing

# Run all tests
bun test

# Run tests in watch mode
bun test --watch

# Run specific test file
bun test src/allow.test.ts

Examples

Check out the examples directory for complete working examples:

API Reference

Core Functions

// Main factory function
function createAllow(config: AuthConfig): AllowInstance

// Strategy management
function useStrategy(allow: AllowInstance, strategy: AuthStrategy): void
function authenticate(allow: AllowInstance, strategyName: string, req: VerbRequest): Promise<AuthResult>
function callback(allow: AllowInstance, strategyName: string, req: VerbRequest): Promise<AuthResult>

// Session management
function createSession(allow: AllowInstance, user: AuthUser, data?: Record<string, any>): Promise<AuthSession>
function getSession(allow: AllowInstance, sessionId: string): Promise<AuthSession | null>
function updateSession(allow: AllowInstance, sessionId: string, data: Record<string, any>): Promise<void>
function destroySession(allow: AllowInstance, sessionId: string): Promise<void>

// User management
function getUser(allow: AllowInstance, req: VerbRequest): Promise<AuthUser | null>
function linkStrategy(allow: AllowInstance, userId: string, strategyName: string, strategyId: string, profile: any, tokens?: any): Promise<UserStrategy>
function unlinkStrategy(allow: AllowInstance, userId: string, strategyName: string): Promise<void>
function getUserStrategies(allow: AllowInstance, userId: string): Promise<UserStrategy[]>

// Middleware and handlers
function getMiddleware(allow: AllowInstance): AuthMiddleware
function getSessionMiddleware(allow: AllowInstance): Function
function getHandlers(allow: AllowInstance): AuthHandlers

Types

interface AuthUser {
  id: string;
  username?: string;
  email?: string;
  profile?: Record<string, any>;
  strategies: UserStrategy[];
  createdAt: Date;
  updatedAt: Date;
}

interface AuthSession {
  id: string;
  userId: string;
  data: Record<string, any>;
  expiresAt: Date;
  createdAt: Date;
}

interface AuthResult {
  success: boolean;
  user?: AuthUser;
  error?: string;
  redirect?: string;
  tokens?: {
    access_token?: string;
    refresh_token?: string;
    expires_at?: Date;
  };
}

Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

License

MIT License - see the LICENSE file for details.

Support