phasmid-profile-gen 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of phasmid-profile-gen might be problematic. Click here for more details.

@@ -0,0 +1,141 @@
1
+ """Generate Phasmid browser profiles.
2
+
3
+ from phasmid_profile_gen import generate_profile
4
+
5
+ profile = generate_profile("windows", exit_ip=proxy_exit_ip) # needs the location extra
6
+ profile = generate_profile("linux", seed="0a1b...", timezone="Europe/Berlin",
7
+ languages=["de-DE", "de", "en-US", "en"])
8
+
9
+ A profile regenerates byte for byte from its seed and inputs (``dumps``).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import os
15
+ import secrets
16
+ from importlib.metadata import PackageNotFoundError, version
17
+ from typing import Any
18
+
19
+ # Submodules are imported by name only: binding a function under a submodule's name here
20
+ # (generate, captures) would hide that submodule as an attribute of the package.
21
+ from . import generate as _generate
22
+ from . import geoip
23
+ from . import location as _location
24
+ from .captures import catalog, gpu_key, validate
25
+ from .claims import claims
26
+ from .generate import FAMILIES, GenerationError, MissingCaptures, dumps
27
+ from .location import Location, LocationError
28
+
29
+ try:
30
+ __version__ = version("phasmid-profile-gen")
31
+ except PackageNotFoundError: # running from a source tree that was never installed
32
+ __version__ = "0.0.0"
33
+
34
+ __all__ = [
35
+ "FAMILIES",
36
+ "GenerationError",
37
+ "Location",
38
+ "LocationError",
39
+ "MissingCaptures",
40
+ "__version__",
41
+ "dumps",
42
+ "generate_profile",
43
+ "list_captures",
44
+ "list_gpus",
45
+ "locate",
46
+ "new_seed",
47
+ "validate",
48
+ ]
49
+
50
+ GeoipDatabase = str | os.PathLike[str] | None
51
+
52
+
53
+ def new_seed() -> str:
54
+ """A fresh profile seed: 32 lowercase hex characters."""
55
+ return secrets.token_hex(16)
56
+
57
+
58
+ def locate(exit_ip: str, seed: str, *, geoip_db: GeoipDatabase = None) -> Location:
59
+ """Where a profile with ``seed`` behind ``exit_ip`` is placed: zone, position, languages.
60
+
61
+ ``geoip_db`` is a DB-IP City Lite .mmdb; by default ``$PHASMID_GEOIP_MMDB``, else the pinned
62
+ build, downloaded into the cache on first use (about 60 MB)."""
63
+ return _location.locate(exit_ip, seed, geoip.reader(geoip_db))
64
+
65
+
66
+ def generate_profile(
67
+ os: str,
68
+ seed: str | None = None,
69
+ *,
70
+ exit_ip: str | None = None,
71
+ timezone: str | None = None,
72
+ languages: list[str] | None = None,
73
+ gpu: str | None = None,
74
+ geoip_db: GeoipDatabase = None,
75
+ ) -> dict[str, Any]:
76
+ """A schema-valid Phasmid profile.
77
+
78
+ - ``os``: ``"linux"`` or ``"windows"``.
79
+ - ``seed``: 32 lowercase hex characters; a new one when omitted (read it back from
80
+ ``profile["seed"]``).
81
+ - ``exit_ip`` or ``timezone``, exactly one. An exit IP places the profile where the proxy
82
+ comes out: zone, geolocation, WebRTC public address and, unless ``languages`` is given,
83
+ Chrome's default languages for that country. Generate Windows profiles with one: Windows
84
+ Chrome answers geolocation from the system provider, so a Windows profile with no
85
+ position is a stronger tell than a Linux one.
86
+ - ``languages``: ``navigator.languages``; default ``["en-US", "en"]`` with a timezone.
87
+ - ``gpu``: ``"vendor_id:device_id"`` of a GPU a bundled capture backs (see ``list_gpus()``).
88
+
89
+ Raises ``GenerationError`` (``MissingCaptures`` when no capture covers the OS),
90
+ ``LocationError`` or ``geoip.GeoipError``.
91
+ """
92
+ if (exit_ip is None) == (timezone is None):
93
+ raise GenerationError("give exactly one of exit_ip and timezone")
94
+ seed = seed or new_seed()
95
+ found: Location | None = None
96
+ data_note = ""
97
+ if exit_ip is not None:
98
+ db = geoip.reader(geoip_db)
99
+ found = _location.locate(exit_ip, seed, db)
100
+ data_note = f"{db.provenance}, {_location.provenance()}"
101
+ timezone = found.timezone
102
+ assert timezone is not None
103
+ langs = list(languages) if languages else (found.languages if found else ["en-US", "en"])
104
+ profile = _generate.generate(os, seed, langs, timezone, gpu, found, data_note)
105
+ errors = validate(profile)
106
+ if errors:
107
+ raise GenerationError("generated profile does not validate: " + "; ".join(errors))
108
+ return profile
109
+
110
+
111
+ def list_gpus() -> list[dict[str, Any]]:
112
+ """Every GPU the bundled captures back, per OS, heaviest first:
113
+ ``[{"os", "gpu", "renderer", "weight"}]``. ``gpu`` is what ``generate_profile(gpu=)`` takes."""
114
+ seen: dict[tuple[str, str], dict[str, Any]] = {}
115
+ for capture in catalog():
116
+ for claim in claims(capture):
117
+ for key in claim.gpu_keys:
118
+ entry = seen.setdefault(
119
+ (capture.family, key),
120
+ {"os": capture.family, "gpu": key, "renderer": claim.renderer, "weight": 0},
121
+ )
122
+ entry["weight"] += claim.weight
123
+ return sorted(seen.values(), key=lambda e: (e["os"], -e["weight"], e["gpu"]))
124
+
125
+
126
+ def list_captures() -> list[dict[str, Any]]:
127
+ """The bundled captures: ``[{"name", "source", "os", "os_version", "gpu", "renderer",
128
+ "date", "dump_sha256"}]``."""
129
+ return [
130
+ {
131
+ "name": c.name,
132
+ "source": c.source,
133
+ "os": c.family,
134
+ "os_version": c.profile["os"]["version"],
135
+ "gpu": gpu_key(c.profile["gpu"]),
136
+ "renderer": c.profile["gpu"]["webgl"]["unmasked_renderer"],
137
+ "date": c.date,
138
+ "dump_sha256": c.dump_sha256,
139
+ }
140
+ for c in catalog()
141
+ ]
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
@@ -0,0 +1,25 @@
1
+ """The bundled data: xz-compressed JSON under ``data/``, built by scripts/build_data.py."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import lzma
7
+ from functools import cache
8
+ from importlib.resources import files
9
+ from typing import Any
10
+
11
+
12
+ def path(name: str):
13
+ return files(__package__).joinpath("data", name)
14
+
15
+
16
+ @cache
17
+ def load(name: str) -> Any:
18
+ """``data/<name>.json.xz``, decompressed and parsed once per process. Callers must not
19
+ mutate what this returns."""
20
+ return json.loads(lzma.decompress(path(f"{name}.json.xz").read_bytes()))
21
+
22
+
23
+ @cache
24
+ def manifest() -> dict[str, Any]:
25
+ return json.loads(path("manifest.json").read_text())
@@ -0,0 +1,81 @@
1
+ """The capture catalog: real devices, already mapped onto the profile schema.
2
+
3
+ Each entry was built by scripts/build_data.py from a harness dump: Phasmid's
4
+ own captures (``profiles/data/captures`` with their records) and dumps the
5
+ collector app received from visitors' browsers. The mapping is Phasmid's
6
+ ``tests/consistency/capture.py``, the code ``consistency capture`` runs, so
7
+ there is one mapping from a dump to profile fields. Only what generation reads
8
+ is bundled; ``data/manifest.json`` names every capture's dump by sha256.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ from dataclasses import dataclass
14
+ from functools import cache
15
+ from typing import Any
16
+
17
+ import jsonschema
18
+
19
+ from . import _data
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Capture:
24
+ name: str
25
+ source: str # "phasmid" or "collector"
26
+ family: str
27
+ gpu: str
28
+ date: str
29
+ dump_sha256: str
30
+ profile: dict[str, Any]
31
+ battery: dict[str, Any] | None
32
+ # media_devices.labels shown after permission. A dump has no capture permission, so it
33
+ # shows no labels; a Phasmid record lists what the host shows after it. Collector
34
+ # captures have none, so profiles generated from them claim no media device.
35
+ media_device_labels: dict[str, list[str]]
36
+
37
+
38
+ def gpu_key(gpu: dict[str, Any]) -> str:
39
+ return f"{gpu['vendor_id']}:{gpu['device_id']}"
40
+
41
+
42
+ @cache
43
+ def catalog() -> tuple[Capture, ...]:
44
+ return tuple(
45
+ Capture(
46
+ name=c["name"],
47
+ source=c["source"],
48
+ family=c["family"],
49
+ gpu=c["gpu"],
50
+ date=c["date"],
51
+ dump_sha256=c["dump_sha256"],
52
+ profile=c["profile"],
53
+ battery=c["battery"],
54
+ media_device_labels=c["media_device_labels"],
55
+ )
56
+ for c in _data.load("captures")["captures"]
57
+ )
58
+
59
+
60
+ def for_os(family: str) -> list[Capture]:
61
+ return [c for c in catalog() if c.family == family]
62
+
63
+
64
+ @cache
65
+ def schema() -> dict[str, Any]:
66
+ """Phasmid's profiles/schema.json at the commit the data was built from."""
67
+ return _data.load("schema")
68
+
69
+
70
+ @cache
71
+ def _validator() -> jsonschema.Draft202012Validator:
72
+ return jsonschema.Draft202012Validator(schema(), format_checker=jsonschema.FormatChecker())
73
+
74
+
75
+ def validate(profile: dict[str, Any]) -> list[str]:
76
+ """Human-readable schema violations, empty when valid (what ``consistency validate`` runs)."""
77
+ errors = []
78
+ for err in sorted(_validator().iter_errors(profile), key=lambda e: list(e.absolute_path)):
79
+ where = "/".join(str(p) for p in err.absolute_path) or "<root>"
80
+ errors.append(f"{where}: {err.message}")
81
+ return errors
@@ -0,0 +1,188 @@
1
+ """Which GPUs a capture's host may claim.
2
+
3
+ Phasmid decision gpu-claims-stay-within-a-captured-host-class.
4
+
5
+ A capture backs its own GPU. It also backs another GPU when the fpgen extract
6
+ (Phasmid's profiles/data/fpgen/<os>.json, bundled as ``data/fpgen.json.xz``)
7
+ shows that GPU reporting the capture's exact WebGL surface in clean sessions:
8
+ within a host class the driver, not the GPU model, sets the extensions, limits
9
+ and rasterization. A claim copies the captured gpu section and derives only
10
+ IDENTITY_FIELDS. It needs:
11
+
12
+ - a surface with the extract's minimum sessions and renderers, and the
13
+ minimum sessions of the claimed renderer with it;
14
+ - the capture's host class, ANGLE vendor and GL version string;
15
+ - the host driver's current table, on the capture's driver branch (NVIDIA's
16
+ README; Mesa has no such rule yet, so a Mesa capture claims only its own GPU);
17
+ - no laptop part: the schema has no hybrid-graphics fields;
18
+ - a desktop device id from pci.ids that the driver lists under that name;
19
+ - when the capture has WebGPU, the capture's adapter architecture: other
20
+ architectures' WebGPU features and limits are unmeasured.
21
+
22
+ Weights are the clean fpgen sessions with the capture's surface; the
23
+ capture's own GPU counts the capture itself as one more.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import copy
29
+ from dataclasses import dataclass
30
+ from typing import Any
31
+
32
+ from . import _data
33
+ from .captures import Capture
34
+ from .surface import host_class, parse_angle, renderer_class, surface_sha256
35
+
36
+ DECISION = "gpu-claims-stay-within-a-captured-host-class"
37
+ IDENTITY_FIELDS = (
38
+ "device_id",
39
+ "device_name",
40
+ "gl_renderer",
41
+ "webgl.unmasked_renderer",
42
+ "webgl2.unmasked_renderer",
43
+ )
44
+
45
+
46
+ class ClaimError(Exception):
47
+ pass
48
+
49
+
50
+ @dataclass(frozen=True)
51
+ class Claim:
52
+ renderer: str # the WebGL unmasked renderer
53
+ vendor_id: str
54
+ device_ids: tuple[str, ...]
55
+ weight: int
56
+ sessions: int # clean fpgen sessions of this renderer with the capture's surface
57
+ records: tuple[tuple[Any, ...], ...] # (gpu, webgl, webgl2 value ids, sessions)
58
+ derived: bool
59
+
60
+ @property
61
+ def gpu_keys(self) -> tuple[str, ...]:
62
+ return tuple(f"{self.vendor_id}:{d}" for d in self.device_ids)
63
+
64
+
65
+ def extract(family: str) -> dict[str, Any] | None:
66
+ return _data.load("fpgen").get(family)
67
+
68
+
69
+ def _parts(renderer: str) -> tuple[str, str, str]:
70
+ parts = parse_angle(renderer)
71
+ if parts is None:
72
+ raise ClaimError(f"not an ANGLE renderer string: {renderer!r}")
73
+ return parts
74
+
75
+
76
+ def _branch(driver_version: str) -> str:
77
+ return driver_version.split(".", 1)[0]
78
+
79
+
80
+ def device_ids(entry: dict[str, Any], gpu: dict[str, Any], data: dict[str, Any]) -> tuple[str, ...]:
81
+ """The device ids a capture may claim for one renderer of its surface; () when it may not."""
82
+ readme = data["sources"].get("nvidia_readme")
83
+ if (
84
+ readme is None
85
+ or entry.get("driver_table") != "current"
86
+ or entry.get("laptop") is not False
87
+ or _branch(readme["driver_version"]) != _branch(gpu.get("driver_version", ""))
88
+ ):
89
+ return ()
90
+ webgpu = gpu.get("webgpu") or {}
91
+ return tuple(
92
+ i
93
+ for i, arch in sorted((entry.get("device_ids") or {}).items())
94
+ if not webgpu.get("available") or arch == webgpu.get("architecture")
95
+ )
96
+
97
+
98
+ def renderers(data: dict[str, Any], gpu: dict[str, Any]) -> dict[str, dict[str, Any]]:
99
+ """The renderers of the extract that share the capture's surface, with enough sessions."""
100
+ t = data["thresholds"]
101
+ sha = surface_sha256(gpu)
102
+ own = _parts(gpu["webgl"]["unmasked_renderer"])
103
+ for s in data["classes"].get(host_class(gpu), {}).get("surfaces", []):
104
+ if (
105
+ s["sha256"] == sha
106
+ and s["sessions"] >= t["k"]
107
+ and s["renderers"] >= t["surface_renderers"]
108
+ ):
109
+ return {
110
+ r: e
111
+ for r, e in s["by_renderer"].items()
112
+ if e["sessions"] >= t["renderer"]
113
+ and renderer_class(r) == host_class(gpu)
114
+ and (_parts(r)[0], _parts(r)[2]) == (own[0], own[2])
115
+ }
116
+ return {}
117
+
118
+
119
+ def claims(capture: Capture) -> list[Claim]:
120
+ """The capture's own GPU first, then every GPU its host may claim, by renderer."""
121
+ gpu = capture.profile["gpu"]
122
+ own = gpu["webgl"]["unmasked_renderer"]
123
+ data = extract(capture.family)
124
+ listed = renderers(data, gpu) if data else {}
125
+ mine = listed.get(own, {"sessions": 0, "records": []})
126
+ out = [
127
+ Claim(
128
+ own,
129
+ gpu["vendor_id"],
130
+ (gpu["device_id"],),
131
+ mine["sessions"] + 1,
132
+ mine["sessions"],
133
+ tuple(tuple(r) for r in mine["records"]),
134
+ False,
135
+ )
136
+ ]
137
+ for renderer, entry in sorted(listed.items()):
138
+ ids = device_ids(entry, gpu, data) if data and renderer != own else ()
139
+ if ids:
140
+ out.append(
141
+ Claim(
142
+ renderer,
143
+ gpu["vendor_id"],
144
+ ids,
145
+ entry["sessions"],
146
+ entry["sessions"],
147
+ tuple(tuple(r) for r in entry["records"]),
148
+ True,
149
+ )
150
+ )
151
+ return out
152
+
153
+
154
+ def _with_device(angle: str, device: str) -> str:
155
+ vendor, _, backend = _parts(angle)
156
+ return f"ANGLE ({vendor}, {device}, {backend})"
157
+
158
+
159
+ def derive(gpu: dict[str, Any], claim: Claim, device_id: str) -> dict[str, Any]:
160
+ """The captured gpu section with a derived claim's identity: its renderer string verbatim,
161
+ the device part of the GL strings replaced, the host driver suffix kept."""
162
+ if not claim.derived or device_id not in claim.device_ids:
163
+ raise ClaimError(f"{device_id} is not a derived device id of {claim.renderer}")
164
+ device = _parts(claim.renderer)[1]
165
+ out = copy.deepcopy(gpu)
166
+ for ctx in ("webgl", "webgl2"):
167
+ out[ctx]["unmasked_renderer"] = claim.renderer
168
+ out["gl_renderer"] = _with_device(gpu["gl_renderer"], device)
169
+ out["device_name"] = _with_device(gpu["device_name"], device)
170
+ out["device_id"] = device_id
171
+ return out
172
+
173
+
174
+ def note(capture: Capture, claim: Claim, device_id: str) -> str:
175
+ """The provenance of a derived identity, for captured.note."""
176
+ data = extract(capture.family)
177
+ if data is None:
178
+ raise ClaimError(f"no fpgen extract for os={capture.family}")
179
+ src, model = data["sources"], data["model"]
180
+ ids = ", ".join(f"{'/'.join(r[:3])} x{r[3]}" for r in claim.records)
181
+ return (
182
+ f"GPU identity {_parts(claim.renderer)[1]} ({device_id}) derived within host class "
183
+ f"{host_class(capture.profile['gpu'])} under decision {DECISION}: fpgen {model['tag']} "
184
+ f"(archive sha256 {model['archive_sha256']}) has {claim.sessions} clean sessions of it "
185
+ f"with the capture's WebGL surface (value ids {ids}); device id from pci.ids sha256 "
186
+ f"{src['pci_ids']['sha256']} and the NVIDIA {src['nvidia_readme']['driver_version']} "
187
+ f"README sha256 {src['nvidia_readme']['sha256']}"
188
+ )
@@ -0,0 +1,177 @@
1
+ """phasmid-profile-gen: generate, place and list Phasmid profiles.
2
+
3
+ phasmid-profile-gen generate --os windows --exit-ip <proxy exit IP> -o profile.json
4
+ phasmid-profile-gen generate --os linux --seed <32 hex> --timezone Europe/Berlin \\
5
+ --languages de-DE,de,en-US,en
6
+ phasmid-profile-gen locate <proxy exit IP> --seed <32 hex>
7
+ phasmid-profile-gen gpus
8
+ phasmid-profile-gen captures
9
+ phasmid-profile-gen geoip [--archive dbip-city-lite-YYYY-MM.mmdb.gz]
10
+ phasmid-profile-gen validate profile.json
11
+
12
+ Placing a profile at an exit IP needs the location extra
13
+ (pip install 'phasmid-profile-gen[location]') and the DB-IP City Lite database,
14
+ downloaded on first use; --geoip-db or $PHASMID_GEOIP_MMDB names another copy.
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import argparse
20
+ import dataclasses
21
+ import json
22
+ import sys
23
+ from pathlib import Path
24
+
25
+ from . import __version__, generate_profile, list_captures, list_gpus, locate, new_seed, validate
26
+ from .generate import FAMILIES, GenerationError, MissingCaptures, dumps
27
+ from .geoip import GeoipError, fetch
28
+ from .locales import LocaleDataError
29
+ from .location import LocationError
30
+
31
+ _ERRORS = (GenerationError, LocationError, GeoipError, LocaleDataError, ValueError)
32
+
33
+
34
+ def _summary(profile: dict) -> str:
35
+ d, h = profile["display"], profile["hardware"]
36
+ w = d["window"]
37
+ return (
38
+ f"{profile['os']['family']} {profile['os'].get('version', '?')}, "
39
+ f"{h['concurrency']} threads, "
40
+ f"{h['device_memory']} GB, {d['width']}x{d['height']}@{d['device_pixel_ratio']} "
41
+ f"window {w['outer_width']}x{w['outer_height']}, "
42
+ f"gpu {profile.get('gpu', {}).get('device_id', '-')}, seed {profile['seed']}"
43
+ )
44
+
45
+
46
+ def _write(text: str, out: str | None) -> None:
47
+ if out is None or out == "-":
48
+ sys.stdout.write(text)
49
+ return
50
+ path = Path(out)
51
+ path.parent.mkdir(parents=True, exist_ok=True)
52
+ path.write_text(text)
53
+
54
+
55
+ def _languages(raw: str | None) -> list[str] | None:
56
+ if not raw:
57
+ return None
58
+ return [lang.strip() for lang in raw.split(",") if lang.strip()]
59
+
60
+
61
+ def _cmd_generate(args: argparse.Namespace) -> int:
62
+ try:
63
+ profile = generate_profile(
64
+ args.os,
65
+ args.seed,
66
+ exit_ip=args.exit_ip,
67
+ timezone=args.timezone,
68
+ languages=_languages(args.languages),
69
+ gpu=args.gpu,
70
+ geoip_db=args.geoip_db,
71
+ )
72
+ except MissingCaptures as e:
73
+ print(e, file=sys.stderr)
74
+ if args.draft:
75
+ _write(dumps(e.draft), args.out)
76
+ for err in validate(e.draft):
77
+ print(f" schema: {err}", file=sys.stderr)
78
+ return 1
79
+ _write(dumps(profile), args.out)
80
+ if args.out not in (None, "-"):
81
+ print(f"wrote {args.out}: {_summary(profile)}", file=sys.stderr)
82
+ return 0
83
+
84
+
85
+ def _cmd_locate(args: argparse.Namespace) -> int:
86
+ found = locate(args.ip, args.seed or new_seed(), geoip_db=args.geoip_db)
87
+ print(json.dumps(dataclasses.asdict(found), indent=1, ensure_ascii=False))
88
+ return 0
89
+
90
+
91
+ def _cmd_gpus(_: argparse.Namespace) -> int:
92
+ print(json.dumps(list_gpus(), indent=1))
93
+ return 0
94
+
95
+
96
+ def _cmd_captures(_: argparse.Namespace) -> int:
97
+ print(json.dumps(list_captures(), indent=1))
98
+ return 0
99
+
100
+
101
+ def _cmd_geoip(args: argparse.Namespace) -> int:
102
+ print(fetch(args.archive))
103
+ return 0
104
+
105
+
106
+ def _cmd_validate(args: argparse.Namespace) -> int:
107
+ errors = validate(json.loads(Path(args.profile).read_text()))
108
+ for err in errors:
109
+ print(err)
110
+ return 1 if errors else 0
111
+
112
+
113
+ def parser() -> argparse.ArgumentParser:
114
+ p = argparse.ArgumentParser(
115
+ prog="phasmid-profile-gen",
116
+ description=__doc__,
117
+ formatter_class=argparse.RawDescriptionHelpFormatter,
118
+ )
119
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
120
+ sub = p.add_subparsers(dest="command", required=True)
121
+
122
+ g = sub.add_parser("generate", help="write one profile")
123
+ g.add_argument("--os", required=True, choices=FAMILIES)
124
+ g.add_argument("--seed", help="32 lowercase hex chars; a new one when omitted")
125
+ where = g.add_mutually_exclusive_group(required=True)
126
+ where.add_argument("--timezone", help="IANA zone, e.g. America/New_York")
127
+ where.add_argument(
128
+ "--exit-ip",
129
+ help="the proxy's exit IP: derives the zone, geolocation, WebRTC public address and "
130
+ "languages",
131
+ )
132
+ g.add_argument(
133
+ "--languages",
134
+ help="navigator.languages, comma separated (default en-US,en, or the exit IP country's)",
135
+ )
136
+ g.add_argument(
137
+ "--gpu", help="vendor_id:device_id of a GPU listed by `gpus`, e.g. 0x10de:0x2504"
138
+ )
139
+ g.add_argument("--geoip-db", help="a DB-IP City Lite .mmdb instead of the pinned build")
140
+ g.add_argument(
141
+ "--draft",
142
+ action="store_true",
143
+ help="when no capture covers the OS, write the partial profile anyway and exit 1",
144
+ )
145
+ g.add_argument("-o", "--out", help="output file (default: stdout)")
146
+ g.set_defaults(run=_cmd_generate)
147
+
148
+ loc = sub.add_parser("locate", help="where a profile behind an exit IP is placed")
149
+ loc.add_argument("ip")
150
+ loc.add_argument("--seed", help="the profile's seed; a new one when omitted")
151
+ loc.add_argument("--geoip-db", help="a DB-IP City Lite .mmdb instead of the pinned build")
152
+ loc.set_defaults(run=_cmd_locate)
153
+
154
+ sub.add_parser("gpus", help="GPUs the bundled captures back").set_defaults(run=_cmd_gpus)
155
+ sub.add_parser("captures", help="the bundled captures").set_defaults(run=_cmd_captures)
156
+
157
+ geo = sub.add_parser("geoip", help="download and verify the pinned DB-IP database")
158
+ geo.add_argument("--archive", type=Path, help="a local copy of the pinned .mmdb.gz")
159
+ geo.set_defaults(run=_cmd_geoip)
160
+
161
+ val = sub.add_parser("validate", help="check a profile against the bundled schema")
162
+ val.add_argument("profile")
163
+ val.set_defaults(run=_cmd_validate)
164
+ return p
165
+
166
+
167
+ def main(argv: list[str] | None = None) -> int:
168
+ args = parser().parse_args(argv)
169
+ try:
170
+ return args.run(args)
171
+ except _ERRORS as e:
172
+ print(e, file=sys.stderr)
173
+ return 1
174
+
175
+
176
+ if __name__ == "__main__":
177
+ sys.exit(main())
@@ -0,0 +1,41 @@
1
+ UNICODE LICENSE V3
2
+
3
+ COPYRIGHT AND PERMISSION NOTICE
4
+
5
+ Copyright © 2004-2025 Unicode, Inc.
6
+
7
+ NOTICE TO USER: Carefully read the following legal agreement. BY
8
+ DOWNLOADING, INSTALLING, COPYING OR OTHERWISE USING DATA FILES, AND/OR
9
+ SOFTWARE, YOU UNEQUIVOCALLY ACCEPT, AND AGREE TO BE BOUND BY, ALL OF THE
10
+ TERMS AND CONDITIONS OF THIS AGREEMENT. IF YOU DO NOT AGREE, DO NOT
11
+ DOWNLOAD, INSTALL, COPY, DISTRIBUTE OR USE THE DATA FILES OR SOFTWARE.
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a
14
+ copy of data files and any associated documentation (the "Data Files") or
15
+ software and any associated documentation (the "Software") to deal in the
16
+ Data Files or Software without restriction, including without limitation
17
+ the rights to use, copy, modify, merge, publish, distribute, and/or sell
18
+ copies of the Data Files or Software, and to permit persons to whom the
19
+ Data Files or Software are furnished to do so, provided that either (a)
20
+ this copyright and permission notice appear with all copies of the Data
21
+ Files or Software, or (b) this copyright and permission notice appear in
22
+ associated Documentation.
23
+
24
+ THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
25
+ KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
27
+ THIRD PARTY RIGHTS.
28
+
29
+ IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS NOTICE
30
+ BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES,
31
+ OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
32
+ WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
33
+ ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA
34
+ FILES OR SOFTWARE.
35
+
36
+ Except as contained in this notice, the name of a copyright holder shall
37
+ not be used in advertising or otherwise to promote the sale, use or other
38
+ dealings in these Data Files or Software without prior written
39
+ authorization of the copyright holder.
40
+
41
+ SPDX-License-Identifier: Unicode-3.0
@@ -0,0 +1,18 @@
1
+ # Bundled data: sources and licences
2
+
3
+ Every file here is built by `scripts/build_data.py`; `manifest.json` names each
4
+ source version and each file's sha256.
5
+
6
+ | File | Source | Licence |
7
+ | --- | --- | --- |
8
+ | `forge.json.xz` | The fingerprint network of [apify/fingerprint-suite](https://github.com/apify/fingerprint-suite) as packaged in `apify_fingerprint_datapoints` (version in `manifest.json`), restricted to desktop Chrome on Windows and Linux and to the nodes the generator draws. The sampler in `forge.py` follows [browserforge](https://github.com/daijro/browserforge)'s `BayesianNode`. | Apache License 2.0 (both projects) |
9
+ | `captures.json.xz` | Harness dumps of real devices mapped onto the Phasmid profile schema: Phasmid's own captures (`profiles/data/captures`, taken on the maintainers' machines) and dumps the [collector app](https://phasmid.ecomeezy.com/about.html) received from visitors' browsers, which it collects anonymously (no IP address, no cookies) to build realistic device profiles for Phasmid. Only device data is kept; no raw dump, no visitor's locale. | BSD 3-Clause (Phasmid) |
10
+ | `fpgen.json.xz` | Phasmid's `profiles/data/fpgen` extract: per WebGL surface, session counts and value ids from scrapfly's [fingerprint-generator](https://github.com/scrapfly/fingerprint-generator) model, plus device-id tables from pci.ids and NVIDIA's driver README (hashes in the extract). The model itself carries no licence and is not bundled; no record of it is. | BSD 3-Clause (Phasmid's extract) |
11
+ | `locale.json.xz` `cldr` | Phasmid's `profiles/data/cldr/cldr.json`, extracted from [Unicode CLDR](https://cldr.unicode.org/) (tag in the file). | Unicode License v3, `CLDR-LICENSE` |
12
+ | `locale.json.xz` `chromium` | Phasmid's `profiles/data/chromium/accept-languages.json`: Chromium's `IDS_ACCEPT_LANGUAGES` per desktop UI locale at Phasmid's Chromium tag, each source file named by git blob id. | Chromium's BSD-style licence |
13
+ | `schema.json.xz` | Phasmid's `profiles/schema.json`. | BSD 3-Clause (Phasmid) |
14
+ | `dbip-city-lite.json` | The pin (URL, sizes, sha256) of a DB-IP IP to City Lite build. The database is downloaded on first use, never bundled. | The database: CC BY 4.0, "IP Geolocation by DB-IP, https://db-ip.com"; profiles placed with it name it in `captured.note` |
15
+
16
+ Not bundled, but used at runtime by the `location` extra: time zone boundaries
17
+ from [timezone-boundary-builder](https://github.com/evansiroky/timezone-boundary-builder)
18
+ via `timezonefinder-data` (ODbL 1.0, © OpenStreetMap contributors).