text
stringlengths
0
1.47k
return {"id": "", "cdpUrl": CDP_URL, "liveUrl": ""}
async with _vendor_client() as c:
r = await c.post(f"{API_BASE}/browsers", json={
"timeout": int(timeout_min), "proxyCountryCode": None, "solveCaptchas": False,
"enableRecording": False, "metadata": {k: str(v)[:100] for k, v in metadata.items()}})
if r.status_code == 402:
raise BrowserRefused("vendor_credits", "The browser service has no credit left. Tell the person.")
if r.status_code == 429:
raise BrowserRefused("vendor_busy", "Every browser is in use right now. Try again in a minute.")
if r.status_code >= 400:
raise BrowserRefused("vendor_error", f"The browser service refused to start a browser ({r.status_code}).")
d = r.json()
if not d.get("id") or not d.get("cdpUrl"):
raise BrowserRefused("vendor_error", "The browser service answered without a browser address.")
return d
async def vendor_stop(vendor_id: str) -> dict:
"""Stop the browser and read what it cost: closing the CDP socket alone keeps the meter
running on the vendor's side."""
async with _vendor_client() as c:
r = await c.patch(f"{API_BASE}/browsers/{vendor_id}", json={"action": "stop"})
if r.status_code >= 400:
r = await c.get(f"{API_BASE}/browsers/{vendor_id}")
try:
return r.json() if r.status_code < 400 else {}
except ValueError:
return {}
def vendor_cost(d: dict) -> float | None:
"""Dollars the vendor reports for a session: its browser time, plus proxy traffic when any.
None when it reported no browser cost, which is the figure of record."""
if d.get("browserCost") is None:
return None
total = 0.0
for p in (d.get("browserCost"), d.get("proxyCost")):
try:
total += float(p or 0)
except (TypeError, ValueError):
pass
return round(total, 6)
# ── the address guard ────────────────────────────────────────────────────────────────────────
_PRIVATE_NAMES = ("localhost", ".localhost", ".local", ".internal", ".home.arpa", ".lan", ".corp")
def _ip_private(ip: str) -> bool:
try:
a = ipaddress.ip_address(ip)
except ValueError:
return False
return (a.is_private or a.is_loopback or a.is_link_local or a.is_multicast or a.is_reserved
or a.is_unspecified or (a.version == 6 and a.ipv4_mapped is not None and _ip_private(str(a.ipv4_mapped))))
def _suffix_match(host: str, patterns: list[str]) -> bool:
for p in patterns:
p = (p or "").strip().lower().lstrip("*").lstrip(".")
if p and (host == p or host.endswith("." + p)):
return True
return False
def host_policy(host: str, allow: list[str], deny: list[str], private_ok: bool = False) -> str | None:
"""Why this host may not be reached, or None. Name rules only; the address rule follows.
`private_ok` lifts the private-address names and literals: the operator's own browser sits on
the operator's own network (HR_BROWSER_CDP_URL), and a loopback address was still refused here
by name after the plane had opened that browser (hr-test, 2026-09-30)."""
h = (host or "").strip().lower().rstrip(".")
if not h:
return "no host"
if h.startswith("[") and h.endswith("]"):
h = h[1:-1]
if not private_ok and _ip_private(h):
return "a private or local address"
if not private_ok and (h == "localhost" or any(h.endswith(s) for s in _PRIVATE_NAMES[1:])):
return "a private or local address"
if deny and _suffix_match(h, deny):
return "a site this agent is not allowed to visit"
if allow and not _suffix_match(h, allow):
return "a site outside the ones this agent is allowed to visit"
return None
async def resolves_private(host: str) -> bool:
"""Whether any address the name resolves to is private. A name that does not resolve counts
as private: this is an address a page chose, and it is asked again on every request."""
h = (host or "").strip().lower().rstrip(".").strip("[]")
if _ip_private(h):
return True
try:
ipaddress.ip_address(h)
return False
except ValueError:
pass
try:
infos = await asyncio.wait_for(asyncio.to_thread(socket.getaddrinfo, h, None), 4)
except Exception: # noqa: BLE001