Update delete old laying visual files
This commit is contained in:
57
README.md
57
README.md
@@ -4,7 +4,7 @@
|
||||
|
||||

|
||||
|
||||
**The world's first P2P messenger with ECDH + DTLS + SAS security, Lightning Network payments and military-grade cryptography**
|
||||
**The world's first P2P messenger with ECDH + DTLS + SAS security and military-grade cryptography**
|
||||
|
||||
[](https://github.com/SecureBitChat/securebit-chat/releases/latest)
|
||||
[](https://securebitchat.github.io/securebit-chat/)
|
||||
@@ -103,17 +103,12 @@
|
||||
### 🏆 Industry Leader
|
||||
|
||||
* **Dominates in 11/15 security categories** vs Signal, Threema, Session
|
||||
* **First messenger** with Lightning Network integration
|
||||
* **First messenger** with enhanced ECDH + DTLS + SAS security
|
||||
* **Military-grade cryptography** exceeding government standards
|
||||
* **Zero servers** — truly decentralized P2P architecture
|
||||
* **PWA technology** — install like native apps without app stores
|
||||
|
||||
### ⚡ Lightning Network Pioneer
|
||||
|
||||
* **Instant satoshi payments** for secure sessions
|
||||
* **Pay-per-session model** — no ads, no data harvesting
|
||||
* **WebLN integration** with all major Lightning wallets
|
||||
* **Sustainable economics** for private communication
|
||||
|
||||
|
||||
### 🔐 15-Layer Military Security
|
||||
|
||||
@@ -152,14 +147,14 @@
|
||||
| Feature | **SecureBit.chat** | Signal | Threema | Session |
|
||||
| --------------------------- | ----------------------------- | ---------------------------- | --------------------- | ---------------------- |
|
||||
| **Architecture** | 🏆 Pure P2P WebRTC | ❌ Centralized servers | ❌ Centralized servers | ⚠️ Onion network |
|
||||
| **Payment Integration** | 🏆 Lightning Network | ❌ None | ❌ None | ❌ None |
|
||||
| **Payment Integration** | ❌ None | ❌ None | ❌ None | ❌ None |
|
||||
| **File Transfer** | 🏆 P2P encrypted + chunked | ✅ Encrypted via servers | ✅ Encrypted via servers | ✅ Encrypted via servers |
|
||||
| **PWA Support** | 🏆 Full PWA installation | ❌ None | ❌ None | ❌ None |
|
||||
| **Registration** | 🏆 Anonymous | ❌ Phone required | ✅ ID generated | ✅ Random ID |
|
||||
| **Traffic Obfuscation** | 🏆 Advanced fake traffic | ❌ None | ❌ None | ✅ Onion routing |
|
||||
| **Censorship Resistance** | 🏆 Hard to block | ⚠️ Blocked in some countries | ⚠️ May be blocked | ✅ Onion routing |
|
||||
| **Data Storage** | 🏆 Zero storage | ⚠️ Local database | ⚠️ Local + backup | ⚠️ Local database |
|
||||
| **Economic Model** | 🏆 Pay‑per‑session | ⚠️ Donations dependent | ✅ One‑time purchase | ⚠️ Donations dependent |
|
||||
| **Economic Model** | ✅ Open-source | ⚠️ Donations dependent | ✅ One‑time purchase | ⚠️ Donations dependent |
|
||||
| **Metadata Protection** | 🏆 Full encryption | ⚠️ Sealed Sender (partial) | ⚠️ Minimal metadata | ✅ Onion routing |
|
||||
| **Key Security** | 🏆 Non‑extractable + hardware | ✅ Secure storage | ✅ Local storage | ✅ Secure storage |
|
||||
| **Perfect Forward Secrecy** | 🏆 Auto rotation (5 min) | ✅ Double Ratchet | ⚠️ Partial (groups) | ✅ Session Ratchet |
|
||||
@@ -178,7 +173,7 @@
|
||||
2. **Install PWA:** Click "Install" button for native app experience
|
||||
3. **Choose:** *Create Channel* or *Join Channel*
|
||||
4. **Complete:** Secure key exchange with verification
|
||||
5. **Select:** Session type (Demo / Basic / Premium)
|
||||
5. **Verify:** Security codes and start a secure chat
|
||||
6. **Communicate:** With military‑grade encryption + secure file transfers
|
||||
|
||||
### Option 2: Self‑Host
|
||||
@@ -227,26 +222,7 @@ open http://localhost:8000
|
||||
|
||||
---
|
||||
|
||||
## ⚡ Lightning Network Integration
|
||||
|
||||
### Session Types
|
||||
|
||||
* **🎮 Demo:** 6 minutes free (testing)
|
||||
* **⚡ Basic:** 1 hour for 50 satoshis
|
||||
* **💎 Premium:** 6 hours for 200 satoshis
|
||||
|
||||
### Supported Wallets
|
||||
|
||||
| Wallet | WebLN | Mobile | Desktop |
|
||||
| ----------------- | :---: | :----: | :-----: |
|
||||
| Alby | ✅ | ✅ | ✅ |
|
||||
| Zeus | ✅ | ✅ | ✅ |
|
||||
| Wallet of Satoshi | ✅ | ✅ | ❌ |
|
||||
| Muun | ⚠️ | ✅ | ❌ |
|
||||
| Breez | ✅ | ✅ | ❌ |
|
||||
| Strike | ✅ | ✅ | ✅ |
|
||||
|
||||
*And many more WebLN‑compatible wallets.*
|
||||
|
||||
|
||||
---
|
||||
|
||||
@@ -260,7 +236,7 @@ open http://localhost:8000
|
||||
🔑 Key Exchange: ECDH P-384 (Perfect Forward Secrecy)
|
||||
🛡️ Transport Layer: WebRTC DTLS 1.2
|
||||
🌐 Network Layer: P2P WebRTC Data Channels
|
||||
⚡ Payment Layer: Lightning Network + WebLN
|
||||
|
||||
📱 PWA Layer: Service Workers + Cache API
|
||||
🔒 ASN.1 Layer: Complete DER parsing and validation
|
||||
```
|
||||
@@ -280,7 +256,7 @@ open http://localhost:8000
|
||||
* Modern browser with WebRTC support (Chrome 60+, Firefox 60+, Safari 12+)
|
||||
* HTTPS connection (required for WebRTC and PWA)
|
||||
* JavaScript enabled
|
||||
* Lightning wallet with WebLN (for payments)
|
||||
|
||||
* Service Worker support for PWA features
|
||||
|
||||
---
|
||||
@@ -322,7 +298,7 @@ open http://localhost:8000
|
||||
|
||||
* P2P group chats (up to 8 participants)
|
||||
* Mesh networking topology
|
||||
* Group Lightning payments
|
||||
|
||||
* Anonymous group administration
|
||||
* Group file sharing
|
||||
|
||||
@@ -482,7 +458,7 @@ We welcome contributions from the community!
|
||||
|
||||
* 🔐 Cryptography — Security improvements and audits
|
||||
* 🌐 Network — P2P optimization and reliability
|
||||
* ⚡ Lightning — Payment integration enhancements
|
||||
|
||||
* 📂 File Transfer — EnhancedSecureFileTransfer improvements
|
||||
* 📱 PWA — Install prompts, offline management, and PWA lifecycle
|
||||
* 🎨 UI/UX — Interface improvements, FileTransfer and DownloadApps components
|
||||
@@ -524,7 +500,7 @@ While SecureBit.chat implements military-grade cryptography and follows security
|
||||
* Always verify security codes out-of-band
|
||||
* Keep devices and browsers updated
|
||||
* Be aware of endpoint security risks
|
||||
* Use reputable Lightning wallets
|
||||
|
||||
* **File transfers are protected with the same military-grade cryptography as chat messages**
|
||||
* **All cryptographic keys now undergo complete ASN.1 structure validation**
|
||||
|
||||
@@ -533,7 +509,7 @@ This software is provided "as is" for educational and research purposes. Users a
|
||||
|
||||
* Cryptographic software usage
|
||||
* Private communications
|
||||
* Bitcoin/Lightning Network transactions
|
||||
|
||||
* File sharing and transfer
|
||||
|
||||
### Privacy Statement
|
||||
@@ -558,12 +534,7 @@ SecureBit.chat:
|
||||
* **Secure P2P file sharing without servers**
|
||||
* **Complete ASN.1 validation for cryptographic keys**
|
||||
|
||||
### For Bitcoin/Lightning Users
|
||||
|
||||
* Native Lightning Network integration
|
||||
* Sustainable pay-per-session model
|
||||
* Support for all major Lightning wallets
|
||||
* No KYC or account requirements
|
||||
|
||||
|
||||
### For Mobile Users
|
||||
|
||||
|
||||
18
SECURITY.md
18
SECURITY.md
@@ -153,8 +153,7 @@ We maintain a hall of fame for security researchers who help improve SecureBit.c
|
||||
2. **Use Official Source:** Only use https://SecureBit.chat
|
||||
3. **Keep Updated:** Use version 4.02.x for complete ASN.1 validation
|
||||
4. **Secure Environment:** Use updated browsers on secure devices
|
||||
5. **Lightning Wallets:** Use reputable Lightning wallets (Alby, Zeus, etc.)
|
||||
6. **Monitor Security Status:** Check for "MAXIMUM SECURITY" indicator in chat
|
||||
5. **Monitor Security Status:** Check for "MAXIMUM SECURITY" indicator in chat
|
||||
|
||||
### Security Indicators:
|
||||
- ✅ **Green Shield:** MAXIMUM SECURITY (Stage 5) active
|
||||
@@ -169,6 +168,13 @@ We maintain a hall of fame for security researchers who help improve SecureBit.c
|
||||
- ❌ Unofficial domains or mirrors
|
||||
- ❌ Missing security layer notifications
|
||||
|
||||
### Research Ethics
|
||||
- **No Disruption:** Don't interfere with live users
|
||||
- **Responsible Disclosure:** Follow our disclosure timeline
|
||||
- **No Data Harvesting:** Don't collect user communications
|
||||
- **Legal Compliance:** Follow all applicable laws
|
||||
- **Respect Privacy:** Don't attempt to break active encrypted sessions
|
||||
|
||||
## 🔬 Security Research Guidelines
|
||||
|
||||
### Scope
|
||||
@@ -191,16 +197,8 @@ We maintain a hall of fame for security researchers who help improve SecureBit.c
|
||||
- ❌ Physical attacks on user devices
|
||||
- ❌ DoS attacks on user connections
|
||||
- ❌ Issues requiring physical access
|
||||
- ❌ Lightning Network protocol issues
|
||||
- ❌ Browser security vulnerabilities
|
||||
|
||||
### Research Ethics
|
||||
- **No Disruption:** Don't interfere with live users
|
||||
- **Responsible Disclosure:** Follow our disclosure timeline
|
||||
- **No Data Harvesting:** Don't collect user communications
|
||||
- **Legal Compliance:** Follow all applicable laws
|
||||
- **Respect Privacy:** Don't attempt to break active encrypted sessions
|
||||
|
||||
## 🔄 Recent Security Updates (Version 4.02)
|
||||
|
||||
### Major Security Enhancements:
|
||||
|
||||
@@ -1,256 +0,0 @@
|
||||
# Security Updates v4.02.985 - ECDH + DTLS + SAS
|
||||
|
||||
## 🛡️ Revolutionary Security System Update
|
||||
|
||||
**Release Date:** January 2025
|
||||
**Version:** 4.02.985
|
||||
**Security Level:** Military-Grade
|
||||
**Breaking Changes:** Yes - Complete PAKE removal
|
||||
|
||||
---
|
||||
|
||||
## 🔥 Major Security Improvements
|
||||
|
||||
### 1. Complete PAKE System Removal
|
||||
|
||||
**What Changed:**
|
||||
- **Removed:** All libsodium dependencies and PAKE-based authentication
|
||||
- **Replaced With:** ECDH + DTLS + SAS triple-layer security system
|
||||
- **Impact:** Eliminates complex PAKE implementation in favor of standardized protocols
|
||||
|
||||
**Security Benefits:**
|
||||
- ✅ **Simplified Architecture** - Reduced attack surface
|
||||
- ✅ **Standards Compliance** - RFC-compliant protocols
|
||||
- ✅ **Better Maintenance** - Native Web Crypto API usage
|
||||
- ✅ **Enhanced Security** - Triple-layer defense system
|
||||
|
||||
### 2. ECDH Key Exchange Implementation
|
||||
|
||||
**New Features:**
|
||||
- **Elliptic Curve Diffie-Hellman** using P-384 (secp384r1)
|
||||
- **Cryptographically secure** key pair generation
|
||||
- **Perfect Forward Secrecy** with session-specific keys
|
||||
- **MITM resistance** requiring knowledge of both private keys
|
||||
|
||||
**Technical Details:**
|
||||
```javascript
|
||||
// ECDH Key Generation
|
||||
const keyPair = await crypto.subtle.generateKey(
|
||||
{ name: 'ECDH', namedCurve: 'P-384' },
|
||||
true,
|
||||
['deriveKey', 'deriveBits']
|
||||
);
|
||||
|
||||
// Shared Secret Derivation
|
||||
const sharedSecret = await crypto.subtle.deriveBits(
|
||||
{ name: 'ECDH', public: peerPublicKey },
|
||||
privateKey,
|
||||
384
|
||||
);
|
||||
```
|
||||
|
||||
### 3. DTLS Fingerprint Verification
|
||||
|
||||
**New Features:**
|
||||
- **WebRTC Certificate Extraction** from SDP offers/answers
|
||||
- **SHA-256 Fingerprint Generation** for transport verification
|
||||
- **Mutual Verification** between both parties
|
||||
- **Transport Layer Security** validation
|
||||
|
||||
**Security Properties:**
|
||||
- ✅ **Connection Integrity** - Prevents hijacking
|
||||
- ✅ **Certificate Validation** - Ensures authentic WebRTC certificates
|
||||
- ✅ **MITM Detection** - Detects man-in-the-middle at transport layer
|
||||
|
||||
### 4. SAS (Short Authentication String) System
|
||||
|
||||
**New Features:**
|
||||
- **7-digit Verification Code** (0000000-9999999)
|
||||
- **HKDF-based Generation** from shared secret and DTLS fingerprints
|
||||
- **Single Code Generation** on Offer side, shared with Answer side
|
||||
- **Mutual Verification** - Both users must confirm the same code
|
||||
|
||||
**Implementation:**
|
||||
```javascript
|
||||
// SAS Generation
|
||||
async _computeSAS(keyMaterialRaw, localFP, remoteFP) {
|
||||
const salt = enc.encode('webrtc-sas|' + [localFP, remoteFP].sort().join('|'));
|
||||
const key = await crypto.subtle.importKey('raw', keyMaterialRaw, 'HKDF', false, ['deriveBits']);
|
||||
const bits = await crypto.subtle.deriveBits(
|
||||
{ name: 'HKDF', hash: 'SHA-256', salt, info: enc.encode('p2p-sas-v1') },
|
||||
key, 64
|
||||
);
|
||||
const n = (new DataView(bits).getUint32(0) ^ new DataView(bits).getUint32(4)) >>> 0;
|
||||
return String(n % 10_000_000).padStart(7, '0');
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔒 Security Flow
|
||||
|
||||
### New Authentication Process
|
||||
|
||||
```
|
||||
1. ECDH Key Exchange
|
||||
├── Generate P-384 key pairs
|
||||
├── Exchange public keys via SDP
|
||||
└── Derive shared secret
|
||||
|
||||
2. DTLS Fingerprint Verification
|
||||
├── Extract certificates from WebRTC SDP
|
||||
├── Generate SHA-256 fingerprints
|
||||
└── Verify transport authenticity
|
||||
|
||||
3. SAS Generation and Sharing
|
||||
├── Generate SAS from shared secret + fingerprints
|
||||
├── Share SAS code via data channel
|
||||
└── Display to both users
|
||||
|
||||
4. Mutual Verification
|
||||
├── Both users confirm the same SAS code
|
||||
├── Connection established only after confirmation
|
||||
└── Secure communication begins
|
||||
```
|
||||
|
||||
### MITM Attack Prevention
|
||||
|
||||
**Triple-Layer Defense:**
|
||||
1. **ECDH Layer** - Requires knowledge of both private keys
|
||||
2. **DTLS Layer** - Validates transport layer certificates
|
||||
3. **SAS Layer** - Human-verifiable out-of-band confirmation
|
||||
|
||||
**Attack Scenarios:**
|
||||
- ❌ **Passive Eavesdropping** - Prevented by ECDH encryption
|
||||
- ❌ **Active MITM** - Prevented by DTLS fingerprint verification
|
||||
- ❌ **Certificate Spoofing** - Prevented by SAS verification
|
||||
- ❌ **Connection Hijacking** - Prevented by mutual verification
|
||||
|
||||
---
|
||||
|
||||
## 🚀 Performance Improvements
|
||||
|
||||
### Reduced Dependencies
|
||||
- **Before:** libsodium.js (~200KB) + custom PAKE implementation
|
||||
- **After:** Native Web Crypto API (0KB additional)
|
||||
- **Improvement:** ~200KB reduction in bundle size
|
||||
|
||||
### Faster Authentication
|
||||
- **Before:** Complex PAKE multi-step protocol
|
||||
- **After:** Streamlined ECDH + SAS verification
|
||||
- **Improvement:** ~40% faster connection establishment
|
||||
|
||||
### Better Browser Compatibility
|
||||
- **Before:** Required libsodium polyfills
|
||||
- **After:** Native browser APIs only
|
||||
- **Improvement:** Better compatibility across all modern browsers
|
||||
|
||||
---
|
||||
|
||||
## 🔧 Technical Implementation
|
||||
|
||||
### Key Components Added
|
||||
|
||||
1. **`_computeSAS()`** - SAS generation using HKDF
|
||||
2. **`_extractDTLSFingerprintFromSDP()`** - Certificate extraction
|
||||
3. **`_decodeKeyFingerprint()`** - Key material processing
|
||||
4. **`confirmVerification()`** - Mutual verification handling
|
||||
5. **`handleSASCode()`** - SAS code reception and validation
|
||||
|
||||
### Key Components Removed
|
||||
|
||||
1. **All PAKE-related methods** - `runPAKE()`, `_handlePAKEMessage()`, etc.
|
||||
2. **libsodium dependencies** - `_getFallbackSodium()`, sodium imports
|
||||
3. **PAKE message types** - `PAKE_STEP1`, `PAKE_STEP2`, `PAKE_FINISH`
|
||||
4. **PAKE state management** - `isPAKEVerified`, `resetPAKE()`
|
||||
|
||||
### Message Types Updated
|
||||
|
||||
**New System Messages:**
|
||||
- `sas_code` - SAS code transmission
|
||||
- `verification_confirmed` - Local verification confirmation
|
||||
- `verification_both_confirmed` - Mutual verification completion
|
||||
|
||||
**Removed System Messages:**
|
||||
- `PAKE_STEP1`, `PAKE_STEP2`, `PAKE_FINISH`
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ Security Analysis
|
||||
|
||||
### Threat Model Updates
|
||||
|
||||
**New Protections:**
|
||||
- ✅ **Enhanced MITM Protection** - Triple-layer defense
|
||||
- ✅ **Transport Security** - DTLS fingerprint verification
|
||||
- ✅ **User Verification** - Human-readable SAS codes
|
||||
- ✅ **Standards Compliance** - RFC-compliant protocols
|
||||
|
||||
**Maintained Protections:**
|
||||
- ✅ **Perfect Forward Secrecy** - Session-specific keys
|
||||
- ✅ **Replay Protection** - Unique session identifiers
|
||||
- ✅ **Race Condition Protection** - Mutex framework
|
||||
- ✅ **Memory Safety** - Secure key storage
|
||||
|
||||
### Security Rating
|
||||
|
||||
**Previous Version (v4.02.442):**
|
||||
- Security Level: High (PAKE + ASN.1)
|
||||
- MITM Protection: Good
|
||||
- Standards Compliance: Partial
|
||||
|
||||
**Current Version (v4.02.985):**
|
||||
- Security Level: Military-Grade (ECDH + DTLS + SAS)
|
||||
- MITM Protection: Maximum
|
||||
- Standards Compliance: Full RFC compliance
|
||||
|
||||
---
|
||||
|
||||
## 📋 Migration Guide
|
||||
|
||||
### For Developers
|
||||
|
||||
**Breaking Changes:**
|
||||
1. **PAKE API Removal** - All PAKE-related methods removed
|
||||
2. **Message Type Changes** - New system message types
|
||||
3. **Authentication Flow** - Complete rewrite of verification process
|
||||
|
||||
**Required Updates:**
|
||||
1. Remove any PAKE-related code
|
||||
2. Update message handling for new system messages
|
||||
3. Implement SAS verification UI
|
||||
4. Update connection establishment logic
|
||||
|
||||
### For Users
|
||||
|
||||
**No Action Required:**
|
||||
- Automatic update to new security system
|
||||
- Improved user experience with SAS verification
|
||||
- Better security with simplified interface
|
||||
|
||||
---
|
||||
|
||||
## 🔮 Future Roadmap
|
||||
|
||||
### v5.0 Post-Quantum (Planned)
|
||||
- **Post-Quantum Cryptography** - NIST-approved algorithms
|
||||
- **Hybrid Classical-Quantum** - Transitional security
|
||||
- **Enhanced SAS** - Quantum-resistant verification
|
||||
|
||||
### v4.03.x (Next)
|
||||
- **Performance Optimizations** - Further speed improvements
|
||||
- **Enhanced UI** - Better SAS verification experience
|
||||
- **Additional Curves** - Support for more elliptic curves
|
||||
|
||||
---
|
||||
|
||||
## 📞 Support
|
||||
|
||||
**Security Issues:** security@securebit.chat
|
||||
**Technical Support:** support@securebit.chat
|
||||
**Documentation:** [GitHub Wiki](https://github.com/SecureBitChat/securebit-chat/wiki)
|
||||
|
||||
---
|
||||
|
||||
**SecureBit.chat v4.02.985 - ECDH + DTLS + SAS**
|
||||
*Military-grade security for the modern web*
|
||||
@@ -1,159 +0,0 @@
|
||||
# SecureBit.chat Security Updates v4.1
|
||||
|
||||
## 🔒 Comprehensive Connection Security Overhaul
|
||||
|
||||
### 🛡️ New Security Technologies Implemented
|
||||
|
||||
#### 1. Advanced Mutex Framework (Layer 13)
|
||||
- **Race Condition Protection:** Custom `_withMutex('connectionOperation')` with 15-second timeout
|
||||
- **Atomic Operations:** Serialized connection operations to prevent conflicts
|
||||
- **Multi-stage Validation:** Step-by-step validation with automatic rollback
|
||||
- **Error Recovery:** `_cleanupFailedOfferCreation()` for failed operations
|
||||
- **Diagnostic Capability:** Unique `operationId` tracking for precise error identification
|
||||
|
||||
#### 2. Secure Key Storage System (Layer 14)
|
||||
- **WeakMap Isolation:** Replaced public key properties with private `WeakMap`-based storage
|
||||
- **Secure Access Methods:** `_getSecureKey()`, `_setSecureKey()`, `_initializeSecureKeyStorage()`
|
||||
- **Key Validation:** `_validateKeyValue()` with type and format checking
|
||||
- **Key Rotation:** `_rotateKeys()` with secure key replacement
|
||||
- **Emergency Wipe:** `_emergencyKeyWipe()` for threat response
|
||||
- **Backward Compatibility:** Getters/setters for existing code compatibility
|
||||
|
||||
#### 3. Production Security Logging (Layer 15)
|
||||
- **Environment Detection:** Automatic production vs development mode detection
|
||||
- **Data Sanitization:** `_secureLog()` replacing `console.log` with sanitization
|
||||
- **Log Level Control:** Production (warn+error only), Development (debug+)
|
||||
- **Rate Limiting:** Automatic log spam prevention and cleanup
|
||||
- **Privacy Protection:** Encryption keys, message content, and tokens are sanitized
|
||||
|
||||
### 🔐 Security Benefits
|
||||
|
||||
#### Enhanced Protection Against:
|
||||
- **Race Conditions:** Timing-based attacks during key generation eliminated
|
||||
- **Key Exposure:** Direct access to cryptographic keys prevented
|
||||
- **Data Leakage:** Sensitive information protected in production logs
|
||||
- **Memory Attacks:** Keys inaccessible via debugger or direct property access
|
||||
- **Connection Conflicts:** Atomic connection establishment ensured
|
||||
|
||||
#### Performance Impact:
|
||||
- **Total Latency:** Increased by ~3.5ms (from 75ms to 78.5ms)
|
||||
- **Memory Usage:** Minimal additional overhead
|
||||
- **Throughput:** Maintained at ~500 messages/second
|
||||
- **Efficiency:** 50% (excellent for security level provided)
|
||||
|
||||
### 📊 Updated Security Architecture
|
||||
|
||||
#### 15-Layer Defense System:
|
||||
1. **Enhanced Authentication** (ECDSA P-384)
|
||||
2. **Key Exchange** (ECDH P-384)
|
||||
3. **Metadata Protection** (Separate AES-GCM)
|
||||
4. **Message Encryption** (Enhanced AES-GCM)
|
||||
5. **Nested Encryption** (Additional AES-GCM)
|
||||
6. **Packet Padding** (Size Obfuscation)
|
||||
7. **Anti-Fingerprinting** (Pattern Obfuscation)
|
||||
8. **Packet Reordering Protection** (Sequence Security)
|
||||
9. **Message Chunking** (Timing Analysis Protection)
|
||||
10. **Fake Traffic Generation** (Traffic Analysis)
|
||||
11. **Enhanced Rate Limiting** (DDoS Protection)
|
||||
12. **Perfect Forward Secrecy** (Key Rotation)
|
||||
13. **Mutex Framework** (Race Condition Protection) ⭐ NEW
|
||||
14. **Secure Key Storage** (WeakMap Isolation) ⭐ NEW
|
||||
15. **Production Security Logging** (Data Sanitization) ⭐ NEW
|
||||
|
||||
### 🔄 Breaking Changes
|
||||
|
||||
#### Connection Establishment:
|
||||
- Now requires mutex coordination for all operations
|
||||
- Automatic rollback on connection failures
|
||||
- Enhanced error diagnostics with phase tracking
|
||||
|
||||
#### Key Storage:
|
||||
- Public key properties (`encryptionKey`, `macKey`, etc.) replaced with private storage
|
||||
- All key access must go through secure methods
|
||||
- Backward compatibility maintained through getters/setters
|
||||
|
||||
#### Logging:
|
||||
- `console.log` replaced with `_secureLog()` in production
|
||||
- Sensitive data automatically sanitized
|
||||
- Environment-aware logging behavior
|
||||
|
||||
### 🚀 Implementation Details
|
||||
|
||||
#### Mutex Framework Usage:
|
||||
```javascript
|
||||
await this._withMutex('connectionOperation', async () => {
|
||||
const operationId = this._generateOperationId();
|
||||
try {
|
||||
await this._generateEncryptionKeys();
|
||||
await this._validateConnectionParameters();
|
||||
await this._establishSecureChannel();
|
||||
} catch (error) {
|
||||
await this._cleanupFailedOfferCreation(operationId);
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
#### Secure Key Storage Usage:
|
||||
```javascript
|
||||
// Initialize secure storage
|
||||
this._initializeSecureKeyStorage();
|
||||
|
||||
// Secure key access
|
||||
const encryptionKey = this._getSecureKey('encryptionKey');
|
||||
this._setSecureKey('encryptionKey', newKey, { validate: true });
|
||||
|
||||
// Emergency key wipe
|
||||
this._emergencyKeyWipe();
|
||||
```
|
||||
|
||||
#### Production Logging Usage:
|
||||
```javascript
|
||||
// Secure logging with data sanitization
|
||||
this._secureLog('debug', 'Connection established', {
|
||||
userId: '[REDACTED]',
|
||||
encryptionKey: '[REDACTED]',
|
||||
messageContent: '[REDACTED]'
|
||||
});
|
||||
```
|
||||
|
||||
### 📈 Security Metrics
|
||||
|
||||
#### Threat Protection Enhancement:
|
||||
- **Race Condition Attacks:** 100% prevention
|
||||
- **Key Exposure:** 100% prevention
|
||||
- **Data Leakage:** 100% prevention in production
|
||||
- **Memory Attacks:** 100% prevention
|
||||
- **Connection Conflicts:** 100% prevention
|
||||
|
||||
#### Compliance Standards:
|
||||
- ✅ **NIST SP 800-57:** Enhanced key management
|
||||
- ✅ **FIPS 140-2 Level 2:** Cryptographic module security
|
||||
- ✅ **GDPR:** Enhanced privacy protection
|
||||
- ✅ **CCPA:** California privacy compliance
|
||||
- ✅ **ISO 27001:** Information security management
|
||||
|
||||
### 🔮 Future Enhancements
|
||||
|
||||
#### Planned for v4.2:
|
||||
- **AI-Powered Pattern Generation:** Machine learning fake traffic
|
||||
- **Protocol Mimicry:** Disguise as common protocols (HTTP, DNS)
|
||||
- **Adaptive Obfuscation:** Real-time pattern adjustment
|
||||
- **Quantum Key Distribution:** Hardware-based key generation
|
||||
|
||||
#### Long-term Roadmap:
|
||||
- **Post-Quantum Cryptography:** CRYSTALS-Kyber and CRYSTALS-Dilithium
|
||||
- **Advanced Traffic Obfuscation:** AI-powered pattern generation
|
||||
- **Enhanced Perfect Forward Secrecy:** Every 1 minute key rotation
|
||||
|
||||
---
|
||||
|
||||
**Version:** 4.1.223
|
||||
**Release Date:** January 15, 2025
|
||||
**Security Level:** Military-Grade (15 layers)
|
||||
**Compatibility:** Backward compatible with v4.0.x
|
||||
**Upgrade Required:** Recommended for all users
|
||||
|
||||
---
|
||||
|
||||
*This update represents a significant advancement in secure communication technology, providing military-grade protection against the most sophisticated threats while maintaining excellent performance and user experience.*
|
||||
354
dist/app.js
vendored
354
dist/app.js
vendored
File diff suppressed because one or more lines are too long
4
dist/app.js.map
vendored
4
dist/app.js.map
vendored
File diff suppressed because one or more lines are too long
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
|
||||
|
||||
|
||||
@@ -72,14 +72,14 @@
|
||||
|
||||
|
||||
<!-- GitHub Pages SEO -->
|
||||
<meta name="description" content="SecureBit.chat v4.02.985 — P2P messenger with ECDH + DTLS + SAS security, 18-layer military-grade cryptography, and Lightning Network payments">
|
||||
<meta name="keywords" content="P2P messenger, ECDH, DTLS, SAS, encryption, Lightning Network, WebRTC, privacy, ASN.1 validation, military-grade security, 18-layer defense, MITM protection">
|
||||
<meta name="description" content="SecureBit.chat v4.02.985 — P2P messenger with ECDH + DTLS + SAS security and 18-layer military-grade cryptography">
|
||||
<meta name="keywords" content="P2P messenger, ECDH, DTLS, SAS, encryption, WebRTC, privacy, ASN.1 validation, military-grade security, 18-layer defense, MITM protection, PFS">
|
||||
<meta name="author" content="Volodymyr">
|
||||
<link rel="canonical" href="https://github.com/SecureBitChat/securebit-chat/">
|
||||
|
||||
<!-- Open Graph -->
|
||||
<meta property="og:title" content="SecureBit.chat - Enhanced Security Edition">
|
||||
<meta property="og:description" content="The first P2P messenger with Lightning Network payments">
|
||||
<meta property="og:description" content="The most secure P2P messenger with military-grade cryptography">
|
||||
<meta property="og:url" content="https://github.com/SecureBitChat/securebit-chat/">
|
||||
<meta property="og:type" content="website">
|
||||
<meta property="og:image" content="https://github.com/SecureBitChat/securebit-chat/favicon.ico">
|
||||
|
||||
@@ -17,7 +17,6 @@
|
||||
"chat",
|
||||
"encryption",
|
||||
"webrtc",
|
||||
"lightning",
|
||||
"privacy",
|
||||
"security"
|
||||
],
|
||||
|
||||
360
src/app.jsx
360
src/app.jsx
@@ -11,12 +11,6 @@
|
||||
title: "18-Layer Military Security",
|
||||
description: "Revolutionary defense system with ECDH P-384 + AES-GCM 256 + ECDSA + Complete ASN.1 Validation. Enhanced Security Edition provides military-grade protection exceeding government standards with complete key structure verification."
|
||||
},
|
||||
{
|
||||
icon: "fas fa-bolt",
|
||||
color: "yellow",
|
||||
title: "Lightning Network Payments",
|
||||
description: "First messenger with Lightning Network integration. Pay-per-session with satoshis via WebLN. Sustainable economic model without ads or data harvesting."
|
||||
},
|
||||
{
|
||||
icon: "fas fa-network-wired",
|
||||
color: "purple",
|
||||
@@ -74,7 +68,7 @@
|
||||
React.createElement('p', {
|
||||
key: 'subtitle',
|
||||
className: "text-secondary max-w-2xl mx-auto"
|
||||
}, 'The only messenger with military-grade cryptography and Lightning payments')
|
||||
}, 'The only messenger with military-grade cryptography')
|
||||
]),
|
||||
|
||||
React.createElement('div', {
|
||||
@@ -509,7 +503,7 @@
|
||||
</h4>
|
||||
<p className="text-secondary leading-relaxed text-lg mb-4">
|
||||
SecureBit.chat dominates in 11 out of 15 security categories, establishing itself as the most secure P2P messenger available.
|
||||
The Enhanced Security Edition introduces revolutionary 18-layer defense architecture with complete ASN.1 validation, Lightning Network integration, and military-grade cryptography that exceeds government and enterprise standards.
|
||||
The Enhanced Security Edition introduces revolutionary 18-layer defense architecture with complete ASN.1 validation, and military-grade cryptography that exceeds government and enterprise standards.
|
||||
</p>
|
||||
<div className="grid md:grid-cols-2 gap-4 mt-6">
|
||||
<div className="p-4 bg-orange-500/5 border border-orange-500/10 rounded-lg">
|
||||
@@ -518,12 +512,6 @@
|
||||
ECDH P-384 + AES-GCM 256 + ECDSA P-384 + Complete ASN.1 Validation with non-extractable keys and 18-layer defense system
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-4 bg-orange-500/5 border border-orange-500/10 rounded-lg">
|
||||
<h5 className="text-orange-400 font-semibold mb-2">⚡ Lightning Integration</h5>
|
||||
<p className="text-sm text-gray-300">
|
||||
First messenger with Lightning Network payments - sustainable economic model with instant satoshi transactions
|
||||
</p>
|
||||
</div>
|
||||
<div className="p-4 bg-orange-500/5 border border-orange-500/10 rounded-lg">
|
||||
<h5 className="text-orange-400 font-semibold mb-2">🌐 True P2P Architecture</h5>
|
||||
<p className="text-sm text-gray-300">
|
||||
@@ -646,7 +634,6 @@
|
||||
"Complete ASN.1 DER validation",
|
||||
"OID and EC point verification",
|
||||
"SPKI structure validation",
|
||||
"Lightning Network payments",
|
||||
"P2P WebRTC architecture",
|
||||
"Metadata protection",
|
||||
"100% open source code"
|
||||
@@ -698,7 +685,6 @@
|
||||
"Signal Double Ratchet for groups",
|
||||
"Anonymous groups without metadata",
|
||||
"Ephemeral groups (disappear after session)",
|
||||
"Group Lightning payments",
|
||||
"Cryptographic group administration",
|
||||
"Group member auditing"
|
||||
]
|
||||
@@ -1487,350 +1473,8 @@
|
||||
React.createElement('h4', { key: 'title', className: "text-xs sm:text-sm font-medium text-primary mb-1" }, "ECDSA P-384 Signatures"),
|
||||
React.createElement('p', { key: 'desc', className: "text-xs text-muted leading-tight" }, "Digital signatures for message integrity")
|
||||
]),
|
||||
React.createElement('div', { key: 'feature6', className: "text-center p-3 sm:p-4" }, [
|
||||
React.createElement('div', { key: 'icon', className: "w-10 h-10 sm:w-12 sm:h-12 bg-yellow-500/10 border border-yellow-500/20 rounded-lg flex items-center justify-center mx-auto mb-2 sm:mb-3" }, [
|
||||
React.createElement('i', { className: 'fas fa-bolt accent-yellow' })
|
||||
]),
|
||||
React.createElement('h4', { key: 'title', className: "text-xs sm:text-sm font-medium text-primary mb-1" }, "Lightning Payments"),
|
||||
React.createElement('p', { key: 'desc', className: "text-xs text-muted leading-tight" }, "Pay-per-session via WebLN")
|
||||
])
|
||||
]),
|
||||
|
||||
// Wallet Logos Section
|
||||
React.createElement('div', {
|
||||
key: 'wallet-logos-section',
|
||||
className: "mt-8"
|
||||
}, [
|
||||
React.createElement('div', {
|
||||
key: 'wallet-logos-header',
|
||||
className: "text-center mb-4"
|
||||
}, [
|
||||
React.createElement('h3', {
|
||||
key: 'title',
|
||||
className: "text-lg font-medium text-primary mb-2"
|
||||
}, "Supported Lightning wallets"),
|
||||
React.createElement('p', {
|
||||
key: 'subtitle',
|
||||
className: "text-secondary text-sm"
|
||||
}, "To pay for sessions, use any of the popular wallets.")
|
||||
]),
|
||||
React.createElement('div', {
|
||||
key: 'wallet-logos-container',
|
||||
className: "wallet-logos-container"
|
||||
}, [
|
||||
React.createElement('div', {
|
||||
key: 'wallet-logos-track',
|
||||
className: "wallet-logos-track"
|
||||
}, [
|
||||
// First set of logos
|
||||
React.createElement('a', {
|
||||
key: 'alby1-link',
|
||||
href: "https://getalby.com",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo alby"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'alby-img1',
|
||||
src: "logo/alby.svg",
|
||||
alt: "Alby Lightning Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'zeus1-link',
|
||||
href: "https://zeusln.app",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo zeus"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'zeus-img1',
|
||||
src: "logo/zeus.svg",
|
||||
alt: "Zeus Lightning Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'wos1-link',
|
||||
href: "https://www.walletofsatoshi.com",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo wos"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'wos-img1',
|
||||
src: "logo/wos.svg",
|
||||
alt: "Wallet of Satoshi",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'muun1-link',
|
||||
href: "https://muun.com",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo muun"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'muun-img1',
|
||||
src: "logo/muun.svg",
|
||||
alt: "Muun Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'atomic1-link',
|
||||
href: "https://atomicwallet.io",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo atomic"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'atomic-img1',
|
||||
src: "logo/atomic.svg",
|
||||
alt: "Atomic Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'breez1-link',
|
||||
href: "https://breez.technology/mobile/",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo breez"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'breez-img1',
|
||||
src: "logo/breez.svg",
|
||||
alt: "Breez Lightning Wallet",
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'lightning-labs1-link',
|
||||
href: "https://lightning.engineering",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo lightning-labs"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'lightning-labs-img1',
|
||||
src: "logo/lightning-labs.svg",
|
||||
alt: "Lightning Labs",
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'lnbits1-link',
|
||||
href: "https://lnbits.com",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo lnbits"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'lnbits-img1',
|
||||
src: "logo/lnbits.svg",
|
||||
alt: "LNbits",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'strike1-link',
|
||||
href: "https://strike.me",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo strike"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'strike-img1',
|
||||
src: "logo/strike.svg",
|
||||
alt: "Strike",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'impervious1-link',
|
||||
href: "https://impervious.ai",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo impervious"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'impervious-img1',
|
||||
src: "logo/impervious.svg",
|
||||
alt: "Impervious",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'bitcoin-lightning1-link',
|
||||
href: "https://www.blink.sv/",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo bitcoin-lightning"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'blink-img1',
|
||||
src: "logo/blink.svg",
|
||||
alt: "Blink Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
// Second set of logos
|
||||
React.createElement('a', {
|
||||
key: 'alby2-link',
|
||||
href: "https://getalby.com",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo alby"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'alby-img2',
|
||||
src: "logo/alby.svg",
|
||||
alt: "Alby Lightning Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'zeus2-link',
|
||||
href: "https://zeusln.app",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo zeus"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'zeus-img2',
|
||||
src: "logo/zeus.svg",
|
||||
alt: "Zeus Lightning Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'wos2-link',
|
||||
href: "https://www.walletofsatoshi.com",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo wos"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'wos-img2',
|
||||
src: "logo/wos.svg",
|
||||
alt: "Wallet of Satoshi",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'muun2-link',
|
||||
href: "https://muun.com",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo muun"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'muun-img2',
|
||||
src: "logo/muun.svg",
|
||||
alt: "Muun Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'atomic2-link',
|
||||
href: "https://atomicwallet.io",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo atomic"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'atomic-img2',
|
||||
src: "logo/atomic.svg",
|
||||
alt: "Atomic Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'breez2-link',
|
||||
href: "https://breez.technology/mobile/",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo breez"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'breez-img2',
|
||||
src: "logo/breez.svg",
|
||||
alt: "Breez Lightning Wallet",
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'lightning-labs2-link',
|
||||
href: "https://lightning.engineering",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo lightning-labs"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'lightning-labs-img2',
|
||||
src: "logo/lightning-labs.svg",
|
||||
alt: "Lightning Labs",
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'lnbits2-link',
|
||||
href: "https://lnbits.com",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo lnbits"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'lnbits-img2',
|
||||
src: "logo/lnbits.svg",
|
||||
alt: "LNbits",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'strike2-link',
|
||||
href: "https://strike.me",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo strike"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'strike-img2',
|
||||
src: "logo/strike.svg",
|
||||
alt: "Strike",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'impervious2-link',
|
||||
href: "https://impervious.ai",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo impervious"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'impervious-img2',
|
||||
src: "logo/impervious.svg",
|
||||
alt: "Impervious",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
]),
|
||||
React.createElement('a', {
|
||||
key: 'bitcoin-lightning2-link',
|
||||
href: "https://www.blink.sv/",
|
||||
target: "_blank",
|
||||
rel: "noindex nofollow",
|
||||
className: "wallet-logo bitcoin-lightning"
|
||||
}, [
|
||||
React.createElement('img', {
|
||||
key: 'blink-img2',
|
||||
src: "logo/blink.svg",
|
||||
alt: "Blink Wallet",
|
||||
className: "wallet-logo-img"
|
||||
})
|
||||
])
|
||||
])
|
||||
])
|
||||
]),
|
||||
React.createElement(UniqueFeatureSlider, { key: 'unique-features-slider' }),
|
||||
|
||||
React.createElement(DownloadApps, { key: 'download-apps' }),
|
||||
|
||||
@@ -962,7 +962,6 @@ class PWAOfflineManager {
|
||||
</h4>
|
||||
<ul class="space-y-2 ml-6">
|
||||
<li>• P2P connections (WebRTC)</li>
|
||||
<li>• Lightning Network payments</li>
|
||||
<li>• Real-time messaging</li>
|
||||
<li>• Session verification</li>
|
||||
<li>• Key exchange with new peers</li>
|
||||
|
||||
4
sw.js
4
sw.js
@@ -17,7 +17,6 @@ const STATIC_ASSETS = [
|
||||
'/src/components/ui/Header.jsx',
|
||||
'/src/components/ui/PasswordModal.jsx',
|
||||
'/src/components/ui/SessionTypeSelector.jsx',
|
||||
'/src/components/ui/LightningPayment.jsx',
|
||||
'/src/components/ui/PaymentModal.jsx',
|
||||
'/src/components/ui/DownloadApps.jsx',
|
||||
'/src/styles/main.css',
|
||||
@@ -42,8 +41,7 @@ const NETWORK_FIRST_PATTERNS = [
|
||||
/\.js$/,
|
||||
/\.jsx$/,
|
||||
/\/src\//,
|
||||
/api/,
|
||||
/lightning/
|
||||
/api/
|
||||
];
|
||||
|
||||
// Cache first patterns (static assets)
|
||||
|
||||
@@ -1,554 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>LNbits Integration Test</title>
|
||||
<style>
|
||||
body {
|
||||
font-family: 'Inter', sans-serif;
|
||||
background: #2A2B2A;
|
||||
color: #f1f5f9;
|
||||
padding: 20px;
|
||||
}
|
||||
.test-container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
background: #1a1a1a;
|
||||
padding: 20px;
|
||||
border-radius: 12px;
|
||||
}
|
||||
.test-section {
|
||||
margin: 20px 0;
|
||||
padding: 15px;
|
||||
border: 1px solid #333;
|
||||
border-radius: 8px;
|
||||
}
|
||||
.success { color: #34d399; }
|
||||
.error { color: #f87171; }
|
||||
.warning { color: #fbbf24; }
|
||||
.info { color: #60a5fa; }
|
||||
button {
|
||||
background: #fb923c;
|
||||
color: white;
|
||||
border: none;
|
||||
padding: 10px 20px;
|
||||
border-radius: 6px;
|
||||
cursor: pointer;
|
||||
margin: 5px;
|
||||
}
|
||||
button:hover { background: #ea580c; }
|
||||
.log {
|
||||
background: #000;
|
||||
padding: 10px;
|
||||
border-radius: 4px;
|
||||
font-family: monospace;
|
||||
font-size: 12px;
|
||||
max-height: 300px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="test-container">
|
||||
<h1>🔧 Тест интеграции LNbits</h1>
|
||||
|
||||
<div class="test-section">
|
||||
<h3>📋 Конфигурация</h3>
|
||||
<p><strong>API URL:</strong> <span id="apiUrl">https://demo.lnbits.com</span></p>
|
||||
<p><strong>API Key:</strong> <span id="apiKey">a7226682253f4dd7bdb2d9487a9a59f8</span></p>
|
||||
<p><strong>Wallet ID:</strong> <span id="walletId">649903697b03457d8b12c4eae7b2fab9</span></p>
|
||||
</div>
|
||||
|
||||
<div class="test-section">
|
||||
<h3>🧪 Тесты</h3>
|
||||
<button onclick="testHealthCheck()">1. Проверка API</button>
|
||||
<button onclick="testCreateInvoice()">2. Создание инвойса</button>
|
||||
<button onclick="testPaymentStatus()">3. Проверка статуса</button>
|
||||
<button onclick="testVerification()">4. Верификация платежа</button>
|
||||
<button onclick="testRealPayment()">5. Тест реального платежа</button>
|
||||
<button onclick="testDemoMode()">6. Тест Demo режима</button>
|
||||
<button onclick="copyBOLT11()">📋 Копировать BOLT11</button>
|
||||
<button onclick="runAllTests()">🚀 Запустить все тесты</button>
|
||||
</div>
|
||||
|
||||
<div class="test-section">
|
||||
<h3>📊 Результаты</h3>
|
||||
<div id="results"></div>
|
||||
</div>
|
||||
|
||||
<div class="test-section">
|
||||
<h3>📝 Логи</h3>
|
||||
<div id="logs" class="log"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script type="module">
|
||||
let testResults = [];
|
||||
let currentInvoice = null;
|
||||
|
||||
function log(message, type = 'info') {
|
||||
const logsDiv = document.getElementById('logs');
|
||||
const timestamp = new Date().toLocaleTimeString();
|
||||
const logEntry = document.createElement('div');
|
||||
logEntry.className = type;
|
||||
logEntry.textContent = `[${timestamp}] ${message}`;
|
||||
logsDiv.appendChild(logEntry);
|
||||
logsDiv.scrollTop = logsDiv.scrollHeight;
|
||||
console.log(`[${type.toUpperCase()}] ${message}`);
|
||||
}
|
||||
|
||||
function addResult(testName, success, details = '') {
|
||||
testResults.push({ testName, success, details, timestamp: Date.now() });
|
||||
updateResults();
|
||||
}
|
||||
|
||||
function updateResults() {
|
||||
const resultsDiv = document.getElementById('results');
|
||||
const passed = testResults.filter(r => r.success).length;
|
||||
const total = testResults.length;
|
||||
|
||||
resultsDiv.innerHTML = `
|
||||
<div class="info">✅ Пройдено: ${passed}/${total}</div>
|
||||
${testResults.map(r => `
|
||||
<div class="${r.success ? 'success' : 'error'}">
|
||||
${r.success ? '✅' : '❌'} ${r.testName}
|
||||
${r.details ? `<br><small>${r.details}</small>` : ''}
|
||||
</div>
|
||||
`).join('')}
|
||||
`;
|
||||
}
|
||||
|
||||
async function testHealthCheck() {
|
||||
log('🔍 Тестирование доступности API...', 'info');
|
||||
|
||||
try {
|
||||
const response = await fetch('https://demo.lnbits.com/api/v1/health', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Api-Key': 'a7226682253f4dd7bdb2d9487a9a59f8'
|
||||
}
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
log('✅ API доступен', 'success');
|
||||
log(`📊 Статус: ${JSON.stringify(data)}`, 'info');
|
||||
addResult('Health Check', true, `Status: ${response.status}`);
|
||||
} else {
|
||||
log(`❌ API недоступен: ${response.status}`, 'error');
|
||||
addResult('Health Check', false, `HTTP ${response.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
log(`❌ Ошибка подключения: ${error.message}`, 'error');
|
||||
addResult('Health Check', false, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function testCreateInvoice() {
|
||||
log('💰 Тестирование создания инвойса...', 'info');
|
||||
|
||||
try {
|
||||
const response = await fetch('https://demo.lnbits.com/api/v1/payments', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'X-Api-Key': 'a7226682253f4dd7bdb2d9487a9a59f8',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({
|
||||
out: false,
|
||||
amount: 500,
|
||||
memo: 'SecureBit.chat test invoice',
|
||||
unit: 'sat',
|
||||
expiry: 300
|
||||
})
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
currentInvoice = data;
|
||||
log('✅ Инвойс создан успешно', 'success');
|
||||
log(`📋 Payment Request: ${data.bolt11 ? data.bolt11.substring(0, 50) + '...' : 'N/A'}`, 'info');
|
||||
log(`🔑 Payment Hash: ${data.payment_hash || 'N/A'}`, 'info');
|
||||
log(`💰 Amount: ${data.amount || 'N/A'} sats`, 'info');
|
||||
log(`📋 BOLT11: ${data.bolt11 ? 'Доступен' : 'N/A'}`, 'info');
|
||||
addResult('Create Invoice', true, `Amount: ${data.amount || 'N/A'} sats`);
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
log(`❌ Ошибка создания инвойса: ${response.status}`, 'error');
|
||||
log(`📄 Ответ: ${errorText}`, 'error');
|
||||
addResult('Create Invoice', false, `HTTP ${response.status}: ${errorText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
log(`❌ Ошибка: ${error.message}`, 'error');
|
||||
addResult('Create Invoice', false, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function testPaymentStatus() {
|
||||
if (!currentInvoice) {
|
||||
log('⚠️ Сначала создайте инвойс', 'warning');
|
||||
addResult('Payment Status', false, 'No invoice available');
|
||||
return;
|
||||
}
|
||||
|
||||
log('🔍 Проверка статуса платежа...', 'info');
|
||||
|
||||
try {
|
||||
const response = await fetch(`https://demo.lnbits.com/api/v1/payments/${currentInvoice.checking_id}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Api-Key': 'a7226682253f4dd7bdb2d9487a9a59f8',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
log('✅ Статус получен', 'success');
|
||||
log(`📊 Оплачен: ${data.paid || false}`, 'info');
|
||||
log(`💰 Сумма: ${data.details?.amount || 'N/A'} sats`, 'info');
|
||||
log(`📋 Статус: ${data.status || 'N/A'}`, 'info');
|
||||
log(`📋 BOLT11: ${data.details?.bolt11 ? 'Доступен' : 'N/A'}`, 'info');
|
||||
addResult('Payment Status', true, `Paid: ${data.paid || false}, Amount: ${data.details?.amount || 'N/A'}`);
|
||||
} else {
|
||||
const errorText = await response.text();
|
||||
log(`❌ Ошибка проверки статуса: ${response.status}`, 'error');
|
||||
addResult('Payment Status', false, `HTTP ${response.status}: ${errorText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
log(`❌ Ошибка: ${error.message}`, 'error');
|
||||
addResult('Payment Status', false, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function testVerification() {
|
||||
log('🔐 Тестирование верификации...', 'info');
|
||||
|
||||
// Создаем фиктивный preimage для теста
|
||||
const testPreimage = Array.from(crypto.getRandomValues(new Uint8Array(32)))
|
||||
.map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
|
||||
log(`🔑 Тестовый preimage: ${testPreimage}`, 'info');
|
||||
|
||||
try {
|
||||
// Криптографическая верификация
|
||||
const preimageBytes = new Uint8Array(testPreimage.match(/.{2}/g).map(byte => parseInt(byte, 16)));
|
||||
const hashBuffer = await crypto.subtle.digest('SHA-256', preimageBytes);
|
||||
const computedHash = Array.from(new Uint8Array(hashBuffer))
|
||||
.map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
|
||||
log(`🔐 Вычисленный hash: ${computedHash}`, 'info');
|
||||
log('✅ Криптографическая верификация работает', 'success');
|
||||
addResult('Cryptographic Verification', true, 'SHA-256 hash computation OK');
|
||||
|
||||
} catch (error) {
|
||||
log(`❌ Ошибка криптографической верификации: ${error.message}`, 'error');
|
||||
addResult('Cryptographic Verification', false, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function testRealPayment() {
|
||||
log('💳 Тестирование реального платежа...', 'info');
|
||||
|
||||
if (!currentInvoice) {
|
||||
log('⚠️ Сначала создайте инвойс', 'warning');
|
||||
addResult('Real Payment Test', false, 'No invoice available');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Создаем фиктивный preimage для теста (в реальности это придет от кошелька)
|
||||
const testPreimage = Array.from(crypto.getRandomValues(new Uint8Array(32)))
|
||||
.map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
|
||||
log(`🔑 Тестовый preimage: ${testPreimage}`, 'info');
|
||||
|
||||
// Проверяем через LNbits API
|
||||
const response = await fetch(`https://demo.lnbits.com/api/v1/payments/${currentInvoice.checking_id}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'X-Api-Key': 'a7226682253f4dd7bdb2d9487a9a59f8',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
log(`📊 Статус платежа: ${JSON.stringify(data)}`, 'info');
|
||||
|
||||
// Симулируем успешный платеж для демо
|
||||
if (data.paid) {
|
||||
log('✅ Платеж уже оплачен!', 'success');
|
||||
addResult('Real Payment Test', true, 'Payment already paid');
|
||||
} else {
|
||||
log('⏳ Платеж ожидает оплаты', 'warning');
|
||||
log('💡 Для тестирования оплатите инвойс через любой Lightning кошелек', 'info');
|
||||
addResult('Real Payment Test', true, 'Payment pending - ready for testing');
|
||||
}
|
||||
} else {
|
||||
throw new Error(`HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
log(`❌ Ошибка тестирования платежа: ${error.message}`, 'error');
|
||||
addResult('Real Payment Test', false, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function testDemoMode() {
|
||||
log('🎮 Тестирование Demo режима...', 'info');
|
||||
|
||||
try {
|
||||
// Симулируем PayPerSessionManager для тестирования
|
||||
const mockSessionManager = {
|
||||
sessionPrices: {
|
||||
demo: { sats: 0, hours: 0.1, 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 }
|
||||
},
|
||||
demoSessions: new Map(),
|
||||
maxDemoSessionsPerUser: 3,
|
||||
demoCooldownPeriod: 60 * 60 * 1000,
|
||||
demoSessionCooldown: 5 * 60 * 1000,
|
||||
demoSessionMaxDuration: 6 * 60 * 1000,
|
||||
usedPreimages: new Set(),
|
||||
|
||||
generateUserFingerprint() {
|
||||
const components = [
|
||||
navigator.userAgent || '',
|
||||
navigator.language || '',
|
||||
screen.width + 'x' + screen.height,
|
||||
Intl.DateTimeFormat().resolvedOptions().timeZone || '',
|
||||
navigator.hardwareConcurrency || 0,
|
||||
navigator.deviceMemory || 0,
|
||||
navigator.platform || '',
|
||||
navigator.cookieEnabled ? '1' : '0'
|
||||
];
|
||||
|
||||
let hash = 0;
|
||||
const str = components.join('|');
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
const char = str.charCodeAt(i);
|
||||
hash = ((hash << 5) - hash) + char;
|
||||
hash = hash & hash;
|
||||
}
|
||||
|
||||
return Math.abs(hash).toString(36);
|
||||
},
|
||||
|
||||
checkDemoSessionLimits(userFingerprint) {
|
||||
const userData = this.demoSessions.get(userFingerprint);
|
||||
const now = Date.now();
|
||||
|
||||
if (!userData) {
|
||||
return {
|
||||
allowed: true,
|
||||
reason: 'first_demo_session',
|
||||
remaining: this.maxDemoSessionsPerUser
|
||||
};
|
||||
}
|
||||
|
||||
const activeSessions = userData.sessions.filter(session =>
|
||||
now - session.timestamp < this.demoCooldownPeriod
|
||||
);
|
||||
|
||||
if (activeSessions.length >= this.maxDemoSessionsPerUser) {
|
||||
const oldestSession = Math.min(...activeSessions.map(s => s.timestamp));
|
||||
const timeUntilNext = this.demoCooldownPeriod - (now - oldestSession);
|
||||
|
||||
return {
|
||||
allowed: false,
|
||||
reason: 'demo_limit_exceeded',
|
||||
timeUntilNext: timeUntilNext,
|
||||
message: `Demo limit reached (${this.maxDemoSessionsPerUser}/day). Try again in ${Math.ceil(timeUntilNext / (60 * 1000))} minutes.`,
|
||||
remaining: 0
|
||||
};
|
||||
}
|
||||
|
||||
if (userData.lastUsed && (now - userData.lastUsed) < this.demoSessionCooldown) {
|
||||
const timeUntilNext = this.demoSessionCooldown - (now - userData.lastUsed);
|
||||
return {
|
||||
allowed: false,
|
||||
reason: 'demo_cooldown',
|
||||
timeUntilNext: timeUntilNext,
|
||||
message: `Please wait ${Math.ceil(timeUntilNext / (60 * 1000))} minutes between demo sessions.`,
|
||||
remaining: this.maxDemoSessionsPerUser - activeSessions.length
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
allowed: true,
|
||||
reason: 'within_limits',
|
||||
remaining: this.maxDemoSessionsPerUser - activeSessions.length
|
||||
};
|
||||
},
|
||||
|
||||
createDemoSession() {
|
||||
const userFingerprint = this.generateUserFingerprint();
|
||||
const demoCheck = this.checkDemoSessionLimits(userFingerprint);
|
||||
|
||||
if (!demoCheck.allowed) {
|
||||
return {
|
||||
success: false,
|
||||
reason: demoCheck.message,
|
||||
timeUntilNext: demoCheck.timeUntilNext,
|
||||
remaining: demoCheck.remaining
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const demoPreimage = this.generateSecureDemoPreimage();
|
||||
const demoPaymentHash = 'demo_' + Array.from(crypto.getRandomValues(new Uint8Array(16)))
|
||||
.map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
|
||||
return {
|
||||
success: true,
|
||||
sessionType: 'demo',
|
||||
preimage: demoPreimage,
|
||||
paymentHash: demoPaymentHash,
|
||||
duration: this.sessionPrices.demo.hours,
|
||||
durationMinutes: Math.round(this.demoSessionMaxDuration / (60 * 1000)),
|
||||
warning: `Demo session - limited to ${Math.round(this.demoSessionMaxDuration / (60 * 1000))} minutes`,
|
||||
remaining: demoCheck.remaining - 1
|
||||
};
|
||||
} catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
reason: 'Failed to generate demo session. Please try again.',
|
||||
remaining: demoCheck.remaining
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
generateSecureDemoPreimage() {
|
||||
const timestamp = Date.now();
|
||||
const randomBytes = crypto.getRandomValues(new Uint8Array(24));
|
||||
const timestampBytes = new Uint8Array(4);
|
||||
const versionBytes = new Uint8Array(4);
|
||||
|
||||
const timestampSeconds = Math.floor(timestamp / 1000);
|
||||
timestampBytes[0] = (timestampSeconds >>> 24) & 0xFF;
|
||||
timestampBytes[1] = (timestampSeconds >>> 16) & 0xFF;
|
||||
timestampBytes[2] = (timestampSeconds >>> 8) & 0xFF;
|
||||
timestampBytes[3] = timestampSeconds & 0xFF;
|
||||
|
||||
versionBytes[0] = 0xDE;
|
||||
versionBytes[1] = 0xE0;
|
||||
versionBytes[2] = 0x00;
|
||||
versionBytes[3] = 0x01;
|
||||
|
||||
const combined = new Uint8Array(32);
|
||||
combined.set(versionBytes, 0);
|
||||
combined.set(timestampBytes, 4);
|
||||
combined.set(randomBytes, 8);
|
||||
|
||||
return Array.from(combined).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||
}
|
||||
};
|
||||
|
||||
// Тестируем demo режим
|
||||
log('🔍 Тестирование лимитов demo сессий...', 'info');
|
||||
|
||||
const userFingerprint = mockSessionManager.generateUserFingerprint();
|
||||
log(`👤 User fingerprint: ${userFingerprint.substring(0, 8)}...`, 'info');
|
||||
|
||||
const demoCheck = mockSessionManager.checkDemoSessionLimits(userFingerprint);
|
||||
log(`📊 Demo check result: ${demoCheck.allowed ? 'Allowed' : 'Denied'}`, demoCheck.allowed ? 'success' : 'warning');
|
||||
|
||||
if (demoCheck.allowed) {
|
||||
log(`✅ Demo session available. Remaining: ${demoCheck.remaining}`, 'success');
|
||||
|
||||
// Создаем demo сессию
|
||||
const demoSession = mockSessionManager.createDemoSession();
|
||||
if (demoSession.success) {
|
||||
log('🎮 Demo session created successfully!', 'success');
|
||||
log(`⏱️ Duration: ${demoSession.durationMinutes} minutes`, 'info');
|
||||
log(`🔑 Preimage: ${demoSession.preimage.substring(0, 16)}...`, 'info');
|
||||
log(`⚠️ Warning: ${demoSession.warning}`, 'warning');
|
||||
log(`📊 Remaining: ${demoSession.remaining}`, 'info');
|
||||
|
||||
addResult('Demo Mode Test', true, `Session created: ${demoSession.durationMinutes}min, Remaining: ${demoSession.remaining}`);
|
||||
} else {
|
||||
log(`❌ Demo session creation failed: ${demoSession.reason}`, 'error');
|
||||
addResult('Demo Mode Test', false, demoSession.reason);
|
||||
}
|
||||
} else {
|
||||
log(`⏳ Demo session not available: ${demoCheck.message}`, 'warning');
|
||||
addResult('Demo Mode Test', true, `Limits working: ${demoCheck.message}`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
log(`❌ Demo mode test failed: ${error.message}`, 'error');
|
||||
addResult('Demo Mode Test', false, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
function copyBOLT11() {
|
||||
if (!currentInvoice) {
|
||||
log('⚠️ Сначала создайте инвойс', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
const bolt11 = currentInvoice.bolt11;
|
||||
if (!bolt11) {
|
||||
log('❌ BOLT11 недоступен', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
navigator.clipboard.writeText(bolt11).then(() => {
|
||||
log('✅ BOLT11 скопирован в буфер обмена', 'success');
|
||||
log(`📋 BOLT11: ${bolt11.substring(0, 50)}...`, 'info');
|
||||
}).catch(err => {
|
||||
log(`❌ Ошибка копирования: ${err.message}`, 'error');
|
||||
});
|
||||
}
|
||||
|
||||
async function runAllTests() {
|
||||
log('🚀 Запуск всех тестов...', 'info');
|
||||
testResults = [];
|
||||
|
||||
await testHealthCheck();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
await testCreateInvoice();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
await testPaymentStatus();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
await testVerification();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
await testRealPayment();
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
|
||||
await testDemoMode();
|
||||
|
||||
log('🎉 Все тесты завершены!', 'success');
|
||||
}
|
||||
|
||||
// Экспортируем функции для использования в HTML
|
||||
window.testHealthCheck = testHealthCheck;
|
||||
window.testCreateInvoice = testCreateInvoice;
|
||||
window.testPaymentStatus = testPaymentStatus;
|
||||
window.testVerification = testVerification;
|
||||
window.testRealPayment = testRealPayment;
|
||||
window.testDemoMode = testDemoMode;
|
||||
window.copyBOLT11 = copyBOLT11;
|
||||
window.runAllTests = runAllTests;
|
||||
|
||||
// Автоматический запуск при загрузке
|
||||
log('🔧 Тест интеграции LNbits загружен', 'info');
|
||||
log('📋 Нажмите "Запустить все тесты" для проверки', 'info');
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user