Repository navigation
Expand file tree
/
Copy pathapp_tracking_debugger.py
More file actions
2429 lines (2142 loc) · 110 KB
/
Copy pathapp_tracking_debugger.py
File metadata and controls
2429 lines (2142 loc) · 110 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
"""
Flashlight - mobile app tracking debugger (proxy addon)
1. Tracking hits UI - http://127.0.0.1:8082
Lists every outgoing analytics hit (GA4/Firebase, Adjust, AppsFlyer, Meta,
Mixpanel, Amplitude, Braze, ... and your own sGTM domains), one row per event,
with filters per tool.
2. GA4 decoder - the Firebase Analytics SDK sends events to app-measurement.com/a
as binary protobuf. This addon decodes them into readable events, parameters
and user properties (also as the "GA4 App Measurement" view in mitmweb).
Schema based on https://github.com/lari/firebase-ga4-app-measurement-protobuf
No dependencies, works with the official mitmproxy binaries. Requires mitmproxy 12+.
https://github.com/michalnovacek96/flashlight - by measure-apps.com, MIT license
Usage:
mitmweb -s app_tracking_debugger.py
"""
from __future__ import annotations
__version__ = "1.0.1"
import base64
import gzip
import json
import logging
import os
import re
import socket
import ssl
import struct
import threading
import time
import urllib.error
import urllib.parse
import urllib.request
import webbrowser
import zlib
from collections import deque
from datetime import datetime, timezone
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from mitmproxy import contentviews, ctx, http, tls
logger = logging.getLogger(__name__)
# Firebase Analytics endpoints (app-analytics-services-att.com = iOS with ATT)
HOST_SUFFIXES = (
"app-measurement.com",
"app-analytics-services.com",
"app-analytics-services-att.com",
)
# --------------------------------------------------------------------------
# Schema (field number -> (name, type[, sub-schema]))
# types: int, sint (signed int64), str, ts (timestamp in ms), msg, float, double
# --------------------------------------------------------------------------
EVENT_PARAM = {
1: ("name", "str"),
2: ("string_value", "str"),
3: ("int_value", "sint"),
4: ("float_value", "float"),
5: ("double_value", "double"),
}
# nested parameters (e.g. items[] in ecommerce events)
EVENT_PARAM[6] = ("nested", "msg", EVENT_PARAM)
EVENT = {
1: ("param", "msg", EVENT_PARAM),
2: ("name", "str"),
3: ("timestamp_millis", "ts"),
4: ("previous_timestamp_millis", "ts"),
}
USER_PROPERTY = {
1: ("set_timestamp_millis", "ts"),
2: ("name", "str"),
3: ("string_value", "str"),
4: ("int_value", "sint"),
5: ("float_value", "float"),
6: ("double_value", "double"),
}
BUNDLE = {
1: ("protocol_version", "int"),
2: ("event", "msg", EVENT),
3: ("user_property", "msg", USER_PROPERTY),
4: ("upload_timestamp_millis", "ts"),
5: ("start_timestamp_millis", "ts"),
6: ("end_timestamp_millis", "ts"),
7: ("previous_bundle_end_timestamp_millis", "ts"),
8: ("platform", "str"),
9: ("operating_system_version", "str"),
10: ("device_model", "str"),
11: ("user_default_language", "str"),
12: ("time_zone_offset_minutes", "sint"),
13: ("install_source", "str"),
14: ("app_id", "str"),
16: ("app_version", "str"),
17: ("gmp_version", "int"),
18: ("uploading_gmp_version", "int"),
19: ("resettable_device_id", "str"),
20: ("npa_non_personalized_ads", "str"),
21: ("app_instance_id", "str"),
22: ("dev_cert_hash", "str"),
23: ("bundle_sequential_index", "int"),
25: ("gmp_app_id", "str"),
26: ("previous_bundle_start_timestamp_millis", "ts"),
27: ("resettable_device_id_alt", "str"),
30: ("firebase_instance_id", "str"),
31: ("app_version_major", "int"),
35: ("config_version", "int"),
46: ("system_properties_dynamite_version", "str"),
52: ("gcs_google_consent_state", "str"),
71: ("consent_diagnostics", "str"),
77: ("system_properties_delivery_index", "int"),
}
BATCH = {1: ("bundle", "msg", BUNDLE)}
# app-measurement.com/config/app/<firebase app id> - measurement config the SDK downloads
CONFIG = {
1: ("config_version", "int"),
2: ("firebase_app_id", "str"),
4: ("setting", "msg", {1: ("key", "str"), 2: ("value", "str")}),
5: ("event", "msg", {1: ("name", "str"), 3: ("key_event", "int")}),
10: ("service", "msg", {1: ("name", "str"), 3: ("enabled", "int")}),
11: ("upload_region", "str"),
14: ("measurement_id", "str"),
17: ("sgtm", "msg", {1: ("url", "str"), 3: ("url_2", "str"), 4: ("percentage", "int"), 5: ("url_3", "str")}),
}
# app-analytics-services.com/skan - SKAdNetwork request sent by the Firebase SDK
SKAN_REQUEST = {
1: ("sdk_version", "int"),
2: ("app_id", "str"),
3: ("app_instance_id", "str"),
4: ("skan_version", "str"),
6: ("timestamp", "ts"),
}
# Short names used by the Firebase SDK
EVENT_NAMES = {
"_s": "session_start",
"_e": "user_engagement",
"_vs": "screen_view",
"_ab": "app_background",
"_au": "app_update",
"_f": "first_open",
"_v": "first_visit",
"_i": "app_install",
"_ui": "app_uninstall",
"_cd": "app_clear_data",
"_ou": "os_update",
"_in": "in_app_purchase",
"_ar": "ad_reward",
"_ai": "ad_impression",
"_ac": "ad_click",
"_aq": "ad_query",
"_ae": "app_exception",
"_cmp": "firebase_campaign",
"_err": "error",
"_ssr": "screen_view (ssr)",
"_nr": "notification_receive",
"_no": "notification_open",
"_nf": "notification_foreground",
"_nd": "notification_dismiss",
}
PARAM_NAMES = {
"_si": "firebase_screen_id",
"_et": "engagement_time_msec",
"_sc": "firebase_screen_class",
"_sn": "firebase_screen",
"_o": "firebase_event_origin",
"_pn": "previous_screen",
"_pc": "previous_screen_class",
"_pi": "previous_screen_id",
"_pv": "previous_app_version",
"_err": "firebase_error",
"_ev": "firebase_error_value",
"_el": "firebase_error_length",
"_r": "realtime",
"_dbg": "ga_debug",
"_c": "firebase_conversion",
"_sid": "ga_session_id",
"_sno": "ga_session_number",
"_fr": "first_run",
"_mst": "manual_screen_tracking",
"_eid": "ad_event_id",
}
USER_PROPERTY_NAMES = {
"_fi": "first_open_after_install",
"_fot": "first_open_time",
"_sid": "ga_session_id",
"_sno": "ga_session_number",
"_lte": "lifetime_user_engagement",
"_se": "session_user_engagement",
"_id": "user_id",
"_npa": "non_personalized_ads",
"_ldl": "last_deep_link_referrer",
"_lgclid": "last_gclid",
}
# --------------------------------------------------------------------------
# Protobuf wire parser
# --------------------------------------------------------------------------
class DecodeError(Exception):
pass
def _varint(buf: bytes, pos: int) -> tuple[int, int]:
result = shift = 0
while True:
if pos >= len(buf):
raise DecodeError("truncated varint")
b = buf[pos]
pos += 1
result |= (b & 0x7F) << shift
if not b & 0x80:
return result, pos
shift += 7
if shift > 70:
raise DecodeError("varint too long")
def parse_fields(buf: bytes) -> list[tuple[int, int, object]]:
"""Return [(field_no, wire_type, raw_value)]."""
out = []
pos = 0
while pos < len(buf):
key, pos = _varint(buf, pos)
field, wt = key >> 3, key & 7
if field == 0:
raise DecodeError("field 0")
if wt == 0:
val, pos = _varint(buf, pos)
elif wt == 1:
if pos + 8 > len(buf):
raise DecodeError("truncated fixed64")
val = buf[pos:pos + 8]
pos += 8
elif wt == 2:
ln, pos = _varint(buf, pos)
if pos + ln > len(buf):
raise DecodeError("truncated bytes")
val = buf[pos:pos + ln]
pos += ln
elif wt == 5:
if pos + 4 > len(buf):
raise DecodeError("truncated fixed32")
val = buf[pos:pos + 4]
pos += 4
else:
raise DecodeError(f"unsupported wire type {wt}")
out.append((field, wt, val))
return out
def _signed(v: int) -> int:
return v - (1 << 64) if v >= 1 << 63 else v
def _as_text(b: bytes) -> str | None:
try:
s = b.decode("utf-8")
except UnicodeDecodeError:
return None
if all(c.isprintable() or c in "\t\r\n" for c in s):
return s
return None
def _decode_unknown(wt: int, val):
"""Best-effort decoding for fields not in the schema."""
if wt == 0:
return _signed(val)
if wt == 1:
return f"{struct.unpack('<d', val)[0]!r} (fixed64 0x{val[::-1].hex()})"
if wt == 5:
return f"{struct.unpack('<f', val)[0]!r} (fixed32 0x{val[::-1].hex()})"
txt = _as_text(val)
if txt is not None:
return txt
try:
sub = parse_fields(val)
if sub:
out: dict = {}
for f, w, v in sub:
key, value = f"#{f}", _decode_unknown(w, v)
if key in out:
# repeated field -> list
if not isinstance(out[key], list) or not out.get("__rep_" + key):
out[key] = [out[key]]
out["__rep_" + key] = True
out[key].append(value)
else:
out[key] = value
return {k: v for k, v in out.items() if not k.startswith("__rep_")}
except DecodeError:
pass
return f"<bytes {val.hex()}>"
def decode_generic(data: bytes):
"""Schema-less protobuf decoding (field numbers as keys)."""
data = unpack_body(data)
if not data:
return None
return _decode_unknown(2, data)
def _is_protobuf(data: bytes) -> bool:
data = unpack_body(data)
if not data or _as_text(data) is not None:
return False
try:
return bool(parse_fields(data))
except DecodeError:
return False
def decode(buf: bytes, schema: dict) -> dict:
"""Decode a message using the schema -> dict {name: value | [values]}."""
msg: dict = {}
for field, wt, val in parse_fields(buf):
spec = schema.get(field)
if spec is None:
key = f"unknown_{field}"
value = _decode_unknown(wt, val)
repeated = False # becomes a list only if the field occurs more than once
else:
key, typ = spec[0], spec[1]
repeated = typ == "msg"
if typ == "msg" and wt == 2:
value = decode(val, spec[2])
elif typ == "str" and wt == 2:
value = val.decode("utf-8", "replace")
elif typ in ("int", "sint", "ts") and wt == 0:
value = _signed(val) if typ != "int" else val
if typ == "ts":
value = ("ts", value)
elif typ in ("float", "double") and wt in (1, 5):
value = struct.unpack("<d" if wt == 1 else "<f", val)[0]
else:
value = _decode_unknown(wt, val)
if repeated:
msg.setdefault(key, []).append(value)
elif key in msg:
# repeated scalar field - turn into a list
if not isinstance(msg[key], list):
msg[key] = [msg[key]]
msg[key].append(value)
else:
msg[key] = value
return msg
# --------------------------------------------------------------------------
# Rendering (YAML-like)
# --------------------------------------------------------------------------
def _scalar(v) -> str:
if isinstance(v, bool):
return "true" if v else "false"
if isinstance(v, tuple) and v and v[0] == "ts":
return _fmt_time(v[1])
if isinstance(v, float):
return f"{v:g}" if abs(v) < 1e15 else repr(v)
if isinstance(v, str):
if v == "" or v != v.strip() or "\n" in v:
return '"' + v.replace("\\", "\\\\").replace('"', '\\"').replace("\n", "\\n") + '"'
return v
return str(v)
def _fmt_time(ms: int) -> str:
try:
dt = datetime.fromtimestamp(ms / 1000, tz=timezone.utc).astimezone()
except (OverflowError, OSError, ValueError):
return str(ms)
return dt.strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
def _fmt_duration(ms: int) -> str:
sec = ms / 1000
h, rem = divmod(int(sec), 3600)
m, s = divmod(rem, 60)
if h:
txt = f"{h}h {m}m {s}s"
elif m:
txt = f"{m}m {s}s"
else:
txt = f"{sec:g}s"
return f"{txt} ({ms} ms)"
# Firebase validation error codes (_err)
FIREBASE_ERRORS = {
4: "parameter value too long",
}
DURATION_KEYS = {"engagement_time_msec", "lifetime_user_engagement", "session_user_engagement"}
BOOL_KEYS = {"first_open_after_install", "non_personalized_ads", "realtime", "ga_debug", "first_run"}
TIME_KEYS = {"first_open_time"}
def _readable(name: str, value):
"""Convert a value to a human-readable form based on the parameter name."""
if isinstance(value, (int, float)) and not isinstance(value, bool):
if name in DURATION_KEYS:
return _fmt_duration(int(value))
if name in BOOL_KEYS and value in (0, 1):
return bool(value)
if name in TIME_KEYS:
return _fmt_time(int(value))
if name == "firebase_error" and value in FIREBASE_ERRORS:
return f"{value} ({FIREBASE_ERRORS[value]})"
return value
def _raw_value(p: dict):
for k in ("string_value", "int_value", "double_value", "float_value"):
if k in p:
return p[k]
return None
def _params_to_map(params: list[dict]) -> dict:
out = {}
for p in params:
raw = p.get("name", "?")
name = PARAM_NAMES.get(raw, raw)
if "nested" in p:
# array of objects (items) - each element is a message of nested params
out[name] = [_params_to_map(n.get("nested", [])) for n in p["nested"]]
else:
out[name] = _readable(name, _raw_value(p))
return out
def _render(obj, indent: int = 0) -> list[str]:
pad = " " * indent
lines: list[str] = []
if isinstance(obj, dict):
for k, v in obj.items():
if isinstance(v, (dict, list)):
if not v:
lines.append(f"{pad}{k}: {'{}' if isinstance(v, dict) else '[]'}")
else:
lines.append(f"{pad}{k}:")
lines += _render(v, indent + 1)
else:
lines.append(f"{pad}{k}: {_scalar(v)}")
elif isinstance(obj, list):
for item in obj:
if isinstance(item, (dict, list)) and item:
sub = _render(item, indent + 1)
sub[0] = f"{pad}- {sub[0].lstrip()}"
lines += sub
else:
lines.append(f"{pad}- {_scalar(item)}")
else:
lines.append(f"{pad}{_scalar(obj)}")
return lines
def _event_name(ev: dict) -> str:
raw = ev.get("name", "?")
return EVENT_NAMES.get(raw, raw)
def _pretty_event(ev: dict) -> dict:
out: dict = {"event": _event_name(ev)}
if "timestamp_millis" in ev:
out["time"] = ev["timestamp_millis"]
out["params"] = _params_to_map(ev.get("param", []))
return out
def _pretty_user_props(props: list[dict]) -> dict:
out = {}
for p in props:
raw = p.get("name", "?")
val = _raw_value(p)
if raw.startswith("_ltv_") and isinstance(val, int):
# lifetime value in micro units of the currency
out[f"lifetime_value_{raw[5:]}"] = f"{val / 1_000_000:.2f} {raw[5:]}"
continue
name = USER_PROPERTY_NAMES.get(raw, raw)
out[name] = _readable(name, val)
return out
DEVICE_KEYS = {
"app_id": "app_id",
"app_version": "app_version",
"platform": "platform",
"operating_system_version": "os_version",
"device_model": "device_model",
"user_default_language": "language",
"install_source": "install_source",
"app_instance_id": "app_instance_id",
"resettable_device_id": "advertising_id",
"resettable_device_id_alt": "vendor_id",
"firebase_instance_id": "firebase_instance_id",
"gmp_app_id": "firebase_app_id",
"gcs_google_consent_state": "consent_state",
"npa_non_personalized_ads": "non_personalized_ads",
"gmp_version": "sdk_version",
"upload_timestamp_millis": "uploaded_at",
}
def _pretty_bundle(b: dict) -> dict:
out: dict = {"events": [_pretty_event(e) for e in b.get("event", [])]}
if "user_property" in b:
out["user_properties"] = _pretty_user_props(b["user_property"])
info: dict = {}
for key, label in DEVICE_KEYS.items():
if key in b:
info[label] = b[key]
if "time_zone_offset_minutes" in b:
off = b["time_zone_offset_minutes"]
info["timezone"] = f"UTC{'+' if off >= 0 else '-'}{abs(off) // 60:02d}:{abs(off) % 60:02d}"
out["device_app"] = info
return out
def unpack_body(data: bytes) -> bytes:
if data[:2] == b"\x1f\x8b":
return gzip.decompress(data)
if data[:1] == b"\x78":
try:
return zlib.decompress(data)
except zlib.error:
pass
return data
def decode_batch(data: bytes) -> dict:
return decode(unpack_body(data), BATCH)
def render_batch(batch: dict) -> str:
bundles = batch.get("bundle", [])
lines: list[str] = []
for i, b in enumerate(bundles):
if i:
lines.append("")
names = ", ".join(_event_name(e) for e in b.get("event", []))
lines.append(f"# {len(b.get('event', []))} event(s): {names}")
for line in _render(_pretty_bundle(b)):
# blank line before each event and each top-level section
if line.startswith(" - event:") or (line and not line.startswith(" ") and line != "events:"):
lines.append("")
lines.append(line)
return "\n".join(lines) + "\n"
# --------------------------------------------------------------------------
# Tracking tools detection
# --------------------------------------------------------------------------
# key, label, color, host suffixes, path regex (None = any path)
TOOLS = [
("skan", "Firebase SKAN", "#5e35b1", HOST_SUFFIXES, r"^/skan"),
("ga4", "GA4 (Firebase)", "#e8710a", HOST_SUFFIXES, None),
("ga4web", "GA4 (web)", "#f9ab00", ("google-analytics.com", "analytics.google.com"), r"/g/collect"),
("firebase", "Firebase", "#ffa000", (
"firebaseinstallations.googleapis.com", "firebaseremoteconfig.googleapis.com",
"firebaselogging-pa.googleapis.com", "firebasedynamiclinks.googleapis.com",
"fcmtoken.googleapis.com", "firebase-settings.crashlytics.com",
), None),
("crashlytics", "Crashlytics", "#c62828", ("crashlyticsreports-pa.googleapis.com", "crashlytics.com"), None),
("adjust", "Adjust", "#1e88e5", ("adjust.com", "adjust.net.in", "adjust.world", "adjust.io"), None),
("appsflyer", "AppsFlyer", "#2e7d32", ("appsflyer.com", "appsflyersdk.com"), None),
("meta", "Meta", "#1877f2", ("graph.facebook.com",), None),
("branch", "Branch", "#0097c7", ("branch.io",), None),
("singular", "Singular", "#7b1fa2", ("singular.net",), None),
("kochava", "Kochava", "#546e7a", ("kochava.com",), None),
("airbridge", "Airbridge", "#3949ab", ("airbridge.io",), None),
("tiktok", "TikTok", "#ee1d52", ("business-api.tiktok.com", "analytics.tiktok.com"), None),
("snap", "Snapchat", "#b8a800", ("tr.snapchat.com", "tr-shadow.snapchat.com"), None),
("googleads", "Google Ads", "#34a853", ("googleadservices.com", "googleads.g.doubleclick.net"), None),
("mixpanel", "Mixpanel", "#7856ff", ("mixpanel.com",), None),
("amplitude", "Amplitude", "#1f5fd6", ("amplitude.com",), None),
("segment", "Segment", "#3c9c78", ("segment.io", "segment.com"), None),
("braze", "Braze", "#e0457b", ("braze.com", "braze.eu", "appboy.com"), None),
("clevertap", "CleverTap", "#d81b60", ("clevertap-prod.com", "wzrkt.com"), None),
("onesignal", "OneSignal", "#e54b4d", ("onesignal.com",), None),
("appmetrica", "AppMetrica", "#c79a00", ("appmetrica.yandex.net", "appmetrica.yandex.com"), None),
("revenuecat", "RevenueCat", "#f2545b", ("revenuecat.com",), None),
("sentry", "Sentry", "#6c5fc7", ("sentry.io",), None),
("datadog", "Datadog", "#632ca6", ("datadoghq.com", "datadoghq.eu"), None),
("clarity", "Clarity", "#0078d4", ("clarity.ms",), None),
]
SGTM = ("sgtm", "sGTM", "#0b8043")
OTHER = ("other", "Other", "#8a8a8a")
# Custom (server-side GTM) domains, editable from the UI, persisted to disk
DOMAINS_FILE = os.path.join(os.path.expanduser("~"), ".mitmproxy", "tracking_custom_domains.json")
CUSTOM_DOMAINS: set[str] = set()
def _load_domains() -> None:
try:
with open(DOMAINS_FILE) as f:
CUSTOM_DOMAINS.update(d for d in json.load(f) if isinstance(d, str))
except (OSError, ValueError):
pass
def _save_domains() -> None:
try:
with open(DOMAINS_FILE, "w") as f:
json.dump(sorted(CUSTOM_DOMAINS), f)
except OSError as e:
logger.warning(f"Could not save custom domains: {e}")
def _host_match(host: str, suffixes) -> bool:
return any(host == s or host.endswith("." + s) for s in suffixes)
def detect_tool(host: str, path: str) -> str:
if CUSTOM_DOMAINS and _host_match(host, CUSTOM_DOMAINS):
return "sgtm"
path = path.split("?")[0]
for key, _, _, suffixes, path_re in TOOLS:
if _host_match(host, suffixes) and (path_re is None or re.search(path_re, path)):
return key
# Firebase traffic routed through a custom endpoint (e.g. sGTM .../app-measurement/a)
if re.search(r"app-measurement|app-analytics-services", host + path):
return "sgtm"
return "other"
def pretty_config(cfg: dict) -> dict:
"""Readable form of the Firebase measurement config."""
out: dict = {}
for key in ("measurement_id", "firebase_app_id", "upload_region"):
if key in cfg:
out[key] = cfg[key]
for sg in cfg.get("sgtm", []):
urls = list(dict.fromkeys(sg[k] for k in ("url", "url_2", "url_3") if k in sg))
out["sgtm_url"] = urls[0] if len(urls) == 1 else urls
if "percentage" in sg:
out["sgtm_percentage"] = f"{sg['percentage']} %"
if "sgtm_url" not in out:
out["sgtm_url"] = "not configured"
if "config_version" in cfg:
out["config_version"] = f"{cfg['config_version']} ({_fmt_time(cfg['config_version'] // 1000)})"
events = cfg.get("event", [])
if events:
out["key_events"] = [e.get("name", "?") for e in events if e.get("key_event")]
other = [e.get("name", "?") for e in events if not e.get("key_event")]
if other:
out["events_config"] = other
for svc in cfg.get("service", []):
out[svc.get("name", "?")] = bool(svc.get("enabled"))
if cfg.get("setting"):
out["settings"] = {st.get("key", "?"): st.get("value") for st in cfg["setting"]}
known = {"measurement_id", "firebase_app_id", "upload_region", "sgtm", "config_version", "event", "service", "setting"}
out.update({k: v for k, v in cfg.items() if k not in known})
return out
def sgtm_hosts(cfg: dict) -> set[str]:
hosts = set()
for sg in cfg.get("sgtm", []):
for k in ("url", "url_2", "url_3"):
if sg.get(k):
host = urllib.parse.urlsplit(sg[k]).hostname
if host:
hosts.add(host.lower())
return hosts
def register_sgtm(hosts: set[str]) -> None:
new = hosts - CUSTOM_DOMAINS
if new:
CUSTOM_DOMAINS.update(new)
_save_domains()
logger.warning(f"sGTM endpoint detected from Firebase config: {', '.join(sorted(new))}")
def _is_ga4(flow) -> bool:
if not isinstance(flow, http.HTTPFlow):
return False
return detect_tool(flow.request.pretty_host, flow.request.path) in ("ga4", "sgtm")
# --------------------------------------------------------------------------
# Hit extraction (request -> list of events)
# --------------------------------------------------------------------------
STRONG_NAME_KEYS = ("_eventName", "eventName", "event_name", "event_type", "event", "en")
NAME_KEYS = STRONG_NAME_KEYS + ("name", "type")
LIST_KEYS = ("events", "batch", "custom_events", "data", "e", "payload")
MAX_TEXT = 5000
def _maybe_json(v):
if isinstance(v, str) and v[:1] in "{[":
try:
return json.loads(v)
except ValueError:
pass
return v
def _parse_form(text: str) -> dict:
return {k: _maybe_json(v) for k, v in urllib.parse.parse_qsl(text, keep_blank_values=True)}
def _looks_like_form(text: str) -> bool:
return "=" in text and not any(c.isspace() for c in text[:500])
def parse_body(req: http.Request):
try:
data = req.get_content()
except ValueError:
data = req.raw_content
if not data:
return None
if data[:2] == b"\x1f\x8b":
try:
data = gzip.decompress(data)
except OSError:
pass
text = _as_text(data)
if text is None:
if _is_protobuf(data):
return decode_generic(data)
return f"<binary {len(data)} bytes>"
s = text.strip()
if s[:1] in "{[":
try:
return json.loads(s)
except ValueError:
pass
if "x-www-form-urlencoded" in req.headers.get("content-type", "") or _looks_like_form(s):
return _parse_form(s)
return s[:MAX_TEXT]
def _name_of(d: dict, keys=NAME_KEYS):
for k in keys:
v = d.get(k)
if isinstance(v, str) and v:
return v
return None
def _event_list(obj):
if isinstance(obj, list):
if obj and all(isinstance(i, dict) for i in obj) and any(_name_of(i) for i in obj):
return obj
return None
if isinstance(obj, dict):
for k in LIST_KEYS:
v = _maybe_json(obj.get(k))
if isinstance(v, list):
found = _event_list(v)
if found:
return found
return None
def _last_segment(path: str) -> str:
segs = [s for s in path.split("?")[0].split("/") if s]
return segs[-1] if segs else "/"
def _extract_ga4_app(body: bytes) -> list[tuple]:
out = []
for b in decode_batch(body).get("bundle", []):
pb = _pretty_bundle(b)
extra = {"user_properties": pb.get("user_properties", {}), "device_app": pb["device_app"]}
for ev in b.get("event", []):
ts = ev.get("timestamp_millis")
out.append((_event_name(ev), _params_to_map(ev.get("param", [])), extra, ts[1] if ts else None))
return out
def _extract_ga4_web(query: dict, body) -> list[tuple]:
lines = []
if isinstance(body, str):
lines = [_parse_form(line) for line in body.splitlines() if line.strip()]
elif isinstance(body, dict):
lines = [body]
if not lines:
lines = [{}]
return [(p.get("en", "page_view"), p, {}, None) for p in ({**query, **line} for line in lines)]
def _extract_generic(tool: str, host: str, path: str, query: dict, body) -> list[tuple]:
# Mixpanel & co. send base64 / JSON in a "data" form field
if isinstance(body, dict) and isinstance(body.get("data"), str):
try:
body = {**body, "data": json.loads(base64.b64decode(body["data"] + "==="))}
except (ValueError, TypeError):
pass
items = _event_list(body)
if items:
context = {k: v for k, v in body.items() if not isinstance(v, list)} if isinstance(body, dict) else {}
extra = {k: v for k, v in (("request", context), ("query", query)) if v}
out = []
for it in items:
name = _name_of(it) or "?"
if tool == "braze" and name == "ce" and isinstance(it.get("data"), dict) and it["data"].get("n"):
name = it["data"]["n"]
out.append((name, it, extra, None))
return out
params = dict(query)
if isinstance(body, dict):
params.update(body)
elif body is not None:
params["body"] = body
name = _name_of(params, STRONG_NAME_KEYS) if params else None
if tool == "adjust":
name = _last_segment(path)
if params.get("event_token"):
name = f"event {params['event_token']}"
elif tool == "appsflyer" and not name:
# launches / inapps / ... name the request; a per-app key subdomain (e.g. 9zswv8.skadsdkless) does not
label = host.split(".")[0].rsplit("-", 1)[-1] # npkfc6-launches -> launches
name = label if label.isalpha() else _last_segment(path)
return [(name or _last_segment(path), params, {}, None)]
def _looks_like_ga4_batch(data: bytes) -> bool:
try:
return any(b.get("event") for b in decode_batch(data).get("bundle", []))
except Exception: # noqa: BLE001
return False
def extract_hits(flow: http.HTTPFlow) -> list[dict]:
req = flow.request
host, path = req.pretty_host, req.path
tool = detect_tool(host, path)
query = {k: _maybe_json(v) for k, v in req.query.items(multi=False)} if req.query else {}
raw = req.get_content(strict=False) or b""
try:
if tool == "skan":
extra = {"response": decode_skan_response(flow.response)} if flow.response else {}
events = [("skan", decode(unpack_body(raw), SKAN_REQUEST), extra, None)]
elif tool == "ga4" and "/config/app" in path:
body = unpack_body(flow.response.get_content(strict=False) or b"") if flow.response else b""
cfg = decode(body, CONFIG) if body else {}
register_sgtm(sgtm_hosts(cfg))
events = [("config", pretty_config(cfg) if cfg else {"response": "empty (not modified?)"}, {"request": query} if query else {}, None)]
elif tool == "ga4" and not re.match(r"^/a/?$", path.split("?")[0]):
# other Firebase endpoints (sdk-exp, ...) - schema-less protobuf
resp = flow.response.get_content(strict=False) if flow.response else b""
req_msg = decode_generic(raw) if raw else None
params = req_msg if isinstance(req_msg, dict) else ({"body": req_msg} if req_msg else {})
if query:
params = {**query, **params}
extra = {"response": decode_generic(resp) if _is_protobuf(resp) else (parse_body(flow.response) if resp else None)}
if not isinstance(extra["response"], dict):
extra = {"response": {"body": extra["response"]}} if extra["response"] else {}
events = [(_last_segment(path), params, extra, None)]
elif tool in ("ga4", "sgtm") and _looks_like_ga4_batch(raw):
events = _extract_ga4_app(raw)
else:
body = parse_body(req)
if tool == "ga4web" or (tool == "sgtm" and ("en" in query or isinstance(body, str) and "en=" in body)):
events = _extract_ga4_web(query, body)
else:
events = _extract_generic(tool, host, path, query, body)
except Exception as e: # noqa: BLE001
events = [(_last_segment(path), {"decode_error": str(e)}, {}, None)]
status = flow.response.status_code if flow.response else ("error" if flow.error else None)
sent = int(req.timestamp_start * 1000)
ua = req.headers.get("user-agent", "")
xrw = req.headers.get("x-requested-with", "")
hits = [
{
"tool": tool,
"event": str(name),
"time": ts or sent,
"sent": sent,
"method": req.method,
"host": host,
"url": req.pretty_url,
"status": status,
"flow_id": flow.id,
"ua": _ua_token(ua),
"xrw": xrw if BUNDLE_RE.match(xrw or "") else None,
"params": _jsonable(params),
"extra": _jsonable(extra),
}
for name, params, extra, ts in (events or [(_last_segment(path), {}, {}, None)])
]
for h in hits:
h["issues"] = detect_issues(h, ua, path)
return hits
# --------------------------------------------------------------------------
# Issue detection (explained in the UI's Issues panel)
# --------------------------------------------------------------------------
GA4_TOOLS = ("ga4", "sgtm", "ga4web")
EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
PHONE_RE = re.compile(r"^\+\d[\d \-]{7,15}\d$")
ECOMMERCE_EVENTS = ("purchase", "refund")
def _is_webview_ua(ua: str) -> bool:
if "; wv)" in ua: # Android WebView
return True
# iOS WKWebView: WebKit on iPhone/iPad without the "Safari/" token Safari itself sends
return ("iPhone" in ua or "iPad" in ua) and "AppleWebKit" in ua and "Safari/" not in ua
# in-app browsers of social apps: User-Agent token -> app name
IN_APP_BROWSERS = (
("Instagram", "Instagram"), ("FBAN/", "Facebook"), ("FBAV/", "Facebook"), ("BytedanceWebview", "TikTok"),
("musical_ly", "TikTok"), ("LinkedInApp", "LinkedIn"), ("Snapchat", "Snapchat"), ("Pinterest", "Pinterest"),
)
def _hit_source(ua: str, xrw: str = "") -> str:
"""Who sent the hit: the app's own SDK, a webview inside an app, or a browser."""
if not ua:
return "unknown"
if "Mozilla/" not in ua: # app User-Agents (CFNetwork, Dalvik, okhttp, app name)
return "app"
for token, name in IN_APP_BROWSERS:
if token in ua:
return f"inapp:{name}"
if _is_webview_ua(ua) or BUNDLE_RE.match(xrw or ""): # Android WebView sends the app's package
return "webview"
for token, key in (("CriOS/", "chrome"), ("FxiOS/", "firefox"), ("EdgiOS/", "edge"), ("EdgA/", "edge"),
("Edg/", "edge"), ("SamsungBrowser/", "samsung"), ("Firefox/", "firefox"), ("Chrome/", "chrome")):
if token in ua:
return key
if "Safari/" in ua:
return "safari"
return "unknown"
def _walk_strings(obj, path=""):
if isinstance(obj, dict):
for k, v in obj.items():
yield from _walk_strings(v, f"{path}.{k}" if path else str(k))
elif isinstance(obj, list):
for i, v in enumerate(obj):
yield from _walk_strings(v, f"{path}[{i}]")
elif isinstance(obj, str):
yield path, obj
def _mask(value: str) -> str:
return value[:2] + "***" + value[-4:] if len(value) > 8 else "***"
ZERO_ID = "00000000-0000-0000-0000-000000000000"
ATT_STATUS = {"0": "not determined", "1": "restricted", "2": "denied", "3": "authorized"}
def detect_issues(h: dict, ua: str, path: str) -> list[dict]:
issues = _marketing_issues(h, path)
if h["tool"] in GA4_TOOLS:
issues += _ga4_issues(h, ua, path)
return issues
# Adjust is left out: it sends SKAN data inside its attribution request, not on its own endpoint
MMP_TOOLS = ("appsflyer", "singular", "branch", "kochava", "airbridge")
def _marketing_issues(h: dict, path: str) -> list[dict]:
"""Attribution / ATT / SKAN moments (Marketing Analytics course topics)."""
issues: list[dict] = []
params = h["params"] if isinstance(h["params"], dict) else {}
extra = h.get("extra") if isinstance(h.get("extra"), dict) else {}
device = extra.get("device_app") if isinstance(extra.get("device_app"), dict) else {}
tool, event = h["tool"], h["event"]
# ATT not authorized: Adjust att_status / zero IDFA, Meta tracking flag, Firebase zero IDFA
att = str(params.get("att_status", ""))
if tool == "adjust" and (att in ("0", "1", "2") or params.get("idfa") == ZERO_ID):
issues.append({"type": "att", "detail": f"Adjust att_status={att} ({ATT_STATUS.get(att, 'no IDFA')})"})