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

@andrejs1979/auth

v1.0.0

Published

Authentication and authorization for NoSQL database platform

Downloads

12

Readme

NoSQL Authentication & Authorization System

A comprehensive, enterprise-grade authentication and authorization system built specifically for NoSQL, designed to run on Cloudflare's edge infrastructure with security-first principles.

🔐 Security Features

Authentication Methods

  • API Key Authentication - Secure API keys with scoping and expiration
  • JWT Token Authentication - Stateless token-based authentication
  • OAuth2 Integration - GitHub and Google OAuth support
  • Service Account Tokens - Machine-to-machine authentication
  • Temporary Access Tokens - Short-lived tokens for specific purposes
  • Certificate-based Authentication - X.509 certificate support

Authorization System

  • Role-Based Access Control (RBAC) - Hierarchical role system
  • Database-level Permissions - Control access to entire databases
  • Collection-level Permissions - Granular collection access
  • Document-level Security Rules - Dynamic document access control
  • Field-level Security - Hide/mask sensitive fields
  • Policy-based Access Control - Dynamic security policies

Security Features

  • Token Rotation & Expiry - Automatic token lifecycle management
  • Rate Limiting - Per-user/IP/API key rate limiting
  • Comprehensive Audit Logging - Complete security audit trail
  • Suspicious Activity Detection - Real-time threat detection
  • Geographic Restrictions - Location-based access control
  • Multi-Factor Authentication - TOTP, SMS, email MFA support

Compliance & Governance

  • GDPR Compliance - Data protection and privacy controls
  • SOC 2 Type II - Security controls and audit trails
  • Data Encryption - AES-256 encryption at rest and in transit
  • Secure Key Storage - Cloudflare Zero Trust integration
  • Data Retention Policies - Automated data lifecycle management

🏗️ Architecture

Core Components

src/auth/
├── types/auth.ts              # Core type definitions
├── services/
│   ├── authentication.ts     # Authentication service
│   ├── authorization.ts      # Authorization service
│   ├── rate-limiting.ts      # Rate limiting service
│   └── audit.ts              # Audit logging service
├── utils/
│   └── crypto.ts             # Cryptographic utilities
├── middleware/
│   └── auth-middleware.ts    # Express/Worker middleware
├── api/
│   └── user-management.ts    # User management APIs
├── mcp/
│   └── mcp-security.ts       # MCP integration security
└── schema/
    └── auth-schema.sql       # Database schema

Security Architecture

graph TB
    A[Client Request] --> B[Auth Middleware]
    B --> C{Authenticated?}
    C -->|No| D[Return 401]
    C -->|Yes| E[Rate Limiting]
    E --> F{Within Limits?}
    F -->|No| G[Return 429]
    F -->|Yes| H[Authorization Check]
    H --> I{Authorized?}
    I -->|No| J[Return 403]
    I -->|Yes| K[Security Policies]
    K --> L{Policies Pass?}
    L -->|No| M[Return 403]
    L -->|Yes| N[Audit Log]
    N --> O[Process Request]

🚀 Quick Start

1. Installation

import { NoSQLAuth, createNoSQLAuth } from './auth';

// Initialize with Cloudflare bindings
const auth = createNoSQLAuth(env.D1_DATABASE, env.KV_NAMESPACE, env);

2. Basic Usage

// Protect a route
export default {
  async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
    const auth = createNoSQLAuth(env.D1, env.KV, env);
    
    // Authenticate request
    const authResult = await auth.middleware.authenticate(request, env, ctx);
    
    if (authResult instanceof Response) {
      return authResult; // Authentication failed
    }
    
    const authContext = authResult;
    
    // Your protected logic here
    return new Response('Authenticated successfully!');
  }
};

3. Route Protection

import { protectRoute, requirePermission } from './auth';

// Simple authentication
const protectedHandler = protectRoute(
  async (request, env, ctx, authContext) => {
    return new Response(`Hello, ${authContext.user?.email}!`);
  },
  env.D1,
  env.KV
);

// Permission-based protection
const adminHandler = requirePermission(
  'user',
  'admin',
  async (request, env, ctx, authContext) => {
    return new Response('Admin area');
  },
  env.D1,
  env.KV
);

📊 Database Schema

The system uses a comprehensive database schema designed for security and performance:

Core Tables

  • users - User accounts and profiles
  • api_keys - API key management
  • jwt_tokens - JWT token tracking
  • roles - Role definitions
  • user_roles - User-role assignments
  • permissions - Permission definitions

