JSPM

  • Created
  • Published
  • Downloads 215
  • Score
    100M100P100Q125398F
  • License MIT

Lightning Network authentication and payment processing library for modern web applications

Package Exports

  • lightning-auth-and-payment
  • lightning-auth-and-payment/dev
  • lightning-auth-and-payment/nextjs

Readme

โšก Lightning Auth & Payment

npm version License: MIT TypeScript Lightning Network

The complete Lightning Network authentication and payment solution for modern web applications

Build Lightning Network-powered applications with ease. From simple single-page shops to complex eCommerce platforms, Lightning Auth & Payment provides everything you need for Lightning Network integration.

๐Ÿš€ Quick Start

For AI Agents (Cursor, etc.)

Use our AI Setup Guide - copy and paste a single prompt to automatically configure everything.

๐Ÿ“š Examples Available

Check out our comprehensive examples in the /examples folder:

โšก Zero-Config Setup (30 seconds!)

  1. Install the library:
npm install lightning-auth-and-payment
  1. Configure Next.js plugin in next.config.js:
import { withLightning } from 'lightning-auth-and-payment/nextjs';

/** @type {import('next').NextConfig} */
const nextConfig = {
  // your existing config
};

// Zero-config: Auto-detects everything!
export default withLightning()(nextConfig);
  1. Start development:
npm run dev:lightning

That's it! The plugin automatically:

  • ๐Ÿ” Detects your project configuration
  • ๐Ÿ”ง Generates all API routes
  • ๐Ÿ“ Creates environment files
  • ๐Ÿ—„๏ธ Sets up database schema
  • ๐Ÿ”’ Configures HTTPS development
  • ๐Ÿš€ Adds development scripts

๐ŸŽฏ Custom Configuration (Optional)

export default withLightning({
  database: 'prisma',     // Auto-detected
  btcpay: true,           // Auto-detected
  development: true,      // Auto-detected
  // ... other options
})(nextConfig);

โœจ What You Get Automatically

๐Ÿ”ง Auto-Generated API Routes

  • /api/auth/lnurl - Generate Lightning authentication URL
  • /api/auth/callback - Handle authentication callback
  • /api/auth/status - Check authentication status
  • /api/auth/logout - User logout
  • /api/user - Get current user information
  • /api/payment/create-invoice - Create Lightning invoice
  • /api/payment/status - Check payment status
  • /api/webhooks/btcpay - BTCPay Server webhooks

๐Ÿ—„๏ธ Auto-Generated Database Schema

  • User management and sessions
  • LNURL challenges and logins
  • Payment and invoice tracking
  • Order and order item management
  • Complete Prisma schema with migrations

๐Ÿš€ Zero-Config Development Features

  • Smart Detection: Auto-detects Prisma, BTCPay, database setup
  • Environment Setup: Auto-creates .env.local with secure defaults
  • Database Setup: Auto-generates Prisma schema and runs migrations
  • HTTPS Development: Auto-configures SSL certificates for Lightning wallets
  • Development Scripts: Auto-adds dev:lightning and other helpful scripts
  • Hot Reloading: Automatic route regeneration on changes
  • TypeScript Support: Full type safety and IntelliSense
  • Mobile Wallet Compatibility: Works with Alby, Zeus, and other Lightning wallets

๐Ÿ’ณ BTCPay Server Setup (Required for Payments)

To use the payment features, you need a BTCPay Server instance with Lightning Network support. The easiest way to set this up is using the SamRock Protocol with AQUA Wallet:

  1. Install BTCPay Server with the SamRock plugin
  2. Install AQUA Wallet on your mobile device
  3. Connect using SamRock Protocol:
    • Install the SamRock plugin in BTCPay Server
    • Click "SamRock Protocol" in the BTCPay dashboard
    • Select payment methods: Bitcoin, Liquid, Lightning
    • Scan the QR code with AQUA Wallet
    • Your wallet securely provides the necessary public keys
    • No private keys are ever exposed to the server

