Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

mejora la seguridad y el rendimiento de esto const pageCache = {}; function…

  1. User

    mejora la seguridad y el rendimiento de esto

    const pageCache = {};

    function inicializarScripts() { ['inicializarWaveforms', 'inicializarReproductorAudio', 'minimizarform', 'selectorformtipo', 'ajax_submit', 'borrarcomentario', 'colab', 'configuser', 'deletepost', 'diferidopost', 'editarcomentario', 'like', 'notificacioncolab', 'busqueda', 'updateBackgroundColor', 'presentacionmusic', 'seguir', 'registro', 'comentarios', 'botoneditarpost', 'fan', 'perfilpanel', 'smooth', 'navpanel', 'borderborder', 'initializeFormFunctions', 'initializeModalregistro', 'submenu', 'selectortipousuario', 'empezarcolab', 'subidaRolaForm', 'avances', 'updateDates', 'initializeProgressSegments', 'initializeCustomTooltips', 'fondoAcciones', 'pestanasgroup', 'manejoDeLogs', 'progresosinteractive', 'setupScrolling', 'inicializarDescargas', 'handleAllRequests', 'textflux', 'autoFillUserInfo', 'inicializarPestanas', 'meta', 'reporteScript', 'reiniciarDiferidoPost', 'generarGrafico', 'grafico', 'IniciadoresConfigPerfil', 'proyectoForm', 'inicializarAlerta', 'autoRows', 'iniciarRS'].forEach(func => { if (typeof window[func] === 'function') { try { windowfunc; } catch (error) { console.error(Error al ejecutar ${func}:, error); } } });

    // 'IniciadorSample', 'inicialRsForm',
    
    ['manageSeparatorsAndOrder', 'updateDaysElapsed'].forEach(func => {
        if (typeof window[func] === 'function') {
            window[func](func === 'manageSeparatorsAndOrder' ? ['.spaceprogreso', '#toggleOrderButton'] : '2024-01-01');
        }
    });
    

    }

    function reinicializar() { inicializarScripts(); if (window.location.hash && typeof window.mostrarPestana === 'function') { window.mostrarPestana(window.location.hash); } }

    window.reinicializar = reinicializar;

    function loadStripe(callback) { if (typeof Stripe !== 'undefined') return callback(); const script = document.createElement('script'); script.src = 'https://js.stripe.com/v3/'; script.async = true; script.onload = callback; document.head.appendChild(script); }

    function initializeStripeFunctions() { ['stripepro', 'stripecompra'].forEach(func => { if (typeof window[func] === 'function') windowfunc; else console.warn(${func} no está definida); }); }

    function shouldCache(url) { return !['https://2upra.com/nocache'].some(noCacheUrl => new RegExp(noCacheUrl.replace('', '.')).test(url)); }

    function loadContent(enlace, isPushState) { console.log('Iniciando carga de contenido:', enlace); if (!enlace || enlace.startsWith('javascript:') || enlace.includes('#') || enlace.includes('descarga_token')) return;

    if (pageCache[enlace] && shouldCache(enlace)) {
        document.getElementById('content').innerHTML = pageCache[enlace];
        if (isPushState) history.pushState(null, '', enlace);
        return reinicializar();
    }
    
    const loadingBar = document.getElementById('loadingBar');
    loadingBar.style.cssText = 'width: 70%; opacity: 1; transition: width 0.4s ease';
    
    fetch(enlace)
        .then(response => response.text())
        .then(data => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(data, 'text/html');
            const content = doc.getElementById('content').innerHTML;
            document.getElementById('content').innerHTML = content;
    
            if (shouldCache(enlace)) pageCache[enlace] = content;
    
            loadingBar.style.cssText = 'width: 100%; transition: width 0.1s ease, opacity 0.3s ease';
            setTimeout(() => loadingBar.style.cssText = 'width: 0%; opacity: 0', 100);
    
            if (isPushState) history.pushState(null, '', enlace);
    
            doc.querySelectorAll('script').forEach(script => {
                const newScript = document.createElement('script');
                newScript.textContent = script.textContent;
                document.body.appendChild(newScript);
            });
    
            setTimeout(reinicializar, 100);
        })
        .catch(error => console.error('Error al cargar la página:', error));
    

    }

    document.addEventListener('DOMContentLoaded', function () { if (!window.location.href.includes('?fb-edit=1')) { if (!window.galleInicializado && typeof window.galle === 'function') { window.galle(); window.galleInicializado = true; } reinicializar(); loadStripe(initializeStripeFunctions); }

    function handleContentLoad(event, enlace, element) {
        if (element.classList.contains('no-ajax') || element.closest('.no-ajax')) return true;
        const lowerCaseLink = enlace.trim().toLowerCase();
        if (!enlace || lowerCaseLink.endsWith('.pdf') || ['https://2upra.com/nocache', 'javascript:', 'data:', 'vbscript:'].some(prefix => lowerCaseLink.startsWith(prefix)) || enlace.includes('#')) return true;
        event.preventDefault();
        loadContent(enlace, true);
    }
    
    document.querySelectorAll('a, button a, .botones-panel').forEach(element => {
        element.addEventListener('click', function (event) {
            const enlace = this.getAttribute('href') || this.getAttribute('data-href') || this.querySelector('a')?.getAttribute('href');
            return handleContentLoad(event, enlace, this);
        });
    });
    
    window.addEventListener('popstate', () => loadContent(location.href, false));
    

    });

  2. Assistant

    Para mejorar la seguridad y el rendimiento de su código, le propongo las siguientes modificaciones y mejores prácticas:

    1. Evitar la ejecución de scripts desde contenido cargado dinámicamente

    Actualmente, está extrayendo y ejecutando scripts del contenido HTML que carga dinámicamente con fetch. Esto puede ser peligroso porque podría introducir vulnerabilidades de Cross-Site Scripting (XSS). Para mejorar la seguridad, evite ejecutar scripts desde contenido cargado y, en su lugar, utilice sus funciones de inicialización existentes.

    Código actual que debe eliminar:

    doc.querySelectorAll('script').forEach(script => {
        const newScript = document.createElement('script');
        newScript.textContent = script.textContent;
        document.body.appendChild(newScript);
    });
    

    Modificación recomendada:

    // Eliminado por seguridad: no ejecutar scripts del contenido cargado
    

    Luego, asegúrese de que todas las funcionalidades necesarias se inicialicen a través de sus funciones conocidas en inicializarScripts().


    2. Utilizar delegación de eventos para mejorar el rendimiento

    En lugar de agregar event listeners a cada enlace y botón individualmente, puede utilizar la delegación de eventos para manejar clics de manera más eficiente. Esto reduce la cantidad de event listeners y mejora el rendimiento.

    Código actualizado:

    document.body.addEventListener('click', function(event) {
        const target = event.target.closest('a, .botones-panel');
        if (!target) return;
    
        if (target.classList.contains('no-ajax') || target.closest('.no-ajax')) return;
    
        let enlace = target.getAttribute('href') || target.getAttribute('data-href');
        if (!enlace) return;
    
        const lowerCaseLink = enlace.trim().toLowerCase();
        if (!enlace || lowerCaseLink.endsWith('.pdf') || ['javascript:', 'data:', 'vbscript:'].some(prefix => lowerCaseLink.startsWith(prefix)) || enlace.includes('#')) return;
    
        event.preventDefault();
        loadContent(enlace, true);
    });
    

    Esto asegura que cualquier clic en un enlace o botón se maneje eficientemente sin necesidad de múltiples event listeners.


    3. Mejorar el manejo de errores al cargar contenido

    Al realizar solicitudes fetch, es importante verificar que la respuesta sea exitosa y manejar los errores adecuadamente. Además, verifique que el contenido esperado esté presente antes de manipular el DOM.

    Código actualizado:

    function loadContent(enlace, isPushState) {
        console.log('Iniciando carga de contenido:', enlace);
        if (!enlace || enlace.startsWith('javascript:') || enlace.includes('#') || enlace.includes('descarga_token')) return;
    
        if (pageCache[enlace] && shouldCache(enlace)) {
            document.getElementById('content').innerHTML = pageCache[enlace];
            if (isPushState) history.pushState(null, '', enlace);
            reinicializar();
            return;
        }
    
        const loadingBar = document.getElementById('loadingBar');
        loadingBar.style.width = '70%';
        loadingBar.style.opacity = '1';
        loadingBar.style.transition = 'width 0.4s ease';
    
        fetch(enlace, {
            method: 'GET',
            credentials: 'same-origin' // Asegura que las cookies se envíen si es necesario
        })
        .then(response => {
            if (!response.ok) {
                throw new Error(`Error en la respuesta HTTP: ${response.status}`);
            }
            return response.text();
        })
        .then(data => {
            const parser = new DOMParser();
            const doc = parser.parseFromString(data, 'text/html');
            const contentElement = doc.getElementById('content');
            if (!contentElement) {
                throw new Error('No se encontró el elemento con id "content" en la respuesta');
            }
            const content = contentElement.innerHTML;
            document.getElementById('content').innerHTML = content;
    
            if (shouldCache(enlace)) pageCache[enlace] = content;
    
            loadingBar.style.width = '100%';
            loadingBar.style.transition = 'width 0.1s ease, opacity 0.3s ease';
            setTimeout(() => {
                loadingBar.style.width = '0%';
                loadingBar.style.opacity = '0';
            }, 100);
    
            if (isPushState) history.pushState(null, '', enlace);
    
            // No ejecutar scripts del contenido cargado
            setTimeout(() => {
                reinicializar();
            }, 100);
        })
        .catch(error => {
            console.error('Error al cargar la página:', error);
            // Mostrar mensaje de error al usuario si es necesario
        });
    }
    

    4. Limitar el uso de variables globales y encapsular su código

    Para mejorar la seguridad y evitar conflictos, es recomendable no contaminar el espacio de nombres global. Puede encapsular su código dentro de una función autoinvocada (IIFE) o un módulo. Sin embargo, si necesita que ciertas funciones estén disponibles globalmente, asegúrese de nombrarlas adecuadamente y minimizar su uso.

    Ejemplo:

    (function() {
        const pageCache = {};
    
        function inicializarScripts() {
            // Funciones de inicialización
        }
    
        function reinicializar() {
            inicializarScripts();
            if (window.location.hash && typeof window.mostrarPestana === 'function') {
                window.mostrarPestana(window.location.hash);
            }
        }
    
        // Asignar funciones necesarias al objeto global si es imprescindible
        window.reinicializar = reinicializar;
    
        // Resto del código...
    })();
    

    5. Evitar el uso de window[func] para invocar funciones

    El uso de window[func] puede ser problemático si no se controla estrictamente. Es mejor tener referencias directas a las funciones o almacenarlas en un objeto específico.

    Modificación propuesta:

    const initFunctions = {
        inicializarWaveforms,
        inicializarReproductorAudio,
        // ... rest of your functions
    };
    
    function inicializarScripts() {
        Object.keys(initFunctions).forEach(funcName => {
            try {
                initFunctions[funcName]();
            } catch (error) {
                console.error(`Error al ejecutar ${funcName}:`, error);
            }
        });
    
        // Funciones que requieren argumentos especiales
        if (typeof manageSeparatorsAndOrder === 'function') {
            manageSeparatorsAndOrder(['.spaceprogreso', '#toggleOrderButton']);
        }
        if (typeof updateDaysElapsed === 'function') {
            updateDaysElapsed('2024-01-01');
        }
    }
    

    Esto evita el acceso dinámico a propiedades del objeto global y mejora la claridad del código.


    6. Generalizaciones y mejores prácticas

    • Caché Inteligente: Mejore su función de caché para invalidar o actualizar el contenido cuando sea necesario. Considere agregar una estructura de datos que registre las fechas de actualización.
    • Manejo de Asincronía: Utilice async/await para mejorar la legibilidad y el manejo de errores en funciones asíncronas.
    • Optimización de Selectores: Reduzca el número de consultas al DOM almacenando referencias a elementos que se usan frecuentemente.
    • Contenido Seguro: Asegúrese de que el contenido cargado sea de fuentes confiables y considere utilizar políticas de seguridad de contenido (CSP) en su servidor.

    Al implementar estas mejoras, su código será más seguro y tendrá un mejor rendimiento. Evitará posibles vulnerabilidades de seguridad, especialmente relacionadas con XSS, y optimizará la forma en que se manejan los eventos y se carga el contenido. Además, estas prácticas hacen que el código sea más mantenible y legible.

    Recuerde siempre validar y sanitizar cualquier entrada o contenido dinámico, mantener su código modular y seguir las mejores prácticas de desarrollo web.