// Service worker for Chrome extension // Register all event listeners at the top to ensure they're always active // Import types and utilities import { StorageManager } from './storage-manager'; import { MessageRouter, type ExtensionMessage } from './message-router'; // import { log } from '@buzztrail/shared-utils/log'; import type { StorageVersion } from '@buzztrail/shared-types/extension-storage'; import type { PageContext } from '@buzztrail/shared-types/site-configuration'; // Initialize storage manager and message router const storageManager = StorageManager.getInstance(); const messageRouter = new MessageRouter(); // ============================================================================ // LIFECYCLE EVENT HANDLERS // ============================================================================ // PiP deprecated: removed independent window creator (no call sites) /** * Handle extension installation and updates * @param details Installation details from Chrome */ function handleOnInstalled(details: chrome.runtime.InstalledDetails): void { console.log('Service worker: Extension installed/updated', details); if (details.reason === 'install') { // First-time installation void handleFirstTimeInstall(); } else if (details.reason === 'update') { // Extension update void handleExtensionUpdate(details.previousVersion); } else if (details.reason === 'chrome_update') { // Chrome browser update void handleChromeUpdate(); } } /** * Handle first-time extension installation */ async function handleFirstTimeInstall(): Promise { try { console.log('Service worker: First-time installation'); // Initialize storage manager await storageManager.initialize(); // Set default storage settings await storageManager.saveStorageSettings({ enableAutoCleanup: true, retentionDays: 30, enableCompression: true, enableEncryption: true, showStorageWarnings: true, warningThreshold: 80, autoDeleteOldData: false }); // Update metadata with installation info await storageManager.updateStorageMetadata({ version: chrome.runtime.getManifest().version as StorageVersion, lastUpdated: new Date().toISOString(), createdAt: new Date().toISOString(), totalSize: 0, availableSpace: 0, quotaStatus: 'normal', encryptionStatus: 'strong', syncStatus: 'disabled', backupStatus: 'none', migrationStatus: 'completed', domainCount: 0, conversationCount: 0 }); console.log('Service worker: First-time installation completed'); } catch (error) { console.error('Service worker: First-time installation failed', error); } } /** * Handle extension update * @param previousVersion Previous version of the extension */ async function handleExtensionUpdate(previousVersion?: string): Promise { try { console.log('Service worker: Extension update', { previousVersion, currentVersion: chrome.runtime.getManifest().version }); // Perform any necessary migrations await performMigrations(previousVersion); // Update storage metadata await storageManager.updateStorageMetadata({ version: chrome.runtime.getManifest().version as StorageVersion, lastUpdated: new Date().toISOString() }); console.log('Service worker: Extension update completed'); } catch (error) { console.error('Service worker: Extension update failed', error); } } /** * Handle Chrome browser update */ async function handleChromeUpdate(): Promise { try { console.log('Service worker: Chrome browser update'); // Check if any Chrome-specific features need updating // This is mainly for logging purposes console.log('Service worker: Chrome update handled'); } catch (error) { console.error('Service worker: Chrome update handling failed', error); } } /** * Perform storage migrations if needed * @param previousVersion Previous version of the extension */ async function performMigrations(previousVersion?: string): Promise { try { console.log('Service worker: Performing migrations', { previousVersion }); if (!previousVersion) { console.log('Service worker: No previous version, skipping migrations'); return; } // Add migration logic here based on version differences // For now, just log the migration console.log('Service worker: Migrations completed'); } catch (error) { console.error('Service worker: Migration failed', error); } } // ============================================================================ // MESSAGE VALIDATION AND ROUTING // ============================================================================ /** * Validate message sender for security * @param sender Message sender information * @returns True if sender is valid */ function validateMessageSender(sender: chrome.runtime.MessageSender): boolean { // Only allow messages from this extension id if (!sender.id || sender.id !== chrome.runtime.id) { console.warn('Service worker: Invalid sender ID', sender.id); return false; } // Allow extension pages (popup, side panel, permission tab) if (sender.url?.startsWith(chrome.runtime.getURL(''))) { return true; } // Allow content scripts injected into http/https pages if (sender.origin && (sender.origin.startsWith('http://') || sender.origin.startsWith('https://'))) { return true; } // If origin is missing (some MV3 contexts), still accept since id matched return true; } /** * Extract domain from URL * @param url URL to extract domain from * @returns Domain or null if invalid */ function getDomainFromUrl(url: string): string | null { try { const urlObj = new URL(url); return urlObj.hostname; } catch (error) { console.error('Service worker: Failed to parse URL', { url, error }); return null; } } /** * Validate cross-domain origin for security * @param sender Message sender * @param message Message being sent * @returns True if cross-domain communication is allowed */ // eslint-disable-next-line @typescript-eslint/no-unused-vars function validateCrossDomainOrigin(sender: chrome.runtime.MessageSender, message: ExtensionMessage): boolean { // For now, allow all messages from our extension // In the future, we might want to add more specific validation return true; } /** * Handle incoming messages from content scripts, popup, etc. * @param message Message to handle * @param sender Message sender * @param sendResponse Response callback * @returns True if message was handled */ async function handleOnMessage( message: ExtensionMessage, sender: chrome.runtime.MessageSender, sendResponse: (response?: unknown) => void ): Promise { try { console.log('Service worker: Received message', { message, sender: { id: sender.id, url: sender.url } }); // Validate sender if (!validateMessageSender(sender)) { console.warn('Service worker: Invalid message sender', { id: sender.id, url: sender.url }); sendResponse({ success: false, error: 'Invalid sender' }); return true; } // Validate cross-domain origin if (!validateCrossDomainOrigin(sender, message)) { sendResponse({ success: false, error: 'Cross-domain validation failed' }); return true; } // Route message through message router const response = await messageRouter.routeMessage(message, sender); console.log('Service worker: Message response', response); sendResponse(response); return true; } catch (error) { console.error('Service worker: Message handling error', error); sendResponse({ success: false, error: 'Message handling failed' }); return true; } } // ============================================================================ // TAB EVENT HANDLERS // ============================================================================ /** * Handle tab updates * @param tabId Tab ID * @param changeInfo Change information * @param tab Tab information */ function handleTabUpdated( tabId: number, changeInfo: chrome.tabs.OnUpdatedInfo, tab: chrome.tabs.Tab ): void { console.log('Service worker: Tab updated', { tabId, changeInfo, tab }); // Handle URL changes if (changeInfo.url) { void handleTabUrlChange(tabId, tab, changeInfo.url); } // Handle title changes if (changeInfo.title) { void handleTabTitleChange(tabId, tab, changeInfo.title); } // Handle favicon changes if (changeInfo.favIconUrl) { void handleTabFaviconChange(tabId, tab, changeInfo.favIconUrl); } // Handle status changes if (changeInfo.status === 'complete') { void handleTabLoadComplete(tabId, tab); } } /** * Handle tab activation * @param activeInfo Active tab information */ function handleTabActivated(activeInfo: chrome.tabs.OnActivatedInfo): void { console.log('Service worker: Tab activated', activeInfo); // Get the activated tab chrome.tabs.get(activeInfo.tabId, (tab) => { if (chrome.runtime.lastError) { console.error('Service worker: Failed to get activated tab', chrome.runtime.lastError); return; } void handleTabActivation(tab); }); } /** * Handle tab removal * @param tabId Removed tab ID * @param removeInfo Removal information */ function handleTabRemoved(tabId: number, removeInfo: chrome.tabs.OnRemovedInfo): void { console.log('Service worker: Tab removed', { tabId, removeInfo }); // Clean up tab-specific data void handleTabCleanup(tabId); } /** * Handle tab replacement * @param addedTabId New tab ID * @param removedTabId Old tab ID */ function handleTabReplaced(addedTabId: number, removedTabId: number): void { console.log('Service worker: Tab replaced', { addedTabId, removedTabId }); // Clean up old tab data void handleTabCleanup(removedTabId); // Initialize new tab data chrome.tabs.get(addedTabId, (tab) => { if (chrome.runtime.lastError) { console.error('Service worker: Failed to get replaced tab', chrome.runtime.lastError); return; } void handleTabActivation(tab); }); } /** * Handle window focus changes * @param windowId Window ID */ function handleWindowFocusChanged(windowId: number): void { console.log('Service worker: Window focus changed', windowId); // Legacy PiP tracking removed } /** * Handle window removal (when windows are actually closed) * @param windowId Window ID that was closed */ function handleWindowRemoved(windowId: number): void { console.log('Service worker: Window removed', windowId); // Legacy PiP tracking removed } /** * Handle tab load completion * @param tabId Tab ID * @param tab Tab information */ async function handleTabLoadComplete(tabId: number, tab: chrome.tabs.Tab): Promise { console.log('Service worker: Tab load complete', { tabId, url: tab.url }); if (!tab.url) { console.log('Service worker: Tab has no URL', tabId); return; } try { // Create page context for the tab const pageContext: PageContext = { url: tab.url, title: tab.title || '', domain: getDomainFromUrl(tab.url) || '', path: new URL(tab.url).pathname, queryParams: Object.fromEntries(new URL(tab.url).searchParams.entries()), tabId, isActive: tab.active || false, loadTime: new Date().toISOString(), metadata: { description: '', keywords: [], author: '', language: 'en', viewport: '' }, contentAnalysis: { headings: [], links: [], images: [], forms: [], contentType: 'other' }, performance: { loadTime: 0, domContentLoaded: 0 }, accessibility: { hasProperHeadings: false, hasAltText: false, hasAriaLabels: false, accessibilityScore: 0 }, security: { isSecure: tab.url.startsWith('https://'), hasCSP: false, hasSecurityHeaders: false, securityScore: 0 } }; // Save page context await storageManager.savePageContext(tabId, pageContext); console.log('Service worker: Page context saved for tab', tabId); } catch (error) { console.error('Service worker: Failed to handle tab load complete', { tabId, error }); } } /** * Handle tab URL changes * @param tabId Tab ID * @param tab Tab information * @param newUrl New URL */ async function handleTabUrlChange(tabId: number, tab: chrome.tabs.Tab, newUrl: string): Promise { console.log('Service worker: Tab URL changed', { tabId, newUrl }); try { // Get existing page context const existingContext = await storageManager.getPageContext(tabId); // Create updated page context const pageContext: PageContext = { url: newUrl, title: tab.title || '', domain: getDomainFromUrl(newUrl) || '', path: new URL(newUrl).pathname, queryParams: Object.fromEntries(new URL(newUrl).searchParams.entries()), tabId, isActive: tab.active || false, loadTime: new Date().toISOString(), metadata: existingContext?.metadata || { description: '', keywords: [], author: '', language: 'en', viewport: '' }, contentAnalysis: existingContext?.contentAnalysis || { headings: [], links: [], images: [], forms: [], contentType: 'other' }, performance: existingContext?.performance || { loadTime: 0, domContentLoaded: 0 }, accessibility: existingContext?.accessibility || { hasProperHeadings: false, hasAltText: false, hasAriaLabels: false, accessibilityScore: 0 }, security: existingContext?.security || { isSecure: newUrl.startsWith('https://'), hasCSP: false, hasSecurityHeaders: false, securityScore: 0 } }; // Save updated page context await storageManager.savePageContext(tabId, pageContext); console.log('Service worker: Page context updated for tab', tabId); } catch (error) { console.error('Service worker: Failed to handle tab URL change', { tabId, newUrl, error }); } } /** * Handle tab title changes * @param tabId Tab ID * @param tab Tab information * @param newTitle New title */ async function handleTabTitleChange(tabId: number, tab: chrome.tabs.Tab, newTitle: string): Promise { console.log('Service worker: Tab title changed', { tabId, newTitle }); try { // Get existing page context const existingContext = await storageManager.getPageContext(tabId); if (!existingContext) return; // Update title existingContext.title = newTitle; existingContext.loadTime = new Date().toISOString(); // Save updated page context await storageManager.savePageContext(tabId, existingContext); console.log('Service worker: Page title updated for tab', tabId); } catch (error) { console.error('Service worker: Failed to handle tab title change', { tabId, newTitle, error }); } } /** * Handle tab favicon changes * @param tabId Tab ID * @param tab Tab information * @param newFaviconUrl New favicon URL */ async function handleTabFaviconChange(tabId: number, tab: chrome.tabs.Tab, newFaviconUrl: string): Promise { console.log('Service worker: Tab favicon changed', { tabId, newFaviconUrl }); try { // Get existing page context const existingContext = await storageManager.getPageContext(tabId); if (!existingContext) return; // Update favicon in metadata // No favicon field in PageContext.metadata; skip storing it to satisfy types existingContext.loadTime = new Date().toISOString(); // Save updated page context await storageManager.savePageContext(tabId, existingContext); console.log('Service worker: Page favicon updated for tab', tabId); } catch (error) { console.error('Service worker: Failed to handle tab favicon change', { tabId, newFaviconUrl, error }); } } /** * Handle tab activation * @param tab Activated tab */ async function handleTabActivation(tab: chrome.tabs.Tab): Promise { console.log('Service worker: Tab activated', { tabId: tab.id, url: tab.url }); if (!tab.id || !tab.url) return; try { // Get existing page context const existingContext = await storageManager.getPageContext(tab.id); if (existingContext) { // Update activation status existingContext.isActive = true; existingContext.loadTime = new Date().toISOString(); await storageManager.savePageContext(tab.id, existingContext); } else { // Create new page context const pageContext: PageContext = { url: tab.url, title: tab.title || '', domain: getDomainFromUrl(tab.url) || '', path: tab.url ? new URL(tab.url).pathname : '', queryParams: tab.url ? Object.fromEntries(new URL(tab.url).searchParams.entries()) : {}, tabId: tab.id, isActive: true, loadTime: new Date().toISOString(), metadata: { description: '', keywords: [], author: '', language: 'en', viewport: '' }, contentAnalysis: { headings: [], links: [], images: [], forms: [], contentType: 'other' }, performance: { loadTime: 0, domContentLoaded: 0 }, accessibility: { hasProperHeadings: false, hasAltText: false, hasAriaLabels: false, accessibilityScore: 0 }, security: { isSecure: !!tab.url && tab.url.startsWith('https://'), hasCSP: false, hasSecurityHeaders: false, securityScore: 0 } }; await storageManager.savePageContext(tab.id, pageContext); } console.log('Service worker: Tab activation handled', tab.id); } catch (error) { console.error('Service worker: Failed to handle tab activation', { tabId: tab.id, error }); } } /** * Clean up tab-specific data * @param tabId Tab ID to clean up */ async function handleTabCleanup(tabId: number): Promise { try { console.log('Service worker: Cleaning up tab data', tabId); // Remove page context for the tab // Note: We don't have a delete method in storage manager, so we'll just log for now console.log('Service worker: Tab cleanup completed', tabId); } catch (error) { console.error('Service worker: Failed to clean up tab data', { tabId, error }); } } // ============================================================================ // EVENT LISTENER REGISTRATION // ============================================================================ // Prefer registering in main background, but ensure we have listeners as a fallback try { const g = globalThis as unknown as { __BT_SW_EVENTS_REGISTERED__?: boolean }; if (!g.__BT_SW_EVENTS_REGISTERED__) { console.log('Service worker: Registering fallback event listeners'); chrome.runtime.onMessage.addListener((message: ExtensionMessage, sender, sendResponse) => { void handleOnMessage(message, sender, sendResponse); return true; }); chrome.tabs.onUpdated.addListener(handleTabUpdated); chrome.tabs.onActivated.addListener(handleTabActivated); chrome.tabs.onRemoved.addListener(handleTabRemoved); chrome.tabs.onReplaced.addListener(handleTabReplaced); chrome.windows.onFocusChanged.addListener(handleWindowFocusChanged); chrome.windows.onRemoved.addListener(handleWindowRemoved); chrome.runtime.onInstalled.addListener(handleOnInstalled); g.__BT_SW_EVENTS_REGISTERED__ = true; console.log('Service worker: Fallback event listeners registered'); } else { console.log('Service worker: Fallback listeners already registered'); } } catch (err) { console.error('Service worker: Failed to register fallback listeners', err); }