Skip to main content

MacWinUA

This README covers 1.0. If you use 0.5.250826, see the 0.5.250826 README.

PyPI version Python Versions License: MIT Coverage (Python 3.11) CI Status

MacWinUA builds the User-Agent and request headers that Chrome on macOS and Windows actually sends.

  • It asks Google's Version History API for the Chrome stable major that most users run today. When the API is unreachable, it estimates the major from a release schedule bundled with the package.
  • Header names, order, and values follow recorded requests from real Chrome and the Chromium source.
  • It uses only the standard library and installs no dependencies.

Installation

pip install macwinua
uv add macwinua

Requires Python 3.11 or later. On Python 3.10, pip picks 0.5.250826. The 0.5 series gets no more releases, including security fixes.

If your project supports both Python 3.10 and 3.11 or later (for example requires-python = ">=3.10", or python = "^3.10" in Poetry), the version you get depends on the lock tool.

  • uv splits the resolution by Python version and, in a single lock file, locks 0.5.250826 for Python 3.10 and 1.0 for 3.11 and later. Installing from the same lock gives you a package with a different API depending on the interpreter.
  • Poetry 1.8 locks only 0.5.250826, so it installs 0.5 even on 3.11 and later.

Either way, pin macwinua<1 so every interpreter gets 0.5.250826, and move to 1.0 when you drop 3.10.

Usage

The package has three public names: the default instance ua, the class HeaderGenerator, and the exception UAError. The installed version is in the module attribute __version__, a string (the version of the first distribution metadata found on the import path, or "0+unknown" when there is none). There are two methods: get_headers(platform, version, extra_headers) and user_agent(platform, version).

from macwinua import ua

headers = ua.get_headers()
mac_headers = ua.get_headers("mac")
win_user_agent = ua.user_agent("win")
print(headers["User-Agent"])
  • platform is "mac" or "win". If you leave it out, each call picks one of the two at random. If the requests in one session must look like they come from the same browser, set platform.
  • If you leave out version, today's major is used.
  • get_headers returns a new dict on every call.

Versions

version is an integer, and only today's major and the two majors below it are accepted. The next major (a value above today's major) is not accepted, because most users do not run it yet. A value out of range raises UAError, and the message lists the accepted values. The major changes about every two weeks, so do not hard-code a number. Compute it from today's major, as in the example.

from macwinua import UAError, ua

user_agent = ua.user_agent("mac")
current = int(user_agent.split("Chrome/")[1].split(".")[0])
try:
    older = ua.get_headers("mac", version=current - 2)
except UAError:
    # Today's major changed between the two calls. Leave out the version and take today's major.
    older = ua.get_headers("mac")

try:
    ua.get_headers("mac", version=current + 1)
except UAError as error:
    print(type(error).__name__, error)
  • Even when you pass version, the library needs today's major to check the allowed range, so the first online call can wait up to 2 seconds. Use offline=True to avoid the wait.
  • The online value and the offline estimate can differ by 1, so the same version=<major-2> can be accepted or raise UAError depending on the network.
  • If today's major changes between two calls (the UTC date changes, or a late online fetch changes the value), a version computed from the earlier major can also raise UAError. That is why the example wraps the call that passes a computed version in except UAError.

Extra headers

extra_headers are merged by name, ignoring case. A header with the same name is replaced in place with your name and value, and new names go at the end.

from macwinua import ua

headers = ua.get_headers(
    "win",
    extra_headers={"accept-language": "ko-KR,ko;q=0.9,en-US;q=0.8", "X-Request-Id": "42", "Sec-Fetch-User": ""},
)
print(list(headers))
  • Names may contain only HTTP token characters (RFC 9110), and values may not contain ASCII control characters other than tab (line breaks, NUL, DEL, and so on). Breaking either rule raises UAError.
  • If a value is an empty string or only whitespace, that header is removed.
  • Passing something that is not a mapping, or names or values that are not strings, also raises UAError.

Errors

The only exception the library raises is UAError, which reports an invalid argument and is a subclass of ValueError. The platform, the type of the version, and the extra headers are checked before the API is asked. The wording of error messages may change, so check the exception type (UAError).

