Repository navigation
Expand file tree
/
Copy pathlog.js
More file actions
1045 lines (959 loc) · 34.6 KB
/
Copy pathlog.js
File metadata and controls
1045 lines (959 loc) · 34.6 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
/* eslint-disable max-lines -- this extension page keeps viewer helpers and export handlers together */
// Probe-log viewer. Loads the full log from the service worker and renders a
// searchable table of origins; each row expands to show per-ID probe counts
// for that origin. Also handles Export / Clear.
const SW = globalThis.__static_sw_utils__;
const fmt = (n) => n.toLocaleString();
const fmtDate = (ts) => (ts ? new Date(ts).toLocaleString() : "—");
const LOG_DIAGNOSTICS = globalThis.__static_log_diagnostics__;
const SEVERITY_LEVELS = {
high: { label: "High", rank: 3 },
medium: { label: "Medium", rank: 2 },
low: { label: "Low", rank: 1 },
info: { label: "Info", rank: 0 },
};
const ADAPTIVE_REASON_INFO = {
audio: {
label: "Audio fingerprinting",
description:
"The site touched offline audio APIs that can reveal device and browser differences.",
},
canvas: {
label: "Canvas readback",
description: "The site read pixels from a canvas, a common browser fingerprinting surface.",
},
crypto: {
label: "Crypto timing or setup",
description:
"The site used Web Crypto near other collection signals, often as part of bot or device checks.",
},
dom_observer: {
label: "DOM observer",
description:
"The site watched broad page changes. Session replay and anti-bot scripts use this to reconstruct activity.",
},
environment: {
label: "Environment snapshot",
description:
"The site read device, locale, screen, storage, or time-zone details that help identify the browser.",
},
input_hooks: {
label: "Input hooks",
description:
"The site registered broad input, keyboard, pointer, or scroll listeners that can collect interaction patterns.",
},
"mutation.subtree": {
label: "Whole-page mutation watch",
description:
"A MutationObserver watched a large page subtree, which can capture page content and UI changes.",
},
navigator: {
label: "Navigator reads",
description:
"The site read browser and device properties exposed through navigator, used in fingerprinting profiles.",
},
"navigator.deviceMemory": {
label: "Device memory read",
description:
"The site read approximate device memory, a coarse hardware signal used in browser fingerprinting.",
},
network: {
label: "Network collection",
description:
"A collection endpoint was contacted near other fingerprinting or replay behavior.",
},
webgl: {
label: "WebGL fingerprinting",
description: "The site queried graphics APIs that can reveal GPU and driver characteristics.",
},
};
const ADAPTIVE_REASON_PREFIXES = [
{
prefix: "listener.",
label: (suffix) => `Global ${suffix} listener`,
description: (suffix) =>
`A page-wide ${suffix} listener was installed, which can observe user interaction timing or content changes.`,
},
{
prefix: "navigator.",
label: (suffix) => `Navigator ${suffix} read`,
description: (suffix) =>
`The site read navigator.${suffix}, a browser or device property used in fingerprinting profiles.`,
},
{
prefix: "canvas.",
label: () => "Canvas readback",
description: () =>
"The site used canvas readback APIs that can expose rendering differences between devices.",
},
{
prefix: "webgl.",
label: () => "WebGL query",
description: () => "The site queried graphics state that can identify GPU and driver behavior.",
},
{
prefix: "webgl2.",
label: () => "WebGL 2 query",
description: () => "The site queried graphics state that can identify GPU and driver behavior.",
},
{
prefix: "audio.",
label: () => "Audio fingerprinting",
description: () =>
"The site used audio APIs that can expose subtle hardware and browser differences.",
},
{
prefix: "crypto.",
label: (suffix) => `Crypto ${suffix}`,
description: (suffix) =>
`The site used crypto.${suffix} near other collection signals, often as part of bot or device checks.`,
},
{
prefix: "screen.",
label: (suffix) => `Screen ${suffix} read`,
description: (suffix) =>
`The site read screen.${suffix}, a display property that can contribute to a fingerprint.`,
},
{
prefix: "vendor:",
label: (suffix) => `${suffix} vendor signature`,
description: (suffix) =>
`Static recognized a client-side ${suffix} integration associated with anti-bot, replay, or fingerprinting workflows.`,
},
{
prefix: "global:",
label: (suffix) => `${suffix} global`,
description: (suffix) =>
`A page global named ${suffix} matched a known collector or anti-bot integration signal.`,
},
{
prefix: "config:",
label: (suffix) => `${suffix} configuration`,
description: (suffix) =>
`A configuration value named ${suffix} helped identify the local collector integration.`,
},
{
prefix: "api:",
label: (suffix) => `${suffix} API call`,
description: (suffix) =>
`A known collector API call named ${suffix} was observed in the page runtime.`,
},
{
prefix: "queue:",
label: (suffix) => `${suffix} queue call`,
description: (suffix) =>
`A queued collector command named ${suffix} was observed before the library fully loaded.`,
},
{
prefix: "script:",
label: (suffix) => `${suffix} script`,
description: (suffix) =>
`A script route or filename matched a known collector integration pattern for ${suffix}.`,
},
];
const totalProbesFor = (entry) => SW.sumCounts(entry.idCounts);
const sortedCountEntries = (counts) =>
Object.entries(counts || {}).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
const buildDriftPill = (drift) => {
const span = document.createElement("span");
span.className = `drift-pill ${drift.level || "learning"}`;
span.textContent = drift.label || "Learning";
return span;
};
const severityLevelForScore = (score) => {
if (score >= 7) return "high";
if (score >= 4) return "medium";
if (score >= 1) return "low";
return "info";
};
const addSeverityReason = (state, points, reason) => {
state.score += points;
state.reasons.push(reason);
};
const addAdaptiveSeveritySignals = (state, adaptive) => {
const scoreMax = adaptive && adaptive.scoreMax ? adaptive.scoreMax : 0;
if (scoreMax >= 9) {
addSeverityReason(state, 7, `Strong adaptive data-collection signal score ${fmt(scoreMax)}.`);
} else if (scoreMax >= 7) {
addSeverityReason(state, 4, `Adaptive signal threshold crossed with score ${fmt(scoreMax)}.`);
}
};
const addProbeSeveritySignals = (state, entry, drift) => {
const total = totalProbesFor(entry);
const unique = Object.keys(entry.idCounts || {}).length;
if (drift.level === "high") {
addSeverityReason(state, 7, "Probe behavior changed sharply from the previous baseline.");
} else if (drift.level === "changed") {
addSeverityReason(state, 4, "Probe behavior changed from the previous baseline.");
}
if (unique >= 20) {
addSeverityReason(state, 2, `${fmt(unique)} unique extension IDs were probed.`);
} else if (unique >= 5) {
addSeverityReason(state, 1, `${fmt(unique)} unique extension IDs were probed.`);
}
if (total >= 100) {
addSeverityReason(state, 2, `${fmt(total)} total extension probes were recorded.`);
} else if (total > 0) {
addSeverityReason(
state,
1,
`${fmt(total)} total extension probe${total === 1 ? "" : "s"} recorded.`
);
}
};
const addDiagnosticSeveritySignals = (state, diagnostics) => {
const count = diagnostics && Array.isArray(diagnostics.events) ? diagnostics.events.length : 0;
if (count > 0) {
addSeverityReason(state, 1, `${fmt(count)} QA diagnostic event${count === 1 ? "" : "s"}.`);
}
};
const severityForEntry = (entry, drift) => {
const state = { score: 0, reasons: [] };
addAdaptiveSeveritySignals(state, entry.__adaptive);
addDiagnosticSeveritySignals(state, entry.__diagnostics);
addProbeSeveritySignals(state, entry, drift);
const level = severityLevelForScore(state.score);
return {
...SEVERITY_LEVELS[level],
level,
reasons:
state.reasons.length > 0
? state.reasons
: ["No elevated probe or adaptive behavior signals were recorded."],
score: state.score,
};
};
const buildSeverityPill = (severity) => {
const span = document.createElement("span");
span.className = `severity-pill ${severity.level}`;
span.textContent = severity.label;
span.title = `Severity score ${fmt(severity.score)}`;
return span;
};
const buildAdaptivePill = (adaptive) => {
if (!adaptive) return null;
const span = document.createElement("span");
span.className = "drift-pill changed";
span.textContent = "Adaptive signals";
return span;
};
const buildDiagnosticPill = (diagnostics) => {
if (!(diagnostics && Array.isArray(diagnostics.events) && diagnostics.events.length > 0)) {
return null;
}
const span = document.createElement("span");
span.className = "drift-pill low";
span.textContent = "QA diagnostics";
return span;
};
const buildReasonsDetail = (titleText, reasons) => {
const box = document.createElement("div");
box.className = "drift-detail";
const title = document.createElement("div");
title.className = "drift-detail-title";
title.textContent = titleText;
box.appendChild(title);
const list = document.createElement("ul");
list.className = "drift-reasons";
for (const reason of reasons || []) {
const li = document.createElement("li");
li.textContent = reason;
list.appendChild(li);
}
box.appendChild(list);
return box;
};
const humanizeReason = (reason) =>
String(reason || "unknown")
.replace(/[._:-]+/g, " ")
.replace(/\s+/g, " ")
.trim();
const reasonInfoFor = (reason) => {
if (ADAPTIVE_REASON_INFO[reason]) return ADAPTIVE_REASON_INFO[reason];
for (const info of ADAPTIVE_REASON_PREFIXES) {
if (reason.startsWith(info.prefix)) {
const suffix = reason.slice(info.prefix.length) || "signal";
return {
label: info.label(suffix),
description: info.description(suffix),
};
}
}
if (/^(fetch|xhr|sendBeacon):/.test(reason)) {
return {
label: "Network API call",
description:
"A network API was used near other collection signals; the suffix is a coarse request-size bucket.",
};
}
return {
label: humanizeReason(reason) || "Observed signal",
description: "This token was observed as part of the local adaptive signal bundle.",
};
};
const isDeviceSignalReason = (reason) =>
["audio", "canvas", "environment", "navigator", "webgl"].includes(reason) ||
/^(audio|canvas|screen|webgl|webgl2|navigator)\./.test(reason) ||
["date.getTimezoneOffset", "intl.resolvedOptions", "storage.estimate"].includes(reason);
const isReplaySurfaceReason = (reason) =>
["dom_observer", "input_hooks", "mutation.subtree"].includes(reason) ||
reason.startsWith("listener.");
const isNetworkReason = (reason) => reason === "network" || /^(fetch|xhr|sendBeacon):/.test(reason);
const protectionTextForReason = (reason) => {
if (isDeviceSignalReason(reason)) {
return fullData && fullData.fingerprintMode === "mask"
? "Device signal poisoning is on for this browser surface."
: "Device signal poisoning can weaken this surface without blocking the read.";
}
if (isReplaySurfaceReason(reason)) {
return "Replay poisoning can mask detected recorder listeners; generic page listeners stay unblocked for compatibility.";
}
if (isNetworkReason(reason)) {
return "Known vendor traffic is handled by rulesets; generic adaptive network blocking remains observe-only.";
}
if (reason === "crypto" || reason.startsWith("crypto.")) {
return "Crypto output stays unmodified because poisoning it would break normal site behavior.";
}
return "";
};
const buildAdaptiveReasonGuide = (reasons) => {
if (reasons.length === 0) return null;
const guide = document.createElement("div");
guide.className = "reason-guide";
const title = document.createElement("div");
title.className = "drift-detail-title";
title.textContent = "Signal guide";
guide.appendChild(title);
const list = document.createElement("dl");
list.className = "reason-list";
for (const [reason, count] of reasons.slice(0, 10)) {
const info = reasonInfoFor(reason);
const item = document.createElement("div");
item.className = "reason-item";
const term = document.createElement("dt");
term.textContent = info.label;
const token = document.createElement("span");
token.className = "reason-token";
token.textContent = reason;
term.appendChild(token);
const description = document.createElement("dd");
const protectionText = protectionTextForReason(reason);
description.textContent = `${info.description} Seen ${fmt(count)} time${
count === 1 ? "" : "s"
}.${protectionText ? ` ${protectionText}` : ""}`;
item.appendChild(term);
item.appendChild(description);
list.appendChild(item);
}
guide.appendChild(list);
return guide;
};
const buildAdaptiveDetail = (adaptive) => {
if (!adaptive) return null;
const box = document.createElement("div");
box.className = "drift-detail";
const title = document.createElement("div");
title.className = "drift-detail-title";
title.textContent = "Adaptive behavior: observe-only";
box.appendChild(title);
const list = document.createElement("ul");
list.className = "drift-reasons";
const categories = sortedCountEntries(adaptive.categories);
const endpoints = sortedCountEntries(adaptive.endpoints);
const reasons = sortedCountEntries(adaptive.reasons);
const lines = [
`Max local score: ${fmt(adaptive.scoreMax || 0)}.`,
categories.length
? `Categories observed: ${categories
.map(([category]) => category)
.slice(0, 4)
.join(", ")}.`
: "",
reasons.length
? `Top signals: ${reasons
.map(([reason, count]) => `${reason} (${fmt(count)})`)
.slice(0, 8)
.join(", ")}.`
: "",
endpoints.length
? `Top endpoint: ${endpoints[0][0]}.`
: "No endpoint was associated with the local signal.",
].filter(Boolean);
for (const line of lines) {
const li = document.createElement("li");
li.textContent = line;
list.appendChild(li);
}
box.appendChild(list);
const reasonGuide = buildAdaptiveReasonGuide(reasons);
if (reasonGuide) box.appendChild(reasonGuide);
return box;
};
const eventTime = (event) => (event && event.at ? new Date(event.at).toLocaleTimeString() : "—");
const diagnosticProbeText = (event) => {
const path = event.extensionPath ? ` ${event.extensionPath}` : "";
return `${eventTime(event)} · probe blocked · ${event.vector || "unknown"} · ${event.pathKind || "unknown"} · ${event.extensionId || "unknown"}${path}`;
};
const diagnosticReplayText = (event) =>
`${eventTime(event)} · replay detected · ${event.signal || "unknown"}`;
const diagnosticAdaptiveText = (event) => {
const reason = Array.isArray(event.reasons) && event.reasons.length ? event.reasons[0] : "";
const suffix = reason ? ` · ${reason}` : "";
return `${eventTime(event)} · adaptive signal · ${event.category || "unknown"} · score ${event.score || 0}${suffix}`;
};
const diagnosticFallbackText = (event) =>
`${eventTime(event)} · ${event.type || "event"} · ${event.action || "observed"}`;
const DIAGNOSTIC_TEXT_BUILDERS = {
adaptive: diagnosticAdaptiveText,
probe: diagnosticProbeText,
replay: diagnosticReplayText,
};
const diagnosticEventText = (event) => {
if (!event) return "Unknown diagnostic event.";
const builder = DIAGNOSTIC_TEXT_BUILDERS[event.type] || diagnosticFallbackText;
return builder(event);
};
const buildDiagnosticDetail = (diagnostics) => {
if (!(diagnostics && Array.isArray(diagnostics.events) && diagnostics.events.length > 0)) {
return null;
}
const box = document.createElement("div");
box.className = "drift-detail";
const title = document.createElement("div");
title.className = "drift-detail-title";
title.textContent = "QA diagnostics";
box.appendChild(title);
const list = document.createElement("ul");
list.className = "drift-reasons";
const totals = diagnostics.totals || {};
const totalLine = Object.entries(totals)
.sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
.map(([type, count]) => `${type} ${fmt(count)}`)
.join(", ");
const summary = document.createElement("li");
summary.textContent = totalLine
? `Captured locally: ${totalLine}.`
: `${fmt(diagnostics.events.length)} local diagnostic events captured.`;
list.appendChild(summary);
for (const event of diagnostics.events.slice(-20).reverse()) {
const li = document.createElement("li");
li.textContent = diagnosticEventText(event);
list.appendChild(li);
}
box.appendChild(list);
return box;
};
const buildIdList = (entry) => {
const box = document.createElement("div");
box.className = "id-list";
const ids = sortedCountEntries(entry.idCounts);
for (const [id, count] of ids) {
const row = document.createElement("div");
row.className = "id-entry";
const idSpan = document.createElement("span");
idSpan.textContent = id;
const cSpan = document.createElement("span");
cSpan.className = "c";
cSpan.textContent = fmt(count);
row.appendChild(idSpan);
row.appendChild(cSpan);
box.appendChild(row);
}
return box;
};
const buildOriginDetail = (entry, drift, severity, rank) => {
const box = document.createElement("div");
box.className = "id-list";
box.appendChild(
buildReasonsDetail(`Severity rank: #${fmt(rank)} (${severity.label})`, severity.reasons)
);
box.appendChild(
buildReasonsDetail(`Probe behavior: ${drift.label || "Learning"}`, drift.reasons)
);
const playbook = LOG_DIAGNOSTICS.buildPlaybookDetail(entry, SW.latestPlaybookComparison(entry));
if (playbook) box.appendChild(playbook);
box.appendChild(LOG_DIAGNOSTICS.buildNoiseReadinessDetail(entry));
const adaptive = buildAdaptiveDetail(entry.__adaptive);
if (adaptive) box.appendChild(adaptive);
const diagnostics = buildDiagnosticDetail(entry.__diagnostics);
if (diagnostics) box.appendChild(diagnostics);
const ids = buildIdList(entry);
ids.classList.add("open");
box.appendChild(ids);
return box;
};
const originMatches = (origin, entry, filter) => {
if (!filter) return true;
const f = filter.toLowerCase();
if (origin.toLowerCase().includes(f)) return true;
if (Object.keys(entry.idCounts || {}).some((id) => id.toLowerCase().includes(f))) return true;
const adaptive = entry.__adaptive || {};
const diagnostics = entry.__diagnostics || {};
if (
(diagnostics.events || []).some((event) =>
[
event.type,
event.action,
event.vector,
event.pathKind,
event.extensionId,
event.extensionPath,
event.signal,
event.category,
]
.filter(Boolean)
.some((value) => String(value).toLowerCase().includes(f))
)
) {
return true;
}
return [
...Object.keys(adaptive.categories || {}),
...Object.keys(adaptive.reasons || {}),
...Object.keys(adaptive.endpoints || {}),
].some((value) => value.toLowerCase().includes(f));
};
let fullData = null;
const rankedEntryFor = (origin, entry) => {
const drift = SW.playbookDriftForEntry(entry);
const severity = severityForEntry(entry, drift);
return { drift, entry, origin, severity };
};
const compareRankedEntries = (a, b) =>
b.severity.rank - a.severity.rank ||
b.severity.score - a.severity.score ||
totalProbesFor(b.entry) - totalProbesFor(a.entry) ||
(b.entry.lastUpdated || 0) - (a.entry.lastUpdated || 0) ||
a.origin.localeCompare(b.origin);
const originNamesForData = (data) =>
new Set([
...Object.keys(data.origins || {}),
...Object.keys(data.adaptiveSignals || {}),
...Object.keys(data.diagnostics || {}),
]);
const lastUpdatedForEntry = (entry, adaptive, diagnostic) =>
entry.lastUpdated ||
(adaptive && adaptive.lastUpdated) ||
(diagnostic && diagnostic.lastUpdated) ||
0;
const rankedEntriesForData = (data) => {
const origins = data.origins || {};
const adaptiveSignals = data.adaptiveSignals || {};
const diagnostics = data.diagnostics || {};
return [...originNamesForData(data)].map((origin) => {
const entry = origins[origin] || { idCounts: {}, lastUpdated: 0 };
const adaptive = adaptiveSignals[origin];
const diagnostic = diagnostics[origin];
return rankedEntryFor(origin, {
...entry,
lastUpdated: lastUpdatedForEntry(entry, adaptive, diagnostic),
__adaptive: adaptive,
__diagnostics: diagnostic,
});
});
};
const renderEmptyState = (content, html) => {
const empty = document.createElement("div");
empty.className = "empty-state";
empty.innerHTML = html;
content.appendChild(empty);
};
const diagnosticEventCountForLog = (diagnostics) =>
Object.values(diagnostics || {}).reduce(
(sum, entry) => sum + ((entry && entry.events && entry.events.length) || 0),
0
);
const totalProbeCountForEntries = (entries) => {
let total = 0;
for (const { entry } of entries) total += totalProbesFor(entry);
return total;
};
const renderSummary = ({
adaptiveCount,
allEntries,
cumulative,
diagnosticEventCount,
filtered,
}) => {
const grand = totalProbeCountForEntries(allEntries);
document.getElementById("summary").textContent = `${fmt(filtered.length)} of ${fmt(
allEntries.length
)} origin${allEntries.length === 1 ? "" : "s"} ranked by severity · ${fmt(
grand
)} total probes recorded · ${fmt(adaptiveCount)} adaptive origin${
adaptiveCount === 1 ? "" : "s"
} observed · ${fmt(diagnosticEventCount)} QA diagnostic event${
diagnosticEventCount === 1 ? "" : "s"
} · ${fmt(cumulative || 0)} probes blocked since install`;
};
const createLogTable = () => {
const table = document.createElement("table");
table.className = "log-table";
table.innerHTML =
"<thead><tr>" +
"<th class='num'>Rank</th>" +
"<th>Origin</th>" +
"<th>Severity</th>" +
"<th class='num'>Unique IDs</th>" +
"<th class='num'>Total probes</th>" +
"<th>Probe behavior</th>" +
"<th>Last seen</th>" +
"</tr></thead>";
const tbody = document.createElement("tbody");
table.appendChild(tbody);
return { table, tbody };
};
const appendOptionalPill = (cell, pill) => {
if (!pill) return;
cell.appendChild(document.createTextNode(" "));
cell.appendChild(pill);
};
const appendRankedEntryRow = (tbody, rankedEntry, index) => {
const { drift, entry, origin, severity } = rankedEntry;
const rank = index + 1;
const unique = Object.keys(entry.idCounts || {}).length;
const total = totalProbesFor(entry);
const tr = document.createElement("tr");
tr.className = "origin-row";
const caret = '<span class="caret">›</span> ';
tr.innerHTML =
`<td class='num rank-cell'>${fmt(rank)}</td>` +
`<td>${caret}${origin.replace(/</g, "<")}</td>` +
`<td class='severity-cell'></td>` +
`<td class='num'>${fmt(unique)}</td>` +
`<td class='num'>${fmt(total)}</td>` +
`<td class='drift-cell'></td>` +
`<td>${fmtDate(entry.lastUpdated)}</td>`;
tr.querySelector(".severity-cell").appendChild(buildSeverityPill(severity));
const driftCell = tr.querySelector(".drift-cell");
driftCell.appendChild(buildDriftPill(drift));
appendOptionalPill(driftCell, buildAdaptivePill(entry.__adaptive));
appendOptionalPill(driftCell, buildDiagnosticPill(entry.__diagnostics));
tbody.appendChild(tr);
const detailTr = document.createElement("tr");
detailTr.className = "detail-row";
const detailTd = document.createElement("td");
detailTd.colSpan = 7;
detailTr.appendChild(detailTd);
tbody.appendChild(detailTr);
tr.addEventListener("click", () => {
if (!detailTd.firstChild) {
detailTd.appendChild(buildOriginDetail(entry, drift, severity, rank));
}
const list = detailTd.firstChild;
const open = list.classList.toggle("open");
tr.classList.toggle("open", open);
});
};
const render = (filter) => {
const content = document.getElementById("content");
content.innerHTML = "";
if (!fullData) return;
const allEntries = rankedEntriesForData(fullData);
if (allEntries.length === 0) {
renderEmptyState(
content,
'<p class="big">No probes logged yet.</p>' +
"<p>Visit a site that fingerprints browser extensions " +
"(LinkedIn, X, major e-commerce) and the log will populate here.</p>"
);
document.getElementById("summary").textContent = "";
return;
}
const filtered = allEntries
.filter(({ entry, origin }) => originMatches(origin, entry, filter))
.sort(compareRankedEntries);
renderSummary({
adaptiveCount: Object.keys(fullData.adaptiveSignals || {}).length,
allEntries,
cumulative: fullData.cumulative,
diagnosticEventCount: diagnosticEventCountForLog(fullData.diagnostics),
filtered,
});
if (filtered.length === 0) {
renderEmptyState(content, '<p class="big">No matches.</p>');
return;
}
const { table, tbody } = createLogTable();
filtered.forEach((entry, index) => appendRankedEntryRow(tbody, entry, index));
content.appendChild(table);
};
const reload = async () => {
try {
fullData = await chrome.runtime.sendMessage({ type: "static_export_log" });
} catch {
fullData = null;
}
render(document.getElementById("search").value);
};
document.getElementById("search").addEventListener("input", (e) => render(e.target.value));
const bucketCount = (n) => {
if (n < 2) return null; // drop: canary filter
if (n < 6) return "2-5";
if (n < 21) return "6-20";
if (n < 101) return "21-100";
if (n < 1001) return "101-1000";
return "1000+";
};
const toHex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
const randomSalt = () => toHex(crypto.getRandomValues(new Uint8Array(16)));
const hashLabel = async (salt, value) => {
const data = new TextEncoder().encode(`${salt}|${value}`);
return toHex(new Uint8Array(await crypto.subtle.digest("SHA-256", data)));
};
// Anonymize the raw log for public sharing. Removes per-user timing signal
// (timestamps, cumulative counter), coarsens counts into log-scale buckets,
// drops single-occurrence IDs (canaries), drops origins with too few surviving
// IDs, and hashes origin/ID labels with a per-export salt that is not retained.
const buildShareableExport = async (raw) => {
const salt = randomSalt();
const out = {
schema: "static.probe-log.shareable.v1",
anonymization: "per-export salted SHA-256 labels; salt is not retained",
exportMonth: new Date().toISOString().slice(0, 7),
origins: {},
};
const originsIn = raw.origins || {};
for (const origin of Object.keys(originsIn)) {
const entry = originsIn[origin] || {};
const ids = entry.idCounts || {};
const buckets = {};
for (const [id, count] of Object.entries(ids)) {
const b = bucketCount(count);
if (b) buckets[await hashLabel(salt, `id:${id}`)] = b;
}
const surviving = Object.keys(buckets).length;
if (surviving >= 3) {
out.origins[await hashLabel(salt, `origin:${origin}`)] = { idBuckets: buckets };
}
}
return out;
};
const countEntriesForReport = (counts, limit = 8) => SW.sortedCountEntries(counts, limit);
const latestWeekForReport = (entry) => {
const weeks = entry && entry.playbook && entry.playbook.weeks;
const keys = Object.keys(weeks || {}).sort();
if (keys.length === 0) return null;
const key = keys[keys.length - 1];
const week = weeks[key] || {};
return {
pathKinds: countEntriesForReport(week.pathKindCounts),
total: week.total || 0,
vectors: countEntriesForReport(week.vectorCounts),
week: key,
};
};
const hashIdBucketsForReport = async (salt, idCounts) => {
const buckets = {};
for (const [id, count] of countEntriesForReport(idCounts, 40)) {
const bucket = bucketCount(count);
if (bucket) buckets[await hashLabel(salt, `id:${id}`)] = bucket;
}
return buckets;
};
const diagnosticTotalsFor = (events) => {
const totals = {};
for (const event of events || []) {
const type = event && event.type ? event.type : "unknown";
totals[type] = (totals[type] || 0) + 1;
}
return totals;
};
const signalKindForReport = (signal) => {
const kind = String(signal || "unknown")
.split(":")[0]
.slice(0, 48);
return /^[a-z0-9._-]+$/i.test(kind) ? kind : "signal";
};
const signalKindCountsForReport = (signals) => {
const counts = {};
for (const [signal, count] of countEntriesForReport(signals, 20)) {
const kind = signalKindForReport(signal);
counts[kind] = (counts[kind] || 0) + count;
}
return counts;
};
const issueProbeEventForReport = async (salt, event) => ({
type: "probe",
action: event.action || "blocked",
extensionIdHash: event.extensionId ? await hashLabel(salt, `id:${event.extensionId}`) : null,
extensionPath: event.extensionPath || "",
pathKind: event.pathKind || "unknown",
vector: event.vector || "unknown",
});
const issueReplayEventForReport = async (salt, event) => ({
type: "replay",
action: event.action || "detected",
signalHash: await hashLabel(salt, `signal:${event.signal || "unknown"}`),
signalKind: signalKindForReport(event.signal),
});
const issueAdaptiveEventForReport = (event) => ({
type: "adaptive",
action: event.action || "observed",
category: event.category || "unknown",
reasons: Array.isArray(event.reasons) ? event.reasons.slice(0, 8) : [],
score: event.score || 0,
});
const issueFallbackEventForReport = (event) => ({
action: event.action || "observed",
type: event.type || "unknown",
});
const ISSUE_EVENT_BUILDERS = {
adaptive: (_salt, event) => issueAdaptiveEventForReport(event),
probe: issueProbeEventForReport,
replay: issueReplayEventForReport,
};
const issueEventForReport = async (salt, event) => {
const builder = ISSUE_EVENT_BUILDERS[event.type];
return builder ? builder(salt, event) : issueFallbackEventForReport(event);
};
const issueOriginNames = ({
adaptiveSignals = {},
diagnostics = {},
origins = {},
replayDetections = {},
}) =>
[
...new Set([
...Object.keys(origins),
...Object.keys(replayDetections),
...Object.keys(adaptiveSignals),
...Object.keys(diagnostics),
]),
].sort();
const issueReportSummary = ({ adaptiveSignals, diagnostics, originNames, origins }) => ({
adaptiveOrigins: Object.keys(adaptiveSignals).length,
diagnosticEvents: diagnosticEventCountForLog(diagnostics),
origins: originNames.length,
totalProbes: Object.values(origins).reduce((sum, entry) => sum + totalProbesFor(entry), 0),
});
const issueOriginReport = async ({
adaptiveEntry,
diagnosticEntry,
events,
origin,
probeEntry,
replayEntry,
salt,
}) => {
const originReport = {
originHash: await hashLabel(salt, `origin:${origin}`),
probes: {
idBuckets: await hashIdBucketsForReport(salt, probeEntry.idCounts),
latestWeek: latestWeekForReport(probeEntry),
total: totalProbesFor(probeEntry),
uniqueIds: Object.keys(probeEntry.idCounts || {}).length,
},
replay: {
signalKinds: signalKindCountsForReport(replayEntry.signals),
total: replayEntry.total || 0,
},
adaptive: {
categories: Object.fromEntries(countEntriesForReport(adaptiveEntry.categories)),
reasons: Object.fromEntries(countEntriesForReport(adaptiveEntry.reasons)),
scoreMax: adaptiveEntry.scoreMax || 0,
total: adaptiveEntry.total || 0,
},
diagnostics: {
events: [],
totals: diagnosticEntry.totals || diagnosticTotalsFor(events),
},
};
for (const event of events) {
originReport.diagnostics.events.push(await issueEventForReport(salt, event));
}
return originReport;
};
const buildIssueReport = async (raw) => {
const salt = randomSalt();
const origins = raw.origins || {};
const replayDetections = raw.replayDetections || {};
const adaptiveSignals = raw.adaptiveSignals || {};
const diagnostics = raw.diagnostics || {};
const originNames = issueOriginNames({ adaptiveSignals, diagnostics, origins, replayDetections });
const report = {
schema: "static.issue-diagnostics.v1",
anonymization:
"per-copy salted SHA-256 labels; site origins, extension IDs, and replay signals are hashed; salt is not retained",
exportMonth: new Date().toISOString().slice(0, 7),
diagnosticsMode: !!raw.diagnosticsMode,
summary: issueReportSummary({ adaptiveSignals, diagnostics, originNames, origins }),
origins: [],
};
for (const origin of originNames) {
const probeEntry = origins[origin] || { idCounts: {} };
const replayEntry = replayDetections[origin] || {};
const adaptiveEntry = adaptiveSignals[origin] || {};
const diagnosticEntry = diagnostics[origin] || {};
const events = Array.isArray(diagnosticEntry.events) ? diagnosticEntry.events.slice(-25) : [];
report.origins.push(
await issueOriginReport({
adaptiveEntry,
diagnosticEntry,
events,
origin,
probeEntry,
replayEntry,
salt,
})
);
}
return report;
};
const downloadJson = (obj, filename) => {
const blob = new Blob([JSON.stringify(obj, null, 2)], { type: "application/json" });
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = filename;
document.body.appendChild(a);
a.click();
setTimeout(() => {
URL.revokeObjectURL(a.href);
a.remove();
}, 1000);
};
document.getElementById("export-raw").addEventListener("click", () => {
if (!fullData) return;
downloadJson(fullData, `static-probe-log-${new Date().toISOString().slice(0, 10)}.json`);
});