feat(security,ui): self-host React deps, Tailwind, fonts; strict CSP; local QR; better selection state

Replace CDN React/ReactDOM/Babel with local libs; remove Babel and inline scripts
Build Tailwind locally, add safelist; switch to assets/tailwind.css
Self-host Font Awesome and Inter (CSS + woff2); remove external font CDNs
Implement strict CSP (no unsafe-inline/eval; scripts/styles/fonts from self)
Extract inline handlers; move PWA scripts to external files
Add local QR code generation (qrcode lib) and remove api.qrserver.com
Improve SessionTypeSelector visual selection (highlighted background and ring)
Keep PWA working with service worker and offline assets
Refs: CSP hardening, offline-first, no external dependencies
This commit is contained in:
lockbitchat
2025-09-08 16:04:58 -04:00
parent 3458270477
commit 0f8399ec88
352 changed files with 84907 additions and 4257 deletions

34
src/scripts/app-boot.js Normal file
View File

@@ -0,0 +1,34 @@
import { EnhancedSecureCryptoUtils } from '../crypto/EnhancedSecureCryptoUtils.js';
import { EnhancedSecureWebRTCManager } from '../network/EnhancedSecureWebRTCManager.js';
import { PayPerSessionManager } from '../session/PayPerSessionManager.js';
import { EnhancedSecureFileTransfer } from '../transfer/EnhancedSecureFileTransfer.js';
// Import UI components (side-effect: they attach themselves to window.*)
import '../components/ui/SessionTimer.jsx';
import '../components/ui/Header.jsx';
import '../components/ui/SessionTypeSelector.jsx';
import '../components/ui/LightningPayment.jsx';
import '../components/ui/PaymentModal.jsx';
import '../components/ui/DownloadApps.jsx';
import '../components/ui/FileTransfer.jsx';
// Expose to global for legacy usage inside app code
window.EnhancedSecureCryptoUtils = EnhancedSecureCryptoUtils;
window.EnhancedSecureWebRTCManager = EnhancedSecureWebRTCManager;
window.PayPerSessionManager = PayPerSessionManager;
window.EnhancedSecureFileTransfer = EnhancedSecureFileTransfer;
// Mount application once DOM and modules are ready
const start = () => {
if (typeof window.initializeApp === 'function') {
window.initializeApp();
} else if (window.DEBUG_MODE) {
console.error('initializeApp is not defined on window');
}
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}

50
src/scripts/bootstrap-modules.js vendored Normal file
View File

@@ -0,0 +1,50 @@
// Temporary bootstrap that still uses eval for JSX components fetched as text.
// Next step is to replace this with proper ESM imports of prebuilt JS.
(async () => {
try {
const timestamp = Date.now();
const [cryptoModule, webrtcModule, paymentModule, fileTransferModule] = await Promise.all([
import(`../crypto/EnhancedSecureCryptoUtils.js?v=${timestamp}`),
import(`../network/EnhancedSecureWebRTCManager.js?v=${timestamp}`),
import(`../session/PayPerSessionManager.js?v=${timestamp}`),
import(`../transfer/EnhancedSecureFileTransfer.js?v=${timestamp}`),
]);
const { EnhancedSecureCryptoUtils } = cryptoModule;
window.EnhancedSecureCryptoUtils = EnhancedSecureCryptoUtils;
const { EnhancedSecureWebRTCManager } = webrtcModule;
window.EnhancedSecureWebRTCManager = EnhancedSecureWebRTCManager;
const { PayPerSessionManager } = paymentModule;
window.PayPerSessionManager = PayPerSessionManager;
const { EnhancedSecureFileTransfer } = fileTransferModule;
window.EnhancedSecureFileTransfer = EnhancedSecureFileTransfer;
async function loadReactComponent(path) {
const response = await fetch(`${path}?v=${timestamp}`);
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
const code = await response.text();
// eslint-disable-next-line no-eval
eval(code);
}
await Promise.all([
loadReactComponent('../components/ui/SessionTimer.jsx'),
loadReactComponent('../components/ui/Header.jsx'),
loadReactComponent('../components/ui/SessionTypeSelector.jsx'),
loadReactComponent('../components/ui/LightningPayment.jsx'),
loadReactComponent('../components/ui/PaymentModal.jsx'),
loadReactComponent('../components/ui/DownloadApps.jsx'),
loadReactComponent('../components/ui/FileTransfer.jsx'),
]);
if (typeof window.initializeApp === 'function') {
window.initializeApp();
} else {
console.error('❌ Function initializeApp not found');
}
} catch (error) {
console.error('❌ Module loading error:', error);
}
})();

