unrestricted.sh autoreg: HTTP flow, IMAP magic-link, farm pacing, key shim
This commit is contained in:
+202
@@ -0,0 +1,202 @@
|
||||
#!/usr/bin/env python3
|
||||
"""ur-shim — OpenAI-совместимый ротатор ключей api.unrestricted.sh для new-api.
|
||||
ENV: UR_PORT(48016) UR_BANK(/opt/ur-shim/bank.jsonl) UR_UPSTREAM(https://api.unrestricted.sh)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import urlparse
|
||||
|
||||
import requests
|
||||
|
||||
PORT = int(os.environ.get("UR_PORT", "48016"))
|
||||
BANK = os.environ.get("UR_BANK", "/opt/ur-shim/bank.jsonl")
|
||||
UPSTREAM = os.environ.get("UR_UPSTREAM", "https://api.unrestricted.sh").rstrip("/")
|
||||
DEAD = os.environ.get("UR_DEAD", "/opt/ur-shim/dead.json")
|
||||
DEAD_TTL = 6 * 3600
|
||||
LOCK = threading.Lock()
|
||||
STATE = {"keys": [], "idx": 0, "dead": {}, "mtime": 0}
|
||||
|
||||
|
||||
def load():
|
||||
with LOCK:
|
||||
try:
|
||||
mt = os.path.getmtime(BANK)
|
||||
except OSError:
|
||||
return
|
||||
if mt <= STATE["mtime"]:
|
||||
return
|
||||
keys, seen = [], set()
|
||||
try:
|
||||
with open(BANK, encoding="utf-8", errors="ignore") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
rec = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
k = rec.get("key") or ""
|
||||
if not k.startswith("unr_sk_") or k in seen:
|
||||
continue
|
||||
bal = rec.get("balance")
|
||||
if bal is not None and float(bal) <= 0:
|
||||
continue
|
||||
seen.add(k)
|
||||
keys.append(k)
|
||||
except OSError:
|
||||
return
|
||||
try:
|
||||
STATE["dead"] = json.load(open(DEAD))
|
||||
except Exception:
|
||||
STATE["dead"] = {}
|
||||
STATE["keys"] = keys
|
||||
STATE["mtime"] = mt
|
||||
print("bank reloaded: %d keys" % len(keys), flush=True)
|
||||
|
||||
|
||||
def alive_keys():
|
||||
now = time.time()
|
||||
out = []
|
||||
for k in STATE["keys"]:
|
||||
until = STATE["dead"].get(k, 0)
|
||||
if until and until > now:
|
||||
continue
|
||||
out.append(k)
|
||||
return out
|
||||
|
||||
|
||||
def mark_dead(k, why=""):
|
||||
with LOCK:
|
||||
STATE["dead"][k] = time.time() + DEAD_TTL
|
||||
try:
|
||||
json.dump(STATE["dead"], open(DEAD, "w"))
|
||||
except Exception:
|
||||
pass
|
||||
print("dead key %s… %s" % (k[:14], why), flush=True)
|
||||
|
||||
|
||||
def pick(n=3):
|
||||
ks = alive_keys()
|
||||
if not ks:
|
||||
return []
|
||||
start = STATE["idx"]
|
||||
out = [ks[(start + i) % len(ks)] for i in range(min(n, len(ks)))]
|
||||
with LOCK:
|
||||
STATE["idx"] = (start + 1) % max(1, len(ks))
|
||||
return out
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def log_message(self, *a):
|
||||
return
|
||||
|
||||
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.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self):
|
||||
p = urlparse(self.path).path
|
||||
if p in ("/health", "/status"):
|
||||
load()
|
||||
self._send(200, json.dumps({"ok": True, "keys": len(STATE["keys"]),
|
||||
"alive": len(alive_keys()),
|
||||
"dead": len(STATE["dead"]), "upstream": UPSTREAM}))
|
||||
return
|
||||
if p.startswith("/v1/models"):
|
||||
load()
|
||||
ks = pick(2)
|
||||
for k in ks:
|
||||
try:
|
||||
r = requests.get(UPSTREAM + "/v1/models", headers={"authorization": "Bearer " + k},
|
||||
timeout=25)
|
||||
if r.status_code == 200:
|
||||
self._send(200, r.content)
|
||||
return
|
||||
if r.status_code == 401:
|
||||
mark_dead(k, '401')
|
||||
elif r.status_code in (402, 403) and 'insufficient_quota' not in r.text:
|
||||
mark_dead(k, str(r.status_code))
|
||||
except Exception as e:
|
||||
print("models err", e, flush=True)
|
||||
self._send(502, json.dumps({"error": {"message": "ur-shim: no live keys"}}))
|
||||
return
|
||||
self._send(404, json.dumps({"error": {"message": "not found"}}))
|
||||
|
||||
def do_POST(self):
|
||||
n = int(self.headers.get("content-length") or 0)
|
||||
body = self.rfile.read(n)
|
||||
p = urlparse(self.path).path
|
||||
if not (p.endswith("/chat/completions") or p.endswith("/messages") or p.endswith("/completions")):
|
||||
self._send(404, json.dumps({"error": {"message": "unsupported path " + p}}))
|
||||
return
|
||||
load()
|
||||
target = UPSTREAM + p
|
||||
ks = pick(3)
|
||||
if not ks:
|
||||
self._send(503, json.dumps({"error": {"message": "ur-shim: no live keys"}}))
|
||||
return
|
||||
try:
|
||||
payload = json.loads(body.decode("utf-8", "ignore") or "{}")
|
||||
except Exception:
|
||||
payload = {}
|
||||
stream = bool(payload.get("stream"))
|
||||
last = None
|
||||
for k in ks:
|
||||
headers = {"authorization": "Bearer " + k, "content-type": "application/json",
|
||||
"accept": "text/event-stream" if stream else "application/json"}
|
||||
if self.headers.get("anthropic-version"):
|
||||
headers["anthropic-version"] = self.headers["anthropic-version"]
|
||||
try:
|
||||
r = requests.post(target, data=body, headers=headers, timeout=300, stream=stream)
|
||||
except Exception as e:
|
||||
last = (502, json.dumps({"error": {"message": "upstream " + str(e)}}))
|
||||
continue
|
||||
if r.status_code == 401:
|
||||
mark_dead(k, "401")
|
||||
last = (r.status_code, r.text[:400])
|
||||
continue
|
||||
if r.status_code in (402, 403) and 'insufficient_quota' not in r.text:
|
||||
mark_dead(k, "%s %s" % (r.status_code, r.text[:80]))
|
||||
last = (r.status_code, r.text[:400])
|
||||
continue
|
||||
if r.status_code == 429:
|
||||
last = (429, r.text[:200])
|
||||
continue
|
||||
if stream and r.status_code == 200:
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", r.headers.get("content-type", "text/event-stream"))
|
||||
self.send_header("cache-control", "no-cache")
|
||||
self.send_header("connection", "close")
|
||||
self.end_headers()
|
||||
try:
|
||||
for chunk in r.iter_content(chunk_size=None):
|
||||
if chunk:
|
||||
self.wfile.write(chunk)
|
||||
self.wfile.flush()
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
self._send(r.status_code, r.content,
|
||||
r.headers.get("content-type", "application/json"))
|
||||
return
|
||||
code, txt = last if last else (502, '{"error":{"message":"no keys"}}')
|
||||
self._send(code if code not in (401, 402, 403) else 429, txt)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
load()
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", PORT), H)
|
||||
print("ur-shim on 127.0.0.1:%d upstream=%s keys=%d" % (PORT, UPSTREAM, len(STATE["keys"])), flush=True)
|
||||
srv.serve_forever()
|
||||
Reference in New Issue
Block a user