This setup eliminates the need to:

  • Run a Lightning node
  • Manage private keys on the server
  • Configure complex XPUB settings
  • Handle Liquid blinding keys manually

Learn more: SamRock Protocol Documentation

Alternative: Manual BTCPay Server Setup

If you prefer manual setup:

  1. Set up BTCPay Server with Lightning support
  2. Configure your Lightning node (LND, CLN, or Eclair)
  3. Create a store and get your API credentials
  4. Add the credentials to your environment variables

๐ŸŽฏ What the Plugin Provides

  • โœ… Automatic API route generation - No manual route creation needed
  • โœ… Database adapter integration - Works with Prisma out of the box
  • โœ… BTCPay Server integration - Complete payment processing
  • โœ… Authentication flow - LNURL-auth with session management
  • โœ… Development server - HTTPS with SSL certificates
  • โœ… TypeScript support - Full type safety and IntelliSense

๐ŸŽฏ Core Features

โœ… Lightning Authentication

  • LNURL-auth protocol - Industry standard Lightning authentication
  • QR Code generation - Works with any Lightning wallet
  • Session management - Secure JWT-based sessions
  • Wallet compatibility - Alby, Phoenix, Breez, Zeus, and more

โœ… Lightning Payments

  • BTCPay Server integration - Real Lightning invoices
  • Automatic polling - Payment status detection
  • QR Code payments - Mobile wallet support
  • Success handling - User-friendly payment confirmation

โœ… Development Experience

  • Local HTTPS server - SSL certificates for wallet compatibility
  • TypeScript support - Full type safety
  • React components - Ready-to-use UI components
  • Hot reload - Fast development iteration

๐Ÿ› ๏ธ Development Server

The library includes a built-in development server for local HTTPS development with Lightning authentication support.

โšก Quick Start with Binary

# Install the library
npm install lightning-auth-and-payment

# Add to package.json scripts
npm pkg set scripts.dev:lightning="lightning-dev-server"
npm pkg set scripts.dev:https="lightning-dev-server"

# Start the development server
npm run dev:lightning

๐ŸŽฏ What You Get

  • ๐Ÿ”’ Automatic SSL certificates - Uses mkcert for trusted local certificates
  • ๐Ÿ”„ Hot reload support - Works with Next.js development server
  • ๐Ÿ“ฑ Mobile wallet compatibility - HTTPS required for Lightning wallets
  • ๐ŸŒ CORS handling - Pre-configured for Lightning wallet requests
  • โšก Lightning-ready - Optimized for Lightning Network development
  • ๐ŸŽจ Beautiful UI - Professional Lightning Network theming
  • ๐Ÿ“Š Real-time logging - Detailed development feedback

Advanced Configuration

import { LightningDevServer } from 'lightning-auth-and-payment/dev';

const devServer = new LightningDevServer({
  nextPort: 3000,        // Next.js development server port
  httpsPort: 3443,       // HTTPS proxy port
  certsDir: 'certs',     // SSL certificates directory
  projectRoot: process.cwd(),
  verbose: true,          // Enable detailed logging
});

await devServer.start();

Package.json Integration

{
  "scripts": {
    "dev": "next dev",
    "dev:lightning": "lightning-dev-server",
    "dev:https": "lightning-dev-server"
  }
}

๐Ÿ“ฆ What's Included

๐Ÿ” Authentication

import { LightningAuth, useAuth } from 'lightning-auth-and-payment';

// Server-side authentication
const auth = new LightningAuth({
  sessionSecret: process.env.SESSION_SECRET!,
  lnurlStore: new MemoryLnurlStore(),
});

// Client-side authentication
const { isAuthenticated, login, logout, user } = useAuth();

๐Ÿ’ณ Payments

import { BTCPayPaymentModal, createBTCPayService } from 'lightning-auth-and-payment';

// Payment modal component
<BTCPayPaymentModal
  isOpen={showPayment}
  onClose={() => setShowPayment(false)}
  amount={1000}
  description="Purchase item"
  onPaymentSuccess={() => console.log('Payment successful!')}
  autoCloseDelay={3000}
  successMessage="Payment confirmed!"
