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

nostr-auth-middleware

v0.3.4

Published

A focused, security-first authentication middleware for Nostr applications

Downloads

33

Readme

Nostr Auth Middleware

A focused, security-first authentication middleware for Nostr applications.

Requirements

  • Node.js ≥18.0.0 (Active LTS versions only)
  • npm ≥7.0.0

Installation

npm install nostr-auth-middleware

Important Security Notice

This library handles cryptographic keys and authentication tokens that are critical for securing your Nostr application and user data. Any private keys (nsec) or authentication tokens must be stored and managed with the utmost security and care.

Developers using this middleware must inform their users about the critical nature of managing private keys and tokens. It is the user's responsibility to securely store and manage these credentials. The library and its authors disclaim any responsibility or liability for lost keys, compromised tokens, or data resulting from mismanagement.

Usage

ESM (Recommended)

import { NostrAuthMiddleware } from 'nostr-auth-middleware';

CommonJS

const { NostrAuthMiddleware } = require('nostr-auth-middleware');

Browser

<script src="dist/browser/nostr-auth-middleware.min.js"></script>
<script>
  const auth = new NostrAuthMiddleware.NostrBrowserAuth();
</script>

Project Philosophy

This middleware follows key principles that promote security, auditability, and simplicity:

1. Single Responsibility

  • Authentication Only: Handles only Nostr key-based authentication
  • No Business Logic: Business rules, user tiers, and application logic belong in your API layer
  • Simple JWT: Issues basic JWTs with minimal claims (npub, timestamp)

2. Security First

  • Open Source: Fully auditable security-critical code
  • Transparent: Clear, readable implementation
  • Focused Scope: Does one thing well - Nostr authentication

3. Integration Ready

+---------------+
|  Client App  |
+-------+-------+
        |
        v
+---------------+
| Nostr Auth    | <-- This Service
|  Service      |     Simple Auth Only
+-------+-------+
        |
        v
+---------------+
| App Platform  | <-- Your Business Logic
|    API        |     User Tiers
+---------------+     Rate Limits

Core Features

  • Authentication: NIP-07 Compatible Authentication
  • Enrollment: Secure User Enrollment with Nostr
  • Validation: Comprehensive Event Validation
  • Cryptography: Advanced Cryptographic Operations
  • Data Persistence: Supabase Integration for Data Persistence
  • Session Management: JWT-based Session Management
  • Profile Management: Profile Management & Synchronization
  • Logging and Monitoring: Detailed Logging and Monitoring
  • Key Management: Automatic Key Management
  • Deployment: Environment-Aware Deployment
  • Modes: Development & Production Modes
  • Directory Management: Automated Directory Management

JWT Configuration & Usage

Basic Setup

const auth = new NostrAuthMiddleware({
  jwtSecret: process.env.JWT_SECRET,  // Required in production
  expiresIn: '24h'                    // Optional, defaults to '24h'
});

Environment-Specific Behavior

  • Production: JWT_SECRET is required. The middleware will throw an error if not provided
  • Development: A default development-only secret is used if JWT_SECRET is not provided (not secure for production use)

JWT Operations

Token Generation

// Generate a JWT token with minimal claims
const token = await auth.generateToken({ pubkey });

// The generated token includes:
// - pubkey (npub)
// - iat (issued at timestamp)
// - exp (expiration timestamp)

Token Verification

// Verify a JWT token
const isValid = await auth.verifyToken(token);
if (isValid) {
  // Token is valid, proceed with authentication
}

Browser Compatibility

The middleware is fully compatible with modern browsers and works seamlessly with build tools like Vite, Webpack, and Rollup. When using in a browser environment:

  1. Import the Package
import { NostrAuthMiddleware } from 'nostr-auth-middleware';
  1. Initialize with Environment Variables
const auth = new NostrAuthMiddleware({
  jwtSecret: import.meta.env.VITE_JWT_SECRET,  // For Vite
  // or
  jwtSecret: process.env.REACT_APP_JWT_SECRET  // For Create React App
});
  1. Handle Browser-Specific Features
  • Automatically detects and uses browser's localStorage for session management
  • Compatible with browser-based Nostr extensions (nos2x, Alby)
  • Handles browser-specific cryptographic operations

Security Best Practices

  1. JWT Secret Management

    • Use a strong, unique secret for JWT signing
    • Never expose the JWT secret in client-side code
    • Rotate secrets periodically in production
  2. Token Storage

    • Store tokens securely using browser's localStorage or sessionStorage
    • Clear tokens on logout
    • Implement token refresh mechanisms for long-lived sessions
  3. Environment Variables

    • Use different JWT secrets for development and production
    • Configure appropriate token expiration times
    • Implement proper error handling for token validation

Session Management

Browser Session Verification

// Verify if a user's session is still valid
const isValid = await auth.verifySession(userPubkey);
if (isValid) {
  console.log('Session is valid');
} else {
  console.log('Session is invalid or expired');
  // Handle logout
}

The session verification:

  • Checks if the Nostr extension is still available
  • Verifies the public key matches
  • Handles disconnection gracefully
  • Works in both browser and server environments

Development Mode

When running in development mode, the middleware provides detailed logging:

// Development mode logs
Cached Profile: { /* profile data */ }
Fresh Profile: { /* profile and event data */ }
Profile Cache Hit: { pubkey, cacheAge }
Profile Cache Expired: { pubkey, cacheAge }
Profile Cached: { pubkey, profile }
Profile Cache Cleared: { pubkey }

Documentation

TypeScript Declaration Pattern

For browser-specific TypeScript declarations, we follow a top-level pattern that avoids module augmentation blocks:

// Define interfaces and types at top level
interface NostrAuthConfig { ... }
interface NostrEvent { ... }

// Declare classes at top level
declare class NostrAuthClient { ... }

// Global augmentations after type definitions
declare global {
  interface Window {
    NostrAuthMiddleware: typeof NostrAuthClient;
  }
}

// Single export at the end
export = NostrAuthClient;

This pattern ensures better IDE support and cleaner type declarations. For more details, see our TypeScript Guide.

Browser Authentication

For client-side applications, we provide a lightweight browser-based authentication flow using NIP-07. This implementation works directly with Nostr browser extensions like nos2x or Alby.

Example Usage

// Browser
const auth = new NostrAuthMiddleware.NostrBrowserAuth({
  customKind: 22242,  // Optional: custom event kind
  timeout: 30000      // Optional: timeout in milliseconds
});

// Get user's public key
const publicKey = await auth.getPublicKey();

// Sign a challenge
const challenge = await auth.signChallenge();

// Verify a session
const isValid = await auth.validateSession(session);

Development Mode

Features enabled in development mode:

  • Hot-reloading enabled
  • Detailed logging
  • No root permissions required

Production Mode

Additional features in production mode:

  • Enhanced security checks
  • Performance optimizations
  • Minimal logging
  • Production-ready JWT configuration

Contributing

Please see our Contributing Guide for details on our code of conduct and the process for submitting pull requests.

License

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

Security

For security issues, please see our Security Policy and report any vulnerabilities responsibly.