-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathbackground.js
More file actions
2117 lines (1900 loc) · 122 KB
/
background.js
File metadata and controls
2117 lines (1900 loc) · 122 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
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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* FrogPost Extension
* Originally Created by thisis0xczar/Lidor
* Refined on: 2025-10-22
* Updated: 2025-11-15 - Handler detection & performance optimizations
*/
// TELEMETRY-FIRST: No AST parsing needed
try {
importScripts(
'./static/handler-extractor.js'
);
} catch (e) {
console.error("Background.js: Failed to import handler-extractor.js", e);
}
let debugMode = false; // Flag to control debug logging - Loaded from storage, false by default
const DEBUG_MODE_STORAGE_KEY = 'frogpostDebugMode';
// Load debug mode from storage on startup
(async () => {
try {
const result = await chrome.storage.local.get([DEBUG_MODE_STORAGE_KEY]);
debugMode = result[DEBUG_MODE_STORAGE_KEY] || false;
} catch (error) {
debugMode = false;
}
})();
const log = {
debug: (...args) => { if (debugMode) console.debug("BG:", ...args); },
info: (...args) => { if (debugMode) console.info("BG:", ...args); },
warn: (...args) => { console.warn("BG:", ...args); }, // Always show warnings
error: (...args) => { console.error("BG:", ...args); }, // Always show errors
handler: (...args) => { if (debugMode) console.log("BG HANDLER:", ...args); },
scan: (...args) => { if (debugMode) console.log("BG SCAN:", ...args); },
};
/**
* BoundedMap - Prevents memory leaks by limiting Map size
* Automatically removes oldest entries when limit is reached
*/
class BoundedMap extends Map {
constructor(maxSize = 100) {
super();
this.maxSize = maxSize;
}
set(key, value) {
// If we're at capacity, remove the oldest entry
if (this.size >= this.maxSize && !this.has(key)) {
const firstKey = this.keys().next().value;
this.delete(firstKey);
}
return super.set(key, value);
}
}
/**
* BoundedSet - Prevents memory leaks by limiting Set size
*/
class BoundedSet extends Set {
constructor(maxSize = 100) {
super();
this.maxSize = maxSize;
}
add(value) {
// If we're at capacity, remove the first entry
if (this.size >= this.maxSize && !this.has(value)) {
const firstValue = this.values().next().value;
this.delete(firstValue);
}
return super.add(value);
}
}
/**
* LRUCache - Least Recently Used cache implementation
* Efficiently tracks access order and evicts least recently used entries
*/
class LRUCache extends Map {
constructor(maxSize = 100) {
super();
this.maxSize = maxSize;
this.accessOrder = []; // Track access order (most recent at end)
}
get(key) {
if (super.has(key)) {
// Move to end (most recently used)
this._updateAccess(key);
return super.get(key);
}
return undefined;
}
set(key, value) {
if (super.has(key)) {
// Update existing entry and move to end
super.set(key, value);
this._updateAccess(key);
} else {
// Add new entry
if (this.size >= this.maxSize) {
// Evict least recently used (first in accessOrder)
const lruKey = this.accessOrder.shift();
if (lruKey !== undefined) {
super.delete(lruKey);
}
}
super.set(key, value);
this.accessOrder.push(key);
}
return this;
}
delete(key) {
if (super.has(key)) {
super.delete(key);
const index = this.accessOrder.indexOf(key);
if (index !== -1) {
this.accessOrder.splice(index, 1);
}
}
return super.has(key);
}
clear() {
super.clear();
this.accessOrder = [];
}
_updateAccess(key) {
const index = this.accessOrder.indexOf(key);
if (index !== -1) {
// Move to end (most recently used)
this.accessOrder.splice(index, 1);
this.accessOrder.push(key);
}
}
}
/**
* In-Memory Handler Cache for Real-Time Capture
* Stores handlers immediately when detected by DOM agent
* Uses LRU eviction to keep most recently accessed handlers
*/
const MAX_CACHE_SIZE = 500;
const MAX_HANDLERS_PER_URL = 10;
const handlerCache = new LRUCache(MAX_CACHE_SIZE);
/**
* OPTIMIZATION: Fast hash function for handler deduplication
* 5-10x faster than full string comparison for long handlers
*/
function fastHashHandler(str) {
let hash = 0;
for (let i = 0; i < str.length; i++) {
hash = ((hash << 5) - hash) + str.charCodeAt(i);
hash = hash & hash; // Convert to 32-bit integer
}
return hash;
}
/**
* RELIABILITY FIX: Generate URL variants for fuzzy matching
* Handles cases where URL has query params, hash, trailing slash variations
*/
function generateUrlVariants(url) {
try {
const urlObj = new URL(url);
const variants = new Set();
// Variant 1: Full URL (primary key - CRITICAL for backward compatibility)
variants.add(url);
// Variant 2: Origin + pathname + search (no hash)
variants.add(urlObj.origin + urlObj.pathname + urlObj.search);
// Variant 3: Origin + pathname (no query/hash)
variants.add(urlObj.origin + urlObj.pathname);
// Variant 4: With trailing slash
const pathWithSlash = urlObj.pathname.endsWith('/') ? urlObj.pathname : urlObj.pathname + '/';
variants.add(urlObj.origin + pathWithSlash);
// Variant 5: Without trailing slash
const pathWithoutSlash = urlObj.pathname.endsWith('/') ? urlObj.pathname.slice(0, -1) : urlObj.pathname;
if (pathWithoutSlash) {
variants.add(urlObj.origin + pathWithoutSlash);
}
return Array.from(variants);
} catch {
// Invalid URL - return as-is
return [url];
}
}
let frameConnections = new BoundedMap(50); // Limit to 50 frame connections
let messageBuffer;
const injectedFramesAgents = new BoundedMap(20); // Limit to 20 injected agents
/**
* StorageBatcher - Batches storage writes to reduce I/O operations
* Accumulates writes over 100ms window and merges writes to same key
*/
class StorageBatcher {
constructor(flushInterval = 100, maxQueueSize = 10) {
this.queue = new Map(); // key -> value
this.flushInterval = flushInterval;
this.maxQueueSize = maxQueueSize;
this.flushTimer = null;
this.flushing = false;
}
set(keyValuePairs, options = {}) {
const immediate = options.immediate || false;
// Add to queue (merge if key already exists)
for (const [key, value] of Object.entries(keyValuePairs)) {
this.queue.set(key, value);
}
// Flush immediately if requested or queue is full
if (immediate || this.queue.size >= this.maxQueueSize) {
this.flush();
} else {
// Schedule flush if not already scheduled
if (!this.flushTimer) {
this.flushTimer = setTimeout(() => this.flush(), this.flushInterval);
}
}
}
async flush() {
if (this.flushing || this.queue.size === 0) return;
this.flushing = true;
if (this.flushTimer) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
try {
const toWrite = Object.fromEntries(this.queue);
this.queue.clear();
await chrome.storage.local.set(toWrite);
log.debug(`[StorageBatcher] Flushed ${Object.keys(toWrite).length} items`);
} catch (error) {
log.error('[StorageBatcher] Flush error:', error);
// Re-queue failed writes
for (const [key, value] of Object.entries(toWrite)) {
this.queue.set(key, value);
}
} finally {
this.flushing = false;
}
}
// Force immediate flush (for critical operations)
async forceFlush() {
if (this.flushTimer) {
clearTimeout(this.flushTimer);
this.flushTimer = null;
}
await this.flush();
}
}
// Global storage batcher instance
const storageBatcher = new StorageBatcher(100, 10);
// Server management
let serverCheckInterval = null;
const SERVER_PORT = 1337;
const SERVER_URL = `http://127.0.0.1:${SERVER_PORT}`;
/**
* Check if local FrogPost server is running
*/
async function isServerRunning() {
try {
const response = await fetch(`${SERVER_URL}/health`, {
method: 'GET',
signal: AbortSignal.timeout(2000)
});
return response.ok;
} catch {
return false;
}
}
/**
* Attempt to start the local server (requires native messaging or user action)
*/
async function ensureServerRunning() {
if (await isServerRunning()) {
log.debug("Server already running");
return true;
}
log.warn("Server not running. LLM features will be limited.");
// Show notification to user about starting server
try {
await chrome.notifications.create('frogpost-server-needed', {
type: 'basic',
iconUrl: 'icons/frog-logo48.png',
title: 'FrogPost Server Needed',
message: 'Start the server with "node server.js" for AI analysis features.'
});
} catch (e) {
log.debug("Could not show notification:", e);
}
return false;
}
/**
* Auto-check server status periodically when extension is active
*/
function startServerMonitoring() {
if (serverCheckInterval) return;
serverCheckInterval = setInterval(async () => {
const running = await isServerRunning();
chrome.storage.session.set({ 'server-running': running });
if (!running) {
log.debug("Server stopped - LLM features disabled");
}
}, 30000); // Check every 30 seconds
}
const HANDLER_ENDPOINT_KEYS_STORAGE_KEY = 'handler_endpoint_keys';
let endpointsWithDetectedHandlers = new BoundedSet(30); // Limit to 30 endpoints
let nativePort = null;
const NATIVE_HOST_NAME = "com.nodeserver.starter";
let consoleSuccessIndices = [];
let activeDebugSessions = new BoundedMap(10); // Limit to 10 debug sessions
const autoAttachInProgress = new BoundedSet(5); // Limit to 5 concurrent attachments
const processedUrlsInSession = new BoundedSet(100); // Limit to 100 processed URLs
let isDebuggerApiModeGloballyEnabled = false;
const DEBUGGER_MODE_STORAGE_KEY = 'debuggerApiModeEnabled';
// PERFORMANCE: Debugger session limiting to prevent browser lag
const MAX_CONCURRENT_DEBUGGER_SESSIONS = 3;
let activeDebuggerCount = 0;
const debuggerQueue = [];
function canAttachDebugger() {
return activeDebuggerCount < MAX_CONCURRENT_DEBUGGER_SESSIONS;
}
function incrementDebuggerCount() {
activeDebuggerCount++;
log.debug(`[Debugger Limit] Active sessions: ${activeDebuggerCount}/${MAX_CONCURRENT_DEBUGGER_SESSIONS}`);
}
function decrementDebuggerCount() {
activeDebuggerCount = Math.max(0, activeDebuggerCount - 1);
log.debug(`[Debugger Limit] Active sessions: ${activeDebuggerCount}/${MAX_CONCURRENT_DEBUGGER_SESSIONS}`);
processDebuggerQueue();
}
function processDebuggerQueue() {
if (debuggerQueue.length > 0 && canAttachDebugger()) {
const nextTask = debuggerQueue.shift();
if (nextTask) {
log.debug(`[Debugger Limit] Processing queued task (${debuggerQueue.length} remaining)`);
nextTask();
}
}
}
(async () => {
try {
const result = await chrome.storage.local.get([DEBUGGER_MODE_STORAGE_KEY]);
isDebuggerApiModeGloballyEnabled = result[DEBUGGER_MODE_STORAGE_KEY] || false;
} catch (error) {
log.error("Error loading initial debugger mode state:", error);
isDebuggerApiModeGloballyEnabled = false;
}
})();
// Helper: Fetch response headers via debugger network interception to reliably read X-Frame-Options/CSP
async function fetchHeadersViaDebugger(targetUrl) {
let tabId = null;
let attached = false;
let headers = {};
let status = 0;
let reason = '';
let finalUrl = targetUrl; // Track final URL after redirects
let redirectChain = []; // Track redirect chain
try {
const tab = await chrome.tabs.create({ url: targetUrl, active: false });
tabId = tab.id;
await chrome.debugger.attach({ tabId }, '1.3');
attached = true;
await chrome.debugger.sendCommand({ tabId }, 'Network.enable');
await chrome.debugger.sendCommand({ tabId }, 'Page.enable');
let resolveOnce;
const done = new Promise(res => { resolveOnce = res; });
const onEvent = (src, method, params) => {
if (src.tabId !== tabId) return;
// Track redirects by monitoring request chains
if (method === 'Network.requestWillBeSent' && params?.type === 'Document') {
const request = params.request || {};
const requestUrl = request.url;
const redirectResponse = params.redirectResponse;
if (redirectResponse && redirectResponse.status >= 300 && redirectResponse.status < 400) {
// This is a redirect!
try {
const location = redirectResponse.headers?.Location || redirectResponse.headers?.location;
redirectChain.push({ from: finalUrl, to: requestUrl, status: redirectResponse.status });
finalUrl = requestUrl;
log.info(`[Debugger] Redirect detected: ${redirectResponse.status} ${finalUrl} → ${requestUrl}`);
} catch (e) {
log.warn(`[Debugger] Failed to track redirect: ${e.message}`);
}
}
}
if (method === 'Network.responseReceived' && params?.type === 'Document') {
try {
const resp = params.response || {};
status = resp.status || 0;
const hs = resp.headers || {};
const map = {};
for (const k in hs) { map[k] = hs[k]; map[k.toLowerCase()] = hs[k]; }
if (status >= 200 && status < 300) {
// Final response - use these headers
headers = map;
// CRITICAL: Check if final URL differs from original (indicates redirect)
if (resp.url && resp.url !== targetUrl) {
if (redirectChain.length === 0) {
// Redirect happened but we didn't catch it in requestWillBeSent
log.warn(`[Debugger] Redirect detected via final URL: ${targetUrl} → ${resp.url}`);
redirectChain.push({ from: targetUrl, to: resp.url, status: 'unknown' });
}
finalUrl = resp.url;
}
resolveOnce();
}
} catch (_) { resolveOnce(); }
} else if (method === 'Page.loadEventFired') {
resolveOnce();
}
};
chrome.debugger.onEvent.addListener(onEvent);
// Navigate explicitly to trigger response
await chrome.debugger.sendCommand({ tabId }, 'Page.navigate', { url: targetUrl });
await Promise.race([done, new Promise(res => setTimeout(res, 6000))]);
chrome.debugger.onEvent.removeListener(onEvent);
reason = 'ok';
if (redirectChain.length > 0) {
log.info(`[Debugger] Redirect chain: ${targetUrl} → ${redirectChain.map(r => r.to).join(' → ')}`);
}
} catch (e) {
reason = e?.message || 'debugger error';
} finally {
try { if (attached && tabId) await chrome.debugger.detach({ tabId }); } catch {}
try { if (tabId) await chrome.tabs.remove(tabId); } catch {}
}
return { status, headers, reason, finalUrl, redirectChain };
}
class CircularMessageBuffer {
constructor(maxSize = 100) { this.maxSize = maxSize; this.buffer = new Array(this.maxSize); this.head = 0; this.size = 0; }
push(message) { message.messageId = message.messageId || `${message.timestamp || Date.now()}-${Math.random().toString(16).slice(2)}`; const existingIndex = this.findIndex(m => m.messageId === message.messageId); if (existingIndex !== -1) { this.buffer[existingIndex] = message; } else { this.buffer[this.head] = message; this.head = (this.head + 1) % this.maxSize; if (this.size < this.maxSize) { this.size++; } } }
findIndex(predicate) { for (let i = 0; i < this.size; i++) { const index = (this.head - this.size + i + this.maxSize) % this.maxSize; if (this.buffer[index] !== undefined && predicate(this.buffer[index])) { return index; } } return -1; }
getMessages() { const messages = []; for (let i = 0; i < this.size; i++) { const index = (this.head - this.size + i + this.maxSize) % this.maxSize; if (this.buffer[index] !== undefined) { messages.push(this.buffer[index]); } } return messages; }
clear() { this.buffer = new Array(this.maxSize); this.head = 0; this.size = 0; }
}
messageBuffer = new CircularMessageBuffer(100);
// Deep JSON sanitizer: caps total keys across nested structure and array lengths (defense-in-depth)
// CRITICAL: Does NOT add any markers to the output - clean truncation only
function sanitizeJsonDeep(value, options = {}) {
const maxKeysTotal = typeof options.maxKeysTotal === 'number' ? options.maxKeysTotal : 50;
const maxArrayLength = typeof options.maxArrayLength === 'number' ? options.maxArrayLength : 50;
const maxDepth = typeof options.maxDepth === 'number' ? options.maxDepth : 8;
let remainingKeys = maxKeysTotal;
function walk(val, depth) {
if (depth > maxDepth) return '[truncated: max depth]';
if (!val || typeof val !== 'object') return val;
if (Array.isArray(val)) {
const out = [];
const len = Math.min(val.length, maxArrayLength);
for (let i = 0; i < len; i++) {
if (remainingKeys <= 0) break;
out.push(walk(val[i], depth + 1));
}
// Silent truncation - no marker objects added
return out;
}
const out = {};
const keys = Object.keys(val);
for (let i = 0; i < keys.length; i++) {
if (remainingKeys <= 0) break;
const k = keys[i];
remainingKeys--;
out[k] = walk(val[k], depth + 1);
}
// Silent truncation - no marker keys added
return out;
}
return walk(value, 0);
}
function normalizeEndpointUrl(url) { try { if (!url || typeof url !== 'string' || ['access-denied-or-invalid', 'unknown-origin', 'null'].includes(url)) { return { normalized: url, components: null }; } let absoluteUrlStr = url; if (!url.includes('://') && !url.startsWith('//')) { absoluteUrlStr = 'https:' + url; } else if (url.startsWith('//')) { absoluteUrlStr = 'https:' + url; } const urlObj = new URL(absoluteUrlStr); if (['about:', 'chrome:', 'moz-extension:', 'chrome-extension:', 'blob:', 'data:'].includes(urlObj.protocol)) { const normalized = url; return { normalized: normalized, components: { origin: urlObj.origin, path: urlObj.pathname, query: urlObj.search, hash: urlObj.hash } }; } const normalized = urlObj.origin + urlObj.pathname + urlObj.search; return { normalized: normalized, components: { origin: urlObj.origin, path: urlObj.pathname, query: urlObj.search, hash: urlObj.hash } }; } catch (e) { return { normalized: url, components: null }; } }
function addFrameConnection(origin, destinationUrl) { let addedNew = false; try { const normalizedOrigin = normalizeEndpointUrl(origin)?.normalized; const normalizedDestination = normalizeEndpointUrl(destinationUrl)?.normalized; if (!normalizedOrigin || !normalizedDestination || normalizedOrigin === 'null' || normalizedDestination === 'null' || normalizedOrigin === 'access-denied-or-invalid' || normalizedDestination === 'access-denied-or-invalid' || normalizedOrigin === normalizedDestination ) { return false; } if (!frameConnections.has(normalizedOrigin)) { frameConnections.set(normalizedOrigin, new Set()); addedNew = true; } const destSet = frameConnections.get(normalizedOrigin); if (!destSet.has(normalizedDestination)) { destSet.add(normalizedDestination); addedNew = true; } } catch (e) {} return addedNew; }
async function isDashboardOpen() { try { const dashboardUrl = chrome.runtime.getURL("dashboard/dashboard.html"); const tabs = await chrome.tabs.query({ url: dashboardUrl }); return tabs.length > 0; } catch (e) { return false; } }
async function notifyDashboard(type, payload) { if (!(await isDashboardOpen())) return; try { let serializablePayload; try { JSON.stringify(payload); serializablePayload = payload; } catch (e) { if (payload instanceof Map) serializablePayload = Object.fromEntries(payload); else if (payload instanceof Set) serializablePayload = Array.from(payload); else serializablePayload = { error: "Payload not serializable", type: payload?.constructor?.name }; } if (chrome?.runtime?.id) { await chrome.runtime.sendMessage({ type: type, payload: serializablePayload }); } } catch (error) { if (!error.message?.includes("Receiving end does not exist") && !error.message?.includes("Could not establish connection")) {} } }
/**
* RELIABILITY FIX: Inject DOM agent with retry logic
* Handles transient failures like "Frame with ID 0 was removed"
*/
async function injectDOMAgent(tabId, frameId = 0, maxRetries = 3) {
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
const results = await chrome.scripting.executeScript({
target: { tabId: tabId, frameIds: [frameId] },
files: ['dom_injection_agent.js'],
world: 'MAIN'
});
if (results?.[0]?.error) {
throw new Error(results[0].error);
}
if (attempt > 1) {
log.info(`[DOM Agent] Successfully injected into tab ${tabId}, frame ${frameId} (attempt ${attempt}/${maxRetries})`);
} else {
log.info(`[DOM Agent] Successfully injected into tab ${tabId}, frame ${frameId}`);
}
return true;
} catch (error) {
const isLastAttempt = (attempt === maxRetries);
const isTransientError = error.message?.includes('Frame with ID') ||
error.message?.includes('was removed') ||
error.message?.includes('No frame with id');
if (!isLastAttempt && isTransientError) {
// Retry with exponential backoff for transient errors
const delay = Math.min(50 * Math.pow(2, attempt - 1), 500); // 50ms, 100ms, 200ms (max 500ms)
log.warn(`[DOM Agent] Transient injection error (attempt ${attempt}/${maxRetries}), retrying in ${delay}ms: ${error.message}`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
// Log error and fail
if (isLastAttempt) {
log.error(`[DOM Agent] All ${maxRetries} injection attempts failed for tab ${tabId}, frame ${frameId}:`, error.message);
} else {
log.error(`[DOM Agent] Non-transient injection error:`, error.message);
}
return false;
}
}
}
return false;
}
function agentFunctionToInject() { const AGENT_VERSION = 'v11_postMsg_inline'; const agentFlag = `__frogPostAgentInjected_${AGENT_VERSION}`; if (window[agentFlag]) return { success: true, alreadyInjected: true, message: `Agent ${AGENT_VERSION} already present.` }; window[agentFlag] = true; let errors = []; const MAX_LISTENER_CODE_LENGTH = 15000; const originalWindowAddEventListener = window.addEventListener; const capturedListenerSources = new Set(); const safeToString = (func) => { try { return func.toString(); } catch (e) { return `[Error converting function: ${e?.message}]`; } }; const sendListenerToForwarder = (listenerCode, contextInfo, destinationUrl) => { try { const codeStr = typeof listenerCode === 'string' ? listenerCode : safeToString(listenerCode); if (!codeStr || codeStr.includes('[native code]') || codeStr.length < 25) { return; } const fingerprint = codeStr.replace(/\s+/g, '').substring(0, 250); if (capturedListenerSources.has(fingerprint)) { return; } capturedListenerSources.add(fingerprint); let stack = ''; try { throw new Error('CaptureStack'); } catch (e) { stack = e.stack || ''; } const payload = { listenerCode: codeStr.substring(0, MAX_LISTENER_CODE_LENGTH), stackTrace: stack, destinationUrl: destinationUrl || window.location.href, context: contextInfo }; window.postMessage({ type: 'frogPostAgent->ForwardToBackground', payload: payload }, window.location.origin || '*'); } catch (e) { errors.push(`sendListener Error (${contextInfo}): ${e.message}`); } }; try { window.addEventListener = function (type, listener, options) { if (type === 'message' && typeof listener === 'function') { sendListenerToForwarder(listener, 'window.addEventListener', window.location.href); } return originalWindowAddEventListener.apply(this, arguments); }; } catch (e) { errors.push(`addEventListener hook failed: ${e.message}`); window.addEventListener = originalWindowAddEventListener; } try { if (window.EventTarget && window.EventTarget.prototype) { const originalProtoAddEventListener = window.EventTarget.prototype.addEventListener; window.EventTarget.prototype.addEventListener = function(type, listener, options) { try { const isWindowLike = this === window || this === self || (typeof Window !== 'undefined' && this instanceof Window); const isMessagePort = typeof MessagePort !== 'undefined' && this instanceof MessagePort; if ((isWindowLike || isMessagePort) && type === 'message' && typeof listener === 'function') { sendListenerToForwarder(listener, isMessagePort ? 'EventTarget(MessagePort).addEventListener' : 'EventTarget(Window).addEventListener', window.location.href); } } catch(e) { errors.push(`EventTarget.prototype.addEventListener hook inner failed: ${e.message}`); } return originalProtoAddEventListener.apply(this, arguments); }; } } catch(e) { errors.push(`EventTarget.prototype.addEventListener hook failed: ${e.message}`); }
let _currentWindowOnmessage = window.onmessage; try { Object.defineProperty(window, 'onmessage', { set: function (listener) { _currentWindowOnmessage = listener; if (typeof listener === 'function') { sendListenerToForwarder(listener, 'window.onmessage_set', window.location.href); } }, get: function () { return _currentWindowOnmessage; }, configurable: true, enumerable: true }); if (typeof _currentWindowOnmessage === 'function') { sendListenerToForwarder(_currentWindowOnmessage, 'window.onmessage_initial', window.location.href); } } catch (e) { errors.push(`onmessage hook failed: ${e.message}`); } try { const originalPortAddEventListener = MessagePort.prototype.addEventListener; MessagePort.prototype.addEventListener = function (type, listener, options) { try { if (type === 'message' && typeof listener === 'function') { sendListenerToForwarder(listener, 'port.addEventListener', window.location.href); } } catch(e) { errors.push(`port.addEventListener inner: ${e.message}`); } return originalPortAddEventListener.apply(this, arguments); }; const portOnMessageDescriptor = Object.getOwnPropertyDescriptor(MessagePort.prototype, 'onmessage'); const originalPortSetter = portOnMessageDescriptor?.set; const originalPortGetter = portOnMessageDescriptor?.get; const portOnmessageTracker = new WeakMap(); Object.defineProperty(MessagePort.prototype, 'onmessage', { set: function(listener) { try { portOnmessageTracker.set(this, listener); if (typeof listener === 'function') { sendListenerToForwarder(listener, 'port.onmessage_set', window.location.href); } if (originalPortSetter) originalPortSetter.call(this, listener); } catch(e) { errors.push(`port.onmessage set inner: ${e.message}`); } }, get: function() { try { let value = portOnmessageTracker.get(this); if (value === undefined && originalPortGetter) value = originalPortGetter.call(this); return value; } catch(e) { errors.push(`port.onmessage get inner: ${e.message}`); return undefined; } }, configurable: true, enumerable: true }); } catch (e) { errors.push(`MessagePort hook failed: ${e.message}`); } return { success: errors.length === 0, alreadyInjected: false, errors: errors, logsAdded: true }; }
async function loadHandlerEndpoints() { try { const result = await chrome.storage.session.get([HANDLER_ENDPOINT_KEYS_STORAGE_KEY]); if (result[HANDLER_ENDPOINT_KEYS_STORAGE_KEY]) { endpointsWithDetectedHandlers = new Set(result[HANDLER_ENDPOINT_KEYS_STORAGE_KEY]); } else { endpointsWithDetectedHandlers = new Set(); } } catch (e) { endpointsWithDetectedHandlers = new Set(); } }
async function saveHandlerEndpoints() {
try {
const data = { [HANDLER_ENDPOINT_KEYS_STORAGE_KEY]: Array.from(endpointsWithDetectedHandlers) };
// Use batched storage - will flush within 100ms or when queue is full
// This reduces I/O overhead while still maintaining reasonable freshness
storageBatcher.set(data);
} catch (e) {}
}
function disconnectNativeHost() { if (nativePort) { nativePort.disconnect(); nativePort = null; } }
async function detachDebugger(debuggee) { const sessionKey = `${debuggee.tabId}:${debuggee.frameId || 0}`; if (activeDebugSessions.has(sessionKey)) { try { await new Promise((resolve, reject) => { chrome.debugger.detach(debuggee, () => { if (chrome.runtime.lastError) reject(chrome.runtime.lastError); else resolve(); }); }); log.debug(`Debugger detached from ${sessionKey}`); } catch (error) { log.warn(`Error detaching debugger from ${sessionKey}:`, error.message); } finally { activeDebugSessions.delete(sessionKey); } } }
async function analyzeHandlerDynamically(details, sendResponse) { const { targetTabId, targetFrameId = 0, handlerSnippet, pointsOfInterest = [] } = details; if (!targetTabId) { sendResponse({ success: false, error: "Missing targetTabId" }); return; } const debuggee = { tabId: targetTabId }; if (targetFrameId !== 0) { debuggee.frameId = targetFrameId; } const sessionKey = `${debuggee.tabId}:${debuggee.frameId || 0}`; if (activeDebugSessions.has(sessionKey)) { sendResponse({ success: false, error: "Debugger session already active for this target" }); return; } let results = { variableStates: {}, errors: [] }; let breakpointId = null; try { await new Promise((resolve, reject) => { chrome.debugger.attach(debuggee, "1.3", () => { if (chrome.runtime.lastError) reject(new Error(`Attach failed: ${chrome.runtime.lastError.message}`)); else resolve(); }); }); activeDebugSessions.set(sessionKey, { target: debuggee, status: 'attached' }); log.debug(`Debugger attached to ${sessionKey}`); await new Promise((resolve, reject) => { chrome.debugger.sendCommand(debuggee, "Debugger.enable", {}, () => { if (chrome.runtime.lastError) reject(new Error(`Debugger.enable failed: ${chrome.runtime.lastError.message}`)); else resolve(); }); }); const scriptSource = await new Promise((resolve, reject) => { chrome.debugger.sendCommand(debuggee, "Debugger.getScriptSource", { scriptId: "SOME_SCRIPT_ID_PLACEHOLDER" }, (result) => { if (chrome.runtime.lastError) reject(new Error(`getScriptSource failed: ${chrome.runtime.lastError.message}`)); else resolve(result?.scriptSource); }); }); const location = { scriptId: "SOME_SCRIPT_ID_PLACEHOLDER", lineNumber: 0, columnNumber: 0 }; breakpointId = await new Promise((resolve, reject) => { chrome.debugger.sendCommand(debuggee, "Debugger.setBreakpoint", { location: location }, (result) => { if (chrome.runtime.lastError) reject(new Error(`setBreakpoint failed: ${chrome.runtime.lastError.message}`)); else resolve(result?.breakpointId); }); }); if (!breakpointId) throw new Error("Failed to set breakpoint."); log.debug(`Breakpoint set for ${sessionKey} at simplified location`); const eventListener = (source, method, params) => { if (source.tabId === debuggee.tabId && (!debuggee.frameId || source.frameId === debuggee.frameId)) { if (method === "Debugger.paused" && params.hitBreakpoints?.includes(breakpointId)) { log.debug(`Breakpoint hit for ${sessionKey}`); const callFrameId = params.callFrames[0].callFrameId; Promise.all(pointsOfInterest.map(varName => new Promise((resolve) => { chrome.debugger.sendCommand(debuggee, "Debugger.evaluateOnCallFrame", { callFrameId: callFrameId, expression: varName, objectGroup: "tempInspect", returnByValue: false, generatePreview: true }, (evalResult) => { if (chrome.runtime.lastError) { results.errors.push(`Eval error for ${varName}: ${chrome.runtime.lastError.message}`); resolve(); } else { results.variableStates[varName] = evalResult?.result; resolve(); } }); }))).then(async () => { chrome.debugger.sendCommand(debuggee, "Debugger.resume", {}, () => { if (chrome.runtime.lastError) log.warn(`Resume failed: ${chrome.runtime.lastError.message}`); }); await new Promise(resolve => setTimeout(resolve, 500)); chrome.debugger.onEvent.removeListener(eventListener); await detachDebugger(debuggee); sendResponse({ success: true, results: results }); }).catch(async (evalErr) => { results.errors.push(`Evaluation error: ${evalErr.message}`); chrome.debugger.onEvent.removeListener(eventListener); await detachDebugger(debuggee); sendResponse({ success: false, results: results }); }); } else if (method === "Debugger.resumed") {} } }; chrome.debugger.onEvent.addListener(eventListener); log.debug(`Debugger setup complete for ${sessionKey}. Waiting for breakpoint...`); } catch (error) { log.error(`Dynamic analysis error for ${sessionKey}:`, error); results.errors.push(error.message); if (breakpointId) { try { await new Promise(r => chrome.debugger.sendCommand(debuggee, "Debugger.removeBreakpoint", { breakpointId }, r)); } catch {} } await detachDebugger(debuggee); sendResponse({ success: false, results: results }); } }
chrome.debugger.onDetach.addListener((source, reason) => { const sessionKey = `${source.tabId}:${source.frameId || 0}`; log.warn(`Debugger detached from ${sessionKey}. Reason: ${reason}`); activeDebugSessions.delete(sessionKey); });
async function handleExtensionPageLoad(tabId, targetUrl) {
const extensionOrigin = new URL(targetUrl).origin;
log.debug(`[AutoAttach] Checking extension page: ${targetUrl}`);
if (processedUrlsInSession.has(targetUrl)) { log.debug(`[AutoAttach] URL ${targetUrl} already processed in this session.`); return; }
if (autoAttachInProgress.has(tabId)) { log.debug(`[AutoAttach] Debugger attach already in progress for tab ${tabId}, skipping.`); return; }
// Check if real-time detection is active - if so, delay debugger attachment
try {
const results = await chrome.scripting.executeScript({
target: { tabId: tabId },
func: () => window.__frogPostRealTimeDetector_v1 ? true : false
});
if (results?.[0]?.result) {
log.info(`[AutoAttach] Real-time detection active for ${targetUrl}, delaying debugger attachment`);
// Delay debugger attachment by 2 seconds to let real-time detection work first
setTimeout(() => {
if (!autoAttachInProgress.has(tabId)) {
handleExtensionPageLoad(tabId, targetUrl);
}
}, 2000);
return;
}
} catch (error) {
log.debug("Could not check real-time detection status:", error.message);
}
// PERFORMANCE: Queue if at debugger limit
if (!canAttachDebugger()) {
log.info(`[AutoAttach] Debugger limit reached, queuing ${targetUrl}`);
debuggerQueue.push(() => handleExtensionPageLoad(tabId, targetUrl));
return;
}
autoAttachInProgress.add(tabId);
processedUrlsInSession.add(targetUrl);
incrementDebuggerCount();
let attached = false; let extractor = null; let analysisTimeout = null;
try {
log.debug(`[AutoAttach] Attaching debugger to: ${targetUrl} (Tab ID: ${tabId})`);
await chrome.debugger.attach({ tabId: tabId }, "1.3"); attached = true; log.debug(`[AutoAttach] Attached successfully.`);
if (typeof HandlerExtractor === 'undefined') { log.warn("[AutoAttach] HandlerExtractor class not available. Cannot analyze scripts."); await chrome.debugger.detach({ tabId: tabId }); attached = false; return; }
extractor = new HandlerExtractor(); extractor.initialize(targetUrl, []);
let analysisCompleteResolve; const analysisCompletionPromise = new Promise(resolve => { analysisCompleteResolve = resolve; }); analysisTimeout = setTimeout(() => { log.warn(`[AutoAttach] Analysis timeout reached for ${targetUrl}. Detaching.`); analysisCompleteResolve(); }, 6000); // OPTIMIZED: Reduced from 12s to 6s
const onEvent = async (source, method, params) => {
if (source.tabId !== tabId) return;
if (method === 'Debugger.scriptParsed') {
const { scriptId, url } = params; const sourceUrl = url || `tab_${tabId}_script_${scriptId}`;
if (url && url.startsWith(extensionOrigin) && url.endsWith('.js') && url.length < 1500000) {
log.debug(`[AutoAttach] Relevant script parsed: ${url}`);
try {
const { scriptSource } = await chrome.debugger.sendCommand({ tabId: tabId }, "Debugger.getScriptSource", { scriptId: scriptId });
if (scriptSource) {
log.debug(`[AutoAttach] Analyzing source for ${url} (Length: ${scriptSource.length})`); const foundHandlers = extractor.analyzeScriptContent(scriptSource, url); log.debug(`[AutoAttach] Found ${foundHandlers.length} potential handlers in ${url}`);
if (foundHandlers.length > 0) {
const bestHandlerInfo = extractor.getBestHandler(foundHandlers);
if (bestHandlerInfo && bestHandlerInfo.handler) {
const endpointKey = normalizeEndpointUrl(targetUrl)?.normalized || targetUrl; log.debug(`[AutoAttach] Best handler found for ${endpointKey} from script ${url}:`, bestHandlerInfo.category);
if (!endpointsWithDetectedHandlers.has(endpointKey)) { endpointsWithDetectedHandlers.add(endpointKey); await saveHandlerEndpoints(); }
notifyDashboard("handlerCapturedForEndpoint", { endpointKey: endpointKey, handlerInfo: { category: bestHandlerInfo.category, source: bestHandlerInfo.source, functionName: bestHandlerInfo.functionName, score: bestHandlerInfo.score } });
const bestHandlerStorageKey = `best-handler-${endpointKey}`;
storageBatcher.set({ [bestHandlerStorageKey]: bestHandlerInfo });
log.debug(`[AutoAttach] Saved best handler for ${endpointKey} to storage.`);
}
}
}
} catch (e) { log.warn(`[AutoAttach] Failed to fetch/analyze source for ${scriptId} (${url}):`, e.message); }
} else { log.debug(`[AutoAttach] Skipping script (not target origin or not .js or too long): ${sourceUrl}`); }
} else if (method === 'Page.loadEventFired') { log.debug("[AutoAttach] Page load event fired. Resetting timeout."); clearTimeout(analysisTimeout); analysisTimeout = setTimeout(() => { log.warn(`[AutoAttach] Analysis timeout reached after load for ${targetUrl}. Detaching.`); analysisCompleteResolve(); }, 8000); }
};
const onDetach = (source, reason) => { if (source.tabId === tabId) { log.warn(`[AutoAttach] Detached from tab ${tabId}. Reason: ${reason}`); attached = false; try{chrome.debugger.onEvent.removeListener(onEvent);}catch(e){} try{chrome.debugger.onDetach.removeListener(onDetach);}catch(e){} clearTimeout(analysisTimeout); analysisCompleteResolve(); } };
chrome.debugger.onEvent.addListener(onEvent); chrome.debugger.onDetach.addListener(onDetach);
await Promise.all([ chrome.debugger.sendCommand({ tabId: tabId }, "Page.enable"), chrome.debugger.sendCommand({ tabId: tabId }, "Runtime.enable"), chrome.debugger.sendCommand({ tabId: tabId }, "Debugger.enable") ]); log.debug(`[AutoAttach] Domains enabled.`);
log.debug("[AutoAttach] Waiting for analysis timeout or detach..."); await analysisCompletionPromise;
} catch (err) { log.error(`[AutoAttach] Error processing extension tab ${tabId}:`, err.message);
} finally { clearTimeout(analysisTimeout); try { chrome.debugger.onEvent.removeListener(onEvent); } catch(e) {} try { chrome.debugger.onDetach.removeListener(onDetach); } catch(e) {} if (attached) { try { await chrome.debugger.detach({ tabId: tabId }); log.debug(`[AutoAttach] Detached in finally block for tab ${tabId}`); } catch (e) { log.warn(`[AutoAttach] Error detaching in finally for tab ${tabId}: ${e.message}`) } } autoAttachInProgress.delete(tabId); decrementDebuggerCount(); } // PERFORMANCE: Decrement counter to allow queued tasks
}
async function handleWebPageLoadForDebug(tabId, targetUrl) {
// Skip handler extraction tabs (check both URL parameter and storage flag)
if (targetUrl.includes('frogpost_handler_extraction=true')) {
log.debug(`[Debug Mode] Skipping handler extraction tab: ${targetUrl} (Tab ID: ${tabId})`);
return;
}
const isHandlerExtractionTab = await chrome.storage.local.get(`handler-extraction-tab-${tabId}`);
if (isHandlerExtractionTab[`handler-extraction-tab-${tabId}`]) {
log.debug(`[Debug Mode] Skipping handler extraction tab: ${targetUrl} (Tab ID: ${tabId})`);
return;
}
log.debug(`[Debug Mode] Checking web page: ${targetUrl} (Tab ID: ${tabId})`);
if (autoAttachInProgress.has(tabId)) { log.debug(`[Debug Mode] Debugger attach already in progress for tab ${tabId}, skipping web page check.`); return; }
// PERFORMANCE: Queue if at debugger limit
if (!canAttachDebugger()) {
log.info(`[Debug Mode] Debugger limit reached, queuing ${targetUrl}`);
debuggerQueue.push(() => handleWebPageLoadForDebug(tabId, targetUrl));
return;
}
autoAttachInProgress.add(tabId);
incrementDebuggerCount();
let attached = false; let extractor = null; let analysisTimeout = null;
try {
log.debug(`[Debug Mode] Attaching debugger to: ${targetUrl} (Tab ID: ${tabId})`);
await chrome.debugger.attach({ tabId: tabId }, "1.3"); attached = true; log.debug(`[Debug Mode] Attached successfully.`);
if (typeof HandlerExtractor === 'undefined') { log.warn("[Debug Mode] HandlerExtractor class not available. Cannot analyze scripts."); await chrome.debugger.detach({ tabId: tabId }); attached = false; return; }
extractor = new HandlerExtractor(); extractor.initialize(targetUrl, []);
let analysisCompleteResolve; const analysisCompletionPromise = new Promise(resolve => { analysisCompleteResolve = resolve; }); analysisTimeout = setTimeout(() => { log.warn(`[Debug Mode] Analysis timeout for ${targetUrl}. Detaching.`); analysisCompleteResolve(); }, 8000); // OPTIMIZED: Reduced from 15s to 8s
let lastScriptParsedAt = Date.now();
let idleTimer = null;
const refreshIdleTimer = () => {
lastScriptParsedAt = Date.now();
if (idleTimer) clearTimeout(idleTimer);
// Detach if idle for 8s with no new scripts
idleTimer = setTimeout(() => {
if (analysisCompleteResolve) analysisCompleteResolve();
}, 8000);
};
const tryDetach = async (tabId) => {
try {
if (attached) {
await chrome.debugger.detach({ tabId });
attached = false;
log.debug(`[Debug Mode] Auto-detached from tab ${tabId} due to idle timeout.`);
}
} catch (e) {
log.warn(`[Debug Mode] Error during auto-detach from tab ${tabId}:`, e.message);
}
};
const onEvent = async (source, method, params) => {
if (source.tabId !== tabId) return;
if (method === "Debugger.scriptParsed") refreshIdleTimer();
if (method === "Debugger.paused" && params?.reason === "EventListener") {
try {
const frame = params.callFrames?.[0];
const scriptId = frame?.location?.scriptId;
if (scriptId) {
const { scriptSource } = await chrome.debugger.sendCommand({ tabId }, "Debugger.getScriptSource", { scriptId });
const found = extractor.analyzeScriptContent(scriptSource, `paused_${scriptId}`);
if (found?.length) {
const best = extractor.getBestHandler(found);
if (best?.handler) {
const endpointKey = normalizeEndpointUrl(targetUrl)?.normalized || targetUrl;
storageBatcher.set({ [`best-handler-${endpointKey}`]: best });
notifyDashboard("handlerCaptured", { endpoint: targetUrl, bestHandler: { fn: best.functionName, score: best.score } });
}
}
}
} catch (e) { log.warn("[Debug Mode] paused handler capture error:", e?.message); }
try { await chrome.debugger.sendCommand({ tabId }, "Debugger.resume"); } catch {}
return;
}
if (method === 'Debugger.scriptParsed') {
const { scriptId, url } = params; const sourceUrl = url || `tab_${tabId}_script_${scriptId}`;
const urlStr = url || '';
const baseUrl = urlStr.split(/[?#]/)[0];
const isLikelyJs = urlStr.startsWith('blob:') || urlStr.startsWith('data:') || urlStr.startsWith('webpack-internal:') || baseUrl.endsWith('.js') || baseUrl.endsWith('.mjs') || baseUrl.endsWith('.cjs');
if (urlStr && !urlStr.startsWith('chrome-extension://') && isLikelyJs && urlStr.length < 1500000) {
log.debug(`[Debug Mode] Relevant script parsed: ${url}`);
try {
const { scriptSource } = await chrome.debugger.sendCommand({ tabId: tabId }, "Debugger.getScriptSource", { scriptId: scriptId });
if (scriptSource) {
log.debug(`[Debug Mode] Analyzing source for ${url} (Length: ${scriptSource.length})`); const foundHandlers = extractor.analyzeScriptContent(scriptSource, url); log.debug(`[Debug Mode] Found ${foundHandlers.length} potential handlers in ${url}`);
if (foundHandlers.length > 0) {
const bestHandlerInfo = extractor.getBestHandler(foundHandlers);
if (bestHandlerInfo && bestHandlerInfo.handler) {
const endpointKey = normalizeEndpointUrl(targetUrl)?.normalized || targetUrl; log.debug(`[Debug Mode] Best handler found for ${endpointKey} from script ${url}:`, bestHandlerInfo.category);
if (!endpointsWithDetectedHandlers.has(endpointKey)) { endpointsWithDetectedHandlers.add(endpointKey); await saveHandlerEndpoints(); }
notifyDashboard("handlerCapturedForEndpoint", { endpointKey: endpointKey, handlerInfo: { category: bestHandlerInfo.category, source: bestHandlerInfo.source, functionName: bestHandlerInfo.functionName, score: bestHandlerInfo.score } });
const bestHandlerStorageKey = `best-handler-${endpointKey}`;
storageBatcher.set({ [bestHandlerStorageKey]: bestHandlerInfo });
log.debug(`[Debug Mode] Saved best handler for ${endpointKey} to storage.`);
}
}
}
} catch (e) { log.warn(`[Debug Mode] Failed to fetch/analyze source for ${scriptId} (${url}):`, e.message); }
} else { log.debug(`[Debug Mode] Skipping script: ${sourceUrl}`); }
} else if (method === 'Page.loadEventFired') { log.debug("[Debug Mode] Page load event fired. Resetting timeout."); clearTimeout(analysisTimeout); analysisTimeout = setTimeout(() => { log.warn(`[Debug Mode] Analysis timeout after load for ${targetUrl}. Detaching.`); analysisCompleteResolve(); }, 5000); }
};
const onDetach = (source, reason) => { if (source.tabId === tabId) { log.warn(`[Debug Mode] Detached from tab ${tabId}. Reason: ${reason}`); attached = false; try{chrome.debugger.onEvent.removeListener(onEvent);}catch(e){} try{chrome.debugger.onDetach.removeListener(onDetach);}catch(e){} clearTimeout(analysisTimeout); analysisCompleteResolve(); } };
chrome.debugger.onEvent.addListener(onEvent); chrome.debugger.onDetach.addListener(onDetach);
await Promise.all([ chrome.debugger.sendCommand({ tabId: tabId }, "Page.enable"), chrome.debugger.sendCommand({ tabId: tabId }, "Runtime.enable"), chrome.debugger.sendCommand({ tabId: tabId }, "Debugger.enable") ]); log.debug(`[Debug Mode] Domains enabled.`);
// Workers discovery & auto-attach
await chrome.debugger.sendCommand({ tabId }, "Target.setDiscoverTargets", { discover: true });
await chrome.debugger.sendCommand({ tabId }, "Target.setAutoAttach", {
autoAttach: true, waitForDebuggerOnStart: false, flatten: true
});
// Break on message listener registration (ignore duplicate)
try {
await chrome.debugger.sendCommand({ tabId }, "DOMDebugger.setEventListenerBreakpoint", { eventName: "message" });
} catch (e) {
if (e && (e.code === -32000 || /already exists/i.test(e.message||''))) {
log.info("[Debug Mode] EventListenerBreakpoint('message') already set; continuing.");
} else {
log.warn("[Debug Mode] DOMDebugger.setEventListenerBreakpoint failed:", e?.message);
}
}
log.debug("[Debug Mode] Waiting for analysis timeout or detach..."); await analysisCompletionPromise;
} catch (err) { log.error(`[Debug Mode] Error processing web page tab ${tabId}:`, err.message);
} finally { clearTimeout(analysisTimeout); try { chrome.debugger.onEvent.removeListener(onEvent); } catch(e) {} try { chrome.debugger.onDetach.removeListener(onDetach); } catch(e) {} if (attached) { try { await chrome.debugger.detach({ tabId: tabId }); log.debug(`[Debug Mode] Detached in finally block for tab ${tabId}`); } catch (e) { log.warn(`[Debug Mode] Error detaching in finally for tab ${tabId}: ${e.message}`) } } autoAttachInProgress.delete(tabId); decrementDebuggerCount(); } // PERFORMANCE: Decrement counter to allow queued tasks
}
async function fetchLatestReleaseInfo(repoOwner, repoName) {
const releasesUrl = `https://github.com/${repoOwner}/${repoName}/releases/`;
if(typeof log !== 'undefined')
try {
const response = await fetch(releasesUrl, {
method: 'GET',
cache: 'no-cache'
});
if (!response.ok) {
throw new Error(`GitHub releases page request failed: ${response.status} ${response.statusText}`);
}
const htmlText = await response.text();
const regex = /href=["']\/thisis0xczar\/FrogPost\/releases\/tag\/([^"']+)["']/i;
const match = htmlText.match(regex);
let tagNameFromHtml = null;
let releaseUrl = releasesUrl;
if (match && match[1]) {
tagNameFromHtml = match[1];
try {
releaseUrl = new URL(match[0].match(/href=["'](.*?)["']/i)[1], releasesUrl).href;
} catch {} // Ignore URL construction errors
if(typeof log !== 'undefined') log.debug("BG: Found latest release tag:", tagNameFromHtml);
} else {
if(typeof log !== 'undefined') log.error("BG: Could not find the latest release tag link using regex on the releases page.");
throw new Error("Could not parse latest release tag from GitHub page HTML using regex.");
}
return {
success: true,
tagName: tagNameFromHtml,
url: releaseUrl
};
} catch (error) {
if(typeof log !== 'undefined') log.error("BG: Error fetching/parsing GitHub releases page:", error);
throw error;
}
}
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === "checkVersion") { // Use a more specific message type
const repoOwner = "thisis0xczar";
const repoName = "FrogPost";
if(typeof log !== 'undefined')
fetchLatestReleaseInfo(repoOwner, repoName)
.then(releaseInfo => {
if(typeof log !== 'undefined') log.debug("BG: Sending release info response:", releaseInfo);
sendResponse(releaseInfo);
})
.catch(error => {
if(typeof log !== 'undefined') log.error("BG: Version check failed in listener:", error);
sendResponse({ success: false, error: error.message || 'Unknown version check error' });
});
return true;
}
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab?.url) {
handleTabUpdated(tabId, changeInfo, tab);
}
});
async function handleTabUpdated(tabId, changeInfo, tab) {
if (changeInfo.status === 'complete' && tab?.url) {
try {
const result = await chrome.storage.local.get([DEBUGGER_MODE_STORAGE_KEY]);
const debuggerModeEnabled = result[DEBUGGER_MODE_STORAGE_KEY] || false;
isDebuggerApiModeGloballyEnabled = debuggerModeEnabled;
if (!debuggerModeEnabled) {
return;
}
if (tab.url.startsWith('chrome-extension://') && tab.url !== chrome.runtime.getURL("dashboard/dashboard.html")) {
handleExtensionPageLoad(tabId, tab.url);
} else if (tab.url.startsWith('http:') || tab.url.startsWith('https://')) {
handleWebPageLoadForDebug(tabId, tab.url);
}
} catch (error) {
log.error(`[onUpdated] Error checking debugger mode or processing tab ${tabId}:`, error);
}
} else if (changeInfo.status === 'loading' && tabId) {
injectedFramesAgents.delete(tabId);
detachDebugger({ tabId: tabId }).catch(()=>{});
}
}
chrome.tabs.onRemoved.addListener(tabId => { injectedFramesAgents.delete(tabId); detachDebugger({ tabId: tabId }).catch(()=>{}); });
// Also inject when tab becomes active (user switches tabs)
chrome.tabs.onActivated.addListener(async (activeInfo) => {
try {
const tab = await chrome.tabs.get(activeInfo.tabId);
if (!tab?.url) return;
if (!tab.url.startsWith('http') && !tab.url.startsWith('https')) return;
// Skip handler extraction tabs (check both URL parameter and storage flag)
if (tab.url.includes('frogpost_handler_extraction=true')) {
log.debug(`[Tab Activation] Skipping handler extraction tab: ${tab.url}`);
return;
}
const isHandlerExtractionTab = await chrome.storage.local.get(`handler-extraction-tab-${activeInfo.tabId}`);
if (isHandlerExtractionTab[`handler-extraction-tab-${activeInfo.tabId}`]) {
log.debug(`[Tab Activation] Skipping handler extraction tab: ${tab.url}`);
return;
}
await injectDOMAgent(activeInfo.tabId, 0);
} catch {}
});
chrome.webNavigation.onCommitted.addListener((details) => {
if (!details.url || details.transitionType === 'server_redirect') { return; }
handleWebNavigationCommitted(details);
});
async function handleWebNavigationCommitted(details) {
// Only inject into http/https pages
const urlStr = details?.url || '';
if (!/^https?:\/\//i.test(urlStr)) {
return;
}
// Skip handler extraction tabs (check both URL parameter and storage flag)
if (urlStr.includes('frogpost_handler_extraction=true')) {
log.debug(`[Navigation] Skipping handler extraction tab: ${urlStr}`);
return;
}
const isHandlerExtractionTab = await chrome.storage.local.get(`handler-extraction-tab-${details.tabId}`);
if (isHandlerExtractionTab[`handler-extraction-tab-${details.tabId}`]) {
log.debug(`[Navigation] Skipping handler extraction tab: ${urlStr}`);
return;
}
const tabFrames = injectedFramesAgents.get(details.tabId);
if (tabFrames?.has(details.frameId)) { return; }
// Try DOM agent injection first
const domAgentSuccess = await injectDOMAgent(details.tabId, details.frameId);
if (domAgentSuccess) {
if (!injectedFramesAgents.has(details.tabId)) {
injectedFramesAgents.set(details.tabId, new Set());
}
injectedFramesAgents.get(details.tabId).add(details.frameId);
return;
}
// Fallback to original agent injection
try {
const results = await chrome.scripting.executeScript({ target: { tabId: details.tabId, frameIds: [details.frameId] }, func: agentFunctionToInject, injectImmediately: true, world: 'MAIN' });
let injectionStatus = { success: false, alreadyInjected: false, errors: ["No result from executeScript"] };
if (results?.[0]?.result) { injectionStatus = results[0].result; } else if (results?.[0]?.error) { injectionStatus.errors = [`executeScript framework error: ${results[0].error.message || results[0].error}`]; }
if (injectionStatus.success || injectionStatus.alreadyInjected) { if (!injectedFramesAgents.has(details.tabId)) { injectedFramesAgents.set(details.tabId, new Set()); } injectedFramesAgents.get(details.tabId).add(details.frameId); }
} catch (error) {
if (!error.message?.includes("Cannot access") && !error.message?.includes("No frame with id") && !error.message?.includes("target frame detached") && !error.message?.includes("The frame was removed") && !error.message?.includes("Could not establish connection") && !error.message?.includes("No tab with id")) {}
const tf = injectedFramesAgents.get(details.tabId);
if (tf) { tf.delete(details.frameId); }
}
}
/**
* Store handler from DOM agent telemetry
* Enhanced to support both old and new telemetry formats
*/
async function storeRealTimeHandler(payload) {
try {
const location = payload.location;
if (!location) return;
// Normalize URL to match Play button expectations
const normalized = normalizeEndpointUrl(location);
const storageKey = `real-time-handlers-${normalized?.normalized || location}`;
const existingResult = await chrome.storage.local.get(storageKey);
const existingHandlers = existingResult[storageKey] || [];
// Add new handler if not already present
const handlerExists = existingHandlers.some(h => h.id === payload.id);
if (!handlerExists) {
existingHandlers.push(payload);
// Keep only last 10 handlers per URL
if (existingHandlers.length > 10) {
existingHandlers.splice(0, existingHandlers.length - 10);
}
// Use batched storage (non-critical)
storageBatcher.set({ [storageKey]: existingHandlers });
// Mark endpoint as having detected handlers
if (normalized?.normalized) {
endpointsWithDetectedHandlers.add(normalized.normalized);
await saveHandlerEndpoints(); // Immediate flush for tracking
}
}
} catch (error) {
log.error("Error in storeRealTimeHandler:", error);
}