47
src/scripts/fa-check.js Normal file
View File

@@ -0,0 +1,47 @@
// Global logging and function settings
window.DEBUG_MODE = true;
// Fake function settings (for stability)
window.DISABLE_FAKE_TRAFFIC = false; // Set true to disable fake messages
window.DISABLE_DECOY_CHANNELS = false; // Set true to disable decoy channels
// Enhanced icon loading fallback
document.addEventListener('DOMContentLoaded', function () {
// Check if Font Awesome loaded properly
function checkFontAwesome() {
const testIcon = document.createElement('i');
testIcon.className = 'fas fa-shield-halved';
testIcon.style.position = 'absolute';
testIcon.style.left = '-9999px';
testIcon.style.visibility = 'hidden';
document.body.appendChild(testIcon);
const computedStyle = window.getComputedStyle(testIcon, '::before');
const content = computedStyle.content;
const fontFamily = computedStyle.fontFamily;
document.body.removeChild(testIcon);
if (!content || content === 'none' || content === 'normal' || (!fontFamily.includes('Font Awesome') && !fontFamily.includes('fa-solid'))) {
console.warn('Font Awesome not loaded properly, using fallback icons');
document.body.classList.add('fa-fallback');
return false;
}
if (window.DEBUG_MODE) {
console.log('Font Awesome loaded successfully');
}
return true;
}
if (!checkFontAwesome()) {
setTimeout(function () {
if (!checkFontAwesome()) {
console.warn('Font Awesome still not loaded, using fallback icons');
document.body.classList.add('fa-fallback');
}
}, 2000);
}
});

View File

@@ -0,0 +1,83 @@
window.forceUpdateHeader = (timeLeft, sessionType) => {
const event = new CustomEvent('force-header-update', {
detail: { timeLeft, sessionType, timestamp: Date.now() },
});
document.dispatchEvent(event);
if (window.sessionManager && window.sessionManager.forceUpdateTimer) {
window.sessionManager.forceUpdateTimer();
}
};
window.updateSessionTimer = (timeLeft, sessionType) => {
document.dispatchEvent(
new CustomEvent('session-timer-update', {
detail: { timeLeft, sessionType },
}),
);
};
document.addEventListener('session-activated', (event) => {
if (window.updateSessionTimer) {
window.updateSessionTimer(event.detail.timeLeft, event.detail.sessionType);
}
if (window.forceUpdateHeader) {
window.forceUpdateHeader(event.detail.timeLeft, event.detail.sessionType);
}
if (window.webrtcManager && window.webrtcManager.handleSessionActivation) {
if (window.DEBUG_MODE) {
console.log('🔐 Notifying WebRTC Manager about session activation');
}
window.webrtcManager.handleSessionActivation({
sessionId: event.detail.sessionId,
sessionType: event.detail.sessionType,
timeLeft: event.detail.timeLeft,
isDemo: event.detail.isDemo,
sessionManager: window.sessionManager,
});
}
});
if (window.DEBUG_MODE) {
console.log('✅ Global timer management functions loaded');
}
// Inline onclick replacement for update notification button
function attachUpdateNotificationHandlers(container) {
const btn = container.querySelector('[data-action="reload"]');
if (btn) {
btn.addEventListener('click', () => window.location.reload());
}
const dismissBtn = container.querySelector('[data-action="dismiss-notification"]');
if (dismissBtn) {
dismissBtn.addEventListener('click', () => {
const host = dismissBtn.closest('div');
if (host && host.parentElement) host.parentElement.remove();
});
}
}
window.showUpdateNotification = function showUpdateNotification() {
if (window.DEBUG_MODE) console.log('🆕 Showing update notification for PWA');
const notification = document.createElement('div');
notification.className = 'fixed top-4 left-1/2 transform -translate-x-1/2 bg-blue-500 text-white p-4 rounded-lg shadow-lg z-50 max-w-sm';
notification.innerHTML = `
<div class="flex items-center space-x-3">
<i class="fas fa-download text-lg"></i>
<div class="flex-1">
<div class="font-medium">Update Available</div>
<div class="text-sm opacity-90">SecureBit.chat v4.02.985 - ECDH + DTLS + SAS is ready</div>
</div>
<button data-action="reload" class="bg-white/20 hover:bg-white/30 px-3 py-1 rounded text-sm font-medium transition-colors">
Update
</button>
</div>`;
document.body.appendChild(notification);
attachUpdateNotificationHandlers(notification);
setTimeout(() => {
if (notification.parentElement) notification.remove();
}, 30000);
};
window.showServiceWorkerError = function showServiceWorkerError(error) {
console.warn('⚠️ Service Worker error:', error);
};

