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

@ztxtxwd/workers-oauth-provider

v0.0.16

Published

Universal OAuth 2.1 Provider Framework with pluggable storage support

Readme

Universal OAuth Provider

npm version Build Status License: MIT TypeScript

A comprehensive, framework-agnostic OAuth 2.1 Provider implementation with pluggable storage support. Built with TypeScript and designed to work seamlessly across different environments - from Node.js servers to Cloudflare Workers and beyond.

✨ Features

  • 🔐 Complete OAuth 2.1 Implementation - Full support for authorization code flow, refresh tokens, and PKCE
  • 🔌 Pluggable Storage - Built-in LowDB support with adapter pattern for custom storage solutions
  • 🚀 Framework Agnostic - Works with Express.js, Fastify, native Node.js HTTP, and Cloudflare Workers
  • 📝 TypeScript First - Full type safety and excellent IDE support
  • 🛡️ Security Focused - Secure token generation, proper PKCE implementation, and no secret storage
  • 🎯 Easy Integration - Drop-in replacement for existing OAuth providers with minimal configuration
  • 📦 Zero Dependencies - Only depends on LowDB for storage, everything else is built-in

📦 Installation

npm install oauth-provider-universal

🚀 Quick Start

Standalone Usage

import { OAuthProvider, createDefaultEnv } from 'oauth-provider-universal';

// Create environment with local file storage
const env = createDefaultEnv('./oauth-data.json');

// Simple API handler
class ApiHandler {
  constructor(ctx, env) {}

  async fetch(request, env, ctx) {
    const user = ctx.props; // Contains authenticated user info

    return new Response(JSON.stringify({
      message: 'Hello from protected API!',
      user
    }), {
      headers: { 'Content-Type': 'application/json' }
    });
  }
}

// Create OAuth provider
const provider = new OAuthProvider({
  apiRoute: '/api/',
  apiHandler: ApiHandler,
  authorizationEndpoint: 'https://yourapp.com/authorize',
});

// Use with any web framework

Express.js Integration

import express from 'express';
import { OAuthProvider, createDefaultEnv } from 'oauth-provider-universal';

const app = express();
const env = createDefaultEnv('./oauth-data.json');

class ProtectedApiHandler {
  constructor(ctx, env) {}

  async fetch(request, env, ctx) {
    const user = ctx.props;
    // Your protected API logic here
  }
}

const oauthProvider = new OAuthProvider({
  apiRoute: '/api/',
  apiHandler: ProtectedApiHandler,
  defaultHandler: YourAuthHandler,
  authorizationEndpoint: 'https://yourapp.com/authorize',
});

// Middleware to handle all requests through OAuth provider
app.use('*', async (req, res) => {
  const request = new Request(`${req.protocol}://${req.get('host')}${req.originalUrl}`, {
    method: req.method,
    headers: req.headers,
    body: req.body
  });

  const ctx = {
    props: {},
    waitUntil: (p) => p.catch(console.error),
    passThroughOnException: () => {}
  };

  const response = await oauthProvider.fetch(request, env, ctx);

  res.status(response.status);
  response.headers.forEach((value, name) => res.set(name, value));
  res.send(await response.text());
});

🔧 Configuration Options

const provider = new OAuthProvider({
  // API Configuration
  apiRoute: '/api/',                    // Routes that require authentication
  apiHandler: MyApiHandler,             // Handler for authenticated requests
  defaultHandler: MyAuthHandler,        // Handler for auth flows

  // OAuth Endpoints
  authorizationEndpoint: 'https://yourapp.com/authorize',
  tokenEndpoint: '/token',              // Default: '/token'

  // Token Settings
  defaultAccessTokenTTL: 3600,          // 1 hour
  defaultRefreshTokenTTL: 2592000,      // 30 days
  defaultAuthorizationCodeTTL: 600,    // 10 minutes

  // Features
  clientRegistrationEndpoint: '/register',  // Optional client registration
  corsAllowOrigins: ['*'],                  // CORS configuration

  // Callbacks
  async getAuthorizationCodeGrantProps(clientId, userId, scope) {
    return { customData: 'value' };
  },

  async apiRouteTokenExchangeCallback(grantType, clientId, userId, scope, props) {
    // Transform user data during token exchange
    return { newProps: { ...props, lastLogin: Date.now() } };
  },

  async resolveExternalToken(token) {
    // Support external tokens (JWT, etc.)
    return { userId: 'external-user', props: {} };
  }
});

