-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathoffscreen-engine.js
More file actions
1643 lines (1459 loc) · 61.1 KB
/
Copy pathoffscreen-engine.js
File metadata and controls
1643 lines (1459 loc) · 61.1 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
/**
* DeTracker Hybrid Engine - Offscreen Script
* Ejecuta el EKF (Filtro Gaussiano de Comportamiento HMM) acelerado por WASM.
* Persistencia de aprendizaje y lógica predictiva v2 (umbral dinámico + histéresis).
*/
let wasmExports = null;
let isWasmLoaded = false;
let messageQueue = [];
let stateKeyToId = new Map();
let nextStateId = 1;
let currentSigmaThreshold = 3.0;
// ─── DedupCache (circular buffer, capacity 50) ───────────────────────────────
// NOTE: Cannot be imported from background.js in offscreen documents — copied inline.
class DedupCache {
constructor(capacity = 50) {
this._capacity = capacity;
this._buf = new Array(capacity).fill(null);
this._set = new Set();
this._ptr = 0;
}
has(msgId) { return this._set.has(msgId); }
add(msgId) {
if (this._set.has(msgId)) return;
const evicted = this._buf[this._ptr];
if (evicted !== null) this._set.delete(evicted);
this._buf[this._ptr] = msgId;
this._set.add(msgId);
this._ptr = (this._ptr + 1) % this._capacity;
}
size() { return this._set.size; }
clear() { this._buf.fill(null); this._set.clear(); this._ptr = 0; }
}
// Module-scope dedup cache for EKF message deduplication (Requirement 13.1–13.3)
const ekfDedupCache = new DedupCache(50);
// Helper: detect "Receiving end does not exist" Chrome runtime errors
function isReceivingEndError(err) {
return /Receiving end does not exist/i.test(err?.message || String(err || ''));
}
// Configuración Global de Logs (Apaga la consola en Producción)
if (typeof ErrorManager !== 'undefined') {
ErrorManager.silenceConsoleInProduction();
}
// Tell background when offscreen is ready to receive messages.
// Retry up to 3 attempts if SW is not yet alive (Requirement 9.3).
const OFFSCREEN_BUILD_ID = '2026-05-08-audio-storageget-2';
(async function sendOffscreenReady() {
const MAX_ATTEMPTS = 3;
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
try {
await chrome.runtime.sendMessage({ action: 'OFFSCREEN_READY', buildId: OFFSCREEN_BUILD_ID });
return; // success
} catch (err) {
if (isReceivingEndError(err) && attempt < MAX_ATTEMPTS) {
console.log(`[DeTracker EKF] OFFSCREEN_READY attempt ${attempt} failed (SW not ready), retrying in 500ms…`);
await new Promise(resolve => setTimeout(resolve, 500));
} else {
// Non-retryable error or last attempt — give up silently
return;
}
}
}
})();
// Audio settings are pushed from the service worker (preferred in MV3 offscreen).
let _audioState = { audioVolume: 0.15, muteSounds: false };
let _audioUnlocked = false;
try {
chrome.runtime.onMessage.addListener((message) => {
if (message?.action === 'AUDIO_STATE_UPDATE') {
if (typeof message.audioVolume !== 'undefined') _audioState.audioVolume = message.audioVolume;
if (typeof message.muteSounds !== 'undefined') _audioState.muteSounds = !!message.muteSounds;
return;
}
if (message?.action === 'AUDIO_UNLOCK') {
AudioEngine.unlock().catch(() => { });
return;
}
});
} catch (e) { }
const LEARNING_VERSION = 1;
const LEARNING_STORAGE_KEY = 'sbfLearningV1';
const PROMOTION_MIN_HITS = 2;
const PROMOTION_MIN_SCORE = 0.75;
const hysteresisState = new Map(); // stateKey -> { suspectCount, confirmedCount, lastSeen, signals: Set }
const quarantine = new Map(); // signature -> { hits, maxScore, lastSeen, signals: Set }
// ─── DFA ─────────────────────────────────────────────────────────────────────
// ─── Bloom Filter (Fast-Path Probabilístico) ──────────────────────────────
class BloomFilter {
constructor(size = 1024) {
this.size = size;
this.bits = new Uint8Array(size / 8);
}
_hash(str, seed) {
let h = seed;
for (let i = 0; i < str.length; i++) {
h = (h << 5) - h + str.charCodeAt(i);
h |= 0;
}
return Math.abs(h) % this.size;
}
add(str) {
for (let seed of [31, 71, 127]) {
const idx = this._hash(str, seed);
this.bits[idx >> 3] |= (1 << (idx & 7));
}
}
test(str) {
for (let seed of [31, 71, 127]) {
const idx = this._hash(str, seed);
if (!(this.bits[idx >> 3] & (1 << (idx & 7)))) return false;
}
return true; // Posible coincidencia
}
}
class TrackerDFA {
constructor() {
this.root = new Map();
this.signatures = new Set();
this.bloom = new BloomFilter(2048);
}
insertSignature(signature) {
if (!signature || typeof signature !== 'string') return;
const normalized = signature.toLowerCase().trim();
if (!normalized || this.signatures.has(normalized)) return;
// Añadir al Bloom Filter para el fast-path
this.bloom.add(normalized);
const parts = normalized.split('.').reverse();
let node = this.root;
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (!node.has(part)) node.set(part, new Map());
const nextNode = node.get(part);
if (i === parts.length - 1) nextNode.isTerminal = true;
node = nextNode;
}
this.signatures.add(normalized);
}
search(inputString) {
if (!inputString || typeof inputString !== 'string') return false;
const normalized = inputString.toLowerCase().trim();
// --- FAST-PATH: Bloom Filter ---
// Si no está en el Bloom, definitivamente no es un tracker confirmado.
if (!this.bloom.test(normalized)) return false;
const parts = normalized.split('.').reverse();
let node = this.root;
for (const part of parts) {
if (!node.has(part)) return false;
node = node.get(part);
if (node.isTerminal) return true;
}
return false;
}
toArray() {
return Array.from(this.signatures.values());
}
}
const dfa = new TrackerDFA();
[
'google-analytics.com',
'pixel.facebook.com',
'doubleclick.net',
'egotisticexcavateplywood.com',
'adscore.com',
'counter.yadro.ru',
'videocdnmetrika67.com',
'videocdnmetrika72.com',
'yt-web-embedded-player.appspot.com'
].forEach(s => dfa.insertSignature(s));
// ─── EKF JS Fallback (Modelo HMM 3D) ─────────────────────────────────────────
class JsKalmanState {
constructor() {
this.x0 = 0.05; this.x1 = 0.05; this.x2 = 0.05;
this.p00 = 1.0; this.p11 = 1.0; this.p22 = 1.0;
this.mean0 = 0.1; this.mean1 = 0.1; this.mean2 = 0.1;
this.var0 = 0.1; this.var1 = 0.1; this.var2 = 0.1;
}
}
const jsStates = new Map();
function jsUpdateEKF(domainId, z0, z1, z2) {
if (!jsStates.has(domainId)) jsStates.set(domainId, new JsKalmanState());
const state = jsStates.get(domainId);
// 1. PREDICCIÓN
let pred_x0 = state.x0 * 0.9 + state.x1 * 0.1;
let pred_x1 = state.x1 * 0.8 + state.x2 * 0.2;
let pred_x2 = state.x2 * 0.9;
let p00 = state.p00 + 0.01;
let p11 = state.p11 + 0.01;
let p22 = state.p22 + 0.01;
// 2. INNOVACIÓN
let y0 = z0 - pred_x0;
let y1 = z1 - pred_x1;
let y2 = z2 - pred_x2;
// 3. GANANCIA
let k0 = p00 / (p00 + 0.1);
let k1 = p11 / (p11 + 0.1);
let k2 = p22 / (p22 + 0.1);
// 4. ACTUALIZACIÓN
state.x0 = pred_x0 + k0 * y0;
state.x1 = pred_x1 + k1 * y1;
state.x2 = pred_x2 + k2 * y2;
state.p00 = (1.0 - k0) * p00;
state.p11 = (1.0 - k1) * p11;
state.p22 = (1.0 - k2) * p22;
// 5. ANOMALÍA
let std0 = Math.sqrt(state.var0); if (std0 < 0.001) std0 = 0.001;
let std1 = Math.sqrt(state.var1); if (std1 < 0.001) std1 = 0.001;
let std2 = Math.sqrt(state.var2); if (std2 < 0.001) std2 = 0.001;
let zScore0 = Math.abs(state.x0 - state.mean0) / std0;
let zScore1 = Math.abs(state.x1 - state.mean1) / std1;
let zScore2 = Math.abs(state.x2 - state.mean2) / std2;
let maxZScore = Math.max(zScore0, zScore1, zScore2);
// 6. APRENDIZAJE
if (maxZScore <= 3.0) {
state.mean0 = state.mean0 * 0.9 + state.x0 * 0.1;
state.mean1 = state.mean1 * 0.9 + state.x1 * 0.1;
state.mean2 = state.mean2 * 0.9 + state.x2 * 0.1;
state.var0 = state.var0 * 0.9 + Math.abs(y0) * 0.1;
state.var1 = state.var1 * 0.9 + Math.abs(y1) * 0.1;
state.var2 = state.var2 * 0.9 + Math.abs(y2) * 0.1;
}
return maxZScore;
}
function jsGetStateX(domainId) {
return jsStates.has(domainId) ? jsStates.get(domainId).x0 : 0.0;
}
// ─── Inicialización ──────────────────────────────────────────────────────────
let wasmFailed = false;
WebAssembly.instantiateStreaming(fetch('ekf.wasm'), {
env: { abort: () => console.error('WASM Aborted') }
}).then(module => {
wasmExports = module.instance.exports;
isWasmLoaded = true;
console.log('[DeTracker EKF] WASM cargado e inicializado.');
messageQueue.forEach(msg => processEkfMessage(msg));
messageQueue = [];
}).catch(e => {
console.error('[DeTracker EKF] Fallo al cargar WASM. Usando fallback JS.', e);
wasmFailed = true;
// Procesar cola con el fallback
messageQueue.forEach(msg => processEkfMessage(msg));
messageQueue = [];
});
loadLearningState();
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'UPDATE_SETTINGS') {
if (message.payload.sbfStrictness === 1) currentSigmaThreshold = 4.0;
else if (message.payload.sbfStrictness === 2) currentSigmaThreshold = 3.0;
else if (message.payload.sbfStrictness === 3) currentSigmaThreshold = 2.0;
return;
}
if (message.action === 'PROCESS_EKF') {
// Dedup check: if msgId is present and already seen, discard silently (Requirement 13.1–13.3)
if (message.msgId !== undefined && message.msgId !== null) {
if (ekfDedupCache.has(message.msgId)) {
return false; // duplicate — no ACK
}
ekfDedupCache.add(message.msgId);
}
if (!isWasmLoaded && !wasmFailed) {
messageQueue.push(message);
} else {
processEkfMessage(message);
}
// Send ACK immediately after queuing/dispatching (Requirement 6.5, 9.3)
try { sendResponse({ ok: true, msgId: message.msgId }); } catch (e) { }
return true; // keep the message channel open for the async sendResponse
}
});
async function processEkfMessage(message) {
const {
type,
pageOrigin,
signalSubject,
observationVector,
rawPayload,
featureContext = {}
} = message.payload || {};
const originHost = pageOrigin || 'unknown';
let signatureToTest = (signalSubject || '').toLowerCase() || originHost;
if (rawPayload && rawPayload.includes('.')) {
try { signatureToTest = new URL(rawPayload, `https://${originHost}`).hostname.toLowerCase(); } catch (e) { }
}
// 1. Check DFA (Bloqueo inmediato por firma confirmada)
const isKnownTracker = dfa.search(signatureToTest);
if (isKnownTracker) {
const enforceHost = signatureToTest !== originHost ? signatureToTest : null;
emitResult({
pageOrigin: originHost,
enforceHost,
stateKey: signatureToTest,
innovation: 0,
zScore: 99.9,
isMalicious: true,
maliciousnessScore: 1.0,
reason: 'DFA_SIGNATURE_MATCH',
decisionState: 'CONFIRMED'
});
return;
}
// 2. Check Swarm Quarantine (Inteligencia Federada) via IndexedDB
const swarmQItem = await storageDB.getSwarmQuarantine(signatureToTest);
const isInSwarmQuarantine = !!swarmQItem;
const stateKey = signalSubject || signatureToTest || originHost;
const stateId = resolveStateId(stateKey);
const z = observationVector || [0, 0, 0];
const z0 = clamp01(z[0] || 0);
const z1 = clamp01(z[1] || 0);
const z2 = clamp01(z[2] || 0);
let zScore, maliciousnessScore;
if (isWasmLoaded) {
zScore = wasmExports.updateEKF(stateId, z0, z1, z2);
maliciousnessScore = wasmExports.getStateX(stateId);
} else {
zScore = jsUpdateEKF(stateId, z0, z1, z2);
maliciousnessScore = jsGetStateX(stateId);
}
const innovation = z0 - maliciousnessScore;
// Si es del Swarm, bajamos el umbral (somos más estrictos con sospechosos externos)
const baseThreshold = isInSwarmQuarantine ? currentSigmaThreshold - 0.5 : currentSigmaThreshold;
const dynamicThreshold = computeDynamicThreshold({
baseSigma: baseThreshold,
type,
signalSubject,
pageOrigin: originHost,
featureContext
});
const decision = applyHysteresis(stateKey, zScore, dynamicThreshold, type);
// Whitelist: Dominios que NUNCA deben ser bloqueados por comportamiento,
// ya que su funcionalidad normal es indistinguible de fingerprinting agresivo.
const WHITELISTED_DOMAINS = [
'youtube.com',
'googlevideo.com',
'google.com',
'netflix.com',
'twitch.tv',
'disneyplus.com',
'amazon.com'
];
const isWhitelisted = WHITELISTED_DOMAINS.some(d => signatureToTest.includes(d));
let isMalicious = (decision === 'CONFIRMED') && !isWhitelisted;
let reason = isMalicious ? 'GAUSSIAN_ANOMALY_WASM' : 'SAFE';
// 3. Validación de Vacuna (Efecto Swarm)
if (isInSwarmQuarantine && (isMalicious || zScore >= dynamicThreshold)) {
console.log(`[DeTracker Swarm] Vacunación exitosa para: ${signatureToTest}. Promoviendo a firma activa.`);
isMalicious = true;
reason = 'SWARM_VACCINATION_CONFIRMED';
dfa.insertSignature(signatureToTest);
// Actualizar reputación del par que aportó la firma
if (swarmQItem.peerId) {
swarm.updatePeerTrust(swarmQItem.peerId, true);
}
// Limpiar IndexedDB
storageDB._transaction('swarmQuarantine', 'readwrite', store => store.delete(signatureToTest));
persistLearningState();
} else if (isMalicious) {
updateQuarantine(signatureToTest, zScore, maliciousnessScore, type);
}
emitResult({
pageOrigin: originHost,
enforceHost: isMalicious && signatureToTest !== originHost ? signatureToTest : null,
stateKey,
innovation,
zScore,
dynamicThreshold,
isMalicious,
maliciousnessScore,
reason,
decisionState: isMalicious ? 'CONFIRMED' : decision,
signals: Array.from(hysteresisState.get(stateKey)?.signals || [])
});
}
function resolveStateId(stateKey) {
if (!stateKeyToId.has(stateKey)) stateKeyToId.set(stateKey, nextStateId++);
return stateKeyToId.get(stateKey);
}
function computeDynamicThreshold(ctx) {
let sigma = ctx.baseSigma;
const { featureContext = {} } = ctx;
const { isCrossSite = false, burstScore = 0, signalQuality = 1 } = featureContext;
if (isCrossSite) sigma -= 0.2;
sigma -= Math.min(0.3, burstScore * 0.3);
// Si no se logra atribuir signalSubject (ambiente privacy/noise), suavizamos umbral.
if (!ctx.signalSubject && ['CANVAS_ACCESS', 'CANVAS_READ', 'AUDIO_CONTEXT_CREATED', 'SCRIPT_INJECTED'].includes(ctx.type)) {
sigma -= 0.35;
}
if (signalQuality === 0) sigma -= 0.15;
if (ctx.type === 'TAB_HIJACK_ATTEMPT' || ctx.type === 'ANTI_FORENSICS_ATTEMPT') sigma = Math.min(sigma, 2.0);
return Math.max(2.0, Math.min(4.5, sigma));
}
function applyHysteresis(stateKey, zScore, threshold, signalType) {
const now = Date.now();
const current = hysteresisState.get(stateKey) || {
suspectCount: 0,
confirmedCount: 0,
lastSeen: now,
signals: new Set()
};
const elapsed = now - current.lastSeen;
current.lastSeen = now;
if (elapsed > 60_000) {
current.suspectCount = 0;
current.confirmedCount = 0;
current.signals.clear();
}
if (signalType) current.signals.add(signalType);
if (zScore >= threshold + 0.4) {
current.suspectCount += 1;
if (current.suspectCount >= 2) {
current.confirmedCount += 1;
hysteresisState.set(stateKey, current);
return 'CONFIRMED';
}
hysteresisState.set(stateKey, current);
return 'SUSPECT';
}
if (zScore >= threshold) {
current.suspectCount += 1;
hysteresisState.set(stateKey, current);
return 'SUSPECT';
}
current.suspectCount = Math.max(0, current.suspectCount - 1);
hysteresisState.set(stateKey, current);
return 'SAFE';
}
function updateQuarantine(signature, zScore, maliciousnessScore, signalType) {
if (!signature || signature === 'unknown') return;
const now = Date.now();
const current = quarantine.get(signature) || {
hits: 0,
maxScore: 0,
lastSeen: now,
signals: new Set()
};
current.hits += 1;
current.maxScore = Math.max(current.maxScore, maliciousnessScore, zScore / 10);
current.lastSeen = now;
if (signalType) current.signals.add(signalType);
quarantine.set(signature, current);
if (current.hits >= PROMOTION_MIN_HITS && current.maxScore >= PROMOTION_MIN_SCORE) {
dfa.insertSignature(signature);
quarantine.delete(signature);
persistLearningState();
}
}
function emitResult(payload) {
if (payload.isMalicious && swarm) {
swarm.poke('detection');
}
chrome.runtime.sendMessage({
action: 'EKF_RESULT',
payload
});
}
function loadLearningState() {
try {
chrome.storage.local.get([LEARNING_STORAGE_KEY], (res) => {
const saved = res[LEARNING_STORAGE_KEY];
if (!saved || saved.version !== LEARNING_VERSION) return;
const learned = Array.isArray(saved.signatures) ? saved.signatures : [];
learned.forEach(sig => dfa.insertSignature(sig));
const q = saved.quarantine || {};
Object.entries(q).forEach(([k, v]) => quarantine.set(k, v));
console.log(`[DeTracker EKF] Aprendizaje cargado: ${learned.length} firmas.`);
});
} catch (e) { }
}
function persistLearningState() {
const payload = {
version: LEARNING_VERSION,
updatedAt: Date.now(),
signatures: dfa.toArray(),
quarantine: Object.fromEntries(quarantine.entries())
};
chrome.storage.local.set({ [LEARNING_STORAGE_KEY]: payload });
}
// ─── Procedural Audio Engine ────────────────────────────────────────────────
const AudioEngine = {
_ctx: null,
_storageGet(keys) {
return new Promise((resolve) => {
try {
chrome.storage.local.get(keys, (res) => {
// Avoid throwing; callers handle missing keys.
resolve(res || {});
});
} catch (e) {
resolve({});
}
});
},
_normalizeVolume(raw) {
// Accept legacy formats:
// - 0..1 number (current)
// - 0..100 number (older percent sliders)
// - numeric strings ("0.15", "15")
let v = raw;
if (typeof v === 'string') {
const parsed = parseFloat(v);
if (!Number.isNaN(parsed)) v = parsed;
}
if (typeof v !== 'number' || Number.isNaN(v)) return 0.15;
// If it looks like a percent (e.g. 15, 50, 100), convert to 0..1.
if (v > 1) v = v / 100;
if (v < 0) return 0;
if (v > 1) return 1;
return v;
},
async _getContext() {
if (!this._ctx || this._ctx.state === 'closed') {
this._ctx = new (window.AudioContext || window.webkitAudioContext)();
}
return this._ctx;
},
async unlock() {
try {
const ctx = await this._getContext();
if (ctx.state === 'suspended') await ctx.resume();
const now = ctx.currentTime;
const osc = ctx.createOscillator();
const gain = ctx.createGain();
gain.gain.setValueAtTime(0.0001, now);
osc.frequency.setValueAtTime(440, now);
osc.connect(gain);
gain.connect(ctx.destination);
osc.start(now);
osc.stop(now + 0.01);
_audioUnlocked = true;
} catch (e) {
console.warn('[DeTracker Audio] unlock error:', e);
}
},
async _getVolume() {
try {
// Prefer service-worker-pushed state.
if (_audioState?.muteSounds) return 0;
if (typeof _audioState?.audioVolume !== 'undefined') {
return this._normalizeVolume(_audioState.audioVolume);
}
// Fallback to direct storage read.
const res = await this._storageGet(['audioVolume', 'muteSounds']);
if (!!res.muteSounds) return 0;
return this._normalizeVolume(res.audioVolume);
} catch (e) {
return 0.15;
}
},
async play(type) {
try {
const debugStorage = await this._storageGet(['audioVolume', 'muteSounds']);
const vol = await this._getVolume();
if (vol === 0) return;
const ctx = await this._getContext();
if (ctx.state !== 'running') {
// Not unlocked (or Chrome suspended it). Skip instead of playing at a misleading fixed loudness.
try {
chrome.runtime.sendMessage({
action: 'AUDIO_DEBUG',
payload: {
type,
skipped: true,
reason: 'ctx_not_running',
ctxState: ctx.state,
stateAudioVolume: _audioState?.audioVolume,
stateMuteSounds: _audioState?.muteSounds,
ts: Date.now()
}
}).catch(() => { });
} catch (e) { }
return;
}
const now = ctx.currentTime;
const osc = ctx.createOscillator();
const env = ctx.createGain();
osc.connect(env);
env.connect(ctx.destination);
// Debug: let other extension pages verify the exact volume used.
// (This is intentionally lightweight and does not throw on failure.)
try {
chrome.runtime.sendMessage({
action: 'AUDIO_DEBUG',
payload: {
type,
vol,
storageAudioVolume: debugStorage.audioVolume,
storageMuteSounds: debugStorage.muteSounds,
stateAudioVolume: _audioState?.audioVolume,
stateMuteSounds: _audioState?.muteSounds,
ctxState: ctx.state,
ts: Date.now()
}
}).catch(() => { });
} catch (e) { }
if (type === 'alert') {
osc.type = 'sawtooth';
osc.frequency.setValueAtTime(880, now);
osc.frequency.exponentialRampToValueAtTime(110, now + 0.1);
env.gain.setValueAtTime(0.8 * vol, now);
env.gain.exponentialRampToValueAtTime(0.001, now + 0.15);
osc.start(now);
osc.stop(now + 0.15);
} else if (type === 'clean') {
osc.type = 'sine';
osc.frequency.setValueAtTime(1200, now);
env.gain.setValueAtTime(0.5 * vol, now);
env.gain.exponentialRampToValueAtTime(0.001, now + 0.3);
osc.start(now);
osc.stop(now + 0.3);
} else if (type === 'hijack') {
osc.type = 'square';
osc.frequency.setValueAtTime(60, now);
osc.frequency.linearRampToValueAtTime(40, now + 0.4);
env.gain.setValueAtTime(0.9 * vol, now);
env.gain.linearRampToValueAtTime(0.001, now + 0.5);
osc.start(now);
osc.stop(now + 0.5);
}
} catch (e) {
console.warn('[DeTracker Audio] Fallo al reproducir sonido:', e);
}
}
};
// ─── Swarm P2P (WebRTC) ──────────────────────────────────────────────────────
const TRUST_LEVELS = { QUESTIONABLE: 0, NEUTRAL: 1, TRUSTED: 2 };
const DEFAULT_SWARM_SIGNALING_URLS = [
'wss://detracker.endev.us',
'wss://detracker.tribr.us',
'wss://ws.detracker.us'
];
function normalizeSwarmSignalingUrl(raw) {
let u = String(raw || '').trim();
if (!u) return null;
if (u.length > 512) return null;
if (/^https:\/\//i.test(u)) {
u = 'wss://' + u.slice(8);
} else if (/^http:\/\//i.test(u)) {
u = 'ws://' + u.slice(7);
}
if (!/^wss?:\/\//i.test(u)) return null;
try {
const parsed = new URL(u);
if (parsed.protocol !== 'wss:' && parsed.protocol !== 'ws:') return null;
return parsed.href;
} catch (e) {
return null;
}
}
class SwarmNode {
constructor() {
this.peers = new Map(); // peerId -> { pc, channel, trust: TRUST_LEVELS, hits: 0, misses: 0 }
this.isColabEnabled = false;
this.iceConfig = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] };
this.ws = null;
this.localId = null;
this.signalingUrls = [...DEFAULT_SWARM_SIGNALING_URLS];
this.currentUrlIndex = 0;
this.room = 'global';
this._reconnectAttempt = 0;
this._discoverTimer = null;
this._signalingQueue = [];
this._pingTimer = null;
this._lastPingAt = 0;
this._lastPongLogAt = new Map(); // peerId -> ts
this._lastDiscoverLogAt = 0;
this._lastPeersCount = 0;
this._mode = 'balanced'; // manual|balanced|aggressive
this._lastDiscoverNowAt = 0;
/** Evita spam de `console.info` en rachas de fallo/reintento del signaler. */
this._lastSignalerInfoLogAt = 0;
// Load persisted mode + optional custom signaling URL (see README).
try {
chrome.storage.local.get(['swarmMode', 'swarmSignalingUrl'], (res) => {
const m = res?.swarmMode;
if (m === 'manual' || m === 'balanced' || m === 'aggressive') this._mode = m;
const customUrl = normalizeSwarmSignalingUrl(res?.swarmSignalingUrl);
if (customUrl && !this.signalingUrls.includes(customUrl)) {
this.signalingUrls.unshift(customUrl);
}
});
} catch (e) { }
}
_getNextSignalingUrl() {
const url = this.signalingUrls[this.currentUrlIndex];
this.currentUrlIndex = (this.currentUrlIndex + 1) % this.signalingUrls.length;
return url;
}
_getMaxPeersForMode() {
if (this._mode === 'manual') return 1;
if (this._mode === 'aggressive') return 4;
return 2; // balanced default
}
_closePeer(peerId, reason = 'prune') {
const p = this.peers.get(peerId);
if (!p) return;
try { if (p.channel && p.channel.readyState !== 'closed') p.channel.close(); } catch (e) { }
try { if (p.pc) p.pc.close(); } catch (e) { }
this.peers.delete(peerId);
if (globalThis.__DeTrackerSwarmDebug?.peers) {
console.debug(`[DeTracker Swarm] Peer closed (${reason}): ${peerId}`);
}
}
_prunePeersToCap() {
const cap = this._getMaxPeersForMode();
if (this.peers.size <= cap) return;
const ranked = Array.from(this.peers.entries()).map(([peerId, p]) => {
const state = p.pc?.connectionState || 'new';
const stateScore = state === 'connected' ? 3 : (state === 'connecting' ? 2 : 1);
const recency = p.lastPongAt || 0;
const created = p.createdAt || 0;
return { peerId, stateScore, recency, created };
});
// Keep highest quality connections first.
ranked.sort((a, b) =>
(b.stateScore - a.stateScore) ||
(b.recency - a.recency) ||
(b.created - a.created)
);
const victims = ranked.slice(cap);
victims.forEach(v => this._closePeer(v.peerId, 'cap'));
}
_signalerInfoThrottled(message) {
const now = Date.now();
if (!globalThis.__DeTrackerSwarmDebug?.signaling && now - this._lastSignalerInfoLogAt < 12_000) return;
this._lastSignalerInfoLogAt = now;
console.info(message);
}
setColab(enabled) {
enabled = !!enabled;
if (this.isColabEnabled === enabled) return;
this.isColabEnabled = enabled;
if (enabled) {
console.log('[DeTracker Swarm] Iniciando secuencia de despegue P2P...');
// Load mode early so reconnect policy can respect it.
try {
chrome.storage.local.get(['swarmMode', 'swarmSignalingUrl'], (res) => {
const m = res?.swarmMode;
if (m === 'manual' || m === 'balanced' || m === 'aggressive') this._mode = m;
const customUrl = normalizeSwarmSignalingUrl(res?.swarmSignalingUrl);
if (customUrl && !this.signalingUrls.includes(customUrl)) {
this.signalingUrls.unshift(customUrl);
}
this.poke('init');
});
} catch (e) {
this.poke('init');
}
} else {
this.disconnectAll();
}
}
/**
* Wakes up the signaling connection if it's dormant or disconnected.
* Triggered by: Local detections (Reactive), Manual sync, or Periodic timer.
*/
poke(reason = 'pulse') {
if (!this.isColabEnabled) return;
const now = Date.now();
this._lastPokeAt = now;
if (this.ws && this.ws.readyState === WebSocket.OPEN) {
// Already online, just perform a discovery refresh if needed
if (reason === 'detection') this.discoverNow();
return;
}
if (this.ws && this.ws.readyState === WebSocket.CONNECTING) return;
// If we are here, we need to connect
this._signalerInfoThrottled(`[DeTracker Swarm] Waking up signaling channel (reason=${reason})`);
this.connectSignaling();
}
/**
* Periodically check if we should go to sleep (Approach A/B refinement).
* If no trackers detected and no active P2P traffic for 15 mins, close signaling.
*/
_checkSleep() {
if (!this.isColabEnabled || !this.ws) return;
const now = Date.now();
const idleTime = now - Math.max(this._lastPokeAt || 0, this._lastTrafficAt || 0);
// Sleep threshold: 15 minutes of inactivity (no detections, no manual pokes)
const sleepThreshold = 15 * 60 * 1000;
if (idleTime > sleepThreshold && this.peers.size === 0) {
this._signalerInfoThrottled('[DeTracker Swarm] Entering DORMANT state due to inactivity.');
this.disconnectSignalingOnly();
}
}
disconnectSignalingOnly() {
if (this.ws) {
try { this.ws.onclose = null; } catch (e) { }
this.ws.close();
this.ws = null;
}
}
connectSignaling() {
if (!this.isColabEnabled) return;
const targetUrl = this._getNextSignalingUrl();
try {
if (this.ws) {
try { this.ws.onclose = null; } catch (e) { }
try { this.ws.close(); } catch (e) { }
this.ws = null;
}
const ws = new WebSocket(targetUrl);
this.ws = ws;
ws.onopen = () => {
this._reconnectAttempt = 0;
this._lastSignalerInfoLogAt = 0;
console.log(`[DeTracker Swarm] Signaler connected (${targetUrl}). Waiting hello...`);
this._flushSignalingQueue();
};
ws.onmessage = (e) => {
let msg = null;
try { msg = JSON.parse(e.data); } catch (err) { return; }
this.handleSignalingMessage(msg);
};
ws.onclose = (evt) => {
this.ws = null;
this.localId = null;
if (!this.isColabEnabled) return;
// Manual mode: do not auto-reconnect. User can use "Discover now" (or re-enable Swarm).
if (this._mode === 'manual') {
const code = evt?.code;
const reason = evt?.reason;
this._signalerInfoThrottled(
`[DeTracker Swarm] Signaler disconnected (code=${code || 'n/a'} reason=${reason || 'n/a'}). Manual mode: not reconnecting automatically.`
);
return;
}
// Balanced mode: if we already have active P2P peers, avoid reconnect loops (battery/CPU).
const hasPeers = (this.peers?.size || 0) > 0;
if (this._mode === 'balanced' && hasPeers) {
const code = evt?.code;
const reason = evt?.reason;
this._signalerInfoThrottled(
`[DeTracker Swarm] Signaler disconnected (code=${code || 'n/a'} reason=${reason || 'n/a'}). Balanced mode + peers active: not reconnecting until Discover now.`
);
return;
}
const attempt = Math.min(10, this._reconnectAttempt++);
// Reconnect policy:
// - manual: slow reconnects to avoid battery drain
// - balanced: moderate reconnects
// - aggressive: fast reconnects
let base = 500;
let cap = 30_000;
if (this._mode === 'balanced') { base = 2_000; cap = 60_000; }
else { base = 500; cap = 15_000; }
const backoff = Math.min(cap, base * Math.pow(2, attempt)) + Math.floor(Math.random() * 250);
// Avoid mojibake in some extension consoles: keep ASCII only.
const code = evt?.code;
const reason = evt?.reason;
this._signalerInfoThrottled(
`[DeTracker Swarm] Signaler disconnected (code=${code || 'n/a'} reason=${reason || 'n/a'}). Retrying in ${backoff}ms.`
);
setTimeout(() => this.connectSignaling(), backoff);
};
ws.onerror = (err) => {
const state = ws.readyState;
const url = targetUrl;
// Silent logging for transient socket errors to avoid cluttering the browser's error log.
// We only promote to console.warn if it's a persistent failure after 5 attempts.
if (this._signalerAttempts > 5) {
console.warn(`[DeTracker Swarm] Signaler socket error (readyState=${state} url=${url})`);
} else {
this._signalerInfoThrottled(`[DeTracker Swarm] Connection attempt failed (readyState=${state} url=${url})`);
}
};
} catch (e) {
this._signalerInfoThrottled(`[DeTracker Swarm] Failed to open signaling tunnel: ${e.message}`);
}
}
handleSignalingMessage(msg) {
switch (msg.type) {
case 'hello':
this.localId = msg.clientId;
this.room = (msg.room && typeof msg.room === 'string') ? msg.room : this.room;
console.log(`[DeTracker Swarm] Ephemeral identity: ${this.localId} (room=${this.room})`);
// Join explícito (server soporta join; mantiene contrato estable)
this._sendSignaling({ type: 'join', room: this.room });
this._flushSignalingQueue();
this._loadModeAndStartLoops();
break;
case 'peer_list':
if (Array.isArray(msg.peers)) {
// High-signal only: log when count changes.
if (msg.peers.length !== this._lastPeersCount) {
this._lastPeersCount = msg.peers.length;
console.log(`[DeTracker Swarm] Peers discovered: ${msg.peers.length}`);
}
msg.peers.forEach(peerId => this._ensurePeer(peerId));