Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

Write a NopeCHA API key into an unpacked [Automation Build](https://developers.nopecha.com/guides/extension_advanced/#automation-build) (`chromium_automation.zip`).

The Automation Build reads its key from the Nopecha Manifest Config, `manifest["nopecha"]["key"]` in `manifest.json`. This package sets that field and leaves every other manifest field alone, including the top-level `"key"` (the Chrome extension public key). It does not modify JavaScript or HTML, and it does not download the Web Store CRX.
The Automation Build reads its key from the Nopecha Manifest Config, `manifest["nopecha"]["key"]` in `manifest.json`. This package sets that field, turns on every captcha `*_auto_solve` and `*_auto_open` flag, and sets `enabled` to `true`. It leaves the rest of the Nopecha Manifest Config alone, including delay times and selectors, and it never rewrites the top-level `"key"` (the Chrome extension public key). It does not modify JavaScript or HTML, and it does not download the Web Store CRX.

If you omit `extension_path`, `load()` downloads `chromium_automation.zip` from NopeCHA GitHub releases into `extensions/NopeCHA` and re-downloads when `manifest["version_name"]` differs from the latest release tag. Pass `version="0.6.1"` to pin a tag. A user-supplied Extension Directory is never overwritten by a download.

The API key stays in the process. `load()` does not call `chrome_extension_python`'s storage writer, so the key is not saved in `site-packages/chrome_extension_python/package_storage.json`.

Expand All @@ -14,7 +16,7 @@ pip install nopecha-extension

## Patch the Extension Directory

`extension_path` is the unpacked Automation Build directory. `update_files()` rewrites `manifest.json` only when `manifest["nopecha"]["key"]` differs. A second call with the same key leaves the file unchanged and reports it under `skipped`.
`extension_path` is the unpacked Automation Build directory. `update_files()` rewrites `manifest.json` when the API key differs or any captcha type is still disabled. A second call with the same key and all captcha types already enabled leaves the file unchanged and reports it under `skipped`.

```python
import os
Expand Down Expand Up @@ -45,7 +47,7 @@ An empty string, a whitespace-only string, `None`, or any non-string raises `Val

## Load it in Botasaurus

Install Botasaurus separately (`pip install botasaurus`). Passing the `Nopecha` instance in `extensions` makes Botasaurus call `load()`, which patches `manifest.json` and returns Chrome's `--load-extension` flag. `load()` raises `FileNotFoundError` when `manifest.json` is not in the Extension Directory.
Install Botasaurus separately (`pip install botasaurus`). Passing the `Nopecha` instance in `extensions` makes Botasaurus call `load()`, which downloads the Automation Build if needed, patches `manifest.json`, and returns Chrome's `--load-extension` flag. `load()` raises `FileNotFoundError` when a user-supplied Extension Directory has no `manifest.json`.

```python
import os
Expand All @@ -54,10 +56,7 @@ from botasaurus.browser import Driver, browser

from nopecha_extension import Nopecha

ext = Nopecha(
api_key=os.environ["NOPECHA_API_KEY"],
extension_path="path/to/chromium_automation",
)
ext = Nopecha(api_key=os.environ["NOPECHA_API_KEY"])

@browser(extensions=[ext])
def open_example(driver: Driver, data):
Expand All @@ -68,7 +67,7 @@ if __name__ == "__main__":
open_example()
```

`load(with_command_line_option=False)` returns the Extension Directory path instead of the flag.
Point `extension_path` at an unpacked Automation Build to skip the download. `load(with_command_line_option=False)` returns the Extension Directory path instead of the flag.

## Command line

Expand Down
167 changes: 156 additions & 11 deletions nopecha_extension/patcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,69 @@
import argparse
import json
import os
import shutil
import sys
from io import BytesIO
from typing import Any
from zipfile import BadZipFile, ZipFile

from requests import get as http_get

from chrome_extension_python import Extension, File, relative_path

_MANIFEST_NAME = "manifest.json"
_MANIFEST_READ_ERRORS = (OSError, UnicodeError, json.JSONDecodeError, TypeError)
_AUTOMATION_ZIP_LATEST = (
"https://github.com/NopeCHALLC/nopecha-extension/releases/latest/download/"
"chromium_automation.zip"
)
_AUTOMATION_ZIP_TAG = (
"https://github.com/NopeCHALLC/nopecha-extension/releases/download/"
"{tag}/chromium_automation.zip"
)
_LATEST_RELEASE_API = (
"https://api.github.com/repos/NopeCHALLC/nopecha-extension/releases/latest"
)


def _fetch_bytes(url: str) -> bytes:
response = http_get(url, timeout=60)
response.raise_for_status()
return response.content


def _fetch_json(url: str) -> dict[str, Any]:
response = http_get(url, timeout=60)
response.raise_for_status()
payload = response.json()
if not isinstance(payload, dict):
raise TypeError("GitHub release response must be a JSON object")
return payload


def _normalized_version(value: str) -> str:
return value.strip().lstrip("vV")


def _latest_release_tag() -> str:
tag = _fetch_json(_LATEST_RELEASE_API).get("tag_name")
if not isinstance(tag, str) or tag.strip() == "":
raise ValueError("GitHub latest release is missing tag_name")
return tag.strip()


def _extract_zip(payload: bytes, dest: str) -> None:
dest = os.path.abspath(dest)
try:
archive = ZipFile(BytesIO(payload))
except BadZipFile as exc:
raise ValueError("Automation Build download is not a valid zip") from exc
with archive:
for info in archive.infolist():
target = os.path.abspath(os.path.join(dest, info.filename))
if target != dest and not target.startswith(dest + os.sep):
raise ValueError(f"unsafe path in Automation Build zip: {info.filename}")
archive.extractall(dest)


def _validated_api_key(api_key: str) -> str:
Expand All @@ -18,15 +74,39 @@ def _validated_api_key(api_key: str) -> str:
raise ValueError("api_key must be a non-empty string")


def _with_nopecha_key(manifest: dict[str, Any], api_key: str) -> dict[str, Any] | None:
def _is_captcha_toggle(name: str) -> bool:
return name.endswith("_auto_solve") or name.endswith("_auto_open")


def _with_captcha_types_enabled(settings: dict[str, Any]) -> dict[str, Any]:
updated = dict(settings)
updated["enabled"] = True
for name in list(updated):
if _is_captcha_toggle(name):
updated[name] = True
return updated


def _nopecha_config_matches(settings: dict[str, Any], api_key: str) -> bool:
if settings.get("key") != api_key or settings.get("enabled") is not True:
return False
return all(
value is True
for name, value in settings.items()
if _is_captcha_toggle(name)
)


def _with_nopecha_config(manifest: dict[str, Any], api_key: str) -> dict[str, Any] | None:
nopecha_settings = manifest.get("nopecha")
if isinstance(nopecha_settings, dict) and nopecha_settings.get("key") == api_key:
if isinstance(nopecha_settings, dict) and _nopecha_config_matches(nopecha_settings, api_key):
return None

if not isinstance(nopecha_settings, dict):
nopecha_settings = {}
else:
nopecha_settings = dict(nopecha_settings)
nopecha_settings = _with_captcha_types_enabled(nopecha_settings)
nopecha_settings["key"] = api_key

updated = dict(manifest)
Expand All @@ -47,24 +127,33 @@ def _manifest_read_error(exc: Exception) -> str:
class Nopecha(Extension):
"""Point an unpacked Automation Build at a NopeCHA API key.

The key is written to the Nopecha Manifest Config, ``manifest["nopecha"]["key"]``.
The key is written to the Nopecha Manifest Config, ``manifest["nopecha"]["key"]``,
and every captcha ``*_auto_solve`` / ``*_auto_open`` flag is turned on.
It is not passed into ``chrome_extension_python``, so ``load()`` does not
persist it in ``package_storage.json``.

When no Extension Directory is supplied, ``load()`` downloads
``chromium_automation.zip`` into ``extensions/NopeCHA``.
"""

def __init__(
self,
api_key: str,
extension_path: str | os.PathLike[str] | None = None,
version: str | None = None,
extension_id: str = "dknlfmjaanfblgfdfebhijalfmhmjjjo",
extension_name: str = "NopeCHA",
) -> None:
key = _validated_api_key(api_key)
self._user_supplied_path = False
self._count_path_as_user_supplied = False
super().__init__(
extension_id=extension_id,
extension_name=extension_name,
)
self._count_path_as_user_supplied = True
self.api_key = key
self.version = version
if extension_path is not None:
self.extension_path = extension_path

Expand All @@ -80,6 +169,8 @@ def extension_path(self, extension_path: str | os.PathLike[str]) -> None:
self.extension_absolute_path = os.path.abspath(path)
else:
self.extension_absolute_path = relative_path(path)
if self._count_path_as_user_supplied:
self._user_supplied_path = True

def get_file(self, path: str) -> File:
relative = path.lstrip("/\\")
Expand All @@ -102,7 +193,7 @@ def _write_manifest(self, manifest: dict[str, Any], relative_manifest_path: str

def _manifest_for_write(self, api_key: str | None) -> dict[str, Any] | None:
key = self._api_key_for_patch(api_key)
return _with_nopecha_key(self._read_manifest(_MANIFEST_NAME), key)
return _with_nopecha_config(self._read_manifest(_MANIFEST_NAME), key)

def _plan_update(self, api_key: str | None) -> tuple[dict[str, list[str]], dict[str, Any] | None]:
report: dict[str, list[str]] = {"modified": [], "skipped": [], "errors": []}
Expand All @@ -118,10 +209,11 @@ def _plan_update(self, api_key: str | None) -> tuple[dict[str, list[str]], dict[
return report, updated

def update_files(self, api_key: str | None = None) -> dict[str, list[str]]:
"""Write the API key into ``manifest.json`` when it differs.
"""Write the API key and enable captcha types in ``manifest.json``.

A matching ``manifest["nopecha"]["key"]`` leaves the file untouched.
``manifest.json`` is listed in ``modified`` only after a successful write.
A matching key with every captcha type already enabled leaves the file
untouched. ``manifest.json`` is listed in ``modified`` only after a
successful write.
"""
report, updated = self._plan_update(api_key)
if updated is None:
Expand All @@ -141,21 +233,74 @@ def quick_patch_file(self, path: str = _MANIFEST_NAME, api_key: str | None = Non
return False
key = self._api_key_for_patch(api_key)
try:
updated = _with_nopecha_key(self._read_manifest(relative_manifest_path), key)
updated = _with_nopecha_config(self._read_manifest(relative_manifest_path), key)
if updated is not None:
self._write_manifest(updated, relative_manifest_path)
except _MANIFEST_READ_ERRORS:
return False
return True

def _cached_version_name(self) -> str | None:
try:
manifest = self._read_manifest(_MANIFEST_NAME)
except _MANIFEST_READ_ERRORS:
return None
name = manifest.get("version_name")
if isinstance(name, str) and name.strip() != "":
return name.strip()
return None

def _pinned_release_tag(self) -> str | None:
if not isinstance(self.version, str):
return None
tag = _normalized_version(self.version)
return tag or None

def _desired_tag(self) -> str:
tag = self._pinned_release_tag()
if tag is not None:
return tag
return _latest_release_tag()

def _cache_is_stale(self) -> bool:
cached = self._cached_version_name()
if cached is None:
return True
return _normalized_version(cached) != _normalized_version(self._desired_tag())

def _automation_zip_url(self) -> str:
tag = self._pinned_release_tag()
if tag is not None:
return _AUTOMATION_ZIP_TAG.format(tag=tag)
return _AUTOMATION_ZIP_LATEST
Comment on lines +271 to +275

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note

P2, agreed by both reviewers. Passing a v-prefixed or whitespace-padded version string (such as version="v0.6.1", matching manifest["version_name"]) passes the staleness check on a warm cache but fails with HTTP 404 when downloading.

_cache_is_stale() normalizes self._desired_tag() via _normalized_version() (value.strip().lstrip("vV")), so version="v0.6.1" matches a cached manifest["version_name"] of "v0.6.1". However, _automation_zip_url() formats raw self.version directly (if self.version: return _AUTOMATION_ZIP_TAG.format(tag=self.version)), requesting .../releases/download/v0.6.1/chromium_automation.zip, which returns 404 because NopeCHALLC/nopecha-extension release tags omit the v prefix (for example 0.6.1 and 0.6.0), and a whitespace-only version=" " is also truthy and produces a malformed URL.

Suggested: Normalize version with _normalized_version() (and treat blank strings as unset in __init__ or helper methods) before using it in _automation_zip_url() and _desired_tag(), so both cache comparison and download URL construction use the same normalized release tag.

The second pass confirmed that _cache_is_stale() strips v/V and whitespace while _automation_zip_url() interpolates raw self.version into a release URL that expects unprefixed tags, so the non-blocking finding stands.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 912bd0a. _pinned_release_tag() now feeds both _desired_tag() and _automation_zip_url(), so version="v0.6.1" downloads .../download/0.6.1/chromium_automation.zip and a blank/whitespace version is treated as unset (latest).


def download(self) -> None:
"""Fetch the Automation Build zip into the Extension Directory cache."""
if self._user_supplied_path:
return
payload = _fetch_bytes(self._automation_zip_url())
dest = self.extension_absolute_path
if os.path.exists(dest):
shutil.rmtree(dest)
os.makedirs(dest, exist_ok=True)
_extract_zip(payload, dest)

def load(self, with_command_line_option: bool = True) -> str:
"""Patch ``manifest.json`` and return the Chrome load flag.

Raises ``FileNotFoundError`` when the manifest is missing. Read and write
failures propagate (``ValueError``, ``TypeError``, or ``OSError``) instead
of returning a path for an unpatched manifest.
When no Extension Directory was supplied, fetches the Automation Build
first. Raises ``FileNotFoundError`` when the manifest is missing. Read
and write failures propagate (``ValueError``, ``TypeError``, or
``OSError``) instead of returning a path for an unpatched manifest.
"""
manifest_path = os.path.join(self.extension_absolute_path, _MANIFEST_NAME)
if not self._user_supplied_path and (
not os.path.isfile(manifest_path)
or self.force_update
or self._cache_is_stale()
):
self.download()
manifest_path = os.path.join(self.extension_absolute_path, _MANIFEST_NAME)
if not os.path.isfile(manifest_path):
raise FileNotFoundError(manifest_path)
updated = self._manifest_for_write(self.api_key)
Expand Down
Loading
Loading