112
src/scripts/pwa-register.js Normal file
View File

@@ -0,0 +1,112 @@
// PWA Service Worker Registration
if ('serviceWorker' in navigator) {
window.addEventListener('load', async () => {
try {
const registration = await navigator.serviceWorker.register('./sw.js', {
scope: './',
});
console.log('✅ PWA: Service Worker registered successfully');
console.log('📡 SW Scope:', registration.scope);
// Store registration for use in other modules
window.swRegistration = registration;
// Listen for updates
registration.addEventListener('updatefound', () => {
console.log('🔄 PWA: Service Worker update found');
const newWorker = registration.installing;
newWorker.addEventListener('statechange', () => {
if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
console.log('🆕 PWA: New version available');
const isPWAInstalled =
window.matchMedia('(display-mode: standalone)').matches ||
window.navigator.standalone === true ||
(window.pwaInstallPrompt && window.pwaInstallPrompt.isInstalled);
if (isPWAInstalled) {
// If this is PWA, show update notification
if (typeof window.showUpdateNotification === 'function') {
window.showUpdateNotification();
}
} else {
// If this is browser, show install prompt
if (window.pwaInstallPrompt && !window.pwaInstallPrompt.isInstalled) {
setTimeout(() => {
window.pwaInstallPrompt.showInstallOptions();
}, 2000);
}
}
}
});
});
} catch (error) {
console.error('❌ PWA: Service Worker registration failed:', error);
if (window.DEBUG_MODE) {
setTimeout(() => {
if (typeof window.showServiceWorkerError === 'function') {
window.showServiceWorkerError(error);
}
}, 2000);
}
}
});
}
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then((registration) => {
console.log('🎯 PWA: Service Worker ready');
const isPWAInstalled =
window.matchMedia('(display-mode: standalone)').matches ||
window.navigator.standalone === true;
console.log('🔍 PWA Installation Status:', {
isStandalone: isPWAInstalled,
displayMode: window.matchMedia('(display-mode: standalone)').matches,
iosStandalone: window.navigator.standalone === true,
});
if (window.pwaInstallPrompt && window.pwaInstallPrompt.setServiceWorkerRegistration) {
window.pwaInstallPrompt.setServiceWorkerRegistration(registration);
if (isPWAInstalled && !window.pwaInstallPrompt.isInstalled) {
console.log('✅ PWA already installed, updating status');
window.pwaInstallPrompt.isInstalled = true;
window.pwaInstallPrompt.hideInstallPrompts();
}
}
if (window.pwaOfflineManager && window.pwaOfflineManager.setServiceWorkerRegistration) {
window.pwaOfflineManager.setServiceWorkerRegistration(registration);
}
});
// Listen to Service Worker messages
navigator.serviceWorker.addEventListener('message', (event) => {
console.log('📨 Message from Service Worker:', event.data);
if (event.data && event.data.type === 'SW_ACTIVATED') {
console.log('🔄 Service Worker activated, checking for updates...');
const isPWAInstalled =
window.matchMedia('(display-mode: standalone)').matches ||
window.navigator.standalone === true ||
(window.pwaInstallPrompt && window.pwaInstallPrompt.isInstalled);
if (isPWAInstalled) {
setTimeout(() => {
if (typeof window.showUpdateNotification === 'function') {
window.showUpdateNotification();
}
}, 1000);
} else {
if (window.pwaInstallPrompt && !window.pwaInstallPrompt.isInstalled) {
setTimeout(() => {
window.pwaInstallPrompt.showInstallOptions();
}, 2000);
}
}
}
});
}

13
src/scripts/qr-local.js Normal file
View File

@@ -0,0 +1,13 @@
// Local QR generator adapter (no external CDNs)
// Exposes: window.generateQRCode(text, { size?: number, margin?: number, errorCorrectionLevel?: 'L'|'M'|'Q'|'H' })
import * as QRCode from 'qrcode';
async function generateQRCode(text, opts = {}) {
const size = opts.size || 300;
const margin = opts.margin ?? 2;
const errorCorrectionLevel = opts.errorCorrectionLevel || 'M';
return await QRCode.toDataURL(text, { width: size, margin, errorCorrectionLevel });
}
window.generateQRCode = generateQRCode;