UNPKG

@usemona/attest-backend-sdk

Version:

Mona Attest Backend SDK - Secure server-side verification for cryptographic attestations and digital signatures. Provides robust signature validation, user verification, and enterprise-grade security for Node.js applications.

321 lines (239 loc) 9.5 kB
# Mona Attest Backend SDK [![npm version](https://badge.fury.io/js/mona-attest-backend.svg)](https://www.npmjs.com/package/mona-attest-backend) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## 🔐 Enterprise-Grade Server-Side Verification for Cryptographic Attestations The **Mona Attest Backend SDK** provides secure server-side verification for cryptographic attestations and digital signatures. Built for Node.js applications requiring robust user verification, signature validation, and enterprise-grade security. ### ✨ Key Features - **🔒 Cryptographic Verification** - Secure signature validation using WebAuthn - **🏢 Enterprise Security** - Production-ready attestation verification - **⚡ High Performance** - Optimized for server-side operations - **🔄 Framework Agnostic** - Works with Express, Fastify, Koa, and more - **📊 Audit Logging** - Comprehensive verification audit trails - **🌐 Production Ready** - Enterprise-grade production environment - **📡 Zero Dependencies** - Lightweight with minimal external dependencies ### 📦 Installation ```bash npm install @usemona/attest-backend-sdk ``` ### 🎯 Quick Start #### Basic Verification ```javascript import { AttestBackendSDK } from '@usemona/attest-backend-sdk'; // Initialize the SDK const attestBackendSDK = new AttestBackendSDK({ apiUrl: 'https://your-attesttool-backend.com', environment: 'production' }); // Verify an attestation signature const verificationResult = await attestBackendSDK.verifyAttestation( attestationSignature, // From client request headers requestData // The data that was signed ); if (verificationResult.verified) { console.log('✅ Signature valid:', verificationResult.user); // Process the authenticated request } else { console.log('❌ Signature invalid:', verificationResult.error); // Reject the request } ``` #### Express.js Middleware Integration ```javascript import express from 'express'; import { AttestBackendSDK } from '@usemona/attest-backend-sdk'; const app = express(); const attestBackendSDK = new AttestBackendSDK(); // Attestation verification middleware const verifyAttestation = async (req, res, next) => { try { const signature = req.headers['x-attestation-signature']; if (!signature) { return res.status(401).json({ error: 'Missing attestation signature' }); } const verification = await attestBackendSDK.verifyAttestation(signature, { body: req.body, headers: req.headers, method: req.method, url: req.url }); if (!verification.verified) { return res.status(403).json({ error: 'Invalid attestation', details: verification.error }); } // Add user info to request req.attestedUser = verification.user; req.verificationId = verification.id; next(); } catch (error) { res.status(500).json({ error: 'Verification failed' }); } }; // Protected route app.post('/api/secure-payment', verifyAttestation, async (req, res) => { console.log(`Authenticated user: ${req.attestedUser.firstName}`); // Process the payment with confidence const result = await processPayment(req.body, req.attestedUser); res.json({ success: true, paymentId: result.id }); }); ``` ### 🔧 Configuration Options #### SDK Configuration ```javascript const attestBackendSDK = new AttestBackendSDK({ // Environment Configuration environment: 'production', // 'production' | 'auto' // API Configuration apiUrl: 'https://api.attest.ng', // Attest API endpoint timeout: 30000, // Request timeout in ms // Security Configuration strictMode: true, // Enable strict signature validation // Logging Configuration auditLog: true, // Enable audit logging logLevel: 'info', // 'debug' | 'info' | 'warn' | 'error' // Custom Headers customHeaders: { 'X-API-Version': '2.0', 'X-Client-ID': 'your-client-id' } }); ``` ### 📚 API Reference #### AttestBackendSDK Methods ##### `verifyAttestation(signature, requestData)` Verifies a cryptographic attestation signature against the provided request data. **Parameters:** - `signature` (string): The attestation signature from client - `requestData` (object): The original request data that was signed - `body`: Request body - `headers`: Request headers - `method`: HTTP method - `url`: Request URL **Returns:** Promise<VerificationResult> ```typescript interface VerificationResult { verified: boolean; // Whether signature is valid user?: UserInfo; // Authenticated user information id?: string; // Verification session ID error?: string; // Error message if verification failed timestamp: number; // Verification timestamp signatureMetadata?: object; // Additional signature data } ``` ##### `getUserInfo(userId)` Retrieves detailed information about an attested user. **Parameters:** - `userId` (string): The user ID from verification result **Returns:** Promise<UserInfo> ```typescript interface UserInfo { userId: string; firstName?: string; lastName?: string; email?: string; phone?: string; verificationLevel: 'basic' | 'enhanced' | 'premium'; lastAttestation: number; attestationCount: number; } ``` ### 🏗️ Architecture The backend SDK provides: 1. **Signature Verification** - Cryptographic validation of client signatures 2. **User Authentication** - Secure user identity verification 3. **Request Integrity** - Ensures request data hasn't been tampered with 4. **Session Management** - Handles attestation session lifecycle 5. **Audit Logging** - Comprehensive security event logging 6. **Error Handling** - Robust error reporting and debugging ### 🔄 Integration with Frontend Use with the companion frontend package: ```bash npm install mona-attest-frontend # For React/Next.js frontend ``` **Frontend (React/Next.js):** ```javascript import { AttestFrontendSDK } from 'mona-attest-frontend'; const frontendSDK = new AttestFrontendSDK(); // Client creates attestation const response = await frontendSDK.fetchWithAttestation( '/api/secure-endpoint', { method: 'POST', body: JSON.stringify(data) } ); ``` **Backend (Node.js):** ```javascript import { AttestBackendSDK } from '@usemona/attest-backend-sdk'; const backendSDK = new AttestBackendSDK(); // Server verifies attestation const verification = await backendSDK.verifyAttestation( signature, requestData ); ``` ### 🌟 Use Cases - **💳 Payment Processing** - Secure payment authorization and validation - **🏦 Banking APIs** - Account operations and financial transactions - **🔐 Identity Services** - User authentication and KYC verification - **📊 Sensitive Data** - Protection of critical business operations - **🚀 High-Value Actions** - Multi-factor verification for important actions - **🔗 API Security** - Enterprise-grade API endpoint protection ### 🛡️ Security Features #### Cryptographic Validation - **WebAuthn Signatures** - Industry-standard public key cryptography - **Timestamp Verification** - Prevents replay attacks - **Data Integrity** - Ensures request data hasn't been modified - **Challenge Validation** - Cryptographic challenge-response verification #### Enterprise Security - **Audit Trails** - Comprehensive logging of all verification attempts - **Rate Limiting** - Built-in protection against abuse - **Production Security** - Enterprise-grade security for production environments - **Error Masking** - Secure error messages that don't leak sensitive data ### 🚀 Performance - **⚡ Fast Verification** - Optimized cryptographic operations - **📈 Scalable** - Handles high-throughput verification workloads - **💾 Memory Efficient** - Minimal memory footprint - **🔄 Connection Pooling** - Efficient API communication ### 📋 Environment Variables ```bash # Attest Configuration ATTEST_API_URL=https://api.attest.ng # Security Configuration ATTEST_STRICT_MODE=true ATTEST_AUDIT_LOG=true # Performance Configuration ATTEST_TIMEOUT=30000 ATTEST_MAX_RETRIES=3 ``` ### 🐛 Error Handling ```javascript try { const verification = await attestBackendSDK.verifyAttestation(signature, data); if (!verification.verified) { // Handle invalid signature console.log('Verification failed:', verification.error); return res.status(403).json({ error: 'Invalid attestation' }); } // Process authenticated request } catch (error) { if (error.code === 'NETWORK_ERROR') { // Handle network issues } else if (error.code === 'SIGNATURE_EXPIRED') { // Handle expired signatures } else { // Handle other errors console.error('Verification error:', error); } } ``` ### 🤝 Support - **Documentation**: [Full API Documentation](https://docs.usemona.com/attest-backend) - **Issues**: [GitHub Issues](https://github.com/usemona/attestBackendSDK/issues) - **Discord**: [Join our community](https://discord.gg/mona-community) - **Email**: support@usemona.com ### 📄 License MIT License - see [LICENSE](LICENSE) file for details. ### 🚀 Getting Started Ready to add secure server-side verification to your API? Check out our [Integration Guide](https://docs.usemona.com/attest-backend/integration). --- Made with ❤️ by the [Mona Team](https://usemona.com)