feat: harden sms activation skill and add deterministic e2e runner

This commit is contained in:
luofengyuan committed 2026-05-18 18:23:17 +08:00
commit 702280a416
22 files changed
+24363

No files matched your search

View File
Whitespace-only changes.
+122
View File
@@ -0,0 +1,122 @@
from __future__ import annotations
import json
import os
import re
import time
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit
from dataclasses import dataclass
from typing import Any, Dict, Optional
import requests
class ProviderError(RuntimeError):
def __init__(self, provider: str, code: str, message: str, *, payload: Any = None):
super().__init__(f"{provider}:{code}:{message}")
self.provider = provider
self.code = code
self.message = message
self.payload = payload
@dataclass
class PollConfig:
attempts: int = 30
interval_sec: float = 3.0
backoff: float = 1.1
def now_ts() -> float:
return time.time()
def sleep_with_backoff(base: float, factor: float, i: int) -> None:
time.sleep(base * (factor ** i))
def parse_json_or_text(resp: requests.Response) -> Any:
ctype = resp.headers.get("content-type", "")
txt = resp.text
if "json" in ctype.lower():
return resp.json()
try:
return resp.json()
except Exception:
return txt.strip()
def extract_code(text: str) -> Optional[str]:
if not text:
return None
m = re.search(r"(?<!\d)(\d{4,8})(?!\d)", text)
return m.group(1) if m else None
def env_first(*names: str) -> Optional[str]:
for n in names:
v = os.getenv(n)
if v:
return v
return None
def read_state(path: str) -> Dict[str, Any]:
if not os.path.exists(path):
return {}
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def write_state(path: str, state: Dict[str, Any]) -> None:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(state, f, ensure_ascii=False, indent=2)
def mask_secret(value: Optional[str]) -> Optional[str]:
if not value:
return value
if len(value) <= 8:
return "*" * len(value)
return value[:4] + "..." + value[-4:]
def redact_url_secrets(url: str) -> str:
if not url:
return url
try:
parts = urlsplit(url)
q = []
for k, v in parse_qsl(parts.query, keep_blank_values=True):
if k.lower() in {"api_key", "token", "authorization", "auth", "key"}:
q.append((k, "***"))
else:
q.append((k, v))
return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(q), parts.fragment))
except Exception:
return url
def normalize_status(provider: str, status_raw: Any, payload: Any = None) -> str:
s = str(status_raw or "").upper()
if provider in {"smsvn", "grizzly"}:
if s.startswith("STATUS_WAIT_CODE") or s in {"WAIT_CODE", "WAITING"}:
return "waiting"
if s.startswith("STATUS_OK") or "CODE" in s:
return "code_received"
if "CANCEL" in s:
return "canceled"
if "ACCESS_ACTIVATION" in s or "FINISH" in s:
return "completed"
if provider == "5sim":
m = {
"PENDING": "waiting",
"RECEIVED": "code_received",
"FINISHED": "completed",
"CANCELED": "canceled",
"TIMEOUT": "timeout",
"BANNED": "banned",
}
return m.get(s, "error")
return "error"
+62
View File
@@ -0,0 +1,62 @@
from __future__ import annotations
from typing import Any, Dict
import requests
from ._common import ProviderError, extract_code, normalize_status, parse_json_or_text
class FiveSimClient:
def __init__(self, token: str, base_url: str = "https://5sim.net"):
self.base_url = base_url.rstrip("/")
self.s = requests.Session()
self.s.headers.update({"Authorization": f"Bearer {token}", "Accept": "application/json"})
def _get(self, path: str, **params: Any) -> Any:
r = self.s.get(self.base_url + path, params=params or None, timeout=25)
if r.status_code in {401, 403}:
raise ProviderError("5sim", "AUTH", f"unauthorized ({r.status_code})", payload=r.text)
if r.status_code >= 400:
raise ProviderError("5sim", "HTTP", f"http {r.status_code}", payload=r.text)
return parse_json_or_text(r)
def profile(self) -> Dict[str, Any]:
return self._get("/v1/user/profile")
def guest_products(self, country: str, operator: str = "any") -> Any:
return self._get(f"/v1/guest/products/{country}/{operator}")
def guest_prices(self, country: str | None = None, product: str | None = None) -> Any:
params: Dict[str, Any] = {}
if country: params["country"] = country
if product: params["product"] = product
return self._get("/v1/guest/prices", **params)
def buy_activation(self, country: str, operator: str, product: str, max_price: float | None = None) -> Dict[str, Any]:
params: Dict[str, Any] = {}
if max_price is not None:
params["maxPrice"] = max_price
out = self._get(f"/v1/user/buy/activation/{country}/{operator}/{product}", **params)
if isinstance(out, dict) and out.get("id"):
return out
raise ProviderError("5sim", "BUY_FAILED", "unexpected buy response", payload=out)
def check(self, order_id: str) -> Dict[str, Any]:
out = self._get(f"/v1/user/check/{order_id}")
status_raw = out.get("status") if isinstance(out, dict) else ""
code = None
sms = out.get("sms") if isinstance(out, dict) else None
if isinstance(sms, list) and sms:
last = sms[-1] or {}
code = last.get("code") or extract_code(last.get("text", ""))
return {"provider": "5sim", "order": out, "status_raw": status_raw, "status": normalize_status("5sim", status_raw), "sms_code": code}
def finish(self, order_id: str) -> Any:
return self._get(f"/v1/user/finish/{order_id}")
def cancel(self, order_id: str) -> Any:
return self._get(f"/v1/user/cancel/{order_id}")
def ban(self, order_id: str) -> Any:
return self._get(f"/v1/user/ban/{order_id}")
+67
View File
@@ -0,0 +1,67 @@
from __future__ import annotations
from typing import Any, Dict
import requests
from ._common import ProviderError, extract_code, normalize_status, parse_json_or_text, redact_url_secrets
class GrizzlyClient:
def __init__(self, api_key: str, base_url: str = "https://api.grizzlysms.com/stubs/handler_api.php", lang: str = "en"):
self.api_key = api_key
self.base_url = base_url
self.lang = lang
def _call(self, action: str, **params: Any) -> Any:
q = {"api_key": self.api_key, "action": action, "lang": self.lang, **params}
try:
r = requests.get(self.base_url, params=q, timeout=20)
r.raise_for_status()
except requests.RequestException as e:
req = getattr(e, "request", None)
req_url = getattr(req, "url", "") or (getattr(e, "response", None).url if getattr(e, "response", None) else "")
safe_url = redact_url_secrets(req_url)
status = getattr(getattr(e, "response", None), "status_code", None)
code = f"HTTP_{status}" if status else "REQUEST_ERROR"
raise ProviderError("grizzly", code, f"{action} request failed", payload={"url": safe_url, "status": status}) from None
out = parse_json_or_text(r)
if isinstance(out, str) and out in {"BAD_KEY", "NO_NUMBERS", "SERVICE_UNAVAILABLE_REGION", "BAD_ACTION", "NO_ACTIVATION", "REQUEST_LIMIT"}:
raise ProviderError("grizzly", out, out, payload=out)
return out
def balance(self) -> Dict[str, Any]:
out = self._call("getBalance")
return {"provider": "grizzly", "balance": str(out)}
def get_number(
self,
service: str,
country: int,
max_price: float | None = None,
provider_ids: str | None = None,
except_provider_ids: str | None = None,
v2: bool = True,
) -> Dict[str, Any]:
action = "getNumberV2" if v2 else "getNumber"
p: Dict[str, Any] = {"service": service, "country": country}
if max_price is not None: p["maxPrice"] = max_price
if provider_ids: p["providerIds"] = provider_ids
if except_provider_ids: p["exceptProviderIds"] = except_provider_ids
out = self._call(action, **p)
if isinstance(out, str) and out.startswith("ACCESS_NUMBER:"):
_, aid, phone = out.split(":", 2)
return {"activationId": aid, "phoneNumber": phone, "raw": out}
if isinstance(out, dict):
return out
raise ProviderError("grizzly", "UNEXPECTED", f"unexpected get_number response: {out}", payload=out)
def get_status(self, activation_id: str) -> Dict[str, Any]:
out = self._call("getStatus", id=activation_id)
raw = str(out)
code = raw.split(":", 1)[1] if raw.startswith("STATUS_OK:") else extract_code(raw)
return {"provider": "grizzly", "activation_id": activation_id, "status_raw": raw, "status": normalize_status("grizzly", raw), "sms_code": code}
def set_status(self, activation_id: str, status: int) -> Dict[str, Any]:
out = self._call("setStatus", id=activation_id, status=status)
return {"provider": "grizzly", "activation_id": activation_id, "result": out}
+68
View File
@@ -0,0 +1,68 @@
from __future__ import annotations
from typing import Any, Dict
import requests
from ._common import ProviderError, extract_code, normalize_status, parse_json_or_text, redact_url_secrets
class SmsVnClient:
def __init__(self, api_key: str, lang: str = "en", base_url: str = "https://sms-verification-number.com/stubs/handler_api"):
self.api_key = api_key
self.lang = lang
self.base_url = base_url
def _call(self, action: str, **params: Any) -> Any:
q = {"api_key": self.api_key, "action": action, "lang": self.lang, **params}
try:
r = requests.get(self.base_url, params=q, timeout=20)
r.raise_for_status()
except requests.RequestException as e:
req = getattr(e, "request", None)
req_url = getattr(req, "url", "") or (getattr(e, "response", None).url if getattr(e, "response", None) else "")
safe_url = redact_url_secrets(req_url)
status = getattr(getattr(e, "response", None), "status_code", None)
code = f"HTTP_{status}" if status else "REQUEST_ERROR"
raise ProviderError("smsvn", code, f"{action} request failed", payload={"url": safe_url, "status": status}) from None
out = parse_json_or_text(r)
if isinstance(out, str) and out in {
"NO_BALANCE", "NO_NUMBERS", "BAD_ACTION", "BAD_KEY", "BAD_LANG", "NO_ACTIVATION", "ERROR_SQL", "ERROR_API", "REQUEST_LIMIT",
}:
raise ProviderError("smsvn", out, out, payload=out)
return out
def balance(self) -> Dict[str, Any]:
out = self._call("getBalance")
return {"provider": "smsvn", "balance": str(out).strip()}
def countries(self) -> Any:
return self._call("getCountryAndOperators")
def services(self, country: int) -> Any:
return self._call("getServicesAndCostWithStatistics", country=country)
def get_number(self, service: str, country: int, operator: str = "any", max_price: float | None = None, v2: bool = True) -> Dict[str, Any]:
action = "getNumberV2" if v2 else "getNumber"
p: Dict[str, Any] = {"service": service, "country": country, "operator": operator}
if max_price is not None:
p["maxPrice"] = max_price
out = self._call(action, **p)
if isinstance(out, str) and out.startswith("ACCESS_NUMBER:"):
_, aid, phone = out.split(":", 2)
return {"activationId": aid, "phoneNumber": phone, "raw": out}
if isinstance(out, dict):
return out
raise ProviderError("smsvn", "UNEXPECTED", f"unexpected get_number response: {out}", payload=out)
def get_status(self, activation_id: str) -> Dict[str, Any]:
out = self._call("getStatus", id=activation_id)
raw = str(out)
code = None
if raw.startswith("STATUS_OK:"):
code = raw.split(":", 1)[1]
return {"provider": "smsvn", "activation_id": activation_id, "status_raw": raw, "status": normalize_status("smsvn", raw), "sms_code": code or extract_code(raw)}
def set_status(self, activation_id: str, status: int) -> Dict[str, Any]:
out = self._call("setStatus", id=activation_id, status=status)
return {"provider": "smsvn", "activation_id": activation_id, "result": out}