Spaces:
Running
Running
File size: 21,831 Bytes
bebe233 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 | // ============================================================
// PhishGuard AI - background.js
// MV3 Service Worker with feedback, retraining triggers, and
// model version polling.
//
// State (chrome.storage.local):
// phishguard_feedback_queue: FeedbackRecord[] (max 500, FIFO)
// scan_count: int (resets at 50)
// feedback_count: int (labeled samples since last retrain)
// last_retrain_ts: ISO8601
// model_version: int
// session_id: UUIDv4
//
// Triggers:
// 1. scan_count >= 50 AND feedback_count >= 10
// 2. chrome.alarms "retrain_alarm" (24h) AND feedback_count >= 10
// ============================================================
// ββ Backend URL ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const BACKEND_URL = "https://phishguard-api-z2wj.onrender.com";
const ANALYZE_URL = `${BACKEND_URL}/analyze`;
const RETRAIN_URL = `${BACKEND_URL}/retrain`;
const MODEL_VERSION_URL = `${BACKEND_URL}/model_version`;
// ββ Constants ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
const CACHE_TTL_MS = 30 * 60 * 1000;
const MAX_QUEUE_SIZE = 500;
const RETRAIN_URL_THRESHOLD = 50;
const MIN_LABELED_SAMPLES = 10;
// ββ In-memory caches βββββββββββββββββββββββββββββββββββββββββββββββββ
const urlCache = new Map();
const tabResultCache = new Map();
const pageSignals = new Map();
// ββ TIER 1: Whitelist (O(1) Set lookup) ββββββββββββββββββββββββββββββ
const WHITELIST = new Set([
"google.com","youtube.com","facebook.com","amazon.com","wikipedia.org",
"twitter.com","instagram.com","linkedin.com","microsoft.com","apple.com",
"github.com","stackoverflow.com","reddit.com","netflix.com","paypal.com",
"bankofamerica.com","chase.com","wellsfargo.com","yahoo.com","bing.com",
"outlook.com","office.com","live.com","adobe.com","dropbox.com",
"zoom.us","slack.com","spotify.com","twitch.tv","ebay.com",
"walmart.com","target.com","bestbuy.com","airbnb.com",
"x.com","tiktok.com","pinterest.com","quora.com","medium.com"
]);
function getRootDomain(url) {
try {
const host = new URL(url).hostname.replace(/^www\./, "");
const parts = host.split(".");
return parts.slice(-2).join(".");
} catch { return null; }
}
// ββ TIER 2: Local heuristic scoring ββββββββββββββββββββββββββββββββββ
function heuristicScore(url) {
let score = 0;
const signals = [];
const u = url.toLowerCase();
// IP as hostname (25 pts)
if (/https?:\/\/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/.test(url)) {
score += 25; signals.push("IP as hostname");
}
// Suspicious TLD (20 pts)
const badTLDs = [".xyz",".tk",".ml",".ga",".cf",".gq",".pw",".top",".click"];
for (const tld of badTLDs) {
if (u.includes(tld)) { score += 20; signals.push(`Suspicious TLD (${tld})`); break; }
}
// Phishing keywords (15 pts)
const keywords = ["login","verify","secure","update","account","banking",
"signin","reset","confirm","suspend","webscr","cmd","payment","alert"];
const kwHits = keywords.filter(kw => u.includes(kw));
if (kwHits.length > 0) { score += 15; signals.push(`Keywords: ${kwHits.join(", ")}`); }
// Brand spoofing (15 pts)
const brands = ["paypal","google","apple","microsoft","amazon","netflix",
"facebook","instagram","chase","wellsfargo","bankofamerica"];
try {
const domain = getRootDomain(url);
for (const brand of brands) {
if (u.includes(brand) && domain && !domain.startsWith(brand)) {
score += 15; signals.push(`Brand spoofing: ${brand}`); break;
}
}
} catch {}
// Excessive subdomains (10 pts)
try {
const host = new URL(url).hostname;
const subCount = host.split(".").length - 2;
if (subCount >= 3) { score += 10; signals.push(`${subCount} subdomains`); }
} catch {}
// URL length (5 pts)
if (url.length > 100) { score += 5; signals.push(`Long URL (${url.length} chars)`); }
// Hyphens (5 pts)
try {
const host = new URL(url).hostname;
const hyphens = (host.match(/-/g) || []).length;
if (hyphens >= 3) { score += 5; signals.push(`${hyphens} hyphens in domain`); }
} catch {}
// Non-standard port (5 pts)
try {
const port = new URL(url).port;
if (port && port !== "80" && port !== "443") {
score += 5; signals.push(`Non-standard port :${port}`);
}
} catch {}
return { score: Math.min(score, 100), signals };
}
// ββ URL Cache ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function getCached(url) {
const entry = urlCache.get(url);
if (!entry) return null;
if (Date.now() - entry.ts > CACHE_TTL_MS) { urlCache.delete(url); return null; }
return entry.result;
}
function setCache(url, result) {
urlCache.set(url, { result, ts: Date.now() });
if (urlCache.size > 500) {
const firstKey = urlCache.keys().next().value;
urlCache.delete(firstKey);
}
}
// ββ Badge ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function setBadge(tabId, status, text) {
const colors = {
safe: "#22C55E", blocked: "#EF4444", warn: "#F59E0B",
loading: "#534AB7", none: "#888888"
};
chrome.action.setBadgeBackgroundColor({ color: colors[status] || colors.none, tabId });
chrome.action.setBadgeText({ text: text || "", tabId });
}
// ββ Backend fetch with retry βββββββββββββββββββββββββββββββββββββββββ
async function fetchBackend(url, payload, retryCount = 1) {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15000);
const response = await fetch(url, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
signal: controller.signal,
});
clearTimeout(timeout);
if (!response.ok) throw new Error(`Server ${response.status}`);
return await response.json();
} catch (err) {
if (retryCount > 0) {
await new Promise(r => setTimeout(r, 2000));
return fetchBackend(url, payload, retryCount - 1);
}
throw err;
}
}
// ββ SHA256 hash ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function sha256(text) {
const encoded = new TextEncoder().encode(text);
const hash = await crypto.subtle.digest("SHA-256", encoded);
return Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, "0")).join("");
}
// ββ Storage helpers ββββββββββββββββββββββββββββββββββββββββββββββββββ
async function getStorage(keys) {
return new Promise(resolve => chrome.storage.local.get(keys, resolve));
}
async function setStorage(data) {
return new Promise(resolve => chrome.storage.local.set(data, resolve));
}
async function getQueue() {
const data = await getStorage(["phishguard_feedback_queue"]);
return data.phishguard_feedback_queue || [];
}
async function setQueue(queue) {
// FIFO eviction
if (queue.length > MAX_QUEUE_SIZE) {
queue = queue.slice(queue.length - MAX_QUEUE_SIZE);
}
await setStorage({ phishguard_feedback_queue: queue });
}
// ββ ON INSTALL βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
chrome.runtime.onInstalled.addListener(async () => {
const sessionId = crypto.randomUUID();
await setStorage({
session_id: sessionId,
scan_count: 0,
feedback_count: 0,
last_retrain_ts: null,
model_version: 0,
phishguard_feedback_queue: [],
});
// 24-hour retraining alarm
chrome.alarms.create("retrain_alarm", { periodInMinutes: 1440 });
// 30-minute model polling alarm
chrome.alarms.create("model_poll_alarm", { periodInMinutes: 30 });
console.log("[PhishGuard] Installed. Session:", sessionId);
});
// ββ ALARM HANDLERS βββββββββββββββββββββββββββββββββββββββββββββββββββ
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === "retrain_alarm") {
console.log("[PhishGuard] Retrain alarm fired");
await checkRetrain("timer");
}
if (alarm.name === "model_poll_alarm") {
await pollModelVersion();
}
});
// ββ MAIN URL LISTENER ββββββββββββββββββββββββββββββββββββββββββββββββ
chrome.webNavigation.onCompleted.addListener(async (details) => {
if (details.frameId !== 0) return;
const url = details.url;
if (!url.startsWith("http")) return;
const tabId = details.tabId;
const domain = getRootDomain(url);
if (!domain) return;
setBadge(tabId, "loading", "β¦");
// TIER 1: Whitelist
if (WHITELIST.has(domain)) {
const result = {
url, status: "safe", tier: 1, method: "whitelist",
confidence: 0, heuristic_score: 0, signals: []
};
await setStorage({ lastResult: result });
tabResultCache.set(tabId, result);
setBadge(tabId, "safe", "β");
return;
}
// Cache check
const cached = getCached(url);
if (cached) {
await setStorage({ lastResult: cached });
tabResultCache.set(tabId, cached);
setBadge(tabId, cached.status, cached.status === "blocked" ? "!" : "β");
if (cached.status === "blocked") blockPage(tabId, url, cached);
return;
}
// TIER 2: Heuristic
const hResult = heuristicScore(url);
if (hResult.score >= 80) {
const result = {
url, status: "blocked", tier: 2, method: "heuristic",
confidence: hResult.score / 100, heuristic_score: hResult.score,
signals: hResult.signals, is_phishing: true
};
setCache(url, result);
await setStorage({ lastResult: result });
tabResultCache.set(tabId, result);
setBadge(tabId, "blocked", "!");
blockPage(tabId, url, result);
await storeFeedbackRecord(url, result);
await incrementScanCount();
return;
}
// TIER 3+4: Send to backend
const signals = pageSignals.get(tabId) || {};
try {
const apiResult = await fetchBackend(ANALYZE_URL, {
url,
heuristic_score: hResult.score,
page_title: signals.title || "",
page_snippet: signals.snippet || "",
});
const finalResult = {
url,
status: apiResult.is_phishing ? "blocked" : "safe",
tier: apiResult.tier || 3,
method: apiResult.method || "ensemble",
confidence: apiResult.confidence || 0,
heuristic_score: apiResult.heuristic_score || hResult.score,
signals: apiResult.signals || hResult.signals,
is_phishing: apiResult.is_phishing,
details: apiResult.details || {},
};
setCache(url, finalResult);
await setStorage({ lastResult: finalResult });
tabResultCache.set(tabId, finalResult);
if (finalResult.status === "blocked") {
setBadge(tabId, "blocked", "!");
blockPage(tabId, url, finalResult);
} else if (finalResult.confidence >= 0.4) {
setBadge(tabId, "warn", "?");
} else {
setBadge(tabId, "safe", "β");
}
await storeFeedbackRecord(url, finalResult);
} catch (err) {
console.log("[PhishGuard] Backend unreachable:", err.message);
const fallback = {
url,
status: hResult.score >= 50 ? "blocked" : "safe",
tier: 2,
method: "heuristic-fallback",
confidence: hResult.score / 100,
heuristic_score: hResult.score,
signals: hResult.signals,
is_phishing: hResult.score >= 50,
details: { backend_error: err.message },
};
setCache(url, fallback);
await setStorage({ lastResult: fallback });
tabResultCache.set(tabId, fallback);
if (hResult.score >= 50) {
setBadge(tabId, "blocked", "!");
blockPage(tabId, url, fallback);
} else if (hResult.score >= 30) {
setBadge(tabId, "warn", "?");
} else {
setBadge(tabId, "none", "");
}
await storeFeedbackRecord(url, fallback);
}
await incrementScanCount();
await checkRetrain("count");
pageSignals.delete(tabId);
}, { url: [{ schemes: ["http", "https"] }] });
// ββ Feedback Record Storage ββββββββββββββββββββββββββββββββββββββββββ
async function storeFeedbackRecord(url, result) {
const urlHash = await sha256(url);
const record = {
url,
verdict: result.is_phishing ? "phishing" : "safe",
confidence: result.confidence || 0,
tier_used: result.tier || 0,
heuristic_score: result.heuristic_score || 0,
signals: result.signals || [],
user_feedback: null,
timestamp: new Date().toISOString(),
feedback_ts: null,
url_hash: urlHash,
session_id: (await getStorage(["session_id"])).session_id || "",
};
const queue = await getQueue();
queue.push(record);
await setQueue(queue);
}
async function incrementScanCount() {
const data = await getStorage(["scan_count"]);
await setStorage({ scan_count: (data.scan_count || 0) + 1 });
}
// ββ Block Page βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
function blockPage(tabId, url, result) {
chrome.storage.local.set({ lastResult: { ...result, status: "blocked" } });
tabResultCache.set(tabId, result);
const score = Math.round((result.confidence || 0) * 100);
chrome.tabs.update(tabId, {
url: chrome.runtime.getURL("popup.html") +
"?blocked=1&url=" + encodeURIComponent(url) +
"&score=" + score +
"&method=" + encodeURIComponent(result.method || "")
});
}
// ββ Retrain Check ββββββββββββββββββββββββββββββββββββββββββββββββββββ
async function checkRetrain(trigger = "count") {
const queue = await getQueue();
const labeled = queue.filter(r => r.user_feedback !== null);
if (labeled.length < MIN_LABELED_SAMPLES) {
console.log(`[PhishGuard] Not enough labeled samples (${labeled.length}/${MIN_LABELED_SAMPLES})`);
return;
}
const data = await getStorage(["scan_count"]);
const scanCount = data.scan_count || 0;
if (trigger === "timer" || scanCount >= RETRAIN_URL_THRESHOLD) {
console.log(`[PhishGuard] Triggering retrain: trigger=${trigger}, labeled=${labeled.length}, scans=${scanCount}`);
await sendRetrainRequest(labeled, trigger);
}
}
async function sendRetrainRequest(samples, trigger) {
const data = await getStorage(["session_id"]);
try {
const result = await fetchBackend(RETRAIN_URL, {
samples,
trigger,
session_id: data.session_id || "",
extension_version: "3.0",
});
if (result.status === "success") {
// Reset counters
await setStorage({
scan_count: 0,
feedback_count: 0,
last_retrain_ts: new Date().toISOString(),
});
// Remove sent records from queue
const queue = await getQueue();
const sentHashes = new Set(samples.map(s => s.url_hash));
const remaining = queue.filter(r => !sentHashes.has(r.url_hash));
await setQueue(remaining);
// Show notification
showRetrainNotification(result.accuracy_delta || {});
console.log("[PhishGuard] Retrain success:", result);
}
} catch (err) {
console.error("[PhishGuard] Retrain request failed:", err.message);
}
}
function showRetrainNotification(delta) {
const bertDelta = delta.bert ? `BERT: ${(delta.bert * 100).toFixed(1)}%` : "";
const gnnDelta = delta.gnn ? `GNN: ${(delta.gnn * 100).toFixed(1)}%` : "";
const parts = [bertDelta, gnnDelta].filter(Boolean).join(", ");
chrome.notifications.create("retrain_complete", {
type: "basic",
iconUrl: "icons/icon48.png",
title: "PhishGuard AI Updated",
message: parts ? `Models improved! ${parts} accuracy from your feedback` :
"Models updated with your feedback",
});
}
// ββ Model Version Polling ββββββββββββββββββββββββββββββββββββββββββββ
async function pollModelVersion() {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 10000);
const resp = await fetch(MODEL_VERSION_URL, { signal: controller.signal });
clearTimeout(timeout);
if (!resp.ok) return;
const info = await resp.json();
const stored = await getStorage(["model_version"]);
if (info.version > (stored.model_version || 0)) {
await setStorage({ model_version: info.version });
// Clear URL cache (stale results)
urlCache.clear();
chrome.notifications.create("model_updated", {
type: "basic",
iconUrl: "icons/icon48.png",
title: "PhishGuard Models Updated",
message: `Model v${info.version} is now active`,
});
}
} catch (err) {
// Silently fail β model polling is best-effort
}
}
// ββ Message Handler ββββββββββββββββββββββββββββββββββββββββββββββββββ
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
// Page signals from content.js
if (msg.type === "page_signals") {
if (sender.tab) {
pageSignals.set(sender.tab.id, {
title: msg.title || "",
snippet: msg.snippet || "",
signals: msg.signals || [],
});
}
}
// Submit feedback from popup.js / content.js
if (msg.type === "submit_feedback") {
(async () => {
const queue = await getQueue();
const idx = queue.findIndex(r => r.url_hash === msg.url_hash);
if (idx >= 0) {
queue[idx].user_feedback = msg.feedback; // "correct" or "incorrect"
queue[idx].feedback_ts = new Date().toISOString();
await setQueue(queue);
// Increment feedback count
const data = await getStorage(["feedback_count"]);
await setStorage({ feedback_count: (data.feedback_count || 0) + 1 });
// Check if we should trigger retraining
await checkRetrain("count");
sendResponse({ success: true });
} else {
sendResponse({ success: false, error: "Record not found" });
}
})();
return true; // async response
}
// Get status for popup
if (msg.type === "get_status") {
(async () => {
const data = await getStorage([
"scan_count", "feedback_count", "last_retrain_ts",
"model_version", "session_id"
]);
const queue = await getQueue();
const labeled = queue.filter(r => r.user_feedback !== null).length;
const lastRetrain = data.last_retrain_ts ? new Date(data.last_retrain_ts) : null;
const now = Date.now();
const nextTimerMs = lastRetrain
? Math.max(0, (24 * 60 * 60 * 1000) - (now - lastRetrain.getTime()))
: 24 * 60 * 60 * 1000;
sendResponse({
scan_count: data.scan_count || 0,
feedback_count: data.feedback_count || 0,
labeled_count: labeled,
last_retrain_ts: data.last_retrain_ts,
model_version: data.model_version || 0,
next_retrain_urls_remaining: Math.max(0, RETRAIN_URL_THRESHOLD - (data.scan_count || 0)),
next_retrain_time_remaining_ms: nextTimerMs,
min_labeled_needed: Math.max(0, MIN_LABELED_SAMPLES - labeled),
});
})();
return true;
}
// Per-tab result cache query from popup
if (msg.type === "get_tab_result") {
const result = tabResultCache.get(msg.tabId);
sendResponse({ result: result || null });
return false;
}
// User override (Proceed Anyway)
if (msg.type === "whitelist_url") {
const override = {
url: msg.url, status: "safe", tier: 0,
method: "user-override", confidence: 0
};
setCache(msg.url, override);
chrome.storage.local.set({ lastResult: override });
sendResponse({ success: true });
}
// Gmail scanner bridge
if (msg.action === "analyzeEmail") {
const emailURL = ANALYZE_URL.replace(/\/analyze\/?$/, "/analyze/email");
fetch(emailURL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(msg.data),
})
.then(r => r.ok ? r.json() : Promise.reject(new Error(`${r.status}`)))
.then(data => sendResponse(data))
.catch(err => sendResponse({
status: "error",
analysis: { isPhishing: false, probability: 0, reason: "Backend unreachable" }
}));
return true;
}
});
// ββ Tab cleanup ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
chrome.tabs.onRemoved.addListener(tabId => {
pageSignals.delete(tabId);
tabResultCache.delete(tabId);
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
if (changeInfo.url) {
tabResultCache.delete(tabId);
setBadge(tabId, "none", "");
}
});
|