Security Tables

  • audit_logs - Complete audit trail
  • security_events - Security incident tracking
  • security_policies - Dynamic security policies
  • rate_limits - Rate limiting configuration

Initialize the schema:

-- Run the schema file
.read src/auth/schema/auth-schema.sql

🔑 Authentication Examples

API Key Authentication

// Generate API key
const { apiKey, keyRecord } = await auth.authService.generateApiKey(
  'user-123',
  'My Application Key',
  ['read', 'write'],
  [{ resource: 'database', action: 'read', effect: 'allow' }]
);

// Use API key
const response = await fetch('/api/data', {
  headers: {
    'X-API-Key': apiKey
  }
});

JWT Authentication

// Login and get tokens
const { access, refresh } = await auth.authService.generateTokenPair(
  user,
  request
);

// Use access token
const response = await fetch('/api/data', {
  headers: {
    'Authorization': `Bearer ${access}`
  }
});

OAuth2 Integration

// Initiate OAuth
const { authUrl, state } = await auth.authService.initiateOAuth(
  'github',
  'https://myapp.com/callback'
);

// Complete OAuth
const { user, tokens } = await auth.authService.completeOAuth(
  'github',
  code,
  state,
  'https://myapp.com/callback',
  request
);

🛡️ Authorization Examples

Role-Based Access Control

// Check user permissions
const hasAccess = await auth.authzService.checkPermission(
  authContext,
  'database',
  'read',
  'my-database-id'
);

// Require specific permission
await auth.authzService.requirePermission(
  authContext,
  'collection',
  'write',
  'my-collection-id'
);

Dynamic Security Rules

// Document-level security
const canAccess = await auth.authzService.checkDocumentPermission(
  authContext,
  'my-database',
  'users',
  'doc-123',
  'read',
  documentData
);

// Field-level filtering
const filteredDoc = await auth.authzService.filterDocumentFields(
  authContext,
  'my-database',
  'users',
  originalDocument
);

📊 Rate Limiting

Configure Rate Limits

// Set custom rate limit
await auth.rateLimitService.setRateLimit({
  id: 'api-user-123',
  scope: 'user',
  scopeId: 'user-123',
  limits: {
    requestsPerMinute: 100,
    requestsPerHour: 1000
  },
  action: 'reject',
  resetInterval: 60
});

// Check rate limit
await auth.rateLimitService.checkRateLimit(
  'user:123',
  request
);

📝 Audit Logging

Security Events

// Log authentication event
await auth.auditService.logAuthEvent({
  eventType: 'user.login',
  result: 'success',
  userId: user.id,
  ipAddress: request.headers.get('CF-Connecting-IP'),
  userAgent: request.headers.get('User-Agent')
});

// Log data access
await auth.auditService.logDataAccessEvent(
  authContext,
  { type: 'database', id: 'my-db', name: 'My Database' },
  'read',
  'success'
);

Query Audit Logs

// Get audit logs
const { logs, totalCount } = await auth.auditService.queryAuditLogs({
  startTime: new Date('2024-01-01'),
  endTime: new Date(),
  userId: 'user-123',
  eventType: 'user.login',
  limit: 100
});

// Generate compliance report
const report = await auth.auditService.generateComplianceReport(
  'SOC2',
  new Date('2024-01-01'),
  new Date(),
  'org-123'
);

🤖 MCP Integration

Agent Authentication

// Authenticate MCP agent
const { authContext, agent, session } = await auth.mcpSecurity.authenticateAgent(
  {
    agentId: 'agent-123',
    apiKey: 'key_abc123'
  },
  request
);

// Authorize tool call
const toolCall = await auth.mcpSecurity.authorizeToolCall(
  session,
  'query_structured',
  { database: 'my-db', query: 'SELECT * FROM users' }
);

Agent Security

// Check resource access
const canAccess = await auth.mcpSecurity.authorizeResourceAccess(
  session,
  'database',
  'my-database-id',
  'read'
);

// Memory operation authorization
await auth.mcpSecurity.authorizeMemoryOperation(
  session,
  'write',
  'agent:123:conversation-history',
  1024 // bytes
);

🏢 User Management

User Registration

// Register new user
const response = await auth.userAPI.registerUser(
  new Request('/register', {
    method: 'POST',
    body: JSON.stringify({
      email: '[email protected]',
      password: 'SecurePassword123!',
      fullName: 'John Doe'
    })
  })
);

Profile Management