💾 Storage Adapters

Built-in LowDB Storage

The library includes a LowDB-based storage adapter that works with local JSON files:

import { createDefaultEnv } from 'oauth-provider-universal';

// Custom storage path
const env = createDefaultEnv('/path/to/storage.json');

Custom Storage Adapter

Implement your own storage by extending the KVNamespace interface:

import { OAuthProvider, type KVNamespace } from 'oauth-provider-universal';

class RedisStorage implements KVNamespace {
  async get(key: string, options?: any): Promise<any> {
    // Redis get implementation
  }

  async put(key: string, value: string, options?: any): Promise<void> {
    // Redis put implementation with TTL support
  }

  async delete(key: string): Promise<void> {
    // Redis delete implementation
  }

  async list(options?: any): Promise<{ keys: Array<{ name: string }>, list_complete: boolean }> {
    // Redis list implementation with pagination
  }
}

const env = { OAUTH_KV: new RedisStorage() };
const provider = new OAuthProvider({ /* ... */ }, env);

🔐 OAuth Flow Implementation

1. Authorization Request

// In your authorization handler
async handleAuthRequest(request, env, ctx) {
  const oauthReq = await env.OAUTH_PROVIDER.parseAuthRequest(request);

  // Authenticate your user (your implementation)
  const user = await authenticateUser(username, password);

  if (user) {
    // Create authorization grant
    const redirectUrl = await env.OAUTH_PROVIDER.createAuthorizationGrant(
      oauthReq,
      user,
      { scope: oauthReq.scope }
    );

    return Response.redirect(redirectUrl, 302);
  }
}

2. Token Exchange

The token endpoint is handled automatically by the provider:

curl -X POST https://yourapp.com/token \
  -H "Content-Type: application/x-www-form-urlencoded" \
  -d "grant_type=authorization_code&code=YOUR_CODE&client_id=test&redirect_uri=https://yourapp.com/callback"

3. Access Protected Resources

curl -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
  https://yourapp.com/api/protected

📚 Examples

🧪 Testing

# Run tests
npm test

# Run tests in watch mode
npm run test:watch

# Run tests with coverage
npm run test:coverage

🏗️ Development

# Clone the repository
git clone https://github.com/your-username/universal-oauth-provider.git
cd universal-oauth-provider

# Install dependencies
npm install

# Start development with watch mode
npm run dev

# Build the project
npm run build

# Type checking
npm run typecheck

# Format code
npm run prettier

📋 API Reference

Classes

  • OAuthProvider - Main OAuth provider class
  • LowDBKVAdapter - LowDB-based storage adapter

Interfaces

  • KVNamespace - Storage adapter interface
  • SimpleExecutionContext - Execution context interface
  • SimpleHandler - Handler interface
  • OAuthProviderEnv - Environment interface

Functions

  • createDefaultEnv(dataPath?) - Create environment with default storage

Types

  • TokenExchangeCallbackResult - Token exchange callback result
  • TokenExchangeCallbackOptions - Token exchange callback options

🔒 Security Features

  • PKCE Support - Proof Key for Code Exchange by OAuth Public Clients
  • Secure Token Generation - Cryptographically random tokens
  • No Secret Storage - Only stores hashes, never plaintext secrets
  • TTL Management - Automatic token expiration
  • CORS Support - Configurable CORS headers
  • State Parameter - CSRF protection via OAuth state parameter

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate and follow the existing code style.

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

🙏 Acknowledgments

🔗 Related Projects


⭐ If this project helped you, please consider giving it a star!