fix: Add error handling for script injection and improve logging for URL mappings

This commit is contained in:
claudi 2026-02-18 10:28:15 +01:00
parent 0eba82b8af
commit 4011f46ab7
2 changed files with 69 additions and 36 deletions

View file

@ -2,29 +2,30 @@
// Prevents browser drag for ALT+drag, hands off to Qt for file drag // Prevents browser drag for ALT+drag, hands off to Qt for file drag
(function() { (function() {
if (window.__webdrop_intercept_injected) return; try {
window.__webdrop_intercept_injected = true; if (window.__webdrop_intercept_injected) return;
window.__webdrop_intercept_injected = true;
// Intercept mode enabled // Intercept mode enabled
var INTERCEPT_ENABLED = true; var INTERCEPT_ENABLED = true;
console.log('%c[WebDrop Intercept] Script loaded - INTERCEPT_ENABLED=' + INTERCEPT_ENABLED, 'background: #2196F3; color: white; font-weight: bold; padding: 4px 8px;'); console.log('%c[WebDrop Intercept] Script loaded - INTERCEPT_ENABLED=' + INTERCEPT_ENABLED, 'background: #2196F3; color: white; font-weight: bold; padding: 4px 8px;');
var currentDragUrl = null; var currentDragUrl = null;
var angularDragHandlers = []; var angularDragHandlers = [];
var originalAddEventListener = EventTarget.prototype.addEventListener; var originalAddEventListener = EventTarget.prototype.addEventListener;
var listenerPatchActive = true; var listenerPatchActive = true;
// Capture Authorization token from XHR requests // Capture Authorization token from XHR requests
window.capturedAuthToken = null; window.capturedAuthToken = null;
var originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader; var originalXHRSetRequestHeader = XMLHttpRequest.prototype.setRequestHeader;
XMLHttpRequest.prototype.setRequestHeader = function(header, value) { XMLHttpRequest.prototype.setRequestHeader = function(header, value) {
if (header === 'Authorization' && value.startsWith('Bearer ')) { if (header === 'Authorization' && value.startsWith('Bearer ')) {
window.capturedAuthToken = value; window.capturedAuthToken = value;
console.log('[Intercept] Captured auth token'); console.log('[Intercept] Captured auth token');
} }
return originalXHRSetRequestHeader.apply(this, arguments); return originalXHRSetRequestHeader.apply(this, arguments);
}; };
// ============================================================================ // ============================================================================
// PART 1: Intercept Angular's dragstart listener registration // PART 1: Intercept Angular's dragstart listener registration
@ -189,4 +190,8 @@
console.log('%c[WebDrop Intercept] Ready! ALT-drag will use Qt file drag.', console.log('%c[WebDrop Intercept] Ready! ALT-drag will use Qt file drag.',
'background: #4CAF50; color: white; font-weight: bold; padding: 4px 8px;'); 'background: #4CAF50; color: white; font-weight: bold; padding: 4px 8px;');
} catch(e) {
console.error('[WebDrop Intercept] FATAL ERROR in bridge script:', e);
console.error('[WebDrop Intercept] Stack:', e.stack);
}
})(); })();

View file

@ -422,7 +422,7 @@ class MainWindow(QMainWindow):
qwebchannel_code = "" qwebchannel_code = ""
qwebchannel_file = QFile(":/qtwebchannel/qwebchannel.js") qwebchannel_file = QFile(":/qtwebchannel/qwebchannel.js")
if qwebchannel_file.open(QIODevice.OpenModeFlag.ReadOnly | QIODevice.OpenModeFlag.Text): if qwebchannel_file.open(QIODevice.OpenModeFlag.ReadOnly | QIODevice.OpenModeFlag.Text):
qwebchannel_code = bytes(qwebchannel_file.readAll()).decode('utf-8') qwebchannel_code = bytes(qwebchannel_file.readAll()).decode('utf-8') # type: ignore
qwebchannel_file.close() qwebchannel_file.close()
logger.debug("Loaded qwebchannel.js inline to avoid CSP issues") logger.debug("Loaded qwebchannel.js inline to avoid CSP issues")
else: else:
@ -454,6 +454,15 @@ class MainWindow(QMainWindow):
if download_interceptor_code: if download_interceptor_code:
combined_code += "\n\n" + download_interceptor_code combined_code += "\n\n" + download_interceptor_code
logger.debug(f"Combined script size: {len(combined_code)} chars "
f"(qwebchannel: {len(qwebchannel_code)}, "
f"config: {len(config_code)}, "
f"bridge: {len(bridge_code)}, "
f"interceptor: {len(download_interceptor_code)})")
logger.debug(f"URL mappings in config: {len(self.config.url_mappings)}")
for i, mapping in enumerate(self.config.url_mappings):
logger.debug(f" Mapping {i+1}: {mapping.url_prefix}{mapping.local_path}")
script.setSourceCode(combined_code) script.setSourceCode(combined_code)
self.web_view.page().scripts().insert(script) self.web_view.page().scripts().insert(script)
logger.debug(f"Installed bridge script from {script_path}") logger.debug(f"Installed bridge script from {script_path}")
@ -478,20 +487,39 @@ class MainWindow(QMainWindow):
"local_path": mapping.local_path "local_path": mapping.local_path
}) })
# Generate JavaScript code logger.debug(f"Generating config injection with {len(mappings)} URL mappings")
config_js = """ for i, m in enumerate(mappings):
(function() { logger.debug(f" [{i+1}] {m['url_prefix']} -> {m['local_path']}")
// WebDrop Bridge - Configuration Injection
window.webdropConfig = """ + json.dumps({ # Generate config object as JSON
"urlMappings": mappings config_obj = {"urlMappings": mappings}
}) + """; config_json = json.dumps(config_obj)
console.log('[WebDrop Config] Injected configuration with',
window.webdropConfig.urlMappings.length, 'URL mappings'); logger.debug(f"Config JSON size: {len(config_json)} bytes")
for (var i = 0; i < window.webdropConfig.urlMappings.length; i++) {
var m = window.webdropConfig.urlMappings[i]; # Generate JavaScript code - Safe injection with error handling
console.log('[WebDrop Config] Mapping', (i+1) + ':', m.url_prefix, '', m.local_path); config_js = f"""
} (function() {{
})(); try {{
// WebDrop Bridge - Configuration Injection
console.log('[WebDrop Config] Starting configuration injection...');
window.webdropConfig = {config_json};
console.log('[WebDrop Config] Configuration object created');
if (window.webdropConfig && window.webdropConfig.urlMappings) {{
console.log('[WebDrop Config] SUCCESS: ' + window.webdropConfig.urlMappings.length + ' URL mappings loaded');
for (var i = 0; i < window.webdropConfig.urlMappings.length; i++) {{
var m = window.webdropConfig.urlMappings[i];
console.log('[WebDrop Config] [' + (i+1) + '] ' + m.url_prefix + ' -> ' + m.local_path);
}}
}} else {{
console.warn('[WebDrop Config] WARNING: No valid URL mappings found in config object');
}}
}} catch(e) {{
console.error('[WebDrop Config] ERROR during configuration injection: ' + e.message);
if (e.stack) console.error('[WebDrop Config] Stack: ' + e.stack);
}}
}})();
""" """
return config_js return config_js