feat: harden sms activation skill and add deterministic e2e runner
This commit is contained in:
commit
702280a416
22 files changed
+24363
No files matched your search
Executable
+104
@@ -0,0 +1,104 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Deterministic E2E runner for sms-activation-providers.
|
||||
|
||||
Usage:
|
||||
python3 scripts/e2e_ci.py
|
||||
"""
|
||||
import json
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
BASE = ["python3", "scripts/sms_activation.py"]
|
||||
REPORT_JSON = Path("reports/e2e_result.json")
|
||||
REPORT_MD = Path("reports/e2e-acceptance.md")
|
||||
|
||||
|
||||
def run(args):
|
||||
p = subprocess.run(BASE + args, capture_output=True, text=True)
|
||||
item = {
|
||||
"cmd": " ".join(shlex.quote(x) for x in BASE + args),
|
||||
"rc": p.returncode,
|
||||
"stdout": p.stdout.strip(),
|
||||
"stderr": p.stderr.strip(),
|
||||
}
|
||||
try:
|
||||
item["json"] = json.loads(p.stdout) if p.stdout.strip() else None
|
||||
except Exception:
|
||||
item["json"] = None
|
||||
return item
|
||||
|
||||
|
||||
def extract_order_id(js):
|
||||
if isinstance(js, dict):
|
||||
return js.get("activationId") or js.get("id")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
Path("reports").mkdir(exist_ok=True)
|
||||
out = {"ts": time.strftime("%Y-%m-%d %H:%M:%S"), "runs": []}
|
||||
|
||||
# Proven combinations from live validation on 2026-05-18
|
||||
plans = {
|
||||
"smsvn": {"country": "12", "operator": "any", "service": "am", "max_price": "0.2"},
|
||||
"5sim": {"country": "usa", "operator": "any", "service": "amazon", "max_price": "0.2"},
|
||||
"grizzly": {"country": "187", "service": "tg", "max_price": "2", "force_v1": True},
|
||||
}
|
||||
|
||||
for provider, plan in plans.items():
|
||||
out["runs"].append(run(["--provider", provider, "--raw", "balance"]))
|
||||
|
||||
if provider == "smsvn":
|
||||
out["runs"].append(run(["--provider", provider, "--raw", "discover", "--country", plan["country"]]))
|
||||
elif provider == "5sim":
|
||||
out["runs"].append(run(["--provider", provider, "--raw", "discover", "--country", plan["country"], "--operator", plan["operator"]]))
|
||||
else:
|
||||
out["runs"].append(run(["--provider", provider, "--raw", "discover"]))
|
||||
|
||||
buy_args = ["--provider", provider, "--raw", "buy", "--country", plan["country"], "--service", plan["service"], "--max-price", plan["max_price"]]
|
||||
if provider in {"smsvn", "5sim"}:
|
||||
buy_args += ["--operator", plan["operator"]]
|
||||
if plan.get("force_v1"):
|
||||
buy_args += ["--v1"]
|
||||
buy = run(buy_args)
|
||||
out["runs"].append(buy)
|
||||
|
||||
oid = extract_order_id(buy.get("json"))
|
||||
if not oid:
|
||||
continue
|
||||
|
||||
oid = str(oid)
|
||||
out["runs"].append(run(["--provider", provider, "--raw", "check", "--order-id", oid]))
|
||||
out["runs"].append(run(["--provider", provider, "--raw", "poll", "--order-id", oid, "--attempts", "4", "--interval", "2", "--backoff", "1.05"]))
|
||||
|
||||
if provider == "5sim":
|
||||
out["runs"].append(run(["--provider", provider, "--raw", "finish", "--order-id", oid]))
|
||||
else:
|
||||
out["runs"].append(run(["--provider", provider, "--raw", "cancel", "--order-id", oid]))
|
||||
|
||||
REPORT_JSON.write_text(json.dumps(out, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
lines = [
|
||||
"# E2E Acceptance Report",
|
||||
"",
|
||||
f"Date: {out['ts']}",
|
||||
"",
|
||||
"Generated by `python3 scripts/e2e_ci.py`.",
|
||||
"",
|
||||
"## Run Summary",
|
||||
"",
|
||||
]
|
||||
for i, r in enumerate(out["runs"], 1):
|
||||
state = "OK" if r["rc"] == 0 else "FAIL"
|
||||
lines.append(f"{i}. [{state}] `{r['cmd']}`")
|
||||
lines += ["", "Raw details: `reports/e2e_result.json`", ""]
|
||||
REPORT_MD.write_text("\n".join(lines), encoding="utf-8")
|
||||
|
||||
print(f"Wrote {REPORT_JSON}")
|
||||
print(f"Wrote {REPORT_MD}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
import json, subprocess, shlex, time
|
||||
from pathlib import Path
|
||||
|
||||
BASE = ["python3", "scripts/sms_activation.py"]
|
||||
OUT = {"ts": time.strftime("%Y-%m-%d %H:%M:%S"), "runs": []}
|
||||
|
||||
|
||||
def run(args):
|
||||
p = subprocess.run(BASE + args, capture_output=True, text=True)
|
||||
item = {
|
||||
"cmd": " ".join(shlex.quote(x) for x in BASE + args),
|
||||
"rc": p.returncode,
|
||||
"stdout": p.stdout.strip(),
|
||||
"stderr": p.stderr.strip(),
|
||||
}
|
||||
try:
|
||||
item["json"] = json.loads(p.stdout) if p.stdout.strip() else None
|
||||
except Exception:
|
||||
item["json"] = None
|
||||
OUT["runs"].append(item)
|
||||
return item
|
||||
|
||||
# Provider plans chosen for likely availability and low cost
|
||||
plans = {
|
||||
"smsvn": {"country": "0", "operator": "any", "service": "tg", "max_price": "0.5"},
|
||||
"5sim": {"country": "any", "operator": "any", "service": "telegram", "max_price": "0.5"},
|
||||
"grizzly": {"country": "0", "operator": "any", "service": "tg", "max_price": "0.5"},
|
||||
}
|
||||
|
||||
for provider, plan in plans.items():
|
||||
run(["--provider", provider, "--raw", "balance"])
|
||||
run(["--provider", provider, "--raw", "discover"])
|
||||
|
||||
buy_args = ["--provider", provider, "--raw", "buy", "--country", plan["country"], "--service", plan["service"], "--max-price", plan["max_price"]]
|
||||
if provider in ("smsvn", "5sim"):
|
||||
buy_args += ["--operator", plan["operator"]]
|
||||
b = run(buy_args)
|
||||
|
||||
data = b.get("json") or {}
|
||||
oid = None
|
||||
if isinstance(data, dict):
|
||||
oid = data.get("activationId") or data.get("id")
|
||||
|
||||
# if buy failed, continue next provider
|
||||
if not oid:
|
||||
continue
|
||||
|
||||
run(["--provider", provider, "--raw", "check", "--order-id", str(oid)])
|
||||
run(["--provider", provider, "--raw", "poll", "--order-id", str(oid), "--attempts", "6", "--interval", "2", "--backoff", "1.05"])
|
||||
|
||||
# best-effort cleanup
|
||||
run(["--provider", provider, "--raw", "cancel", "--order-id", str(oid)])
|
||||
|
||||
Path("reports/e2e_result.json").write_text(json.dumps(OUT, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print("wrote reports/e2e_result.json")
|
||||
Executable
+185
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python3
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
from typing import Any, Dict
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(__file__))
|
||||
if ROOT not in sys.path:
|
||||
sys.path.insert(0, ROOT)
|
||||
|
||||
from protocols._common import PollConfig, ProviderError, env_first, now_ts, read_state, sleep_with_backoff, write_state
|
||||
from protocols.fivesim import FiveSimClient
|
||||
from protocols.grizzly import GrizzlyClient
|
||||
from protocols.smsvn import SmsVnClient
|
||||
|
||||
# Hardcoded fallback keys for this skill workspace.
|
||||
# Environment variables still take precedence for easy override/rotation.
|
||||
HARDCODED_KEYS = {
|
||||
"smsvn": "9e0c6fa9cc3040c0b65c15e6c35aa3b3",
|
||||
"5sim": "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3OTI4MDQ4NTEsImlhdCI6MTc2MTI2ODg1MSwicmF5IjoiM2NiNzMyNDYwOWZhOWE2NzY4YWNhMjFjMTUxOTY4ZTQiLCJzdWIiOjI5ODI3Mjh9.K7mIk1P4N9UBqLST2i2LE27tq_qgECM_WvcAlls6OkJSd9AyPjc8J9pt3crcISfGlXucFB8rt2-g4qJQpecREHj8H-bkGA8P5q2wZlVrTSuqVUfwDQQS2_rkbdc8L7vzoZMA-_P9jQmsxIOmZucq6qDBG4UT0KOxKE6KvlqJq37pUxoFxxSJSOOjqPgyPV62WhC0VFrAZitnkuvsavuCWhU_6CkJhC2F7Do-LlIHdOTWGpIw5_PCBjSheLQg_ymmmwLZPlqfYsnSDrWLi2ZykGgI4Zo13gTzUD7gDljRvLUNv8P4y0yRndECLbNPMWRcDV6A9sYPy2BHpZLcsrbaTA",
|
||||
"grizzly": "91d5f04819f20eafbb51f991126f1f54",
|
||||
}
|
||||
|
||||
|
||||
def get_client(provider: str):
|
||||
if provider == "smsvn":
|
||||
key = env_first("SMS_VERIFICATION_NUMBER_API_KEY", "SMSVN_API_KEY") or HARDCODED_KEYS["smsvn"]
|
||||
if not key:
|
||||
raise RuntimeError("missing SMS_VERIFICATION_NUMBER_API_KEY")
|
||||
return SmsVnClient(api_key=key)
|
||||
if provider == "5sim":
|
||||
tok = env_first("FIVE_SIM_API_TOKEN", "FIVESIM_API_TOKEN") or HARDCODED_KEYS["5sim"]
|
||||
if not tok:
|
||||
raise RuntimeError("missing FIVE_SIM_API_TOKEN")
|
||||
return FiveSimClient(token=tok)
|
||||
if provider == "grizzly":
|
||||
key = env_first("GRIZZLYSMS_API_KEY", "GRIZZLY_API_KEY") or HARDCODED_KEYS["grizzly"]
|
||||
if not key:
|
||||
raise RuntimeError("missing GRIZZLYSMS_API_KEY")
|
||||
return GrizzlyClient(api_key=key)
|
||||
raise RuntimeError(f"unknown provider: {provider}")
|
||||
|
||||
|
||||
def do_balance(client, provider: str):
|
||||
if provider == "5sim":
|
||||
p = client.profile()
|
||||
return {"provider": "5sim", "balance": p.get("balance"), "rating": p.get("rating")}
|
||||
return client.balance()
|
||||
|
||||
|
||||
def do_buy(client, args):
|
||||
if args.provider == "smsvn":
|
||||
return client.get_number(service=args.service, country=int(args.country), operator=args.operator, max_price=args.max_price, v2=not args.v1)
|
||||
if args.provider == "grizzly":
|
||||
return client.get_number(service=args.service, country=int(args.country), max_price=args.max_price, provider_ids=args.provider_ids, except_provider_ids=args.except_provider_ids, v2=not args.v1)
|
||||
return client.buy_activation(country=args.country, operator=args.operator, product=args.service, max_price=args.max_price)
|
||||
|
||||
|
||||
def do_check(client, args):
|
||||
if args.provider == "5sim":
|
||||
return client.check(args.order_id)
|
||||
return client.get_status(args.order_id)
|
||||
|
||||
|
||||
def do_finish(client, args):
|
||||
if args.provider == "5sim":
|
||||
return client.finish(args.order_id)
|
||||
return client.set_status(args.order_id, 6)
|
||||
|
||||
|
||||
def do_cancel(client, args):
|
||||
if args.provider == "5sim":
|
||||
return client.cancel(args.order_id)
|
||||
return client.set_status(args.order_id, 8)
|
||||
|
||||
|
||||
def do_ban(client, args):
|
||||
if args.provider == "5sim":
|
||||
return client.ban(args.order_id)
|
||||
return {"provider": args.provider, "error": "ban_not_supported_by_default"}
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description="SMS activation unified operator")
|
||||
ap.add_argument("--provider", choices=["smsvn", "5sim", "grizzly"], required=True)
|
||||
ap.add_argument("--state-file", default=".sms-skill/state.json")
|
||||
ap.add_argument("--raw", action="store_true")
|
||||
ap.add_argument("--debug-errors", action="store_true", help="include sanitized payload details in error output")
|
||||
|
||||
sub = ap.add_subparsers(dest="cmd", required=True)
|
||||
sub.add_parser("balance")
|
||||
|
||||
p_cov = sub.add_parser("discover")
|
||||
p_cov.add_argument("--country")
|
||||
p_cov.add_argument("--operator", default="any")
|
||||
p_cov.add_argument("--service")
|
||||
|
||||
p_buy = sub.add_parser("buy")
|
||||
p_buy.add_argument("--country", required=True)
|
||||
p_buy.add_argument("--operator", default="any")
|
||||
p_buy.add_argument("--service", required=True)
|
||||
p_buy.add_argument("--max-price", type=float)
|
||||
p_buy.add_argument("--provider-ids")
|
||||
p_buy.add_argument("--except-provider-ids")
|
||||
p_buy.add_argument("--v1", action="store_true")
|
||||
|
||||
p_chk = sub.add_parser("check")
|
||||
p_chk.add_argument("--order-id", required=True)
|
||||
|
||||
p_poll = sub.add_parser("poll")
|
||||
p_poll.add_argument("--order-id", required=True)
|
||||
p_poll.add_argument("--attempts", type=int, default=30)
|
||||
p_poll.add_argument("--interval", type=float, default=3.0)
|
||||
p_poll.add_argument("--backoff", type=float, default=1.08)
|
||||
|
||||
for name in ["finish", "cancel", "ban"]:
|
||||
p = sub.add_parser(name)
|
||||
p.add_argument("--order-id", required=True)
|
||||
|
||||
args = ap.parse_args()
|
||||
state = read_state(args.state_file)
|
||||
|
||||
try:
|
||||
client = get_client(args.provider)
|
||||
if args.cmd == "balance":
|
||||
out = do_balance(client, args.provider)
|
||||
elif args.cmd == "discover":
|
||||
if args.provider == "smsvn":
|
||||
if not args.country:
|
||||
out = client.countries()
|
||||
elif not args.service:
|
||||
out = client.services(int(args.country))
|
||||
else:
|
||||
out = client._call("getPrices", country=int(args.country))
|
||||
elif args.provider == "5sim":
|
||||
if not args.country:
|
||||
out = client._get("/v1/guest/countries")
|
||||
elif not args.service:
|
||||
out = client.guest_products(args.country, args.operator)
|
||||
else:
|
||||
out = client.guest_prices(args.country, args.service)
|
||||
else:
|
||||
out = {"provider": "grizzly", "note": "activation API discovery is limited; use service/country catalog sources if available"}
|
||||
elif args.cmd == "buy":
|
||||
out = do_buy(client, args)
|
||||
oid = out.get("activationId") or out.get("id")
|
||||
phone = out.get("phoneNumber") or out.get("phone")
|
||||
state[args.provider] = {"order_id": str(oid) if oid else None, "phone": phone, "service": args.service, "country": args.country, "updated_at": now_ts()}
|
||||
write_state(args.state_file, state)
|
||||
elif args.cmd == "check":
|
||||
out = do_check(client, args)
|
||||
elif args.cmd == "poll":
|
||||
cfg = PollConfig(attempts=args.attempts, interval_sec=args.interval, backoff=args.backoff)
|
||||
last: Dict[str, Any] = {}
|
||||
for i in range(cfg.attempts):
|
||||
last = do_check(client, argparse.Namespace(provider=args.provider, order_id=args.order_id))
|
||||
if last.get("status") in {"code_received", "completed", "canceled", "timeout", "banned", "error"}:
|
||||
break
|
||||
sleep_with_backoff(cfg.interval_sec, cfg.backoff, i)
|
||||
out = last
|
||||
elif args.cmd == "finish":
|
||||
out = do_finish(client, args)
|
||||
elif args.cmd == "cancel":
|
||||
out = do_cancel(client, args)
|
||||
else:
|
||||
out = do_ban(client, args)
|
||||
except ProviderError as e:
|
||||
out = {"ok": False, "provider": e.provider, "error_code": e.code, "error": e.message}
|
||||
if args.debug_errors and e.payload is not None:
|
||||
out["payload"] = e.payload
|
||||
except Exception as e:
|
||||
out = {"ok": False, "error": str(e)}
|
||||
|
||||
if args.raw:
|
||||
print(json.dumps(out, ensure_ascii=False, indent=2, default=str))
|
||||
else:
|
||||
print(json.dumps(out, ensure_ascii=False, default=str))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in new issue
Block a user