| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566 |
- """Provision a private, account-scoped browser profile for local Italy Query tools."""
- from __future__ import annotations
- import hashlib
- import os
- import stat
- from pathlib import Path
- PROJECT_ROOT = Path(__file__).resolve().parents[1]
- ITA_QUERY_ACCOUNT_FILE = PROJECT_ROOT / "config" / "ita_query_account.local.json"
- ITA_QUERY_PROFILE_ROOT = PROJECT_ROOT / "data" / "ita_query_profiles"
- class ItaLocalProfileError(ValueError):
- """Raised when a local Italy Query browser profile is unsafe to use."""
- def _ensure_private_directory(path: Path) -> Path:
- if path.is_symlink():
- raise ItaLocalProfileError("browser profile directory must not be a symlink")
- try:
- path.mkdir(mode=0o700, parents=True, exist_ok=True)
- except OSError as exc:
- raise ItaLocalProfileError(
- f"cannot create browser profile directory ({type(exc).__name__})"
- ) from exc
- if path.is_symlink() or not path.is_dir():
- raise ItaLocalProfileError(
- "browser profile path must be a private directory"
- )
- if os.name == "posix":
- try:
- path.chmod(0o700)
- mode = stat.S_IMODE(path.stat().st_mode)
- except OSError as exc:
- raise ItaLocalProfileError(
- f"cannot secure browser profile directory ({type(exc).__name__})"
- ) from exc
- if mode != 0o700:
- raise ItaLocalProfileError(
- "browser profile directory permissions must be 700"
- )
- return path.resolve()
- def prepare_ita_query_profile(
- username: str,
- *,
- profile_root: str | Path | None = None,
- ) -> Path:
- """Create a deterministic private profile without putting the username in its path."""
- normalized_username = str(username or "").strip().casefold()
- if not normalized_username:
- raise ItaLocalProfileError("Italy Query username is required for its profile")
- root = Path(profile_root or ITA_QUERY_PROFILE_ROOT).expanduser()
- private_root = _ensure_private_directory(root)
- profile_id = hashlib.sha256(normalized_username.encode("utf-8")).hexdigest()[:24]
- return _ensure_private_directory(private_root / profile_id)
|