phasmid-profile-gen 0.1.1__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.
@@ -0,0 +1,165 @@
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 Capture, catalog, gpu_key, validate
25
+ from .generate import (
26
+ FAMILIES,
27
+ GenerationError,
28
+ MissingCaptures,
29
+ ProfileGenerator,
30
+ RandomCapture,
31
+ Request,
32
+ dumps,
33
+ from_capture,
34
+ )
35
+ from .location import Location, LocationError
36
+
37
+ try:
38
+ __version__ = version("phasmid-profile-gen")
39
+ except PackageNotFoundError: # running from a source tree that was never installed
40
+ __version__ = "0.0.0"
41
+
42
+ __all__ = [
43
+ "FAMILIES",
44
+ "Capture",
45
+ "GenerationError",
46
+ "Location",
47
+ "LocationError",
48
+ "MissingCaptures",
49
+ "ProfileGenerator",
50
+ "RandomCapture",
51
+ "Request",
52
+ "__version__",
53
+ "catalog",
54
+ "dumps",
55
+ "from_capture",
56
+ "generate_profile",
57
+ "list_captures",
58
+ "list_gpus",
59
+ "locate",
60
+ "new_seed",
61
+ "validate",
62
+ ]
63
+
64
+ GeoipDatabase = str | os.PathLike[str] | None
65
+
66
+
67
+ def new_seed() -> str:
68
+ """A fresh profile seed: 32 lowercase hex characters."""
69
+ return secrets.token_hex(16)
70
+
71
+
72
+ def locate(exit_ip: str, seed: str, *, geoip_db: GeoipDatabase = None) -> Location:
73
+ """Where a profile with ``seed`` behind ``exit_ip`` is placed: zone, position, languages.
74
+
75
+ ``geoip_db`` is a DB-IP City Lite .mmdb; by default ``$PHASMID_GEOIP_MMDB``, else the pinned
76
+ build, downloaded into the cache on first use (about 60 MB)."""
77
+ return _location.locate(exit_ip, seed, geoip.reader(geoip_db))
78
+
79
+
80
+ def generate_profile(
81
+ os: str,
82
+ seed: str | None = None,
83
+ *,
84
+ exit_ip: str | None = None,
85
+ timezone: str | None = None,
86
+ languages: list[str] | None = None,
87
+ gpu: str | None = None,
88
+ geoip_db: GeoipDatabase = None,
89
+ generator: ProfileGenerator | None = None,
90
+ ) -> dict[str, Any]:
91
+ """A schema-valid Phasmid profile.
92
+
93
+ - ``os``: ``"linux"`` or ``"windows"``.
94
+ - ``seed``: 32 lowercase hex characters; a new one when omitted (read it back from
95
+ ``profile["seed"]``).
96
+ - ``exit_ip`` or ``timezone``, exactly one. An exit IP places the profile where the proxy
97
+ comes out: zone, geolocation, WebRTC public address and, unless ``languages`` is given,
98
+ Chrome's default languages for that country. Generate Windows profiles with one: Windows
99
+ Chrome answers geolocation from the system provider, so a Windows profile with no
100
+ position is a stronger tell than a Linux one.
101
+ - ``languages``: ``navigator.languages``; default ``["en-US", "en"]`` with a timezone.
102
+ - ``gpu``: ``"vendor_id:device_id"`` of a GPU a bundled capture has (see ``list_gpus()``).
103
+ - ``generator``: how the capture behind the profile is chosen (a ``ProfileGenerator``);
104
+ default ``RandomCapture()``, one of the OS's captures drawn uniformly from the seed.
105
+
106
+ Raises ``GenerationError`` (``MissingCaptures`` when no capture covers the OS),
107
+ ``LocationError`` or ``geoip.GeoipError``.
108
+ """
109
+ if (exit_ip is None) == (timezone is None):
110
+ raise GenerationError("give exactly one of exit_ip and timezone")
111
+ seed = seed or new_seed()
112
+ found: Location | None = None
113
+ data_note = ""
114
+ if exit_ip is not None:
115
+ db = geoip.reader(geoip_db)
116
+ found = _location.locate(exit_ip, seed, db)
117
+ data_note = f"{db.provenance}, {_location.provenance()}"
118
+ timezone = found.timezone
119
+ assert timezone is not None
120
+ langs = list(languages) if languages else (found.languages if found else ["en-US", "en"])
121
+ profile = _generate.generate(
122
+ os, seed, langs, timezone, gpu, found, data_note, generator=generator
123
+ )
124
+ errors = validate(profile)
125
+ if errors:
126
+ raise GenerationError("generated profile does not validate: " + "; ".join(errors))
127
+ return profile
128
+
129
+
130
+ def list_gpus() -> list[dict[str, Any]]:
131
+ """Every GPU of the bundled captures, per OS, most captures first:
132
+ ``[{"os", "gpu", "renderer", "captures"}]``. ``gpu`` is what ``generate_profile(gpu=)``
133
+ takes."""
134
+ seen: dict[tuple[str, str], dict[str, Any]] = {}
135
+ for capture in catalog():
136
+ gpu = capture.profile["gpu"]
137
+ key = gpu_key(gpu)
138
+ entry = seen.setdefault(
139
+ (capture.family, key),
140
+ {
141
+ "os": capture.family,
142
+ "gpu": key,
143
+ "renderer": gpu["webgl"]["unmasked_renderer"],
144
+ "captures": 0,
145
+ },
146
+ )
147
+ entry["captures"] += 1
148
+ return sorted(seen.values(), key=lambda e: (e["os"], -e["captures"], e["gpu"]))
149
+
150
+
151
+ def list_captures() -> list[dict[str, Any]]:
152
+ """The bundled captures: ``[{"name", "os", "os_version", "gpu", "renderer", "date",
153
+ "dump_sha256"}]``."""
154
+ return [
155
+ {
156
+ "name": c.name,
157
+ "os": c.family,
158
+ "os_version": c.profile["os"]["version"],
159
+ "gpu": gpu_key(c.profile["gpu"]),
160
+ "renderer": c.profile["gpu"]["webgl"]["unmasked_renderer"],
161
+ "date": c.date,
162
+ "dump_sha256": c.dump_sha256,
163
+ }
164
+ for c in catalog()
165
+ ]
@@ -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,17 @@
1
+ """Per-decision randomness: every draw a seed decides has its own RNG.
2
+
3
+ ``decision_rng(seed, decision)`` is ``random.Random(sha256(seed + ":" + decision))``, so a
4
+ seed gives the same profile byte for byte and the global ``random`` state is never read or
5
+ advanced.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import random
12
+
13
+
14
+ def decision_rng(seed: str, decision: str) -> random.Random:
15
+ return random.Random(
16
+ int.from_bytes(hashlib.sha256(f"{seed}:{decision}".encode()).digest(), "big")
17
+ )
@@ -0,0 +1,78 @@
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 of a real
4
+ device. The mapping is Phasmid's ``tests/consistency/capture.py``, the code
5
+ ``consistency capture`` runs, so there is one mapping from a dump to profile
6
+ fields. Only what generation reads is bundled, under a neutral name (OS family
7
+ and PCI ids); ``data/manifest.json`` names every capture's dump by sha256.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from dataclasses import dataclass
13
+ from functools import cache
14
+ from typing import Any
15
+
16
+ import jsonschema
17
+
18
+ from . import _data
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class Capture:
23
+ name: str
24
+ family: str
25
+ gpu: str
26
+ date: str
27
+ dump_sha256: str
28
+ profile: dict[str, Any]
29
+ battery: dict[str, Any] | None
30
+ # media_devices.labels shown after permission. A dump has no capture permission, so it
31
+ # shows no labels; a Phasmid record lists what the host shows after it. A capture
32
+ # without any makes profiles that claim no media device.
33
+ media_device_labels: dict[str, list[str]]
34
+
35
+
36
+ def gpu_key(gpu: dict[str, Any]) -> str:
37
+ return f"{gpu['vendor_id']}:{gpu['device_id']}"
38
+
39
+
40
+ @cache
41
+ def catalog() -> tuple[Capture, ...]:
42
+ return tuple(
43
+ Capture(
44
+ name=c["name"],
45
+ family=c["family"],
46
+ gpu=c["gpu"],
47
+ date=c["date"],
48
+ dump_sha256=c["dump_sha256"],
49
+ profile=c["profile"],
50
+ battery=c["battery"],
51
+ media_device_labels=c["media_device_labels"],
52
+ )
53
+ for c in _data.load("captures")["captures"]
54
+ )
55
+
56
+
57
+ def for_os(family: str) -> list[Capture]:
58
+ return [c for c in catalog() if c.family == family]
59
+
60
+
61
+ @cache
62
+ def schema() -> dict[str, Any]:
63
+ """Phasmid's profiles/schema.json at the commit the data was built from."""
64
+ return _data.load("schema")
65
+
66
+
67
+ @cache
68
+ def _validator() -> jsonschema.Draft202012Validator:
69
+ return jsonschema.Draft202012Validator(schema(), format_checker=jsonschema.FormatChecker())
70
+
71
+
72
+ def validate(profile: dict[str, Any]) -> list[str]:
73
+ """Human-readable schema violations, empty when valid (what ``consistency validate`` runs)."""
74
+ errors = []
75
+ for err in sorted(_validator().iter_errors(profile), key=lambda e: list(e.absolute_path)):
76
+ where = "/".join(str(p) for p in err.absolute_path) or "<root>"
77
+ errors.append(f"{where}: {err.message}")
78
+ return errors
@@ -0,0 +1,168 @@
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
+ return 1
75
+ _write(dumps(profile), args.out)
76
+ if args.out not in (None, "-"):
77
+ print(f"wrote {args.out}: {_summary(profile)}", file=sys.stderr)
78
+ return 0
79
+
80
+
81
+ def _cmd_locate(args: argparse.Namespace) -> int:
82
+ found = locate(args.ip, args.seed or new_seed(), geoip_db=args.geoip_db)
83
+ print(json.dumps(dataclasses.asdict(found), indent=1, ensure_ascii=False))
84
+ return 0
85
+
86
+
87
+ def _cmd_gpus(_: argparse.Namespace) -> int:
88
+ print(json.dumps(list_gpus(), indent=1))
89
+ return 0
90
+
91
+
92
+ def _cmd_captures(_: argparse.Namespace) -> int:
93
+ print(json.dumps(list_captures(), indent=1))
94
+ return 0
95
+
96
+
97
+ def _cmd_geoip(args: argparse.Namespace) -> int:
98
+ print(fetch(args.archive))
99
+ return 0
100
+
101
+
102
+ def _cmd_validate(args: argparse.Namespace) -> int:
103
+ errors = validate(json.loads(Path(args.profile).read_text()))
104
+ for err in errors:
105
+ print(err)
106
+ return 1 if errors else 0
107
+
108
+
109
+ def parser() -> argparse.ArgumentParser:
110
+ p = argparse.ArgumentParser(
111
+ prog="phasmid-profile-gen",
112
+ description=__doc__,
113
+ formatter_class=argparse.RawDescriptionHelpFormatter,
114
+ )
115
+ p.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
116
+ sub = p.add_subparsers(dest="command", required=True)
117
+
118
+ g = sub.add_parser("generate", help="write one profile")
119
+ g.add_argument("--os", required=True, choices=FAMILIES)
120
+ g.add_argument("--seed", help="32 lowercase hex chars; a new one when omitted")
121
+ where = g.add_mutually_exclusive_group(required=True)
122
+ where.add_argument("--timezone", help="IANA zone, e.g. America/New_York")
123
+ where.add_argument(
124
+ "--exit-ip",
125
+ help="the proxy's exit IP: derives the zone, geolocation, WebRTC public address and "
126
+ "languages",
127
+ )
128
+ g.add_argument(
129
+ "--languages",
130
+ help="navigator.languages, comma separated (default en-US,en, or the exit IP country's)",
131
+ )
132
+ g.add_argument(
133
+ "--gpu", help="vendor_id:device_id of a GPU listed by `gpus`, e.g. 0x10de:0x2504"
134
+ )
135
+ g.add_argument("--geoip-db", help="a DB-IP City Lite .mmdb instead of the pinned build")
136
+ g.add_argument("-o", "--out", help="output file (default: stdout)")
137
+ g.set_defaults(run=_cmd_generate)
138
+
139
+ loc = sub.add_parser("locate", help="where a profile behind an exit IP is placed")
140
+ loc.add_argument("ip")
141
+ loc.add_argument("--seed", help="the profile's seed; a new one when omitted")
142
+ loc.add_argument("--geoip-db", help="a DB-IP City Lite .mmdb instead of the pinned build")
143
+ loc.set_defaults(run=_cmd_locate)
144
+
145
+ sub.add_parser("gpus", help="GPUs of the bundled captures").set_defaults(run=_cmd_gpus)
146
+ sub.add_parser("captures", help="the bundled captures").set_defaults(run=_cmd_captures)
147
+
148
+ geo = sub.add_parser("geoip", help="download and verify the pinned DB-IP database")
149
+ geo.add_argument("--archive", type=Path, help="a local copy of the pinned .mmdb.gz")
150
+ geo.set_defaults(run=_cmd_geoip)
151
+
152
+ val = sub.add_parser("validate", help="check a profile against the bundled schema")
153
+ val.add_argument("profile")
154
+ val.set_defaults(run=_cmd_validate)
155
+ return p
156
+
157
+
158
+ def main(argv: list[str] | None = None) -> int:
159
+ args = parser().parse_args(argv)
160
+ try:
161
+ return args.run(args)
162
+ except _ERRORS as e:
163
+ print(e, file=sys.stderr)
164
+ return 1
165
+
166
+
167
+ if __name__ == "__main__":
168
+ 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,16 @@
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
+ | `captures.json.xz` | Harness dumps of real devices mapped onto the Phasmid profile schema. Only device data is kept, under a neutral name: no raw dump, no file name, no locale. | BSD 3-Clause (Phasmid) |
9
+ | `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` |
10
+ | `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 |
11
+ | `schema.json.xz` | Phasmid's `profiles/schema.json`. | BSD 3-Clause (Phasmid) |
12
+ | `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` |
13
+
14
+ Not bundled, but used at runtime by the `location` extra: time zone boundaries
15
+ from [timezone-boundary-builder](https://github.com/evansiroky/timezone-boundary-builder)
16
+ via `timezonefinder-data` (ODbL 1.0, © OpenStreetMap contributors).
@@ -0,0 +1,11 @@
1
+ {
2
+ "attribution": "IP Geolocation by DB-IP, https://db-ip.com",
3
+ "build": "2026-10",
4
+ "licence": "CC BY 4.0, https://creativecommons.org/licenses/by/4.0/ (db-ip.com/db/download/ip-to-city-lite)",
5
+ "mmdb_sha256": "9e250f02722d1ad1780f88192f0e908af285478a33e76b88b349c9181ae9d0f5",
6
+ "mmdb_size": 126998165,
7
+ "name": "DB-IP IP to City Lite",
8
+ "sha256": "c839d407f85a1e0bddba354cef16b2c398182d1c34ed8d985555dce134b36b14",
9
+ "size": 60193321,
10
+ "url": "https://download.db-ip.com/free/dbip-city-lite-2026-10.mmdb.gz"
11
+ }
Binary file