Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
165 changes: 114 additions & 51 deletions src/background/background.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@

class SafeWebBackground {
constructor() {
console.log("Safe-Web: Background script constructor called");
this.initializeExtension();
this.setupEventListeners();
console.log("Safe-Web: Background script initialized successfully");
}

async initializeExtension() {
console.log("Safe-Web: Initializing extension...");
// Initialize default settings
const defaultSettings = {
maskingEnabled: false,
Expand All @@ -34,13 +37,19 @@ class SafeWebBackground {
if (!existingSettings.safeWebSettings) {
await chrome.storage.sync.set({ safeWebSettings: defaultSettings });
console.log("Safe-Web: Default settings initialized");
} else {
console.log(
"Safe-Web: Existing settings found:",
existingSettings.safeWebSettings
);
}
} catch (error) {
console.error("Safe-Web: Failed to initialize settings:", error);
}
}

setupEventListeners() {
console.log("Safe-Web: Setting up event listeners...");
// Extension installation/update handling
chrome.runtime.onInstalled.addListener(this.handleInstallation.bind(this));

Expand All @@ -55,6 +64,8 @@ class SafeWebBackground {

// Action (browser button) click handling
chrome.action.onClicked.addListener(this.handleActionClick.bind(this));

console.log("Safe-Web: Event listeners set up successfully");
}

async handleInstallation(details) {
Expand All @@ -69,50 +80,76 @@ class SafeWebBackground {
}
}

async handleMessage(message, sender, sendResponse) {
handleMessage(message, sender, sendResponse) {
console.log("Safe-Web: Received message:", message.type, "from:", sender);
const { type, data } = message;

try {
switch (type) {
case "GET_SETTINGS":
const settings = await this.getSettings();
sendResponse({ success: true, data: settings });
break;

case "UPDATE_SETTINGS":
await this.updateSettings(data);
sendResponse({ success: true });
break;

case "TOGGLE_MASKING":
await this.toggleMasking(sender.tab.id);
sendResponse({ success: true });
break;

case "GET_TAB_STATE":
const tabState = await this.getTabState(sender.tab.id);
sendResponse({ success: true, data: tabState });
break;

case "UPDATE_TAB_STATE":
await this.updateTabState(sender.tab.id, data);
sendResponse({ success: true });
break;

case "ANALYZE_CONTENT":
const analysis = await this.analyzeContent(data);
sendResponse({ success: true, data: analysis });
break;

default:
console.warn("Safe-Web: Unknown message type:", type);
sendResponse({ success: false, error: "Unknown message type" });
}
} catch (error) {
console.error("Safe-Web: Message handling error:", error);
sendResponse({ success: false, error: error.message });
// Handle PING synchronously
if (type === "PING") {
console.log("Safe-Web: Ping received from:", sender);
const response = { success: true, data: "pong" };
console.log("Safe-Web: Sending response:", response);
sendResponse(response);
return false; // Don't keep channel open
}

// Handle async operations
const handleAsyncOperation = async () => {
try {
let response;

switch (type) {
case "GET_SETTINGS":
console.log("Safe-Web: Getting settings...");
const settings = await this.getSettings();
console.log("Safe-Web: Settings retrieved:", settings);
response = { success: true, data: settings };
break;

case "UPDATE_SETTINGS":
console.log("Safe-Web: Updating settings:", data);
await this.updateSettings(data);
console.log("Safe-Web: Settings updated successfully");
response = { success: true };
break;

case "TOGGLE_MASKING":
console.log("Safe-Web: Toggling masking for tab:", sender.tab?.id);
await this.toggleMasking(sender.tab.id);
response = { success: true };
break;

case "GET_TAB_STATE":
const tabState = await this.getTabState(sender.tab.id);
response = { success: true, data: tabState };
break;

case "UPDATE_TAB_STATE":
await this.updateTabState(sender.tab.id, data);
response = { success: true };
break;

case "ANALYZE_CONTENT":
const analysis = await this.analyzeContent(data);
response = { success: true, data: analysis };
break;

default:
console.warn("Safe-Web: Unknown message type:", type);
response = { success: false, error: "Unknown message type" };
}

console.log("Safe-Web: Sending response:", response);
sendResponse(response);
} catch (error) {
console.error("Safe-Web: Message handling error:", error);
sendResponse({ success: false, error: error.message });
}
};

// Start async operation
handleAsyncOperation();

// Keep message channel open for async response
return true;
}
Expand Down Expand Up @@ -153,12 +190,12 @@ class SafeWebBackground {
async getSettings() {
try {
const result = await chrome.storage.sync.get("safeWebSettings");

// Return default settings if none exist
if (!result.safeWebSettings) {
const defaultSettings = {
maskingEnabled: false,
maskingStyle: 'blur',
maskingStyle: "blur",
maskingIntensity: 5,
sensitivePatterns: {
email: true,
Expand All @@ -167,20 +204,20 @@ class SafeWebBackground {
creditCard: true,
names: false,
addresses: false,
customPatterns: []
customPatterns: [],
},
shortcuts: {
toggleMasking: 'Ctrl+Shift+M'
toggleMasking: "Ctrl+Shift+M",
},
theme: 'dark',
animations: true
theme: "dark",
animations: true,
};

// Initialize with default settings
await chrome.storage.sync.set({ safeWebSettings: defaultSettings });
return defaultSettings;
}

return result.safeWebSettings;
} catch (error) {
console.error("Safe-Web: Failed to get settings:", error);
Expand Down Expand Up @@ -288,9 +325,35 @@ class SafeWebBackground {

async handleUpdate(previousVersion) {
console.log(`Safe-Web updated from ${previousVersion}`);
// Handle any migration logic here
}
}

// Initialize the background service
new SafeWebBackground();
// Initialize the background service worker
console.log("Safe-Web: Starting background script initialization...");
const safeWebBackground = new SafeWebBackground();
console.log(
"Safe-Web: Background script instance created:",
!!safeWebBackground
);

// Ensure the service worker stays alive
self.addEventListener("install", (event) => {
console.log("Safe-Web service worker installing...");
self.skipWaiting();
});

self.addEventListener("activate", (event) => {
console.log("Safe-Web service worker activated");
event.waitUntil(self.clients.claim());
});

// Keep service worker alive
self.addEventListener("message", (event) => {
console.log("Safe-Web: Service worker received message:", event.data);
if (event.data && event.data.type === "KEEP_ALIVE") {
// Respond to keep-alive ping
event.ports[0].postMessage({ type: "KEEP_ALIVE_RESPONSE" });
}
});

console.log("Safe-Web: Background script setup completed");
59 changes: 55 additions & 4 deletions src/content/content.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

class SafeWebContentScript {
constructor() {
console.log("Safe-Web Content Script: Constructor called");
this.settings = null;
this.maskingActive = false;
this.maskedElements = new Map();
Expand All @@ -15,30 +16,45 @@ class SafeWebContentScript {
async init() {
if (this.initialized) return;

console.log("Safe-Web Content Script: Initializing...");
try {
await this.loadSettings();
console.log("Safe-Web Content Script: Settings loaded:", this.settings);
this.setupMessageListener();
this.setupMutationObserver();
this.setupKeyboardShortcuts();

// Initial scan if masking is enabled
if (this.settings?.maskingEnabled) {
console.log(
"Safe-Web Content Script: Masking is enabled, starting masking..."
);
await this.startMasking();
} else {
console.log("Safe-Web Content Script: Masking is disabled");
}

this.initialized = true;
console.log("Safe-Web content script initialized");
console.log("Safe-Web content script initialized successfully");
} catch (error) {
console.error("Safe-Web: Content script initialization failed:", error);
}
}

async loadSettings() {
console.log("Safe-Web Content Script: Loading settings...");
return new Promise((resolve) => {
chrome.runtime.sendMessage({ type: "GET_SETTINGS" }, (response) => {
console.log("Safe-Web Content Script: Settings response:", response);
if (response?.success) {
this.settings = response.data;
this.maskingActive = this.settings.maskingEnabled;
console.log(
"Safe-Web Content Script: Settings applied, maskingActive:",
this.maskingActive
);
} else {
console.error("Safe-Web Content Script: Failed to load settings");
}
resolve();
});
Expand Down Expand Up @@ -163,14 +179,31 @@ class SafeWebContentScript {
}

async scanPage() {
console.log(
"Safe-Web Content Script: Scanning page for sensitive information..."
);
if (!this.settings) await this.loadSettings();

const patterns = this.getSensitivePatterns();
console.log("Safe-Web Content Script: Using patterns:", patterns);
const textNodes = this.getTextNodes(document.body);
console.log(
"Safe-Web Content Script: Found",
textNodes.length,
"text nodes to scan"
);

let maskedCount = 0;
textNodes.forEach((node) => {
this.scanTextNode(node, patterns);
const result = this.scanTextNode(node, patterns);
if (result) maskedCount++;
});

console.log(
"Safe-Web Content Script: Masked",
maskedCount,
"text nodes with sensitive information"
);
}

async scanAndMaskNewContent() {
Expand Down Expand Up @@ -255,20 +288,34 @@ class SafeWebContentScript {
scanTextNode(textNode, patterns) {
const text = textNode.textContent;
let hasMatches = false;
let matchDetails = [];

for (const [type, pattern] of Object.entries(patterns)) {
if (pattern.regex.test(text)) {
const matches = text.match(pattern.regex);
if (matches) {
hasMatches = true;
break;
matchDetails.push({ type, matches: matches.length });
}
}

if (hasMatches) {
console.log(
"Safe-Web Content Script: Found matches in text node:",
matchDetails,
"Text:",
text.substring(0, 100)
);
this.maskTextNode(textNode, patterns);
return true;
}
return false;
}

maskTextNode(textNode, patterns) {
console.log(
"Safe-Web Content Script: Masking text node:",
textNode.textContent.substring(0, 100)
);
const parent = textNode.parentElement;
if (!parent) return;

Expand All @@ -278,12 +325,14 @@ class SafeWebContentScript {
// Apply masking for each pattern type
for (const [type, pattern] of Object.entries(patterns)) {
maskedHTML = maskedHTML.replace(pattern.regex, (match) => {
console.log("Safe-Web Content Script: Masking", type, ":", match);
return this.createMaskedElement(match, pattern.className, type);
});
}

// Only replace if we actually found matches
if (maskedHTML !== originalText) {
console.log("Safe-Web Content Script: Applying masking to element");
const tempDiv = document.createElement("div");
tempDiv.innerHTML = maskedHTML;

Expand All @@ -301,6 +350,8 @@ class SafeWebContentScript {
textNode,
type: "text",
});
} else {
console.log("Safe-Web Content Script: No changes made to text node");
}
}

Expand Down
Loading