UNPKG

lightning-auth-and-payment

Version:

Lightning Network authentication and payment processing library for modern web applications

178 lines (156 loc) 4.85 kB
import express from 'express'; import cors from 'cors'; import dotenv from 'dotenv'; import { LightningAuth, createBTCPayService } from 'lightning-auth-and-payment'; dotenv.config(); const app = express(); const PORT = process.env.PORT || 3000; // Middleware app.use(cors()); app.use(express.json()); // Initialize Lightning Auth const lightningAuth = new LightningAuth({ secret: process.env.SESSION_SECRET || 'your-secret-key', domain: process.env.SESSION_COOKIE_DOMAIN || 'localhost', }); // Initialize BTCPay Service (optional) const btcpayService = process.env.BTCPAY_HOST ? createBTCPayService({ host: process.env.BTCPAY_HOST, storeId: process.env.BTCPAY_STORE_ID, apiKey: process.env.BTCPAY_API_KEY, webhookSecret: process.env.BTCPAY_WEBHOOK_SECRET, }) : null; // Routes app.get('/', (req, res) => { res.json({ message: 'Lightning Express Example', endpoints: { auth: '/auth/lnurl', callback: '/auth/callback', status: '/auth/status', user: '/user', payment: '/payment/create', webhook: '/webhooks/btcpay' } }); }); // Lightning Authentication Routes app.get('/auth/lnurl', async (req, res) => { try { const result = await lightningAuth.generateLnurl(); res.json(result); } catch (error) { console.error('LNURL generation error:', error); res.status(500).json({ error: 'Failed to generate LNURL' }); } }); app.get('/auth/callback', async (req, res) => { try { const { k1, sig, key } = req.query; const result = await lightningAuth.verifyCallback({ k1, sig, key }); res.json(result); } catch (error) { console.error('Auth callback error:', error); res.status(400).json({ error: 'Authentication failed' }); } }); app.get('/auth/status', async (req, res) => { try { const { k1 } = req.query; const result = await lightningAuth.checkAuthStatus(k1); res.json(result); } catch (error) { console.error('Auth status error:', error); res.status(500).json({ error: 'Failed to check auth status' }); } }); // User route app.get('/user', async (req, res) => { try { const session = await lightningAuth.getSession(req); if (!session) { return res.status(401).json({ error: 'Not authenticated' }); } res.json({ user: session.user, isAuthenticated: true }); } catch (error) { console.error('User route error:', error); res.status(500).json({ error: 'Internal server error' }); } }); // Payment routes (if BTCPay is configured) if (btcpayService) { app.post('/payment/create', async (req, res) => { try { const { amount, description, metadata } = req.body; const session = await lightningAuth.getSession(req); if (!session) { return res.status(401).json({ error: 'Not authenticated' }); } const invoice = await btcpayService.createInvoice({ amount: amount, currency: 'BTC', description: description, metadata: metadata }); res.json({ invoiceId: invoice.id, amount: invoice.amount, status: invoice.status, checkoutLink: invoice.checkoutLink, bolt11: invoice.bolt11 }); } catch (error) { console.error('Payment creation error:', error); res.status(500).json({ error: 'Failed to create payment' }); } }); app.get('/payment/status/:invoiceId', async (req, res) => { try { const { invoiceId } = req.params; const invoice = await btcpayService.getInvoice(invoiceId); res.json({ invoiceId: invoice.id, status: invoice.status, amount: invoice.amount, settledAt: invoice.settledAt }); } catch (error) { console.error('Payment status error:', error); res.status(500).json({ error: 'Failed to get payment status' }); } }); app.post('/webhooks/btcpay', async (req, res) => { try { const result = await btcpayService.handleWebhook(req); res.json(result); } catch (error) { console.error('Webhook error:', error); res.status(400).json({ error: 'Webhook processing failed' }); } }); } // Logout route app.post('/auth/logout', async (req, res) => { try { await lightningAuth.clearSession(res); res.json({ success: true }); } catch (error) { console.error('Logout error:', error); res.status(500).json({ error: 'Logout failed' }); } }); // Error handling app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: 'Something went wrong!' }); }); app.listen(PORT, () => { console.log(`🚀 Lightning Express server running on port ${PORT}`); console.log(`📱 Lightning auth endpoint: http://localhost:${PORT}/auth/lnurl`); if (btcpayService) { console.log(`💳 BTCPay integration enabled`); } });