from macwinua import UAError, ua

try:
    headers = ua.get_headers(extra_headers={"Bad Name": "1"})
except UAError:
    headers = ua.get_headers()

Types

In the public signatures, platform is Literal["mac", "win"] | None. This alias is not a public name, so when you pass a string variable, annotate it with the same Literal in your own code. An invalid value at runtime raises UAError. The package ships py.typed, so type checkers such as mypy read its signatures.

from typing import Literal

from macwinua import ua

platform: Literal["mac", "win"] = "win"
headers = ua.get_headers(platform)

Headers

get_headers returns the following 13 headers in the order Chrome sends them. The name casing is the form Chrome uses over HTTP/1.1.

sec-ch-ua
sec-ch-ua-mobile
sec-ch-ua-platform
Upgrade-Insecure-Requests
User-Agent
Accept
Sec-Fetch-Site
Sec-Fetch-Mode
Sec-Fetch-User
Sec-Fetch-Dest
Accept-Encoding
Accept-Language
Priority
  • These are the values for a top-level navigation where the user types an HTTPS address into the address bar. Chrome sends different values for plain http targets and for XHR and fetch requests.
  • Accept-Language is en-US,en;q=0.9. To use another language, override it with an extra header.
  • Headers cannot change the TLS fingerprint (JA3, JA4) or the HTTP/2 fingerprint. If those must match Chrome too, pass these headers to a client such as curl_cffi.

Passing the headers to an HTTP client

  • Accept-Encoding is the real Chrome value (gzip, deflate, br, zstd). When you send these headers with requests or httpx, overwrite Accept-Encoding with gzip, deflate, because neither client can decode br or zstd responses without extra packages. To keep sending br and zstd, install the decoders for your client.
    • For br, both requests (urllib3) and httpx decode with brotli.
    • To decode zstd with requests (urllib3) on Python 3.13 or earlier, install urllib3[zstd] (it installs backports.zstd). On Python 3.14 and later the standard library decodes it, so nothing extra is needed. This is the behavior of urllib3 2.6.0 through 2.8.0.
    • To decode zstd with httpx, install zstandard (httpx[zstd]) on any Python version.
  • The standard library urllib does not decode compressed responses, so remove Accept-Encoding.
  • Chrome sends Priority only over HTTP/2, so remove it with headers.pop("Priority") for clients that send HTTP/1.1 (requests, urllib).
  • HTTP clients can change header order and name casing. requests puts the session's default headers first, so replace Session.headers entirely with these headers (session.headers = headers). urllib capitalizes only the first letter of each name, as in Sec-ch-ua.
import urllib.request

from macwinua import ua

headers = ua.get_headers("win")
# urllib does not decode compressed responses and sends HTTP/1.1, so remove these two headers.
headers.pop("Accept-Encoding")
headers.pop("Priority")
request = urllib.request.Request("https://example.com/", headers=headers)

How today's major is chosen

The library is online by default. The first time it needs a major, it asks the Version History API for the win64 stable releases that are currently being served, and picks the major that most users run. It keeps that value in memory and in the cache file for cache_ttl (24 hours by default) and does not ask again during that time.

  • A call waits at most 2 seconds for the fetch. After that deadline it returns the schedule estimate, while the fetch keeps running in the background and its value is used once it finishes. Calls that arrive while that fetch is still running do not wait again and return the schedule estimate.
  • If a signal handler or log handler in the same thread calls the same generator again during a call, the reentrant call does not wait and returns the remembered major or the schedule estimate right away. The same holds when a log handler inside the background fetch thread calls that generator.
  • This wait blocks the calling thread, so a call from inside a coroutine also stalls the event loop for that time. In a coroutine, call it from another thread, as in await asyncio.to_thread(ua.get_headers, "mac"), or call it once before you start the event loop (it can wait again after cache_ttl passes, or 10 minutes after a fetch fails or misses the deadline).
  • After a failed fetch, the library does not ask the API again for 10 minutes and uses the schedule estimate. This backoff takes precedence over cache_ttl=timedelta(0). Within one process, instances that use the same cache file share the backoff. A fetch that misses the 2 second deadline starts the same backoff, so instances created while it is still running also use the estimate without waiting. If that fetch succeeds later, the backoff is lifted.
  • The library reads at most 1 MiB of an API response, does not follow redirects, and accepts only majors from 1 to 9999. Any other response counts as a failure.
  • When offline, or when the API is unreachable, the library estimates the major from the Chromium Dash release schedule bundled with the package. It assumes that a new major becomes dominant 6 days after its stable date, and after the schedule ends it counts one more major every two weeks.
  • For 180 days from the day the built-in release schedule was generated, an online value that differs from the estimate by 2 or more is not trusted, and the estimate is used instead.
  • Today's major is counted by UTC date, so a major decided by the date changes at 00:00 UTC (09:00 KST).

