diff --git a/README.md b/README.md index 5e3d470..6dcdfd9 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,24 @@ Autoreg for [Composio](https://composio.dev) accounts and `ck_...` consumer API Free tier: **$0, no card**, $2 credits one-time, up to 3 members, **10,000 tool calls/month**, all 1,700+ toolkits connectable. Instant tools (Exa, Apollo, Higgsfield, ...) run on the $2 credit with 0% markup. +## Start here + +- **[docs/GUIDE.md](docs/GUIDE.md)** — пошагово от пула почт до рабочего ключа: команды, проверки, лимиты, FAQ по пойманным ошибкам. +- **Dashboard + rotator** — `python dash/app.py --bank bank/accounts.jsonl --port 8850 --rotator 8851` + + + +Dashboard shows the pool (accounts, live keys, credit, calls/month), filters, per-account +**Проверить** button and **Проверить все**. Rotator on `:8851` hands out keys round-robin: + +```bash +curl -s -X POST http://127.0.0.1:8851/run -H 'content-type: application/json' \ + -d '{"tool":"COMPOSIO_SEARCH_TOOLS","arguments":{"query":"gmail send email"}}' +``` + +`GET /next` — next alive key, `GET /stats` — counters. Stdlib only, no build, keys masked in UI. +Try it on sample data: `python dash/app.py --bank bank.sample.jsonl --port 8850 --rotator 8851` + ## Why a real browser Composio runs on **WorkOS AuthKit hosted** (`login.composio.dev`, deployment `hosted-authkit-2f3c943e...`). diff --git a/bank.sample.jsonl b/bank.sample.jsonl new file mode 100644 index 0000000..ff43087 --- /dev/null +++ b/bank.sample.jsonl @@ -0,0 +1,8 @@ +{"email": "061845…@example.com", "workspace": "0618455607-001_workspace", "api_key": "ck_sample_000000000000000000000", "credit_usd": 2, "ok": true, "stage": "", "last_check": "", "alive": null} +{"email": "068032…@example.com", "workspace": "demo_workspace", "api_key": "ck_sample_000000000000000000001", "credit_usd": 0, "ok": false, "stage": "key", "last_check": "", "alive": null} +{"email": "andrea…@example.com", "workspace": "demo_workspace", "api_key": "ck_sample_000000000000000000002", "credit_usd": 0, "ok": false, "stage": "exc", "last_check": "", "alive": null} +{"email": "andrea…@example.com", "workspace": "demo_workspace", "api_key": "ck_sample_000000000000000000003", "credit_usd": 0, "ok": false, "stage": "exc", "last_check": "", "alive": null} +{"email": "andrea…@example.com", "workspace": "demo_workspace", "api_key": "ck_sample_000000000000000000004", "credit_usd": 0, "ok": false, "stage": "key", "last_check": "", "alive": null} +{"email": "andrea…@example.com", "workspace": "demo_workspace", "api_key": "ck_sample_000000000000000000005", "credit_usd": 0, "ok": false, "stage": "key", "last_check": "", "alive": null} +{"email": "andrea…@example.com", "workspace": "demo_workspace", "api_key": "ck_sample_000000000000000000006", "credit_usd": 0, "ok": false, "stage": "key", "last_check": "", "alive": null} +{"email": "andrea…@example.com", "workspace": "demo_workspace", "api_key": "ck_sample_000000000000000000007", "credit_usd": 0, "ok": false, "stage": "key", "last_check": "", "alive": null} diff --git a/dash/app.py b/dash/app.py new file mode 100644 index 0000000..7b9e441 --- /dev/null +++ b/dash/app.py @@ -0,0 +1,378 @@ +"""Composio pool dashboard + key rotator. + +Two servers in one process: + :8850 dashboard - cards, table, filters, live key checks + :8851 rotator - GET /next, GET /stats, POST /run (JSON, for scripts/agents) + +Usage: + python dash/app.py --bank bank/accounts.jsonl --port 8850 --rotator 8851 + python dash/app.py --bank bank.sample.jsonl --port 8850 --rotator 8851 + +Stdlib only. No build step. Keys are masked in the UI, never printed whole. +""" +import argparse +import json +import os +import threading +import time +import urllib.error +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlparse + +MCP = "https://connect.composio.dev/mcp" +LOCK = threading.Lock() +STATE = {"rr": 0, "served": 0, "checks": 0} + + +def mask(key): + if not key or len(key) < 12: + return "—" + return key[:7] + "…" + key[-4:] + + +class Bank: + def __init__(self, path): + self.path = path + self.rows = [] + self.load() + + def load(self): + rows = [] + if os.path.exists(self.path): + with open(self.path, encoding="utf-8", errors="replace") as fh: + for line in fh: + line = line.strip() + if not line: + continue + try: + r = json.loads(line) + except Exception: + continue + rows.append({ + "email": r.get("email", ""), + "workspace": r.get("workspace", ""), + "key": r.get("api_key", ""), + "credit": r.get("credit_usd", 0) or 0, + "ok": bool(r.get("ok")), + "stage": r.get("stage", ""), + "last_check": r.get("last_check", ""), + "alive": r.get("alive"), + }) + self.rows = rows + + def save(self): + tmp = self.path + ".tmp" + with open(tmp, "w", encoding="utf-8") as fh: + for r in self.rows: + fh.write(json.dumps({ + "email": r["email"], "workspace": r["workspace"], + "api_key": r["key"], "credit_usd": r["credit"], + "ok": r["ok"], "stage": r["stage"], + "last_check": r["last_check"], "alive": r["alive"], + }, ensure_ascii=False) + "\n") + os.replace(tmp, self.path) + + def stats(self): + total = len(self.rows) + ok = sum(1 for r in self.rows if r["ok"] and r["key"]) + alive = sum(1 for r in self.rows if r.get("alive") is True) + dead = sum(1 for r in self.rows if r.get("alive") is False) + credit = sum(float(r["credit"] or 0) for r in self.rows) + return {"accounts": total, "with_key": ok, "alive": alive, "dead": dead, + "credit_usd": round(credit, 2), "calls_month": ok * 10000, + "served": STATE["served"], "checks": STATE["checks"]} + + def alive_keys(self): + return [r["key"] for r in self.rows if r["ok"] and r["key"] and r.get("alive") is not False] + + +def check_key(key, timeout=20): + """MCP initialize. Returns (alive, detail).""" + body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "initialize", + "params": {"protocolVersion": "2024-11-05", + "capabilities": {}, + "clientInfo": {"name": "pool-dash", "version": "1.0"}}}).encode() + req = urllib.request.Request(MCP, data=body, method="POST", headers={ + "content-type": "application/json", + "accept": "application/json, text/event-stream", + "x-consumer-api-key": key, + }) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8", "replace") + return (resp.status == 200 and "serverInfo" in raw), f"HTTP {resp.status}" + except urllib.error.HTTPError as e: + return False, f"HTTP {e.code}" + except Exception as e: + return False, type(e).__name__ + + +BANK = None + + +class DashHandler(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _send(self, code, body, ctype="application/json; charset=utf-8"): + data = body.encode("utf-8") if isinstance(body, str) else body + self.send_response(code) + self.send_header("content-type", ctype) + self.send_header("content-length", str(len(data))) + self.send_header("cache-control", "no-store") + self.end_headers() + self.wfile.write(data) + + def do_GET(self): + u = urlparse(self.path) + if u.path in ("/", "/index.html"): + return self._send(200, HTML, "text/html; charset=utf-8") + if u.path == "/api/stats": + return self._send(200, json.dumps(BANK.stats())) + if u.path == "/api/accounts": + q = parse_qs(u.query).get("q", [""])[0].lower() + only_credit = parse_qs(u.query).get("credit", [""])[0] == "1" + out = [] + for i, r in enumerate(BANK.rows): + hay = f"{r['email']} {r['workspace']}".lower() + if q and q not in hay: + continue + if only_credit and not r["credit"]: + continue + out.append({"i": i, "email": r["email"], "workspace": r["workspace"], + "key": mask(r["key"]), "credit": r["credit"], + "ok": r["ok"], "alive": r["alive"], + "stage": r["stage"], "last_check": r["last_check"]}) + return self._send(200, json.dumps({"rows": out[:500], "total": len(out)})) + return self._send(404, json.dumps({"error": "not found"})) + + def do_POST(self): + u = urlparse(self.path) + length = int(self.headers.get("content-length") or 0) + payload = {} + if length: + try: + payload = json.loads(self.rfile.read(length).decode("utf-8", "replace")) + except Exception: + payload = {} + if u.path == "/api/check": + idx = payload.get("i") + if not isinstance(idx, int) or not (0 <= idx < len(BANK.rows)): + return self._send(400, json.dumps({"error": "bad index"})) + row = BANK.rows[idx] + alive, detail = check_key(row["key"]) if row["key"] else (False, "no key") + with LOCK: + row["alive"] = alive + row["last_check"] = time.strftime("%Y-%m-%d %H:%M") + STATE["checks"] += 1 + BANK.save() + return self._send(200, json.dumps({"i": idx, "alive": alive, "detail": detail})) + if u.path == "/api/checkall": + results = [] + + def work(i, r): + alive, detail = check_key(r["key"]) if r["key"] else (False, "no key") + with LOCK: + r["alive"] = alive + r["last_check"] = time.strftime("%Y-%m-%d %H:%M") + STATE["checks"] += 1 + results.append({"i": i, "alive": alive, "detail": detail}) + + threads = [] + for i, r in enumerate(BANK.rows): + if not r["key"]: + continue + t = threading.Thread(target=work, args=(i, r), daemon=True) + t.start() + threads.append(t) + if len(threads) % 6 == 0: + time.sleep(0.4) + for t in threads: + t.join(timeout=25) + with LOCK: + BANK.save() + alive = sum(1 for x in results if x["alive"]) + return self._send(200, json.dumps({"checked": len(results), "alive": alive})) + return self._send(404, json.dumps({"error": "not found"})) + + +class RotatorHandler(BaseHTTPRequestHandler): + def log_message(self, *a): + pass + + def _send(self, code, obj): + data = json.dumps(obj, ensure_ascii=False).encode() + self.send_response(code) + self.send_header("content-type", "application/json; charset=utf-8") + self.send_header("content-length", str(len(data))) + self.send_header("cache-control", "no-store") + self.end_headers() + self.wfile.write(data) + + def _next_key(self): + keys = BANK.alive_keys() + if not keys: + return None + with LOCK: + key = keys[STATE["rr"] % len(keys)] + STATE["rr"] += 1 + STATE["served"] += 1 + return key + + def do_GET(self): + u = urlparse(self.path) + if u.path == "/next": + k = self._next_key() + if not k: + return self._send(503, {"error": "no alive keys"}) + return self._send(200, {"key": k}) + if u.path == "/stats": + return self._send(200, BANK.stats()) + return self._send(404, {"error": "not found"}) + + def do_POST(self): + u = urlparse(self.path) + if u.path != "/run": + return self._send(404, {"error": "not found"}) + length = int(self.headers.get("content-length") or 0) + try: + payload = json.loads(self.rfile.read(length).decode("utf-8", "replace")) + except Exception: + return self._send(400, {"error": "bad json"}) + tool = payload.get("tool") + args = payload.get("arguments") or {} + if not tool: + return self._send(400, {"error": "tool required"}) + key = self._next_key() + if not key: + return self._send(503, {"error": "no alive keys"}) + if tool.startswith("COMPOSIO_"): + call_name, call_args = tool, args + else: + call_name = "COMPOSIO_MULTI_EXECUTE_TOOL" + call_args = {"tools": [{"tool_slug": tool, "arguments": args}]} + body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": {"name": call_name, "arguments": call_args}}).encode() + req = urllib.request.Request(MCP, data=body, method="POST", headers={ + "content-type": "application/json", + "accept": "application/json, text/event-stream", + "x-consumer-api-key": key}) + try: + with urllib.request.urlopen(req, timeout=180) as resp: + raw = resp.read().decode("utf-8", "replace") + except Exception as e: + return self._send(502, {"error": type(e).__name__}) + text = raw + for line in raw.splitlines(): + if line.startswith("data: "): + try: + text = json.loads(line[6:])["result"]["content"][0]["text"] + except Exception: + text = line[6:] + break + try: + return self._send(200, json.loads(text)) + except Exception: + return self._send(200, {"raw": text[:4000]}) + + +HTML = r"""
+ +ck_, ротатор на :8851| # | Адрес | Воркспейс | Ключ | Кредит | Статус | Проверен |
|---|
POST http://127.0.0.1:8851/run с телом {"tool":"COMPOSIO_SEARCH_TOOLS","arguments":{"query":"..."}}GET :8851/next · счётчики: GET :8851/stats
+