/>

// BTCPay service
const btcpayService = createBTCPayService();
const invoice = await btcpayService.createInvoice({
  amount: 1000,
  currency: 'SATS',
  description: 'Purchase item',
});

๐ŸŽจ UI Components

import { 
  AuthHeader, 
  BTCPayPaymentModal, 
  Button, 
  Card 
} from 'lightning-auth-and-payment';

// Pre-built components with Lightning Network styling
<AuthHeader />
<Button onClick={handlePayment}>Buy Now</Button>
<Card>Your content here</Card>

๐Ÿ› ๏ธ Environment Setup

Create .env.local:

# Session Configuration
SESSION_SECRET=your-super-secret-session-key-here-make-it-long-and-random
SESSION_COOKIE_DOMAIN=localhost

# BTCPay Server Configuration (required for payments)
BTCPAY_HOST=https://your-btcpay-server.com
BTCPAY_STORE_ID=your-store-id
BTCPAY_API_KEY=your-api-key
BTCPAY_WEBHOOK_SECRET=your-webhook-secret

# Application Configuration
NEXT_PUBLIC_APP_URL=https://localhost:3443
NODE_ENV=development

๐Ÿ—๏ธ API Routes

๐ŸŽฏ Automatic Route Generation with Next.js Plugin

The library's Next.js plugin automatically generates all API routes for you:

// next.config.js
import { withLightning } from 'lightning-auth-and-payment/nextjs';

export default withLightning({
  // your existing config
});

โœจ What Gets Generated Automatically

  • /api/auth/lnurl - LNURL generation for Lightning wallets
  • /api/auth/callback - Authentication callback handling
  • /api/auth/status - Authentication status checking
  • /api/auth/logout - User logout functionality
  • /api/user - User data retrieval
  • /api/payment/create-invoice - BTCPay Server invoice creation
  • /api/payment/status - Payment status checking
  • /api/webhooks/btcpay - BTCPay Server webhook handling

๐ŸŽฏ Benefits of Automatic Generation

  • โœ… Zero boilerplate - No manual route creation needed
  • โœ… Database integration - Works with Prisma out of the box
  • โœ… BTCPay Server ready - Complete payment processing
  • โœ… CORS handling - Pre-configured for Lightning wallets
  • โœ… Error handling - Built-in status codes and error responses
  • โœ… TypeScript support - Full type safety and IntelliSense
  • โœ… Hot reload - Routes update automatically during development

๐Ÿ”ง Manual Route Creation (Advanced)

If you prefer manual control, you can still create routes manually:

// /api/auth/lnurl/route.ts - LNURL generation
import { NextRequest, NextResponse } from 'next/server';
import { handleLnurlRequest, getAuthCorsHeaders } from 'lightning-auth-and-payment';
import { lnurlStore } from '@/lib/lnurl-store';

export async function GET(request: NextRequest) {
  const result = await handleLnurlRequest(lnurlStore, request);
  const response = NextResponse.json(result);
  
  // Apply CORS headers
  const corsHeaders = getAuthCorsHeaders();
  Object.entries(corsHeaders).forEach(([key, value]) => {
    response.headers.set(key, value);
  });
  
  return response;
}

๐Ÿ’ณ Payment Routes

// Payment routes use BTCPay utilities
import { 
  handleBTCPayInvoiceCreation, 
  handleBTCPayInvoiceStatus,
  handleBTCPayWebhook 
} from 'lightning-auth-and-payment';

๐Ÿ”ง Development Server

Start the Lightning development server with HTTPS support:

npm run dev:lightning

This provides:

  • โœ… HTTPS with trusted SSL certificates
  • โœ… Wallet-compatible LNURL endpoints
  • โœ… Hot reload and debugging
  • โœ… Automatic certificate management

๐Ÿ“ฑ Wallet Compatibility

