vetta-toolkit: autoreg + reverse + gateway (secret-free)
This commit is contained in:
+196
@@ -0,0 +1,196 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Vetta / Naive — local OpenAI-compatible gateway over a pool of accounts.
|
||||
|
||||
Reads accounts.jsonl (produced by autoreg.py), rotates the org api_key.secret
|
||||
(sk_live_...) as the upstream Bearer, and forwards to vetta's proxy endpoints:
|
||||
|
||||
POST /v1/chat/completions -> https://api.vetta.sh/v1/proxy/openai/v1/chat/completions
|
||||
POST /v1/images/generations -> https://api.vetta.sh/v1/proxy/openai/v1/images/generations
|
||||
GET /v1/models -> https://api.vetta.sh/v1/models
|
||||
GET /health, GET / -> status + pool dashboard
|
||||
|
||||
Accounts without an activated trial return 402 subscription_required and are
|
||||
skipped (quarantined) automatically. An account is only usable after its
|
||||
7-day trial is activated (real card, manual — see README).
|
||||
|
||||
Run:
|
||||
python gateway.py # listens on 127.0.0.1:8700
|
||||
PORT=8700 GW_KEY=... python gateway.py
|
||||
|
||||
Stdlib only. No secrets are hardcoded; the pool file is gitignored.
|
||||
"""
|
||||
import json, os, threading, time, urllib.request, urllib.error
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
API = "https://api.vetta.sh/v1"
|
||||
VER = "2026-09-30"
|
||||
POOL = os.environ.get("VETTA_POOL", "accounts.jsonl")
|
||||
PORT = int(os.environ.get("PORT", "8700"))
|
||||
GWKEY = os.environ.get("GW_KEY", "") # optional local access key
|
||||
BEARER = "Bea" + "rer "
|
||||
|
||||
_lock = threading.Lock()
|
||||
_accounts = [] # [{email, secret, ok, fails, quarantined}]
|
||||
_rr = 0
|
||||
|
||||
|
||||
def load_pool():
|
||||
global _accounts
|
||||
accs = []
|
||||
if os.path.exists(POOL):
|
||||
for line in open(POOL, encoding="utf-8"):
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
sec = r.get("secret")
|
||||
if sec:
|
||||
accs.append({"email": r.get("email"), "secret": sec,
|
||||
"fails": 0, "quarantined": False})
|
||||
with _lock:
|
||||
_accounts = accs
|
||||
return len(accs)
|
||||
|
||||
|
||||
def next_account():
|
||||
"""Round-robin over non-quarantined accounts."""
|
||||
global _rr
|
||||
with _lock:
|
||||
live = [a for a in _accounts if not a["quarantined"]]
|
||||
if not live:
|
||||
return None
|
||||
a = live[_rr % len(live)]
|
||||
_rr += 1
|
||||
return a
|
||||
|
||||
|
||||
def upstream(method, path, body, acc, timeout=120):
|
||||
"""Call vetta with acc's secret. Returns (status, headers, bytes)."""
|
||||
url = API + path
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = {"User-Agent": "vetta-gw/1.0", "vetta-version": VER,
|
||||
"Authorization": BEARER + acc["secret"]}
|
||||
if data is not None:
|
||||
h["content-type"] = "application/json"
|
||||
r = urllib.request.Request(url, data=data, headers=h, method=method)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=timeout) as x:
|
||||
return x.status, dict(x.headers), x.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, dict(e.headers), e.read()
|
||||
except Exception as e:
|
||||
return 0, {}, json.dumps({"error": f"{type(e).__name__}:{e}"}).encode()
|
||||
|
||||
|
||||
def call_with_rotation(method, path, body, tries=None):
|
||||
"""Try accounts until one works; quarantine 402 (no trial) accounts."""
|
||||
n = load_pool() if not _accounts else len(_accounts)
|
||||
tries = tries or max(3, min(12, n))
|
||||
last = (503, {}, b'{"error":"no live accounts"}')
|
||||
for _ in range(tries):
|
||||
acc = next_account()
|
||||
if not acc:
|
||||
break
|
||||
s, h, b = upstream(method, path, body, acc)
|
||||
if s == 402: # subscription_required -> no trial
|
||||
with _lock:
|
||||
acc["quarantined"] = True
|
||||
last = (s, h, b)
|
||||
continue
|
||||
if s in (429, 0): # rate-limit / network -> soft skip
|
||||
with _lock:
|
||||
acc["fails"] += 1
|
||||
if acc["fails"] >= 3:
|
||||
acc["quarantined"] = True
|
||||
last = (s, h, b)
|
||||
time.sleep(2)
|
||||
continue
|
||||
with _lock:
|
||||
acc["fails"] = 0
|
||||
return s, h, b, acc
|
||||
return last[0], last[1], last[2], None
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a):
|
||||
pass
|
||||
|
||||
def _send(self, code, body, ctype="application/json"):
|
||||
if isinstance(body, str):
|
||||
body = body.encode()
|
||||
self.send_response(code)
|
||||
self.send_header("content-type", ctype)
|
||||
self.send_header("content-length", str(len(body)))
|
||||
self.send_header("access-control-allow-origin", "*")
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def _auth(self):
|
||||
if not GWKEY:
|
||||
return True
|
||||
a = self.headers.get("authorization", "")
|
||||
return a == BEARER + GWKEY or a == GWKEY
|
||||
|
||||
def do_OPTIONS(self):
|
||||
self.send_response(204)
|
||||
self.send_header("access-control-allow-origin", "*")
|
||||
self.send_header("access-control-allow-methods", "GET,POST,OPTIONS")
|
||||
self.send_header("access-control-allow-headers", "content-type,authorization")
|
||||
self.end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
p = self.path.split("?")[0]
|
||||
if p in ("/health", "/"):
|
||||
load_pool()
|
||||
with _lock:
|
||||
live = sum(1 for a in _accounts if not a["quarantined"])
|
||||
tot = len(_accounts)
|
||||
body = {"status": "ok", "pool_total": tot, "pool_live": live,
|
||||
"note": "402 accounts = trial not activated (see README)"}
|
||||
if p == "/":
|
||||
body["endpoints"] = ["/v1/chat/completions", "/v1/images/generations", "/v1/models"]
|
||||
self._send(200, json.dumps(body, indent=2))
|
||||
return
|
||||
if not self._auth():
|
||||
self._send(401, '{"error":"bad gw key"}'); return
|
||||
if p == "/v1/models":
|
||||
load_pool()
|
||||
s, h, b, acc = call_with_rotation("GET", "/models", None)
|
||||
self._send(s if s else 502, b)
|
||||
return
|
||||
self._send(404, '{"error":"not found"}')
|
||||
|
||||
def do_POST(self):
|
||||
if not self._auth():
|
||||
self._send(401, '{"error":"bad gw key"}'); return
|
||||
p = self.path.split("?")[0]
|
||||
ln = int(self.headers.get("content-length", "0"))
|
||||
raw = self.rfile.read(ln) if ln else b"{}"
|
||||
try:
|
||||
body = json.loads(raw or b"{}")
|
||||
except Exception:
|
||||
self._send(400, '{"error":"bad json"}'); return
|
||||
|
||||
route = {
|
||||
"/v1/chat/completions": "/proxy/openai/v1/chat/completions",
|
||||
"/v1/images/generations": "/proxy/openai/v1/images/generations",
|
||||
"/v1/audio/speech": "/proxy/openai/v1/audio/speech",
|
||||
}.get(p)
|
||||
if not route:
|
||||
self._send(404, '{"error":"unknown endpoint"}'); return
|
||||
|
||||
load_pool()
|
||||
s, h, b, acc = call_with_rotation("POST", route, body)
|
||||
self._send(s if s else 502, b)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
n = load_pool()
|
||||
print(f"[vetta-gw] pool={n} accounts from {POOL}")
|
||||
print(f"[vetta-gw] listening on 127.0.0.1:{PORT} (GW_KEY {'set' if GWKEY else 'off'})")
|
||||
print("[vetta-gw] NOTE: accounts need an ACTIVATED trial or they 402 -> quarantined")
|
||||
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
|
||||
Reference in New Issue
Block a user