Offline mode

If you create the generator with HeaderGenerator(offline=True) or the environment variable MACWINUA_OFFLINE is on, the library uses neither the network nor files (it does not even read the cache) and decides the major from the built-in release schedule and today's date only. Either one turns offline mode on.

  • MACWINUA_OFFLINE is on when its value is 1, true, yes, or on. Case and surrounding whitespace are ignored, and any other value means off.
  • The variable is read every time a major is decided, so turning it on after import still affects the default ua. A fetch that started before you turned it on can still write the cache file when it finishes.
  • In your own tests and CI, set MACWINUA_OFFLINE=1 so the value depends only on the date, with no network.
MACWINUA_OFFLINE=1 python app.py

Cache

from datetime import timedelta
from pathlib import Path

from macwinua import HeaderGenerator

offline = HeaderGenerator(offline=True)
shared = HeaderGenerator(cache_dir=Path.home() / ".my-app" / "cache", cache_ttl=timedelta(hours=6))
refresh = HeaderGenerator(cache_ttl=timedelta(0))
print(offline.user_agent("mac"))

If you leave out cache_dir, the library uses the operating system's user cache directory. The file name is chrome-stable-major.json.

  • macOS: ~/Library/Caches/macwinua/
  • Windows: %LOCALAPPDATA%\macwinua\Cache\ (~\AppData\Local\macwinua\Cache\ when LOCALAPPDATA is unset or a relative path)
  • Others: $XDG_CACHE_HOME/macwinua/ (~/.cache/macwinua/ when XDG_CACHE_HOME is unset or a relative path)

How the library uses the cache directory:

  • Pass a directory as cache_dir, not a file. A relative path is used as is, relative to the current directory. An empty string, or a value that is neither a string nor a path, raises UAError.
  • When the library creates the cache directory, it gives it mode 0700 so only you can use it (on Windows this mode takes effect only on Python with the CVE-2024-4030 fix: 3.11.10 or later in the 3.11 series, and 3.12.4 or later). It reads the cache file only if it is a regular file of at most 4 KiB, and on POSIX it does not follow links (Windows has no such protection).
  • An existing directory is used as is. The library does not check the owner or permissions of an existing directory, so do not point it at a place where others can create the directory first, such as under /tmp or /var/tmp. Use a place only you can write to, such as a directory under your home.
  • cache_ttl is a timedelta, 24 hours by default. With timedelta(0), that instance asks the API on every call. A negative value, or a value that is not a timedelta, raises UAError.
  • 1.0 does not use ~/.macwinua/ from 0.5, so you can delete it.

Logging

The library logs only at DEBUG level, under the logger name macwinua. It emits nothing at WARNING or above, and its only handler is a NullHandler, so nothing is printed unless you configure logging. To see details such as why a fetch failed, add a handler, for example with logging.basicConfig(level=logging.DEBUG).

Forking

  • From Python 3.12, calling os.fork() in a process that has running threads emits a DeprecationWarning. The online fetch runs in a background thread.
  • On macOS, a child forked from a process that had threads can hang or crash in the system proxy lookup when it uses urllib. To fetch in the child, set a proxy environment variable such as no_proxy, or start the process with spawn.
  • The library rebuilds its fetch state in a forked child, so the child never hangs on a lock inherited from the parent.

Migrating from 0.5 to 1.0

1.0 shrinks the public surface and has no compatibility layer that keeps the old names. The code in the 1.0 column runs as is, and <major> stands for an integer major.

