Compare commits

..

No commits in common. "422ceef3e97627518d45bb92b835313963c8b8ce" and "8af1fd055d4c5cb906e58f68dcbc2669cc4afb9d" have entirely different histories.

9 changed files with 336 additions and 632 deletions

View File

@ -1230,45 +1230,6 @@ select[data-multi-select-plugin] {
box-shadow: 0 2px 8px rgba(220, 53, 69, 0.3);
}
/* Authentication Button Styles */
.auth-container {
text-align: center;
padding: 20px;
}
.auth-button {
background: linear-gradient(135deg, #007bff, #0056b3);
color: white;
border: none;
padding: 16px 32px;
border-radius: 12px;
cursor: pointer;
font-size: 16px;
font-weight: 600;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
margin: 20px 0;
min-width: 250px;
}
.auth-button:hover {
background: linear-gradient(135deg, #0056b3, #004085);
transform: translateY(-2px);
box-shadow: 0 6px 20px rgba(0, 123, 255, 0.4);
}
.auth-button:active {
transform: translateY(0);
box-shadow: 0 4px 15px rgba(0, 123, 255, 0.3);
}
.auth-hint {
color: #6c757d;
font-size: 14px;
margin-top: 10px;
font-style: italic;
}
/* Responsive Design for Mode Selection */
@media (max-width: 768px) {
.mode-buttons {
@ -1283,10 +1244,4 @@ select[data-multi-select-plugin] {
position: static;
margin-top: 10px;
}
.auth-button {
min-width: 200px;
padding: 14px 28px;
font-size: 14px;
}
}

View File

@ -10,7 +10,8 @@
<div class="status-container">
<div class="status-indicator" id="main-status">
<!-- Content will be set by JavaScript -->
<div class="spinner"></div>
<span>Initializing secure pairing...</span>
</div>
</div>
@ -19,4 +20,12 @@
</div>
</div>
<!-- Loading State -->
<div id="loading-flow" class="card pairing-card">
<div class="loading-container">
<div class="spinner large"></div>
<h2>Initializing...</h2>
<p>Setting up secure pairing</p>
</div>
</div>
</div>

View File

@ -1,7 +1,9 @@
import Routing from '../../services/modal.service';
import Services from '../../services/service';
import { addSubscription } from '../../utils/subscription.utils';
import { displayEmojis, generateCreateBtn, addressToEmoji, prepareAndSendPairingTx } from '../../utils/sp-address.utils';
import { getCorrectDOM } from '../../utils/html.utils';
// import { navigate, registerAllListeners } from '../../router'; // Unused imports
import { IframePairingComponent } from '../../components/iframe-pairing/iframe-pairing';
// Extend WindowEventMap to include custom events
@ -14,19 +16,97 @@ declare global {
}
}
// Home page loading spinner functions
function showHomeLoadingSpinner(message: string = 'Loading...') {
// Remove existing spinner if any
hideHomeLoadingSpinner();
let isInitializing = false;
// Create spinner overlay
const overlay = document.createElement('div');
overlay.id = 'home-loading-overlay';
overlay.style.cssText = `
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 9998;
backdrop-filter: blur(3px);
`;
export async function initHomePage(): Promise<void> {
if (isInitializing) {
console.log('⚠️ Home page already initializing, skipping...');
return;
// Create spinner content
const spinnerContent = document.createElement('div');
spinnerContent.style.cssText = `
background: rgba(255, 255, 255, 0.95);
border-radius: 12px;
padding: 30px;
text-align: center;
box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
border: 1px solid rgba(255, 255, 255, 0.2);
max-width: 350px;
width: 90%;
`;
// Create spinner
const spinner = document.createElement('div');
spinner.style.cssText = `
width: 40px;
height: 40px;
border: 3px solid #f3f3f3;
border-top: 3px solid #3a506b;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 15px auto;
`;
// Create message
const messageEl = document.createElement('div');
messageEl.textContent = message;
messageEl.style.cssText = `
font-size: 14px;
color: #3a506b;
font-weight: 500;
`;
// Add CSS animation if not already present
if (!document.getElementById('home-spinner-styles')) {
const style = document.createElement('style');
style.id = 'home-spinner-styles';
style.textContent = `
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
`;
document.head.appendChild(style);
}
isInitializing = true;
// Assemble spinner
spinnerContent.appendChild(spinner);
spinnerContent.appendChild(messageEl);
overlay.appendChild(spinnerContent);
// Add to document
document.body.appendChild(overlay);
}
function hideHomeLoadingSpinner() {
const overlay = document.getElementById('home-loading-overlay');
if (overlay) {
overlay.remove();
}
}
export async function initHomePage(): Promise<void> {
console.log('INIT-HOME');
// No loading spinner - let the interface load naturally
// Show loading spinner during home page initialization
showHomeLoadingSpinner('Initializing pairing interface...');
// Initialize iframe pairing, content menu, and communication only if in iframe
if (window.parent !== window) {
@ -62,31 +142,6 @@ export async function initHomePage(): Promise<void> {
try {
console.log('🔧 Getting services instance...');
const service = await Services.getInstance();
// Check if wallet exists, create if not
console.log('🔍 Checking for existing wallet...');
const existingDevice = await service.getDeviceFromDatabase();
if (!existingDevice) {
console.log('📱 No wallet found, creating new device...');
const spAddress = await service.createNewDevice();
console.log('✅ New device created with address:', spAddress);
// Verify wallet was created successfully
const verifyDevice = await service.getDeviceFromDatabase();
if (!verifyDevice) {
throw new Error('Failed to create wallet - device not found after creation');
}
console.log('✅ Wallet creation verified');
} else {
console.log('📱 Existing wallet found');
console.log('🔍 Wallet details:', {
hasSpendKey: !!existingDevice.sp_wallet?.spend_key,
hasScanKey: !!existingDevice.sp_wallet?.scan_key,
birthday: existingDevice.sp_wallet?.birthday
});
}
console.log('🔧 Getting device address...');
const spAddress = await service.getDeviceAddress();
console.log('🔧 Generating create button...');
@ -94,19 +149,86 @@ export async function initHomePage(): Promise<void> {
console.log('🔧 Displaying emojis...');
displayEmojis(spAddress);
// Now trigger WebAuthn authentication
console.log('🔐 Triggering WebAuthn authentication...');
// Auto-trigger WebAuthn authentication
console.log('🔐 Auto-triggering WebAuthn authentication...');
await handleMainPairing();
// Hide loading spinner after initialization
console.log('🔧 Hiding loading spinner...');
hideHomeLoadingSpinner();
console.log('✅ Home page initialization completed');
} catch (error) {
console.error('❌ Error initializing home page:', error);
hideHomeLoadingSpinner();
throw error;
} finally {
isInitializing = false;
}
}
//// Modal
export async function openModal(myAddress: string, receiverAddress: string) {
const router = await Routing.getInstance();
router.openLoginModal(myAddress, receiverAddress);
}
// const service = await Services.getInstance()
// service.setNotification()
function scanDevice() {
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
const scannerImg = container.querySelector('#scanner') as HTMLElement;
if (scannerImg) scannerImg.style.display = 'none';
const scannerQrCode = container.querySelector('.qr-code-scanner') as HTMLElement;
if (scannerQrCode) scannerQrCode.style.display = 'block';
const scanButton = container?.querySelector('#scan-btn') as HTMLElement;
if (scanButton) scanButton.style.display = 'none';
// QR scanner functionality removed
}
async function populateMemberSelect() {
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
const memberSelect = container.querySelector('#memberSelect') as HTMLSelectElement;
if (!memberSelect) {
console.error('Could not find memberSelect element');
return;
}
const service = await Services.getInstance();
const members = await service.getAllMembersSorted();
for (const [processId, member] of Object.entries(members)) {
// Use member variable
console.log('Processing member:', member);
const process = await service.getProcess(processId);
let memberPublicName;
if (process) {
const publicMemberData = service.getPublicData(process);
if (publicMemberData) {
const extractedName = publicMemberData['memberPublicName'];
if (extractedName !== undefined && extractedName !== null) {
memberPublicName = extractedName;
}
}
}
if (!memberPublicName) {
memberPublicName = 'Unnamed Member';
}
// Récupérer les emojis pour ce processId
const emojis = await addressToEmoji(processId);
const option = document.createElement('option');
option.value = processId;
option.textContent = `${memberPublicName} (${emojis})`;
memberSelect.appendChild(option);
}
}
(window as any).populateMemberSelect = populateMemberSelect;
(window as any).scanDevice = scanDevice;
// Initialize iframe pairing component
let iframePairing: IframePairingComponent | null = null;
@ -402,36 +524,10 @@ export function setupIframePairingButtons() {
}
}
// Main Pairing Interface - Automatic WebAuthn trigger
// Main Pairing Interface - Auto-triggered, no button needed
export function setupMainPairing(): void {
const container = getCorrectDOM('login-4nk-component') as HTMLElement;
const mainStatus = container.querySelector('#main-status') as HTMLElement;
if (mainStatus) {
mainStatus.innerHTML = '<span style="color: var(--info-color)">⏳ Waiting for user to validate secure key access...</span>';
}
console.log('🔐 Main pairing setup - waiting for user interaction');
}
function setupUserInteractionListener(): void {
let hasTriggered = false;
const triggerWebAuthn = async (event: Event) => {
if (hasTriggered) return;
hasTriggered = true;
console.log('🔐 User interaction detected:', event.type, 'triggering WebAuthn...');
await handleMainPairing();
};
// Listen for any user interaction with more specific events
document.addEventListener('click', triggerWebAuthn, { once: true, passive: true });
document.addEventListener('keydown', triggerWebAuthn, { once: true, passive: true });
document.addEventListener('touchstart', triggerWebAuthn, { once: true, passive: true });
document.addEventListener('mousedown', triggerWebAuthn, { once: true, passive: true });
console.log('🔐 User interaction listeners set up');
// No button setup needed since authentication is automatic
console.log('🔐 Main pairing setup - authentication will be automatic');
}
async function handleMainPairing(): Promise<void> {
@ -439,127 +535,59 @@ async function handleMainPairing(): Promise<void> {
const mainStatus = container.querySelector('#main-status') as HTMLElement;
try {
// Update UI to show authentication in progress
// Update UI
if (mainStatus) {
mainStatus.innerHTML = '<div class="spinner"></div><span>Authenticating with browser...</span>';
}
// Always trigger WebAuthn flow for authentication
console.log('🔐 Triggering WebAuthn authentication...');
if (mainStatus) {
mainStatus.innerHTML = '<div class="spinner"></div><span>Authenticating with browser...</span>';
}
// Import and trigger WebAuthn directly
const { secureCredentialsService } = await import('../../services/secure-credentials.service');
// Check if we have existing credentials (regardless of wallet existence)
console.log('🔍 Checking for existing WebAuthn credentials...');
// Check if we have existing credentials
const hasCredentials = await secureCredentialsService.hasCredentials();
if (hasCredentials) {
console.log('🔓 Existing WebAuthn credentials found, decrypting...');
console.log('🔓 Existing credentials found, decrypting...');
if (mainStatus) {
mainStatus.innerHTML = '<div class="spinner"></div><span>Decrypting existing credentials...</span>';
}
// This will trigger WebAuthn for decryption of existing credentials
console.log('🔐 Starting WebAuthn decryption process...');
// This will trigger WebAuthn for decryption
await secureCredentialsService.retrieveCredentials('');
console.log('✅ WebAuthn decryption completed');
if (mainStatus) {
mainStatus.innerHTML = '<span style="color: var(--success-color)">✅ Credentials decrypted successfully</span>';
}
} else {
console.log('🔐 No existing WebAuthn credentials, creating new ones...');
console.log('🔐 No existing credentials, creating new ones...');
if (mainStatus) {
mainStatus.innerHTML = '<div class="spinner"></div><span>Creating new credentials...</span>';
}
// This will trigger WebAuthn for creation of new credentials
console.log('🔐 Starting WebAuthn creation process...');
const credentialData = await secureCredentialsService.generateSecureCredentials('');
console.log('✅ WebAuthn creation completed');
// Store the credentials in IndexedDB
console.log('💾 Storing credentials in IndexedDB...');
await secureCredentialsService.storeCredentials(credentialData, '');
console.log('✅ Credentials stored successfully');
// This will trigger WebAuthn for creation
await secureCredentialsService.generateSecureCredentials('');
if (mainStatus) {
mainStatus.innerHTML = '<span style="color: var(--success-color)">✅ New credentials created successfully</span>';
}
}
// Ensure WebAuthn process is completely finished
console.log('🔐 WebAuthn process completed, waiting for final confirmation...');
await new Promise(resolve => setTimeout(resolve, 1000)); // Additional wait to ensure completion
// Wait longer to ensure credentials are fully processed and stored
console.log('⏳ Waiting for credentials to be fully processed...');
await new Promise(resolve => setTimeout(resolve, 5000)); // Increased wait time to 5 seconds
// Verify credentials are available before proceeding with retry mechanism
let credentialsReady = false;
let attempts = 0;
const maxAttempts = 10; // Increased attempts
const delayMs = 2000; // Increased delay between attempts
while (!credentialsReady && attempts < maxAttempts) {
attempts++;
console.log(`🔍 Checking credentials availability (attempt ${attempts}/${maxAttempts})...`);
try {
credentialsReady = await secureCredentialsService.hasCredentials();
if (credentialsReady) {
console.log('✅ Credentials verified, proceeding with pairing...');
break;
} else {
console.log(`⏳ Credentials not ready yet, waiting ${delayMs}ms... (attempt ${attempts}/${maxAttempts})`);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
} catch (error) {
console.warn(`⚠️ Error checking credentials (attempt ${attempts}):`, error);
await new Promise(resolve => setTimeout(resolve, delayMs));
}
}
if (!credentialsReady) {
console.error('❌ Credentials not ready after creation - checking IndexedDB directly...');
// Try to check IndexedDB directly for debugging
try {
const directCheck = await secureCredentialsService.getEncryptedCredentials();
console.log('🔍 Direct IndexedDB check result:', directCheck);
} catch (error) {
console.error('❌ Direct IndexedDB check failed:', error);
}
if (mainStatus) {
mainStatus.innerHTML = '<span style="color: var(--error-color)">❌ Failed to create credentials</span>';
}
return;
}
// Now proceed with pairing process
console.log('🚀 Starting pairing process...');
await prepareAndSendPairingTx();
} catch (error) {
// If WebAuthn fails due to no user gesture, wait for real interaction
if (error instanceof Error && error.message && error.message.includes('WebAuthn authentication was cancelled or timed out')) {
console.log('🔐 WebAuthn requires user interaction, waiting...');
if (mainStatus) {
mainStatus.innerHTML = '<span style="color: var(--info-color)">⏳ Waiting for user to validate secure key access...</span>';
}
// Set up listener for real user interaction
setupUserInteractionListener();
} else {
console.error('Pairing failed:', error);
if (mainStatus) {
mainStatus.innerHTML = '<span style="color: var(--info-color)">⏳ Waiting for user to validate secure key access...</span>';
}
}
}
}

View File

@ -153,20 +153,10 @@ export async function init(): Promise<void> {
// No wallet exists, create new account
console.log('🔍 No existing wallet found, creating new account...');
await services.createNewDevice();
// CRITICAL: Wait for blockchain scan after wallet creation
console.log('🔄 Synchronizing new wallet with blockchain...');
await services.updateDeviceBlockHeight();
console.log('✅ Wallet synchronization completed');
} else {
// Wallet exists, restore it and check pairing
console.log('🔍 Existing wallet found, restoring account...');
services.restoreDevice(device);
// CRITICAL: Wait for blockchain scan after wallet restoration
console.log('🔄 Synchronizing existing wallet with blockchain...');
await services.updateDeviceBlockHeight();
console.log('✅ Wallet synchronization completed');
}
// Restore data from database (these operations can fail, so we handle them separately)

View File

@ -353,34 +353,10 @@ export class Database {
};
public addObject(payload: { storeName: string; object: any; key: any }): Promise<void> {
return this.addObjectWithRetry(payload, 3);
}
private async addObjectWithRetry(payload: { storeName: string; object: any; key: any }, maxRetries: number): Promise<void> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
await this.addObjectAttempt(payload);
return; // Success, exit retry loop
} catch (error) {
console.warn(`Attempt ${attempt}/${maxRetries} failed for addObject:`, error);
if (attempt === maxRetries) {
console.error('All retry attempts failed for addObject');
throw new Error(`Failed to add object after ${maxRetries} attempts: ${error}`);
}
// Wait before retry (exponential backoff)
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
}
}
}
private addObjectAttempt(payload: { storeName: string; object: any; key: any }): Promise<void> {
return new Promise(async (resolve, reject) => {
try {
// Check if the service worker is active
if (!this.serviceWorkerRegistration) {
console.log('Service worker registration not ready, waiting...');
// console.warn('Service worker registration is not ready. Waiting...');
this.serviceWorkerRegistration = await navigator.serviceWorker.ready;
}
@ -388,21 +364,11 @@ export class Database {
this.serviceWorkerRegistration
);
if (!activeWorker) {
throw new Error('Service worker not available');
}
// Create a message channel for communication
const messageChannel = new MessageChannel();
// Set timeout for the operation
const timeout = setTimeout(() => {
reject(new Error('Operation timeout - service worker did not respond'));
}, 10000); // 10 second timeout
// Handle the response from the service worker
messageChannel.port1.onmessage = event => {
clearTimeout(timeout);
if (event.data.status === 'success') {
resolve();
} else {
@ -412,7 +378,8 @@ export class Database {
};
// Send the add object request to the service worker
activeWorker.postMessage(
try {
activeWorker?.postMessage(
{
type: 'ADD_OBJECT',
payload,
@ -428,60 +395,18 @@ export class Database {
public batchWriting(payload: {
storeName: string;
objects: { key: any; object: any }[];
}): Promise<void> {
return this.batchWritingWithRetry(payload, 3);
}
private async batchWritingWithRetry(payload: {
storeName: string;
objects: { key: any; object: any }[];
}, maxRetries: number): Promise<void> {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
await this.batchWritingAttempt(payload);
return; // Success, exit retry loop
} catch (error) {
console.warn(`Attempt ${attempt}/${maxRetries} failed for batchWriting:`, error);
if (attempt === maxRetries) {
console.error('All retry attempts failed for batchWriting');
throw new Error(`Failed to batch write objects after ${maxRetries} attempts: ${error}`);
}
// Wait before retry (exponential backoff)
await new Promise(resolve => setTimeout(resolve, Math.pow(2, attempt) * 1000));
}
}
}
private batchWritingAttempt(payload: {
storeName: string;
objects: { key: any; object: any }[];
}): Promise<void> {
return new Promise(async (resolve, reject) => {
try {
if (!this.serviceWorkerRegistration) {
console.log('Service worker registration not ready, waiting...');
this.serviceWorkerRegistration = await navigator.serviceWorker.ready;
}
const activeWorker = await this.waitForServiceWorkerActivation(
this.serviceWorkerRegistration
);
if (!activeWorker) {
throw new Error('Service worker not available');
}
const messageChannel = new MessageChannel();
// Set timeout for the operation
const timeout = setTimeout(() => {
reject(new Error('Batch writing timeout - service worker did not respond'));
}, 30000); // 30 second timeout for batch operations
messageChannel.port1.onmessage = event => {
clearTimeout(timeout);
if (event.data.status === 'success') {
resolve();
} else {
@ -490,7 +415,8 @@ export class Database {
}
};
activeWorker.postMessage(
try {
activeWorker?.postMessage(
{
type: 'BATCH_WRITING',
payload,

View File

@ -19,15 +19,14 @@ export interface CacheEntry<T> {
export class MemoryManager {
private static instance: MemoryManager;
private caches: Map<string, Map<string, CacheEntry<any>>> = new Map();
private maxCacheSize = 0; // Disabled caches completely
private maxCacheAge = 0; // No cache expiry
private maxCacheSize = 100;
private maxCacheAge = 5 * 60 * 1000; // 5 minutes
private cleanupInterval: number | null = null;
private memoryThreshold = 200 * 1024 * 1024; // 200MB (increased from 100MB)
private memoryThreshold = 100 * 1024 * 1024; // 100MB
private isMonitoring = false;
private constructor() {
// Disabled to save memory
// this.startCleanupInterval();
this.startCleanupInterval();
}
public static getInstance(): MemoryManager {
@ -268,7 +267,7 @@ export class MemoryManager {
private startCleanupInterval(): void {
this.cleanupInterval = setInterval(() => {
this.cleanupExpiredEntries();
}, 120000) as any; // Nettoyage toutes les 2 minutes (reduced frequency)
}, 60000) as any; // Nettoyage toutes les minutes
}
/**

View File

@ -99,32 +99,16 @@ export class SecureCredentialsService {
authenticatorAttachment: "platform", // Force l'authentificateur intégré
userVerification: "required"
},
timeout: 300000, // 5 minutes timeout
timeout: 60000,
attestation: "direct"
};
console.log('🔐 Requesting WebAuthn credential creation for encryption key...');
// Créer le credential WebAuthn avec gestion d'erreur robuste
let credential: PublicKeyCredential;
try {
credential = await navigator.credentials.create({
// Créer le credential WebAuthn
const credential = await navigator.credentials.create({
publicKey: publicKeyCredentialCreationOptions
}) as PublicKeyCredential;
} catch (error) {
if (error instanceof Error) {
if (error.name === 'NotAllowedError') {
throw new Error('WebAuthn authentication was cancelled or timed out. Please try again and complete the authentication when prompted.');
} else if (error.name === 'NotSupportedError') {
throw new Error('WebAuthn is not supported in this browser. Please use a modern browser with WebAuthn support.');
} else if (error.name === 'SecurityError') {
throw new Error('WebAuthn security error. Please ensure you are using HTTPS and try again.');
} else {
throw new Error(`WebAuthn error: ${error.message}`);
}
}
throw error;
}
if (!credential) {
throw new Error('WebAuthn credential creation failed');
@ -299,10 +283,8 @@ export class SecureCredentialsService {
throw new Error('WebAuthn not supported for decryption');
}
// Demander l'authentification WebAuthn avec gestion d'erreur robuste
let credential: PublicKeyCredential;
try {
credential = await navigator.credentials.get({
// Demander l'authentification WebAuthn
const credential = await navigator.credentials.get({
publicKey: {
challenge: crypto.getRandomValues(new Uint8Array(32)),
allowCredentials: [{
@ -310,23 +292,9 @@ export class SecureCredentialsService {
type: 'public-key'
}],
userVerification: 'required',
timeout: 300000 // 5 minutes timeout
timeout: 60000
}
}) as PublicKeyCredential;
} catch (error) {
if (error instanceof Error) {
if (error.name === 'NotAllowedError') {
throw new Error('WebAuthn authentication was cancelled or timed out. Please try again and complete the authentication when prompted.');
} else if (error.name === 'NotSupportedError') {
throw new Error('WebAuthn is not supported in this browser. Please use a modern browser with WebAuthn support.');
} else if (error.name === 'SecurityError') {
throw new Error('WebAuthn security error. Please ensure you are using HTTPS and try again.');
} else {
throw new Error(`WebAuthn decryption error: ${error.message}`);
}
}
throw error;
}
if (!credential) {
throw new Error('WebAuthn authentication failed');
@ -418,36 +386,22 @@ export class SecureCredentialsService {
*/
private async storeEncryptedCredentials(credentials: any): Promise<void> {
return new Promise((resolve, reject) => {
console.log('💾 Storing encrypted credentials in IndexedDB...');
const request = indexedDB.open('4NK_SecureCredentials', 1);
request.onerror = () => {
console.error('❌ Failed to open IndexedDB for storing credentials');
reject(new Error('Failed to open IndexedDB for credentials'));
};
request.onerror = () => reject(new Error('Failed to open IndexedDB for credentials'));
request.onsuccess = () => {
const db = request.result;
console.log('💾 IndexedDB opened for storing, creating transaction...');
const transaction = db.transaction(['credentials'], 'readwrite');
const store = transaction.objectStore('credentials');
const putRequest = store.put(credentials, 'webauthn_credentials');
putRequest.onsuccess = () => {
console.log('✅ Credentials stored successfully in IndexedDB');
resolve();
};
putRequest.onerror = () => {
console.error('❌ Failed to store encrypted credentials');
reject(new Error('Failed to store encrypted credentials'));
};
putRequest.onsuccess = () => resolve();
putRequest.onerror = () => reject(new Error('Failed to store encrypted credentials'));
};
request.onupgradeneeded = () => {
const db = request.result;
console.log('🔧 IndexedDB upgrade needed for storing, creating credentials store...');
if (!db.objectStoreNames.contains('credentials')) {
db.createObjectStore('credentials');
}
@ -462,33 +416,20 @@ export class SecureCredentialsService {
return new Promise((resolve, reject) => {
const request = indexedDB.open('4NK_SecureCredentials', 1);
request.onerror = () => {
console.error('❌ Failed to open IndexedDB for credentials');
reject(new Error('Failed to open IndexedDB for credentials'));
};
request.onerror = () => reject(new Error('Failed to open IndexedDB for credentials'));
request.onsuccess = () => {
const db = request.result;
console.log('🔍 IndexedDB opened successfully, checking for credentials...');
const transaction = db.transaction(['credentials'], 'readonly');
const store = transaction.objectStore('credentials');
const getRequest = store.get('webauthn_credentials');
getRequest.onsuccess = () => {
const result = getRequest.result || null;
console.log('🔍 IndexedDB get result:', result ? 'credentials found' : 'no credentials');
resolve(result);
};
getRequest.onerror = () => {
console.error('❌ Failed to retrieve encrypted credentials');
reject(new Error('Failed to retrieve encrypted credentials'));
};
getRequest.onsuccess = () => resolve(getRequest.result || null);
getRequest.onerror = () => reject(new Error('Failed to retrieve encrypted credentials'));
};
request.onupgradeneeded = () => {
const db = request.result;
console.log('🔧 IndexedDB upgrade needed, creating credentials store...');
if (!db.objectStoreNames.contains('credentials')) {
db.createObjectStore('credentials');
}
@ -558,11 +499,8 @@ export class SecureCredentialsService {
async hasCredentials(): Promise<boolean> {
try {
const credentials = await this.getEncryptedCredentials();
const hasCredentials = credentials !== null && credentials !== undefined;
console.log(`🔍 hasCredentials check: ${hasCredentials}`, credentials ? 'credentials found' : 'no credentials');
return hasCredentials;
return credentials !== null;
} catch (error) {
console.warn('⚠️ Error checking credentials:', error);
return false;
}
}

View File

@ -140,8 +140,8 @@ export default class Services {
private myProcesses: Set<string> = new Set();
private notifications: any[] | null = null;
// private subscriptions: { element: Element; event: string; eventHandler: string }[] = [];
private maxCacheSize = 0; // Disabled caches completely
private cacheExpiry = 0; // No cache expiry
private maxCacheSize = 100;
private cacheExpiry = 5 * 60 * 1000; // 5 minutes
// private database: any;
private routingInstance!: ModalService;
private relayAddresses: { [wsurl: string]: string } = {};
@ -215,22 +215,23 @@ export default class Services {
// DO NOT clear user data - only clear non-essential caches
console.log('⚠️ Skipping storage cleanup to preserve user data');
// Light memory cleanup only
console.log('🔧 Performing light memory cleanup...');
// Force aggressive memory cleanup
console.log('🔧 Performing aggressive memory cleanup...');
// Minimal cleanup to avoid memory leaks
// Clear only non-essential browser data (NOT user data)
try {
// Only clear HTTP caches if they exist
// Clear only HTTP caches (NOT IndexedDB with user data)
if ('caches' in window) {
const cacheNames = await caches.keys();
if (cacheNames.length > 0) {
// Only clear HTTP caches, not application data
const httpCaches = cacheNames.filter(name => name.startsWith('http'));
if (httpCaches.length > 0) {
await Promise.all(httpCaches.map(name => caches.delete(name)));
console.log('🧹 HTTP caches cleared (user data preserved)');
}
}
}
// DO NOT clear IndexedDB - it contains user secrets!
// DO NOT clear service workers - they manage user data!
} catch (e) {
console.log('⚠️ Safe cleanup error:', e);
}
@ -241,32 +242,33 @@ export default class Services {
const usedPercent = (memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100;
console.log(`📊 Memory usage after cleanup: ${usedPercent.toFixed(1)}% (${(memory.usedJSHeapSize / 1024 / 1024).toFixed(1)}MB)`);
if (usedPercent > 75) {
console.warn('⚠️ High memory usage detected, performing aggressive cleanup...');
if (usedPercent > 70) {
console.warn('⚠️ High memory usage detected, forcing additional cleanup...');
// More aggressive cleanup
// Debug: Check what's consuming memory
console.log('🔍 Debugging memory usage...');
console.log('📦 Document elements:', document.querySelectorAll('*').length);
console.log('📦 Script tags:', document.querySelectorAll('script').length);
console.log('📦 Style tags:', document.querySelectorAll('style').length);
console.log('📦 Images:', document.querySelectorAll('img').length);
// Multiple garbage collections
// Force more aggressive cleanup
if (window.gc) {
for (let i = 0; i < 3; i++) {
for (let i = 0; i < 5; i++) {
window.gc();
await new Promise(resolve => setTimeout(resolve, 100));
}
}
// Clear any cached data
if (window.localStorage) {
const keys = Object.keys(localStorage);
keys.forEach(key => {
if (key.startsWith('temp_') || key.startsWith('cache_')) {
localStorage.removeItem(key);
// Clear DOM references
const elements = document.querySelectorAll('*');
elements.forEach(el => {
if (el.removeAttribute) {
el.removeAttribute('data-cached');
}
});
}
console.log('🧹 Aggressive memory cleanup completed');
console.log('🧹 Additional memory cleanup completed');
}
}
} catch (error) {
@ -281,7 +283,7 @@ export default class Services {
const memory = (performance as any).memory;
const usedPercent = (memory.usedJSHeapSize / memory.jsHeapSizeLimit) * 100;
if (usedPercent > 95) {
if (usedPercent > 70) {
console.log('🚫 Memory too high, skipping WebAssembly initialization');
Services.instance = new Services();
Services.initializing = null;
@ -600,10 +602,6 @@ export default class Services {
public isPaired(): boolean {
try {
if (!this.sdkClient) {
console.log('WebAssembly SDK not initialized - assuming not paired');
return false;
}
return this.sdkClient.is_paired();
} catch (e) {
// During pairing process, it's normal for the device to not be paired yet
@ -653,7 +651,12 @@ export default class Services {
}
private async getTokensFromFaucet(): Promise<void> {
try {
await this.ensureSufficientAmount();
} catch (e) {
console.error('Failed to get tokens from relay, check connection');
return;
}
}
// If we're updating a process, we must call that after update especially if roles are part of it
@ -752,80 +755,30 @@ export default class Services {
const availableAmt = this.getAmount();
const target: BigInt = DEFAULTAMOUNT * BigInt(10);
console.log(`💰 Current amount: ${availableAmt}, target: ${target}`);
if (availableAmt < target) {
console.log('🪙 Requesting tokens from faucet...');
const faucetMsg = this.createFaucetMessage();
console.log('🪙 Faucet message created:', faucetMsg);
this.sendFaucetMessage(faucetMsg);
console.log('🪙 Faucet message sent, waiting for tokens...');
await this.waitForAmount(target);
} else {
console.log('✅ Sufficient tokens already available');
}
}
private updateUserStatus(message: string): void {
try {
const container = document.querySelector('login-4nk-component') as HTMLElement;
const mainStatus = container?.querySelector('#main-status') as HTMLElement;
if (mainStatus) {
mainStatus.innerHTML = `<span style="color: var(--info-color)">${message}</span>`;
}
} catch (error) {
console.warn('Could not update user status:', error);
}
}
private async waitForAmount(target: BigInt): Promise<BigInt> {
let attempts = 20; // Increased attempts for blockchain confirmation
let attempts = 3;
while (attempts > 0) {
const amount = this.getAmount();
console.log(`🪙 Attempt ${21 - attempts}: current amount ${amount}, target ${target}`);
if (amount >= target) {
console.log('✅ Sufficient tokens received!');
this.updateUserStatus('✅ Tokens received successfully!');
return amount;
}
// Force SDK to scan blocks to update wallet state
if (attempts < 20) { // Don't scan on first attempt
console.log('🔄 Forcing SDK block scan to update wallet state...');
this.updateUserStatus('🔄 Synchronizing wallet with blockchain...');
try {
await this.sdkClient.scan_blocks(this.currentBlockHeight, BLINDBITURL);
console.log('✅ SDK block scan completed');
// Check amount again after scanning
const newAmount = this.getAmount();
console.log(`💰 Amount after forced scan: ${newAmount}`);
if (newAmount > 0) {
this.updateUserStatus(`💰 Found ${newAmount} tokens in wallet!`);
} else {
this.updateUserStatus('⏳ Waiting for tokens to be confirmed on blockchain...');
}
} catch (scanError) {
console.error('❌ Error during forced block scan:', scanError);
this.updateUserStatus('⚠️ Blockchain synchronization in progress...');
}
} else {
this.updateUserStatus('🪙 Requesting tokens from faucet...');
}
attempts--;
if (attempts > 0) {
console.log(`⏳ Waiting 5 seconds before next attempt (${attempts} attempts left)...`);
this.updateUserStatus(`⏳ Checking for tokens... (${attempts} attempts remaining)`);
await new Promise(resolve => setTimeout(resolve, 5000)); // Wait for 5 seconds
await new Promise(resolve => setTimeout(resolve, 1000)); // Wait for 1 second
}
}
throw new Error('Amount is still insufficient after 20 attempts - faucet may be down or transaction not confirmed');
throw new Error('Amount is still 0 after 3 attempts');
}
public async createPairingProcess(userName: string, pairWith: string[]): Promise<ApiReturn> {
@ -944,18 +897,9 @@ export default class Services {
console.log('🔍 DEBUG: Members type:', typeof membersObj);
console.log('🔍 DEBUG: Members keys:', Object.keys(membersObj));
// Check if membersList is empty
if (!membersObj || Object.keys(membersObj).length === 0) {
console.warn('⚠️ No members available for create_new_process, waiting for handshake...');
throw new Error('No members available - handshake not completed yet');
}
// Convert membersObj to array format for WebAssembly (it expects a sequence, not a map)
const members = Object.values(membersObj).map(member => ({
sp_addresses: member.sp_addresses
}));
// Convert object to array for WebAssembly
const members = Object.values(membersObj);
console.log('🔍 DEBUG: Members array length:', members.length);
console.log('🔍 DEBUG: Members array sample:', members.slice(0, 3));
const result = this.sdkClient.create_new_process(
encodedPrivateData,
@ -999,15 +943,12 @@ export default class Services {
...this.sdkClient.encode_binary(publicSplitData.binaryData),
};
try {
const members = Object.values(this.getAllMembers()).map(member => ({
sp_addresses: member.sp_addresses
}));
const result = this.sdkClient.update_process(
process,
encodedPrivateData,
roles,
encodedPublicData,
members
Object.values(this.getAllMembers())
);
if (result.updated_process) {
await this.checkConnections(result.updated_process.current_process);
@ -1028,10 +969,7 @@ export default class Services {
await this.checkConnections(process);
}
try {
const members = Object.values(this.getAllMembers()).map(member => ({
sp_addresses: member.sp_addresses
}));
return this.sdkClient.create_update_message(process, stateId, members);
return this.sdkClient.create_update_message(process, stateId, Object.values(this.getAllMembers()));
} catch (e) {
throw new Error(`Failed to create prd update: ${e}`);
}
@ -1043,10 +981,7 @@ export default class Services {
throw new Error('Unknown process');
}
try {
const members = Object.values(this.getAllMembers()).map(member => ({
sp_addresses: member.sp_addresses
}));
return this.sdkClient.create_response_prd(process, stateId, members);
return this.sdkClient.create_response_prd(process, stateId, Object.values(this.getAllMembers()));
} catch (e) {
throw new Error(`Failed to create response prd: ${e}`);
}
@ -1058,10 +993,7 @@ export default class Services {
throw new Error('Failed to get process from db');
}
try {
const members = Object.values(this.getAllMembers()).map(member => ({
sp_addresses: member.sp_addresses
}));
const result = this.sdkClient.validate_state(process, stateId, members);
const result = this.sdkClient.validate_state(process, stateId, Object.values(this.getAllMembers()));
if (result.updated_process) {
await this.checkConnections(result.updated_process.current_process);
return result;
@ -1117,9 +1049,7 @@ export default class Services {
}
async parseCipher(message: string) {
const membersList = Object.values(this.getAllMembers()).map(member => ({
sp_addresses: member.sp_addresses
}));
const membersList = Object.values(this.getAllMembers());
const processes = await this.getProcesses();
try {
// console.log('parsing new cipher');
@ -1147,16 +1077,10 @@ export default class Services {
const parsedMsg: NewTxMessage = typeof newTxMsg === 'string' ? JSON.parse(newTxMsg) : newTxMsg;
if (parsedMsg.error !== null) {
console.error('Received error in new tx message:', parsedMsg.error);
this.updateUserStatus('❌ Transaction error received');
return;
}
// Notify user that a transaction was received
this.updateUserStatus('📨 New transaction received from blockchain...');
const membersList = Object.values(this.getAllMembers()).map(member => ({
sp_addresses: member.sp_addresses
}));
const membersList = Object.values(this.getAllMembers());
try {
// Does the transaction spend the tip of a process?
const prevouts = this.sdkClient.get_prevouts(parsedMsg.transaction);
@ -1192,59 +1116,6 @@ export default class Services {
await this.handleApiReturn(parsedTx);
const newDevice = this.dumpDeviceFromMemory();
await this.saveDeviceInDatabase(newDevice);
// Force SDK to scan blocks to update wallet state after receiving tokens
console.log('🔄 Forcing SDK to scan blocks to update wallet state...');
try {
await this.sdkClient.scan_blocks(this.currentBlockHeight, BLINDBITURL);
console.log('✅ SDK block scan completed, wallet state should be updated');
// Force wallet synchronization
console.log('🔄 Forcing wallet synchronization...');
try {
const device = await this.getDeviceFromDatabase();
if (device && device.sp_wallet) {
// Update last_scan to current block height
device.sp_wallet.last_scan = this.currentBlockHeight;
await this.updateDeviceInDatabase(device);
console.log('✅ Wallet last_scan updated to current block height');
}
} catch (syncError) {
console.error('❌ Error during wallet synchronization:', syncError);
}
// Check amount after scanning
const updatedAmount = this.getAmount();
console.log(`💰 Amount after block scan: ${updatedAmount}`);
// Update user with scan results
if (updatedAmount > 0) {
this.updateUserStatus(`💰 Wallet updated! Found ${updatedAmount} tokens`);
} else {
this.updateUserStatus('⏳ Transaction processed, waiting for confirmation...');
}
// Additional debugging: check if SDK is properly initialized
console.log('🔍 SDK debugging info:');
console.log('- Current block height:', this.currentBlockHeight);
console.log('- Blindbit URL:', BLINDBITURL);
console.log('- SDK client initialized:', !!this.sdkClient);
// Check wallet state in SDK
try {
const device = await this.getDeviceFromDatabase();
if (device && device.sp_wallet) {
console.log('🔍 Wallet state:');
console.log('- Last scan:', device.sp_wallet.last_scan);
console.log('- Current block:', this.currentBlockHeight);
console.log('- Scan needed:', device.sp_wallet.last_scan < this.currentBlockHeight);
}
} catch (error) {
console.error('❌ Error checking wallet state:', error);
}
} catch (scanError) {
console.error('❌ Failed to scan blocks:', scanError);
}
} catch (e) {
console.error('Failed to update device with new tx');
}
@ -1618,24 +1489,12 @@ export default class Services {
}
public getAmount(): BigInt {
if (!this.sdkClient) {
throw new Error('SDK not initialized - cannot get amount');
}
try {
const amount = this.sdkClient.get_available_amount();
console.log(`💰 SDK get_available_amount() returned: ${amount}`);
return amount;
} catch (error) {
console.error('❌ Error calling get_available_amount():', error);
throw error;
}
}
getDeviceAddress(): string {
try {
if (!this.sdkClient) {
throw new Error('WebAssembly SDK not initialized - memory too high');
}
return this.sdkClient.get_address();
} catch (e) {
throw new Error(`Failed to get device address: ${e}`);
@ -1799,9 +1658,6 @@ export default class Services {
async createNewDevice() {
let spAddress = '';
try {
if (!this.sdkClient) {
throw new Error('WebAssembly SDK not initialized - cannot create device');
}
// We set birthday later when we have the chain tip from relay
spAddress = await this.sdkClient.create_new_device(0, 'signet');
const device = this.dumpDeviceFromMemory();
@ -1826,9 +1682,6 @@ export default class Services {
throw new Error('Current block height not set');
}
// Update user status
this.updateUserStatus('🔄 Synchronizing wallet with blockchain...');
let device: Device | null = null;
try {
device = await this.getDeviceFromDatabase();
@ -1873,14 +1726,11 @@ export default class Services {
try {
const device = this.dumpDeviceFromMemory();
await this.saveDeviceInDatabase(device);
this.updateUserStatus('✅ Wallet synchronized with blockchain');
} catch (e) {
console.error(`Failed to save updated device: ${e}`);
this.updateUserStatus('⚠️ Wallet synchronization completed with warnings');
}
} else {
// Up to date, just returns
this.updateUserStatus('✅ Wallet already synchronized');
return;
}
}
@ -2087,10 +1937,6 @@ export default class Services {
public async restoreSecretsFromDB() {
const db = await Database.getInstance();
try {
if (!this.sdkClient) {
console.log('WebAssembly SDK not initialized - skipping secrets restoration');
return;
}
const sharedSecrets: Record<string, string> = await db.dumpStore('shared_secrets');
const unconfirmedSecrets = await db.dumpStore('unconfirmed_secrets');
const secretsStore = {
@ -2332,7 +2178,7 @@ export default class Services {
}
// Add a flag to prevent processing the same handshake multiple times
const handshakeKey = `${url}_${JSON.stringify(handshakeMsg.processes_list)}`;
const handshakeKey = `${url}_${Date.now()}`;
if (this.processedHandshakes && this.processedHandshakes.has(handshakeKey)) {
console.debug('Handshake already processed for', url);
return;
@ -2633,9 +2479,7 @@ export default class Services {
roles: Record<string, RoleDefinition>[]
) {
console.log('Requesting data from peers');
const membersList = Object.values(this.getAllMembers()).map(member => ({
sp_addresses: member.sp_addresses
}));
const membersList = Object.values(this.getAllMembers());
try {
// Convert objects to strings for WASM compatibility
const rolesString = JSON.stringify(roles);

View File

@ -2542,20 +2542,35 @@ async function onCreateButtonClick() {
console.log('🔍 DEBUG: protocol:', window.location.protocol);
const { secureCredentialsService } = await import('../services/secure-credentials.service');
updateCreatorStatus('🔐 Authenticating with browser...');
updateCreatorStatus('🔐 Click to authenticate with browser...');
// Auto-trigger WebAuthn authentication
console.log('🔍 DEBUG: Auto-triggering WebAuthn authentication...');
// Force user interaction before WebAuthn
console.log('🔍 DEBUG: Waiting for user interaction...');
// Create a button that requires user click
const authButton = document.createElement('button');
authButton.textContent = '🔐 Authenticate with Browser';
authButton.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);z-index:9999;padding:20px;font-size:18px;background:#007bff;color:white;border:none;border-radius:8px;cursor:pointer;';
// Show button and wait for click
document.body.appendChild(authButton);
await new Promise<void>((resolve) => {
authButton.onclick = async () => {
document.body.removeChild(authButton);
try {
// This should trigger the browser popup automatically
// This should trigger the browser popup immediately after user click
await secureCredentialsService.generateSecureCredentials('4nk-pairing-password');
console.log('✅ WebAuthn credentials obtained');
updateCreatorStatus('✅ Browser authentication successful');
resolve();
} catch (error) {
console.error('❌ WebAuthn failed:', error);
updateCreatorStatus('❌ Browser authentication failed');
resolve();
}
};
});
} catch (error) {
console.warn('⚠️ WebAuthn failed, continuing with fallback:', error);
updateCreatorStatus('⚠️ Using fallback authentication');