Desktop Wallets

  • Alby - Browser extension (recommended for development)
  • Phoenix - Desktop Lightning wallet
  • Breez - Mobile/desktop Lightning wallet

Mobile Wallets

  • Phoenix - iOS/Android Lightning wallet
  • Breez - Mobile Lightning wallet
  • Zeus - Advanced Lightning wallet
  • Wallet of Satoshi - Simple Lightning wallet

๐ŸŽจ UI Components

Authentication Components

import { AuthHeader, useAuth } from 'lightning-auth-and-payment';

function MyApp() {
  const { isAuthenticated, login, logout } = useAuth();
  
  return (
    <AuthHeader 
      onLogin={login}
      onLogout={logout}
      isAuthenticated={isAuthenticated}
    />
  );
}

Payment Components

import { BTCPayPaymentModal } from 'lightning-auth-and-payment';

function PaymentButton() {
  const [showPayment, setShowPayment] = useState(false);
  
  return (
    <BTCPayPaymentModal
      isOpen={showPayment}
      onClose={() => setShowPayment(false)}
      amount={1000}
      description="Purchase item"
      onPaymentSuccess={() => {
        // Handle successful payment
        setShowPayment(false);
      }}
      autoCloseDelay={3000}
      successMessage="Payment confirmed!"
    />
  );
}

Utility Components

import { 
  Button, 
  Card, 
  Badge, 
  Dialog 
} from 'lightning-auth-and-payment';

// Pre-styled components with Lightning Network theming
<Button variant="primary">Lightning Button</Button>
<Card>Lightning Card</Card>
<Badge variant="success">Success</Badge>

๐Ÿ” Hooks

Authentication Hooks

import { 
  useLightningAuth,
  useSession 
} from 'lightning-auth-and-payment';

// Lightning authentication with all features
const { isAuthenticated, login, logout, user, isLoading } = useLightningAuth();

// Session management
const { session, refreshSession } = useSession();

Payment Hooks

import { 
  useBTCPayPayment,
  useLightningPayment 
} from 'lightning-auth-and-payment';

// BTCPay Server payments
const { 
  paymentState, 
  createInvoice, 
  copyBolt11 
} = useBTCPayPayment();

// Basic Lightning payments
const { 
  createPayment, 
  paymentStatus, 
  resetPayment 
} = useLightningPayment();

Utility Hooks

import { 
  useCopyToClipboard,
  useCountdown,
  useDebounce,
  useLocalStorage 
} from 'lightning-auth-and-payment';

// Copy to clipboard
const { copied, copy } = useCopyToClipboard();

// Countdown timer
const { timeLeft, isExpired } = useCountdown(targetDate);

// Debounced values
const debouncedValue = useDebounce(value, 500);

// Local storage
const [storedValue, setStoredValue] = useLocalStorage('key', defaultValue);

๐Ÿช E-Commerce Features

import { 
  ECommerceManager,
  OrderManager,
  ProductManager 
} from 'lightning-auth-and-payment';

// E-commerce management
const ecommerce = new ECommerceManager();
const orders = new OrderManager();
const products = new ProductManager();

๐Ÿงช Testing

import { 
  createTestAuth,
  createTestStore,
  mockUser,
  mockInvoice 
} from 'lightning-auth-and-payment/testing';

// Test utilities
const testAuth = createTestAuth();
const testStore = createTestStore();
const user = mockUser();
const invoice = mockInvoice();

๐Ÿ“š Examples

Check out the examples directory for complete implementations:

  • Next.js App Router - Modern Next.js 13+ with App Router
  • Express.js - Traditional Express.js server
  • E-commerce - Complete shopping cart implementation

๐Ÿค Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. Submit a pull request

๐Ÿ“„ License

MIT License - see LICENSE for details.

๐Ÿ†˜ Support

๐ŸŽฏ Roadmap

  • WebLN integration for browser wallets
  • Lightning Address support
  • Multi-currency support
  • Advanced payment flows
  • Mobile app templates

Built with โšก for the Lightning Network