The full list of changes is in the changelog.

0.5 1.0 Notes
MacWinUA() HeaderGenerator() MacWinUA was an alias for HeaderGenerator.
macwinua.get_chrome_headers() ua.get_headers() Use the method on the default instance ua instead of the module function.
ua.chrome ua.user_agent() Without a platform, it picks mac or win. The version is always today's major. 0.5 picked one of the recent versions at random.
ua.random ua.user_agent() Same as ua.chrome.
ua.mac ua.user_agent("mac") A method instead of a property.
ua.windows ua.user_agent("win") The platform name is "win".
ua.latest ua.user_agent() Without a version, it is always today's major.
ua.get_headers(chrome_version="<major>") ua.get_headers(version=<major>) Takes integers only. The old keyword raises TypeError, and a string version (get_headers("mac", "<major>")) raises UAError.
ua.force_update(), macwinua.force_update() No replacement The library asks again every 24 hours on its own. To refresh once, call an instance created with HeaderGenerator(cache_ttl=timedelta(0)) once. The new value goes only into that instance and the cache file, so the default ua, which already has a value, can return the old value for up to 24 hours. For 10 minutes after a fetch fails or misses the deadline (or until the overdue fetch succeeds, if that comes first), new instances that use the same cache file do not ask again either, and the first call waits at most 2 seconds for the fetch and returns the schedule estimate after that.
HeaderGenerator(data_manager=DataManager()) No replacement There is no way to plug in a different version source. To avoid the network, use offline=True. If you passed DataManager(cache_path=...) only to move the cache, pass the directory that contains that file as cache_dir (if you pass the path of the old cache file itself while that file still exists, the library cannot create a directory there and file caching is turned off).
from macwinua.exceptions import UAError from macwinua import UAError UAError is now a subclass of ValueError.
APIFetchError, CacheError, DataValidationError No replacement These were caught internally and never reached users. The only exception 1.0 raises is UAError.
from macwinua.ua import HeaderGenerator, import macwinua.core, import macwinua.constants from macwinua import HeaderGenerator Only the submodule paths are gone. The name macwinua.ua still refers to the default instance, as in 0.5. The only submodules left are internal ones whose names start with an underscore, so import public names from macwinua.
~/.macwinua/ Per-OS cache directory See "Cache" above. You can delete the old directory.
7-day cache TTL 24-hour cache TTL The default changed. You can change it with cache_ttl.
Logger name macwinua.core Logger name macwinua Attach your logging configuration to the new name. 1.0 logs only at DEBUG level (see "Logging" above).
extra_headers sent unchecked extra_headers validated A name with characters outside HTTP token characters, or a value with ASCII control characters, raises UAError (see "Extra headers" above).
7 headers 13 headers Names, order, and values match a real Chrome top-level navigation (see "Headers" above). Accept-Encoding includes br and zstd, so with requests or httpx, overwrite this header or install the decoders (see "Passing the headers to an HTTP client" above).
Python 3.10 or later Python 3.11 or later A project that locks 3.10 together with 3.11 or later should pin macwinua<1 (see "Installation" above).

Versioning policy

  • Throughout 1.x, the three public names (ua, HeaderGenerator, UAError), the two methods (get_headers, user_agent), and the module attribute __version__ stay the same. Header values follow real Chrome and can change, even within 1.x.
  • Python 3.11 and later are supported. The first release after Python 3.11 reaches end of life (2027-10) raises the minimum to 3.12 and moves type aliases and generics to PEP 695 syntax. After that, support follows the CPython end-of-life schedule.

Development

CI uses uv 0.13.10.

uv sync
uv run pytest
uv run ruff check .
uv run ruff format --check .
uv run mypy
  • Tests run with the network blocked and MACWINUA_OFFLINE=1 set. Tests that call the real Version History API run separately with uv run pytest -m live.
  • Measure coverage with uv run coverage run -m pytest and uv run coverage report. The badge value is measured on Python 3.11.
  • Build the distributions with uv build --no-sources, and check their file lists and that they have no runtime dependencies with uv run python tools/check_dist.py dist. Try each installed distribution with uv run --isolated --no-project --with <dist-file> python -I tools/smoke_installed.py. CI runs the same checks.