// Update user profile
const response = await auth.userAPI.updateUserProfile(
  new Request('/users/123', {
    method: 'PATCH',
    body: JSON.stringify({
      fullName: 'John Smith',
      avatar: 'https://example.com/avatar.jpg'
    })
  }),
  authContext
);

MFA Setup

// Setup TOTP
const response = await auth.userAPI.setupTOTP(
  new Request('/users/mfa/totp', { method: 'POST' }),
  authContext
);

// Verify and enable
const verifyResponse = await auth.userAPI.verifyTOTP(
  new Request('/users/mfa/verify', {
    method: 'POST',
    body: JSON.stringify({ code: '123456' })
  }),
  authContext
);

⚙️ Configuration

Environment Variables

# Required
JWT_SIGNING_SECRET=your-jwt-secret
API_SIGNING_SECRET=your-api-secret
ENCRYPTION_KEY=your-encryption-key

# OAuth (optional)
GITHUB_CLIENT_ID=your-github-client-id
GITHUB_CLIENT_SECRET=your-github-secret
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-secret

# Email service (optional)
SMTP_HOST=smtp.example.com
[email protected]
SMTP_PASS=your-smtp-password

Security Configuration

const config = {
  passwordPolicy: {
    minLength: 12,
    requireUppercase: true,
    requireLowercase: true,
    requireNumbers: true,
    requireSpecialChars: true,
    preventReuse: 10,
    maxAge: 90
  },
  mfaRequired: true,
  maxLoginAttempts: 3,
  lockoutDuration: 30,
  auditRetentionDays: 2555, // 7 years
  gdprEnabled: true
};

🔒 Security Best Practices

1. Strong Authentication

  • Use strong API keys (32+ characters)
  • Enable MFA for all admin accounts
  • Rotate keys regularly
  • Monitor for suspicious activity

2. Authorization

  • Follow principle of least privilege
  • Use role-based access control
  • Implement defense in depth
  • Regular permission audits

3. Rate Limiting

  • Set appropriate limits per tier
  • Monitor for abuse patterns
  • Implement burst capacity
  • Use distributed rate limiting

4. Audit & Monitoring

  • Log all security events
  • Monitor for anomalies
  • Set up real-time alerts
  • Regular compliance reviews

🚨 Security Considerations

Production Deployment

  1. Environment Secrets

    • Use Cloudflare Workers secrets
    • Rotate secrets regularly
    • Never commit secrets to code
  2. Network Security

    • Enable HTTPS only
    • Use Cloudflare security features
    • Implement IP allowlisting where appropriate
  3. Monitoring

    • Set up security alerts
    • Monitor audit logs
    • Track suspicious patterns
    • Regular security reviews

Compliance Requirements

  • GDPR: Data protection and privacy
  • SOC 2: Security controls and processes
  • HIPAA: Healthcare data protection (if applicable)
  • PCI DSS: Payment data security (if applicable)

📈 Performance

The authentication system is optimized for edge performance:

  • Sub-millisecond authentication with cached permissions
  • Distributed rate limiting across edge locations
  • Efficient audit logging with batching
  • Memory-optimized permission checking
  • CDN-friendly static security policies

🧪 Testing

// Example test
import { NoSQLAuth } from './auth';

describe('Authentication', () => {
  it('should authenticate valid API key', async () => {
    const auth = new NoSQLAuth(testConfig);
    const request = new Request('/', {
      headers: { 'X-API-Key': 'valid-key' }
    });
    
    const result = await auth.middleware.authenticate(request, env, ctx);
    expect(result).not.toBeInstanceOf(Response);
  });
});

📚 API Reference

Core Classes

  • NoSQLAuth - Main authentication system
  • AuthMiddleware - Request authentication middleware
  • AuthenticationService - Authentication methods
  • AuthorizationService - Permission checking
  • AuditService - Security logging
  • CryptoService - Cryptographic operations

Utility Functions

  • createNoSQLAuth() - Quick setup
  • protectRoute() - Route protection
  • requirePermission() - Permission-based protection

🤝 Contributing

  1. Follow security-first development practices
  2. Write comprehensive tests
  3. Document security implications
  4. Use secure coding guidelines
  5. Regular security reviews

📄 License

This authentication system is part of NoSQL and follows the same licensing terms.

🆘 Support

For security issues or questions:

  • Review the security documentation
  • Check audit logs for issues
  • Follow incident response procedures
  • Contact security team for critical issues

⚠️ Security Notice: This system handles sensitive authentication data. Always follow security best practices and conduct regular security audits.