camoucore 0.1.2__tar.gz

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,26 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 JWriter20 and the CamouCore contributors
4
+ Copyright (c) 2024-2026 daijro and the Camoufox contributors
5
+
6
+ CamouCore is derived from the Camoufox Python launcher
7
+ (https://github.com/daijro/camoufox, python/), which is distributed under this
8
+ same license, by way of the Camouwolf launcher.
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: camoucore
3
+ Version: 0.1.2
4
+ Summary: The browser-independent core of the Camoufox and Camouwolf launchers
5
+ License: MIT
6
+ License-File: LICENSE
7
+ Author: JWriter20
8
+ Requires-Python: >=3.11,<4.0
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Programming Language :: Python :: 3.15
16
+ Provides-Extra: geoip
17
+ Requires-Dist: fpgen (>=1.3.0,<2.0.0)
18
+ Requires-Dist: language-tags
19
+ Requires-Dist: maxminddb ; extra == "geoip"
20
+ Requires-Dist: numpy
21
+ Requires-Dist: platformdirs
22
+ Requires-Dist: pyyaml
23
+ Requires-Dist: requests
24
+ Requires-Dist: rich
25
+ Requires-Dist: screeninfo
26
+ Requires-Dist: typing_extensions
27
+ Project-URL: Repository, https://github.com/CamouBrowser/camoucore
28
+ Description-Content-Type: text/markdown
29
+
30
+ # CamouCore
31
+
32
+ The browser-independent core shared by the [Camoufox](https://github.com/daijro/camoufox)
33
+ (Firefox) and Camouwolf (Chromium) launchers. A launcher keeps only what its
34
+ engine needs and takes everything else from here, so the two launchers cannot
35
+ drift apart.
36
+
37
+ | Module | What it does |
38
+ |---|---|
39
+ | `product` | `Product` and `Engine`: the launcher's name, cache directory, environment prefix and engine defaults. Every engine-specific choice in the core reads them. |
40
+ | `locales`, `territoryInfo.xml` | Locale parsing and region-weighted language choice. |
41
+ | `geolocation`, `geoip.yml` | GeoIP lookup of a proxy's exit. The database cache is shared by every launcher. |
42
+ | `ip` | Proxy parsing and public IP lookup. |
43
+ | `fpgen_model`, `fpgen-model.json` | Installs the pinned fpgen model before fpgen loads. Every launcher pins the same model. |
44
+ | `display`, `virtdisplay` | Monitor probing and the Xvfb display for `headless="virtual"`. |
45
+ | `cpu_affinity`, `download`, `host` | CPU pinning, verified downloads, host OS and architecture. |
46
+
47
+ A launcher declares itself once:
48
+
49
+ ```python
50
+ from pathlib import Path
51
+ from camoucore import CHROMIUM, Product
52
+
53
+ PRODUCT = Product('camouwolf', 'Camouwolf', CHROMIUM, package=Path(__file__).parent)
54
+ ```
55
+
56
+ The TypeScript package (`typescript/`, npm `camoucore`) is the twin of the
57
+ Python one, for launchers written in Node:
58
+
59
+ ```ts
60
+ import { CHROMIUM, Product } from "camoucore";
61
+
62
+ export const PRODUCT = new Product("camouwolf", "Camouwolf", CHROMIUM);
63
+ ```
64
+
65
+ Its data files are the Python package's; `pnpm build` copies them into
66
+ `dist/data-files/`, so each exists once in the repository.
67
+
68
+ ## Development
69
+
70
+ ```bash
71
+ cd python
72
+ pip install -e '.[geoip]' pytest
73
+ pytest tests -q
74
+
75
+ cd ../typescript # Node 22.15 or newer
76
+ pnpm install
77
+ pnpm exec tsc --noEmit && pnpm test && pnpm check
78
+ ```
79
+
@@ -0,0 +1,49 @@
1
+ # CamouCore
2
+
3
+ The browser-independent core shared by the [Camoufox](https://github.com/daijro/camoufox)
4
+ (Firefox) and Camouwolf (Chromium) launchers. A launcher keeps only what its
5
+ engine needs and takes everything else from here, so the two launchers cannot
6
+ drift apart.
7
+
8
+ | Module | What it does |
9
+ |---|---|
10
+ | `product` | `Product` and `Engine`: the launcher's name, cache directory, environment prefix and engine defaults. Every engine-specific choice in the core reads them. |
11
+ | `locales`, `territoryInfo.xml` | Locale parsing and region-weighted language choice. |
12
+ | `geolocation`, `geoip.yml` | GeoIP lookup of a proxy's exit. The database cache is shared by every launcher. |
13
+ | `ip` | Proxy parsing and public IP lookup. |
14
+ | `fpgen_model`, `fpgen-model.json` | Installs the pinned fpgen model before fpgen loads. Every launcher pins the same model. |
15
+ | `display`, `virtdisplay` | Monitor probing and the Xvfb display for `headless="virtual"`. |
16
+ | `cpu_affinity`, `download`, `host` | CPU pinning, verified downloads, host OS and architecture. |
17
+
18
+ A launcher declares itself once:
19
+
20
+ ```python
21
+ from pathlib import Path
22
+ from camoucore import CHROMIUM, Product
23
+
24
+ PRODUCT = Product('camouwolf', 'Camouwolf', CHROMIUM, package=Path(__file__).parent)
25
+ ```
26
+
27
+ The TypeScript package (`typescript/`, npm `camoucore`) is the twin of the
28
+ Python one, for launchers written in Node:
29
+
30
+ ```ts
31
+ import { CHROMIUM, Product } from "camoucore";
32
+
33
+ export const PRODUCT = new Product("camouwolf", "Camouwolf", CHROMIUM);
34
+ ```
35
+
36
+ Its data files are the Python package's; `pnpm build` copies them into
37
+ `dist/data-files/`, so each exists once in the repository.
38
+
39
+ ## Development
40
+
41
+ ```bash
42
+ cd python
43
+ pip install -e '.[geoip]' pytest
44
+ pytest tests -q
45
+
46
+ cd ../typescript # Node 22.15 or newer
47
+ pnpm install
48
+ pnpm exec tsc --noEmit && pnpm test && pnpm check
49
+ ```
@@ -0,0 +1,33 @@
1
+ [build-system]
2
+ requires = ["poetry-core>=1.0.0"]
3
+ build-backend = "poetry.core.masonry.api"
4
+
5
+ [tool.poetry]
6
+ name = "camoucore"
7
+ version = "0.1.2"
8
+ description = "The browser-independent core of the Camoufox and Camouwolf launchers"
9
+ authors = ["JWriter20", "daijro <daijro.dev@gmail.com>"]
10
+ license = "MIT"
11
+ repository = "https://github.com/CamouBrowser/camoucore"
12
+ readme = "README.md"
13
+ packages = [{ include = "camoucore", from = "src" }]
14
+ include = ["src/camoucore/*.json", "src/camoucore/*.yml", "src/camoucore/*.xml"]
15
+
16
+ [tool.poetry.dependencies]
17
+ python = "^3.11"
18
+ requests = "*"
19
+ rich = "*"
20
+ pyyaml = "*"
21
+ platformdirs = "*"
22
+ typing_extensions = "*"
23
+ screeninfo = "*"
24
+ language-tags = "*"
25
+ numpy = "*"
26
+ fpgen = "^1.3.0"
27
+ maxminddb = {version = "*", optional = true}
28
+
29
+ [tool.poetry.extras]
30
+ geoip = ["maxminddb"]
31
+
32
+ [tool.pytest.ini_options]
33
+ pythonpath = ["src"]
@@ -0,0 +1,3 @@
1
+ from .product import CHROMIUM, FIREFOX, Engine, Product
2
+
3
+ __all__ = ['CHROMIUM', 'FIREFOX', 'Engine', 'Product']
@@ -0,0 +1,56 @@
1
+ import inspect
2
+ import warnings
3
+ from pathlib import Path
4
+ from typing import Optional, Set, Type
5
+
6
+ from yaml import CLoader, load
7
+
8
+ with open(Path(__file__).parent / 'warnings.yml', 'r') as _f:
9
+ WARNINGS_DATA = load(_f, Loader=CLoader)
10
+
11
+ # Packages whose frames a warning skips: camoucore and every launcher built on it.
12
+ _INTERNAL: Set[Path] = {Path(__file__).parent}
13
+
14
+
15
+ def register_internal(package: Path) -> None:
16
+ _INTERNAL.add(Path(package))
17
+
18
+
19
+ def _warn_from_caller(message: str, category: Type[Warning]) -> None:
20
+ """Attribute the warning to the first frame outside camoucore and the
21
+ launchers, so it points at the user's call rather than at their internals."""
22
+ frame = inspect.currentframe()
23
+ while frame:
24
+ filename = Path(frame.f_code.co_filename)
25
+ if not any(filename.is_relative_to(package) for package in _INTERNAL):
26
+ break
27
+ frame = frame.f_back
28
+
29
+ if frame:
30
+ warnings.warn_explicit(
31
+ message,
32
+ category=category,
33
+ filename=frame.f_code.co_filename,
34
+ lineno=frame.f_lineno,
35
+ )
36
+ return
37
+
38
+ warnings.warn(message, category=category)
39
+
40
+
41
+ class LeakWarning(RuntimeWarning):
42
+ """
43
+ Raised when a the user has a setting enabled that can cause detection.
44
+ """
45
+
46
+ @staticmethod
47
+ def warn(warning: str, i_know_what_im_doing: Optional[bool] = None) -> None:
48
+ """
49
+ Warns the user if a passed parameter can cause leaks. `warning` is the
50
+ message itself: each launcher words its own.
51
+ """
52
+ if i_know_what_im_doing:
53
+ return
54
+ if i_know_what_im_doing is not None:
55
+ warning += '\nIf this is intentional, pass `i_know_what_im_doing=True`.'
56
+ _warn_from_caller(warning, LeakWarning)
@@ -0,0 +1,154 @@
1
+ """Pin the browser to as many CPU cores as the identity reports.
2
+
3
+ navigator.hardwareConcurrency is spoofed by the browser, but the number of
4
+ cores a page can *measure* (timing N parallel workers) is the number the OS
5
+ lets the browser run on. Reporting the fingerprint's value and pinning the
6
+ browser's CPU affinity to that many cores makes the two agree, so the drawn
7
+ value survives instead of being replaced by the host count.
8
+
9
+ The pin is applied to the Playwright driver process right before the browser
10
+ is launched -- child processes inherit the affinity mask on Linux and Windows,
11
+ so the browser and every content/GPU process it spawns run on the pinned set
12
+ -- and lifted from the driver again afterwards. macOS has no process affinity
13
+ API, so nothing can be pinned there and the launcher falls back to reporting
14
+ the host's (snapped) count.
15
+ """
16
+
17
+ import os
18
+ import platform
19
+ import random
20
+ from typing import Iterable, List, Optional, Sequence
21
+
22
+
23
+ def supported() -> bool:
24
+ """Whether this host can constrain a process to a subset of its cores."""
25
+ system = platform.system()
26
+ if system == 'Linux':
27
+ return hasattr(os, 'sched_setaffinity')
28
+ return system == 'Windows'
29
+
30
+
31
+ def host_cores() -> Optional[List[int]]:
32
+ """The cores this process may run on, in order."""
33
+ try:
34
+ if hasattr(os, 'sched_getaffinity'):
35
+ return sorted(os.sched_getaffinity(0)) # type: ignore[attr-defined]
36
+ except OSError:
37
+ pass
38
+ if platform.system() == 'Windows':
39
+ mask = _win_get_mask(os.getpid())
40
+ if mask:
41
+ return _mask_to_cores(mask)
42
+ n = os.cpu_count()
43
+ return list(range(n)) if n else None
44
+
45
+
46
+ def _pick(cores: Sequence[int], count: int) -> List[int]:
47
+ """`count` adjacent cores from a random starting point (wrapping). Always
48
+ taking the first `count` stacked every browser on one host onto cores
49
+ 0..count-1, so concurrent browsers measured far less parallelism than they
50
+ report; adjacent cores keep the SMT topology a real machine of that size
51
+ would have."""
52
+ start = random.randrange(len(cores))
53
+ return sorted((list(cores[start:]) + list(cores[:start]))[:count])
54
+
55
+
56
+ def pin(pid: int, count: int) -> Optional[Sequence[int]]:
57
+ """Restrict `pid` to `count` of its cores. Returns the previous set so it
58
+ can be handed back to `restore()`, or None if nothing was changed.
59
+
60
+ The caller must not pin the same process for two launches at once: the
61
+ browser inherits whatever mask the driver has when it is spawned."""
62
+ if count < 1 or not supported():
63
+ return None
64
+ system = platform.system()
65
+ if system == 'Linux':
66
+ try:
67
+ before = sorted(os.sched_getaffinity(pid)) # type: ignore[attr-defined]
68
+ if count >= len(before):
69
+ return None
70
+ os.sched_setaffinity(pid, set(_pick(before, count))) # type: ignore[attr-defined]
71
+ return before
72
+ except OSError:
73
+ return None
74
+ if system == 'Windows':
75
+ before_mask = _win_get_mask(pid)
76
+ if not before_mask:
77
+ return None
78
+ before = _mask_to_cores(before_mask)
79
+ if count >= len(before):
80
+ return None
81
+ return before if _win_set_mask(pid, _cores_to_mask(_pick(before, count))) else None
82
+ return None
83
+
84
+
85
+ def restore(pid: int, previous: Optional[Sequence[int]]) -> None:
86
+ """Give `pid` back the cores it had before `pin()`."""
87
+ if not previous:
88
+ return
89
+ system = platform.system()
90
+ try:
91
+ if system == 'Linux':
92
+ os.sched_setaffinity(pid, set(previous)) # type: ignore[attr-defined]
93
+ elif system == 'Windows':
94
+ _win_set_mask(pid, _cores_to_mask(previous))
95
+ except OSError:
96
+ pass
97
+
98
+
99
+ # -- Windows ---------------------------------------------------------------
100
+
101
+ _PROCESS_QUERY_INFORMATION = 0x0400
102
+ _PROCESS_SET_INFORMATION = 0x0200
103
+
104
+
105
+ def _mask_to_cores(mask: int) -> List[int]:
106
+ return [i for i in range(mask.bit_length()) if mask >> i & 1]
107
+
108
+
109
+ def _cores_to_mask(cores: Iterable[int]) -> int:
110
+ mask = 0
111
+ for c in cores:
112
+ mask |= 1 << c
113
+ return mask
114
+
115
+
116
+ def _win_handle(pid: int):
117
+ import ctypes
118
+
119
+ k32 = ctypes.windll.kernel32 # type: ignore[attr-defined]
120
+ return k32, k32.OpenProcess(_PROCESS_QUERY_INFORMATION | _PROCESS_SET_INFORMATION, False, pid)
121
+
122
+
123
+ def _win_get_mask(pid: int) -> int:
124
+ try:
125
+ import ctypes
126
+
127
+ k32, h = _win_handle(pid)
128
+ if not h:
129
+ return 0
130
+ try:
131
+ proc_mask = ctypes.c_size_t()
132
+ sys_mask = ctypes.c_size_t()
133
+ if not k32.GetProcessAffinityMask(h, ctypes.byref(proc_mask), ctypes.byref(sys_mask)):
134
+ return 0
135
+ return int(proc_mask.value)
136
+ finally:
137
+ k32.CloseHandle(h)
138
+ except Exception:
139
+ return 0
140
+
141
+
142
+ def _win_set_mask(pid: int, mask: int) -> bool:
143
+ try:
144
+ import ctypes
145
+
146
+ k32, h = _win_handle(pid)
147
+ if not h:
148
+ return False
149
+ try:
150
+ return bool(k32.SetProcessAffinityMask(h, ctypes.c_size_t(mask)))
151
+ finally:
152
+ k32.CloseHandle(h)
153
+ except Exception:
154
+ return False
@@ -0,0 +1,114 @@
1
+ """
2
+ Host display geometry, in the units the browser lays its windows out in.
3
+
4
+ The browser sizes windows in **CSS pixels**, but `screeninfo` marks the process
5
+ per-monitor DPI aware and therefore reports **physical** pixels. Where Windows
6
+ display scaling is enabled the two differ by the scale factor: a 1920x1080 panel
7
+ at 150% is only 1280x720 CSS px. Deriving a window size from the physical
8
+ numbers overshoots the screen by that factor, so the window opens partly
9
+ off-screen.
10
+
11
+ macOS (`NSScreen.frame`) and X11 (xrandr) already report CSS pixels, so scaling
12
+ only ever applies on Windows.
13
+ """
14
+
15
+ from typing import Any, Mapping, NamedTuple, Optional
16
+
17
+ from screeninfo import get_monitors
18
+
19
+ from .host import OS_NAME
20
+
21
+ # Windows expresses DPI relative to this baseline: 144 DPI == 150% scaling.
22
+ _WINDOWS_BASE_DPI = 96
23
+
24
+ # shcore.h / winuser.h constants
25
+ _MDT_EFFECTIVE_DPI = 0
26
+ _MONITOR_DEFAULTTONEAREST = 2
27
+
28
+
29
+ class DisplaySize(NamedTuple):
30
+ """Size of a monitor in CSS pixels."""
31
+
32
+ width: int
33
+ height: int
34
+
35
+
36
+ def has_display(env: Mapping[str, Any]) -> bool:
37
+ """
38
+ Whether the host has a desktop session for the browser's window to open on.
39
+
40
+ DISPLAY / WAYLAND_DISPLAY only ever exist on Linux, so they cannot be the
41
+ sole probe: keying off DISPLAY alone skipped the screen constraints entirely
42
+ on Windows and macOS, where a session is always present.
43
+ """
44
+ if OS_NAME != 'lin':
45
+ return True
46
+ return bool(env.get('DISPLAY') or env.get('WAYLAND_DISPLAY'))
47
+
48
+
49
+ def largest_display() -> Optional[DisplaySize]:
50
+ """
51
+ Size of the roomiest attached monitor in CSS pixels, or None when the
52
+ display cannot be probed (no monitors, or enumeration failed).
53
+ """
54
+ try:
55
+ monitors = get_monitors()
56
+ except Exception:
57
+ return None
58
+ if not monitors:
59
+ return None
60
+
61
+ monitor = max(monitors, key=lambda m: m.width * m.height)
62
+ scale = _scale_factor(monitor)
63
+ return DisplaySize(
64
+ width=max(1, int(monitor.width / scale)),
65
+ height=max(1, int(monitor.height / scale)),
66
+ )
67
+
68
+
69
+ def _scale_factor(monitor: Any) -> float:
70
+ """
71
+ Physical pixels per CSS pixel on `monitor`. Always 1.0 outside Windows.
72
+ """
73
+ if OS_NAME != 'win':
74
+ return 1.0
75
+ try:
76
+ dpi = _windows_monitor_dpi(monitor)
77
+ except Exception:
78
+ return 1.0 # Pre-Windows 8.1, or the shcore call is unavailable
79
+ return dpi / _WINDOWS_BASE_DPI if dpi > 0 else 1.0
80
+
81
+
82
+ def _windows_monitor_dpi(monitor: Any) -> int:
83
+ """
84
+ Effective DPI of `monitor`, via shcore!GetDpiForMonitor (Windows 8.1+).
85
+
86
+ Private WinDLL handles are used rather than the process-wide `ctypes.windll`
87
+ cache so that annotating the prototypes cannot affect other libraries.
88
+ """
89
+ import ctypes
90
+ from ctypes import wintypes
91
+
92
+ user32 = ctypes.WinDLL('user32') # type: ignore[attr-defined]
93
+ user32.MonitorFromPoint.argtypes = (wintypes.POINT, wintypes.DWORD)
94
+ user32.MonitorFromPoint.restype = wintypes.HANDLE
95
+ handle = user32.MonitorFromPoint(
96
+ wintypes.POINT(int(monitor.x), int(monitor.y)), _MONITOR_DEFAULTTONEAREST
97
+ )
98
+
99
+ shcore = ctypes.WinDLL('shcore') # type: ignore[attr-defined]
100
+ shcore.GetDpiForMonitor.argtypes = (
101
+ wintypes.HANDLE,
102
+ ctypes.c_int,
103
+ ctypes.POINTER(wintypes.UINT),
104
+ ctypes.POINTER(wintypes.UINT),
105
+ )
106
+ shcore.GetDpiForMonitor.restype = ctypes.c_long # HRESULT
107
+ dpi_x, dpi_y = wintypes.UINT(), wintypes.UINT()
108
+
109
+ hresult = shcore.GetDpiForMonitor(
110
+ handle, _MDT_EFFECTIVE_DPI, ctypes.byref(dpi_x), ctypes.byref(dpi_y)
111
+ )
112
+ if hresult != 0:
113
+ raise OSError(f'GetDpiForMonitor failed (0x{hresult & 0xFFFFFFFF:08X})')
114
+ return dpi_x.value