One-time setup

A repository admin does these steps once, before the publish workflow is used for the first time. A workflow file cannot do them.

  1. In the project settings on TestPyPI, register a Trusted Publisher: owner Nuung, repository MacWinUA, workflow publish.yaml, and environment testpypi.
  2. In the GitHub repository settings, create the environments pypi and testpypi and add protection rules. Both require reviewers, and pypi allows deployments only from v* tags.
  3. Create the label testpypi-publish.
  4. The PyPI upload uses the repository secret PYPI_TOKEN while it exists and otherwise uses Trusted Publishing, so keep the secret until PyPI has a Trusted Publisher. To move to Trusted Publishing later, register one in the project settings on PyPI (owner Nuung, repository MacWinUA, workflow publish.yaml, and environment pypi), and then delete the secret and revoke the token on PyPI.

A manual run (workflow_dispatch) needs the workflow file on the default branch. So before this workflow is merged into the default branch, upload an rc to TestPyPI by adding the testpypi-publish label to a PR from the same repository.

Release process

  1. Fetch a fresh built-in release schedule. The tool prints the major estimated from the new schedule and the API's dominant major. If they differ by more than 1, or if the API or Dash data looks wrong (Dash is unreachable, a response exceeds 1 MiB, and so on), it writes nothing and exits with status 1.

    uv run python tools/update_release_data.py
    
  2. On a Mac, record the headers of real Chrome again and run the tests: uv run python tools/capture_chrome_headers.py --out tests/data/ --mode headed, then uv run pytest. The tool records HTTP/1.1 captures only. Take the HTTP/2 capture with the NetLog extraction command in "HTTP/2 capture command" in the defect ledger docs/review-1.0.0.md, and save it as tests/data/chrome-<version>-mac-headed-h2.json before running the tests. The header comparison test checks every headed Chrome capture in tests/data/ against the date and the major of that capture.

  3. Bump the version with uv version <new-version>. Keep the classifier in pyproject.toml in step with it: Development Status :: 4 - Beta for a pre-release such as 1.1.0rc1, and Development Status :: 5 - Production/Stable for a final release. tests/test_project_config.py checks this.

  4. Open a PR, get CI to pass, and merge it.

  5. Push a v<version> tag, and the publish workflow uploads the release to PyPI. It uploads with the repository secret PYPI_TOKEN while that secret exists and with Trusted Publishing otherwise, and the upload job runs in the GitHub environment pypi.

A v* tag uploads to the real PyPI even for an rc version. Make test releases on TestPyPI only (run the publish workflow by hand, or add the testpypi-publish label to a PR from the same repository).

License

MIT

Metadata

Release files for macwinua 1.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for macwinua 1.0.0
File Size Uploaded Provenance Actions
macwinua-1.0.0.tar.gz 35.9 kB Without provenance Details for macwinua-1.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for macwinua 1.0.0
File Interpreter ABI Platform Actions
macwinua-1.0.0-py3-none-any.whl Python 3 none any Details for macwinua-1.0.0-py3-none-any.whl

Total release size: 66.3 kB

Release files / macwinua-1.0.0.tar.gz

Download URL macwinua-1.0.0.tar.gz
Size 35.9 kB
Tags Source
SHA-256 checksum
How to use checksums
289121ac92c637f743ecad91bc55b8532eb08d5b7826893f2fafe8f3c699b4c1
BLAKE2b-256 checksum
How to use checksums
6e2b752f2dc14192d70f85b0b0a2fc864648496a45182b5d580de1047e2743ca
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / macwinua-1.0.0-py3-none-any.whl

Download URL macwinua-1.0.0-py3-none-any.whl
Size 30.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ea5da4e95506d32852a40ca72638ca7062cade85602422a7849aeac4cef4da06
BLAKE2b-256 checksum
How to use checksums
4123480937129a2fa3762d48b21a88dbe588e5eac712c3da4c66293a0cf7de30
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.10 {"installer":{"name":"uv","version":"0.13.10","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for macwinua 1.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page