Update delete old laying visual files
This commit is contained in:
353
doc/API.md
353
doc/API.md
@@ -2,14 +2,13 @@
|
||||
|
||||
## 🏗️ Architecture Overview
|
||||
|
||||
SecureBit.chat is built as a client-side application with no backend servers. The "API" consists of JavaScript classes and methods that handle cryptography, P2P connections, and Lightning Network integration. **Version 4.02.442 introduces complete ASN.1 validation for enhanced key security.**
|
||||
SecureBit.chat is built as a client-side application with no backend servers. The "API" consists of JavaScript classes and methods that handle cryptography, P2P connections. **Version 4.02.442 introduces complete ASN.1 validation for enhanced key security.**
|
||||
|
||||
## 📋 Table of Contents
|
||||
|
||||
1. [Core Classes](#-core-classes)
|
||||
- [EnhancedSecureCryptoUtils](#-enhancedsecurecryptoutils)
|
||||
- [EnhancedSecureWebRTCManager](#-enhancedsecurewebrtcmanager)
|
||||
- [LightningNetworkManager](#-lightningnetworkmanager)
|
||||
2. [Security Framework APIs](#-security-framework-apis)
|
||||
- [SecureKeyManager](#-securekeymanager)
|
||||
- [ConnectionMutexManager](#-connectionmutexmanager)
|
||||
@@ -848,356 +847,6 @@ Cleanly disconnects and cleans up all resources.
|
||||
confirmVerification()
|
||||
javascriptconfirmVerification(): void
|
||||
Confirms that verification codes match (called after manual verification).
|
||||
⚡ PayPerSessionManager
|
||||
Handles Lightning Network payment integration.
|
||||
Constructor
|
||||
javascriptnew PayPerSessionManager()
|
||||
Session Types
|
||||
typescriptinterface SessionPricing {
|
||||
free: { sats: 0, hours: 1/60, usd: 0.00 };
|
||||
basic: { sats: 500, hours: 1, usd: 0.20 };
|
||||
premium: { sats: 1000, hours: 4, usd: 0.40 };
|
||||
extended: { sats: 2000, hours: 24, usd: 0.80 };
|
||||
}
|
||||
Payment Methods
|
||||
createInvoice()
|
||||
javascriptcreateInvoice(sessionType: string): LightningInvoice
|
||||
Creates Lightning invoice for session payment.
|
||||
Parameters:
|
||||
|
||||
sessionType - One of: 'free', 'basic', 'premium', 'extended'
|
||||
|
||||
Returns:
|
||||
typescriptinterface LightningInvoice {
|
||||
amount: number; // satoshis
|
||||
memo: string;
|
||||
sessionType: string;
|
||||
timestamp: number;
|
||||
paymentHash: string;
|
||||
lightningAddress: string;
|
||||
}
|
||||
Example:
|
||||
javascriptconst sessionManager = new PayPerSessionManager();
|
||||
const invoice = sessionManager.createInvoice('premium');
|
||||
console.log(`Pay ${invoice.amount} sats to ${invoice.lightningAddress}`);
|
||||
verifyPayment()
|
||||
javascriptasync verifyPayment(preimage: string, paymentHash: string): Promise<boolean>
|
||||
Verifies Lightning payment preimage.
|
||||
Parameters:
|
||||
|
||||
preimage - Payment preimage (64 hex characters)
|
||||
paymentHash - Payment hash from invoice
|
||||
|
||||
Returns: true if payment is valid
|
||||
activateSession()
|
||||
javascriptactivateSession(sessionType: string, preimage: string): Session
|
||||
Activates paid session.
|
||||
Returns:
|
||||
typescriptinterface Session {
|
||||
type: string;
|
||||
startTime: number;
|
||||
expiresAt: number;
|
||||
preimage: string;
|
||||
}
|
||||
Session Management
|
||||
hasActiveSession()
|
||||
javascripthasActiveSession(): boolean
|
||||
Returns true if there's an active, non-expired session.
|
||||
getTimeLeft()
|
||||
javascriptgetTimeLeft(): number
|
||||
Returns milliseconds remaining in current session.
|
||||
Example:
|
||||
javascriptconst timeLeft = sessionManager.getTimeLeft();
|
||||
const hoursLeft = Math.floor(timeLeft / (1000 * 60 * 60));
|
||||
console.log(`${hoursLeft} hours remaining`);
|
||||
cleanup()
|
||||
javascriptcleanup(): void
|
||||
Cleans up session data and timers.
|
||||
🔧 Integration Examples
|
||||
Basic P2P Chat Setup
|
||||
javascript// Initialize WebRTC manager
|
||||
const webrtcManager = new EnhancedSecureWebRTCManager(
|
||||
(message, type) => {
|
||||
console.log(`${type}: ${message}`);
|
||||
addMessageToUI(message, type);
|
||||
},
|
||||
(status) => {
|
||||
console.log(`Status: ${status}`);
|
||||
updateStatusIndicator(status);
|
||||
},
|
||||
(fingerprint) => {
|
||||
console.log(`Key fingerprint: ${fingerprint}`);
|
||||
displayFingerprint(fingerprint);
|
||||
},
|
||||
(code) => {
|
||||
console.log(`Verification code: ${code}`);
|
||||
showVerificationModal(code);
|
||||
}
|
||||
);
|
||||
|
||||
// Create secure offer
|
||||
const offer = await webrtcManager.createSecureOffer();
|
||||
console.log('Share this encrypted offer:', JSON.stringify(offer));
|
||||
|
||||
// Send message (after connection established)
|
||||
await webrtcManager.sendSecureMessage('Hello, secure world!');
|
||||
Lightning Payment Integration
|
||||
javascript// Initialize session manager
|
||||
const sessionManager = new PayPerSessionManager();
|
||||
|
||||
// Create invoice for premium session
|
||||
const invoice = sessionManager.createInvoice('premium');
|
||||
console.log(`Pay ${invoice.amount} sats to: ${invoice.lightningAddress}`);
|
||||
|
||||
// Handle payment (WebLN)
|
||||
if (window.webln) {
|
||||
try {
|
||||
await window.webln.enable();
|
||||
const result = await window.webln.sendPayment({
|
||||
amount: invoice.amount,
|
||||
memo: invoice.memo
|
||||
});
|
||||
|
||||
// Verify and activate session
|
||||
const isValid = await sessionManager.verifyPayment(
|
||||
result.preimage,
|
||||
invoice.paymentHash
|
||||
);
|
||||
|
||||
if (isValid) {
|
||||
const session = sessionManager.activateSession('premium', result.preimage);
|
||||
console.log(`Session active until: ${new Date(session.expiresAt)}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('WebLN payment failed:', error);
|
||||
}
|
||||
}
|
||||
Custom Cryptographic Operations
|
||||
javascript// Generate fresh key pairs
|
||||
const ecdhKeys = await EnhancedSecureCryptoUtils.generateECDHKeyPair();
|
||||
const ecdsaKeys = await EnhancedSecureCryptoUtils.generateECDSAKeyPair();
|
||||
|
||||
// Create and verify signature
|
||||
const data = 'Important message to sign';
|
||||
const signature = await EnhancedSecureCryptoUtils.signData(
|
||||
ecdsaKeys.privateKey,
|
||||
data
|
||||
);
|
||||
|
||||
const isValid = await EnhancedSecureCryptoUtils.verifySignature(
|
||||
ecdsaKeys.publicKey,
|
||||
signature,
|
||||
data
|
||||
);
|
||||
console.log('Signature valid:', isValid);
|
||||
|
||||
// Derive shared keys
|
||||
const salt = EnhancedSecureCryptoUtils.generateSalt();
|
||||
const sharedKeys = await EnhancedSecureCryptoUtils.deriveSharedKeys(
|
||||
ecdhKeys.privateKey,
|
||||
remotePublicKey,
|
||||
salt
|
||||
);
|
||||
|
||||
// Encrypt message
|
||||
const encrypted = await EnhancedSecureCryptoUtils.encryptMessage(
|
||||
"Secret message",
|
||||
sharedKeys.encryptionKey,
|
||||
sharedKeys.macKey,
|
||||
sharedKeys.metadataKey,
|
||||
"msg_001",
|
||||
1
|
||||
);
|
||||
Full Connection Flow
|
||||
javascript// Complete initiator flow
|
||||
async function initiatorFlow() {
|
||||
// 1. Create WebRTC manager
|
||||
const manager = new EnhancedSecureWebRTCManager(
|
||||
handleMessage,
|
||||
handleStatusChange,
|
||||
handleKeyExchange,
|
||||
handleVerification
|
||||
);
|
||||
|
||||
// 2. Create offer
|
||||
const offer = await manager.createSecureOffer();
|
||||
|
||||
// 3. Encrypt offer for sharing
|
||||
const password = EnhancedSecureCryptoUtils.generateSecurePassword();
|
||||
const encryptedOffer = await EnhancedSecureCryptoUtils.encryptData(offer, password);
|
||||
|
||||
// 4. Share encrypted offer and password with peer
|
||||
console.log('Encrypted offer:', encryptedOffer);
|
||||
console.log('Password:', password);
|
||||
|
||||
// 5. Wait for encrypted answer from peer
|
||||
const encryptedAnswer = await getAnswerFromPeer();
|
||||
const answerPassword = await getPasswordFromPeer();
|
||||
|
||||
// 6. Decrypt and process answer
|
||||
const answer = await EnhancedSecureCryptoUtils.decryptData(
|
||||
encryptedAnswer,
|
||||
answerPassword
|
||||
);
|
||||
await manager.handleSecureAnswer(answer);
|
||||
|
||||
// 7. Verify out-of-band codes
|
||||
await verifySecurityCodes();
|
||||
|
||||
// 8. Start secure communication
|
||||
await manager.sendSecureMessage("Hello from initiator!");
|
||||
}
|
||||
Responder Flow
|
||||
javascriptasync function responderFlow() {
|
||||
// 1. Get encrypted offer from initiator
|
||||
const encryptedOffer = await getOfferFromPeer();
|
||||
const offerPassword = await getPasswordFromPeer();
|
||||
|
||||
// 2. Decrypt offer
|
||||
const offer = await EnhancedSecureCryptoUtils.decryptData(
|
||||
encryptedOffer,
|
||||
offerPassword
|
||||
);
|
||||
|
||||
// 3. Create WebRTC manager
|
||||
const manager = new EnhancedSecureWebRTCManager(
|
||||
handleMessage,
|
||||
handleStatusChange,
|
||||
handleKeyExchange,
|
||||
handleVerification
|
||||
);
|
||||
|
||||
// 4. Create answer
|
||||
const answer = await manager.createSecureAnswer(offer);
|
||||
|
||||
// 5. Encrypt answer for sharing
|
||||
const password = EnhancedSecureCryptoUtils.generateSecurePassword();
|
||||
const encryptedAnswer = await EnhancedSecureCryptoUtils.encryptData(answer, password);
|
||||
|
||||
// 6. Share encrypted answer and password
|
||||
await sendAnswerToPeer(encryptedAnswer);
|
||||
await sendPasswordToPeer(password);
|
||||
|
||||
// 7. Verify out-of-band codes
|
||||
await verifySecurityCodes();
|
||||
|
||||
// 8. Start secure communication
|
||||
await manager.sendSecureMessage("Hello from responder!");
|
||||
}
|
||||
🔒 Security Considerations
|
||||
Key Security
|
||||
|
||||
All keys are non-extractable - Cannot be exported from WebCrypto
|
||||
Hardware security module - Keys protected by browser's HSM
|
||||
Perfect Forward Secrecy - Old messages stay secure even if current keys compromised
|
||||
Automatic key rotation - Keys change every 5 minutes
|
||||
|
||||
Message Security
|
||||
|
||||
Authenticated encryption - AES-GCM provides confidentiality + integrity
|
||||
Metadata protection - Message metadata separately encrypted
|
||||
Replay protection - Sequence numbers prevent message replay
|
||||
Rate limiting - Prevents spam and DoS attacks
|
||||
|
||||
Connection Security
|
||||
|
||||
Out-of-band verification - Manual code verification prevents MITM
|
||||
Mutual authentication - Both parties prove identity
|
||||
Direct P2P - No intermediate servers to compromise
|
||||
WebRTC encryption - DTLS transport layer security
|
||||
|
||||
Payment Security
|
||||
|
||||
Lightning Network - No credit card or banking data exposure
|
||||
Preimage verification - Cryptographic proof of payment
|
||||
No payment data stored - Payments verified and discarded
|
||||
|
||||
🐛 Error Handling
|
||||
Common Error Types
|
||||
typescript// Cryptographic errors
|
||||
class CryptoError extends Error {
|
||||
constructor(message: string) {
|
||||
super(`Crypto Error: ${message}`);
|
||||
this.name = 'CryptoError';
|
||||
}
|
||||
}
|
||||
|
||||
// Connection errors
|
||||
class ConnectionError extends Error {
|
||||
constructor(message: string) {
|
||||
super(`Connection Error: ${message}`);
|
||||
this.name = 'ConnectionError';
|
||||
}
|
||||
}
|
||||
|
||||
// Payment errors
|
||||
class PaymentError extends Error {
|
||||
constructor(message: string) {
|
||||
super(`Payment Error: ${message}`);
|
||||
this.name = 'PaymentError';
|
||||
}
|
||||
}
|
||||
Error Recovery Patterns
|
||||
javascript// Robust message sending with retry
|
||||
async function sendMessageWithRetry(manager, message, maxRetries = 3) {
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
await manager.sendSecureMessage(message);
|
||||
return; // Success
|
||||
} catch (error) {
|
||||
console.warn(`Send attempt ${attempt} failed:`, error.message);
|
||||
|
||||
if (error.message.includes('Session expired')) {
|
||||
throw new PaymentError('Session expired - payment required');
|
||||
}
|
||||
|
||||
if (error.message.includes('Rate limit')) {
|
||||
// Wait before retry
|
||||
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (attempt === maxRetries) {
|
||||
throw error; // Final attempt failed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Connection error handling
|
||||
function handleConnectionError(error) {
|
||||
if (error.message.includes('MITM')) {
|
||||
alert('⚠️ Security threat detected! Connection terminated.');
|
||||
return 'security_threat';
|
||||
}
|
||||
|
||||
if (error.message.includes('timeout')) {
|
||||
return 'timeout';
|
||||
}
|
||||
|
||||
if (error.message.includes('ice')) {
|
||||
return 'nat_traversal';
|
||||
}
|
||||
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
// Payment error handling
|
||||
function handlePaymentError(error) {
|
||||
if (error.message.includes('preimage')) {
|
||||
return 'invalid_payment';
|
||||
}
|
||||
|
||||
if (error.message.includes('expired')) {
|
||||
return 'session_expired';
|
||||
}
|
||||
|
||||
if (error.message.includes('webln')) {
|
||||
return 'webln_failed';
|
||||
}
|
||||
|
||||
return 'payment_failed';
|
||||
}
|
||||
🧪 Testing
|
||||
Unit Testing Examples
|
||||
javascript// Test encryption/decryption round-trip
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
🎉 **Thank you for your interest in contributing to SecureBit.chat!**
|
||||
|
||||
We're building the most secure P2P messenger with Lightning Network integration, and we need your help to make it even better. **Version 4.02.442 introduces complete ASN.1 validation for enhanced key security.**
|
||||
**Version 4.02.442 introduces complete ASN.1 validation for enhanced key security.**
|
||||
|
||||
## 🌟 Ways to Contribute
|
||||
|
||||
|
||||
Reference in New Issue
Block a user