Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
192 lines (167 loc) · 5.31 KB
/
Copy pathbackground.js
File metadata and controls
192 lines (167 loc) · 5.31 KB
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
/**
* StackScope Background Service Worker (Manifest V3)
*
* This service worker handles:
* - Extension lifecycle events
* - Message passing between popup and content scripts
* - Storage management for detection results
*
* IMPORTANT: Service workers are ephemeral and may be terminated by Chrome
* at any time. Do not rely on global state persisting between events.
*/
// Service worker installation
chrome.runtime.onInstalled.addListener((details) => {
if (details.reason === 'install') {
// First-time installation
chrome.storage.local.set({
detectionHistory: [],
settings: {
autoDetect: true,
showConfidence: true,
enableMutationObserver: true
}
});
}
});
// Service worker startup
chrome.runtime.onStartup.addListener(() => {
// Service worker activated
});
/**
* Message handler for communication between popup and content scripts
* Messages supported:
* - detectTechnologies: Inject detector and run analysis
* - getResults: Retrieve cached results for current tab
*/
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'detectTechnologies') {
handleDetection(message.tabId)
.then(results => sendResponse({ success: true, data: results }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true; // Keep channel open for async response
}
if (message.action === 'getStoredResults') {
chrome.storage.local.get(['lastDetection'], (data) => {
sendResponse({ success: true, data: data.lastDetection || null });
});
return true;
}
if (message.action === 'saveResults') {
saveDetectionResults(message.data)
.then(() => sendResponse({ success: true }))
.catch(error => sendResponse({ success: false, error: error.message }));
return true;
}
});
/**
* Main detection handler
* Injects detector script into active tab and collects results
*/
async function handleDetection(tabId) {
try {
// First, inject the fingerprints database
const fingerprints = await loadFingerprints();
// Inject detector script into the page
const injectionResults = await chrome.scripting.executeScript({
target: { tabId: tabId },
files: ['detector.js']
});
if (!injectionResults || injectionResults.length === 0) {
throw new Error('Failed to inject detector script');
}
// Execute detection with fingerprints
const detectionResults = await chrome.scripting.executeScript({
target: { tabId: tabId },
func: runDetection,
args: [fingerprints]
});
if (!detectionResults || detectionResults.length === 0) {
throw new Error('Detection returned no results');
}
const results = detectionResults[0].result;
// Store results with timestamp and URL
const tab = await chrome.tabs.get(tabId);
const enrichedResults = {
url: tab.url,
title: tab.title,
timestamp: Date.now(),
technologies: results
};
await saveDetectionResults(enrichedResults);
return enrichedResults;
} catch (error) {
console.error('[StackScope] Detection error:', error);
throw error;
}
}
/**
* Load fingerprints from local JSON file
*/
async function loadFingerprints() {
try {
const response = await fetch(chrome.runtime.getURL('fingerprints.json'));
const data = await response.json();
return data.technologies || [];
} catch (error) {
console.error('[StackScope] Failed to load fingerprints:', error);
return [];
}
}
/**
* Function injected into page context to run detection
* This runs in the page's context and has access to window object
*/
function runDetection(fingerprints) {
// This function will be called after detector.js is loaded
if (typeof window.StackScopeDetector !== 'undefined') {
return window.StackScopeDetector.detect(fingerprints);
} else {
throw new Error('Detector not loaded');
}
}
/**
* Save detection results to storage
*/
async function saveDetectionResults(results) {
try {
// Store last detection
await chrome.storage.local.set({ lastDetection: results });
// Add to history (keep last 50)
const { detectionHistory = [] } = await chrome.storage.local.get(['detectionHistory']);
detectionHistory.unshift({
url: results.url,
timestamp: results.timestamp,
techCount: results.technologies.length
});
// Limit history size
if (detectionHistory.length > 50) {
detectionHistory.splice(50);
}
await chrome.storage.local.set({ detectionHistory });
} catch (error) {
console.error('[StackScope] Failed to save results:', error);
throw error;
}
}
/**
* Handle service worker keep-alive if needed
* Note: Chrome may terminate service workers after 30 seconds of inactivity
* This is normal behavior and should be handled gracefully
*/
let keepAliveInterval;
chrome.runtime.onConnect.addListener((port) => {
if (port.name === 'keepAlive') {
if (keepAliveInterval) {
clearInterval(keepAliveInterval);
}
keepAliveInterval = setInterval(() => {
// Keep-alive ping
}, 20000); // Ping every 20 seconds
port.onDisconnect.addListener(() => {
if (keepAliveInterval) {
clearInterval(keepAliveInterval);
keepAliveInterval = null;
}
});
}
});