@ztxtxwd/workers-oauth-provider
v0.0.16
Published
Universal OAuth 2.1 Provider Framework with pluggable storage support
Maintainers
Readme
Universal OAuth Provider
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 frameworkExpress.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
- Standalone HTTP Server - Native Node.js implementation
- Express.js Integration - Express.js middleware approach
- Custom Storage - Redis storage adapter
- Multi-Handler Setup - Multiple API routes with different handlers
🧪 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 classLowDBKVAdapter- LowDB-based storage adapter
Interfaces
KVNamespace- Storage adapter interfaceSimpleExecutionContext- Execution context interfaceSimpleHandler- Handler interfaceOAuthProviderEnv- Environment interface
Functions
createDefaultEnv(dataPath?)- Create environment with default storage
Types
TokenExchangeCallbackResult- Token exchange callback resultTokenExchangeCallbackOptions- 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
- Originally based on @cloudflare/workers-oauth-provider
- Built with LowDB for lightweight storage
- OAuth 2.1 security best practices from RFC 6749 and RFC 7636
🔗 Related Projects
⭐ If this project helped you, please consider giving it a star!
