vendor lib modules (newapi_lib/gh_http/reg_http/proxy_patch/conol_secrets), repo-relative paths, requirements.txt, README accuracy fixes

This commit is contained in:
2026-10-20 07:30:44 +00:00
parent ad3f804ee3
commit bde89988c0
14 changed files with 2289 additions and 1068 deletions

View File

@@ -1,211 +1,212 @@
# beat_gh_reg.py — BeatAPI (new-api) авторег через GitHub OAuth. Без капчи (turnstile_enabled=False).
# Usage: python beat_gh_reg.py N [start_idx]
import sys, os, json, time, random, re, urllib.request, urllib.error, urllib.parse
sys.path.insert(0, 'C:/Users/User/tmp/regfarm/github_oauth')
import gh_http
API = 'https://api.beatapi.io/api'
CLIENT_ID = 'Ov23liL5qt3yDfI1xJi8'
REDIRECT_URI = 'https://beatapi.io/oauth/github'
AFF = '7WEA'
BANK = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'accounts.jsonl')
USED = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'used_gh.txt')
POOL = 'C:/Users/User/tmp/gh_accounts.json'
HDRS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0',
'Accept': 'application/json', 'Origin': 'https://beatapi.io', 'Referer': 'https://beatapi.io/'}
def api(path, method='GET', data=None, token=None, sid=None, uid=None):
h = dict(HDRS)
if token:
h['Authorization'] = 'Bea' + 'rer ' + token
if sid:
h['x-auth-session'] = sid
if uid:
h['New-Api-User'] = str(uid)
body = json.dumps(data).encode() if data is not None else None
if body:
h['Content-Type'] = 'application/json'
r = urllib.request.Request(API + path, data=body, headers=h, method=method)
try:
with urllib.request.urlopen(r, timeout=40) as resp:
return resp.status, json.loads(resp.read().decode('utf-8', 'replace'))
except urllib.error.HTTPError as e:
raw = e.read().decode('utf-8', 'replace')
try:
return e.code, json.loads(raw)
except Exception:
return e.code, {'raw': raw[:300]}
def load_used():
if os.path.exists(USED):
return set(l.strip() for l in open(USED) if l.strip())
return set()
def mark_used(login):
with open(USED, 'a') as f:
f.write(login + '\n')
def save(rec):
with open(BANK, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
def register_one(acc, idx):
login = acc['login']
out = {'idx': idx, 'gh_login': login, 'gh_email': acc.get('email'), 'ts': int(time.time())}
# 1. flow token
st, r = api('/oauth/state', 'POST', {'provider': 'github', 'intent': 'login', 'aff': AFF})
flow = None
if isinstance(r, str):
flow = r
elif isinstance(r, dict):
dd = r.get('data')
if isinstance(dd, dict):
flow = dd.get('flow_token')
elif isinstance(dd, str):
flow = dd
flow = flow or r.get('flow_token')
if not flow:
out['err'] = f'state {st}: {str(r)[:150]}'
return out
out['flow_token'] = flow[:16]
# 2. GH login
print(' step: gh login', flush=True)
s = gh_http.GHSession(bind=False)
try:
ok = s.login(login, acc['password'], acc.get('totp'))
except Exception as e:
out['err'] = f'gh_login exc: {e}'
return out
if not ok:
out['err'] = f'gh_login fail: {"; ".join(s.detail[-3:])[:200]}'
return out
# 3. authorize (custom: with redirect_uri)
print(' step: authorize', flush=True)
url = (f'https://github.com/login/oauth/authorize?client_id={CLIENT_ID}'
f'&redirect_uri={urllib.parse.quote(REDIRECT_URI, safe="")}'
f'&response_type=code&scope={urllib.parse.quote("read:user user:email")}'
f'&state={urllib.parse.quote(flow)}')
code, err = None, None
stt, hh, body = s.get(url)
loc = hh.get('Location', '')
if stt in (301, 302):
code = s._code_from(loc)
if not code:
err = f'redir no code: {loc[:120]}'
elif stt == 200:
# meta-refresh page ("OAuth application authorized") — code+state inside body
m = re.search(r'oauth/github\?code=([a-f0-9]{16,})[^"\']*state=([A-Za-z0-9_\-]+)', body)
if m:
code, flow = m.group(1), m.group(2)
else:
m = re.search(r'code=([a-f0-9]{16,})', body)
if m:
code = m.group(1)
if not code:
tok = re.search(r'name="authenticity_token"[^>]*value="([^"]+)"', body)
if tok:
fields = {'authorize': '1', 'authenticity_token': tok.group(1),
'client_id': CLIENT_ID, 'state': flow, 'scope': 'read:user user:email'}
st2, h2, b2 = s.post_form(url, fields)
loc2 = h2.get('Location', '')
code = s._code_from(loc2) if st2 in (301, 302) else None
if not code:
m2 = re.search(r'oauth/github\?code=([a-f0-9]{16,})[^"\']*state=([A-Za-z0-9_\-]+)', b2)
if m2:
code, flow = m2.group(1), m2.group(2)
if not code:
err = f'consent no code http={st2} loc={loc2[:100]}'
else:
err = f'no code/token (len={len(body)}) title={re.search(r"<title>([^<]*)", body).group(1) if re.search(r"<title>([^<]*)", body) else "?"}'
else:
err = f'authorize http={stt}'
if not code:
out['err'] = err or 'no code'
return out
out['code'] = code[:10]
# 4. exchange
print(' step: exchange', flush=True)
st, r = api(f'/oauth/github?code={urllib.parse.quote(code)}&state={urllib.parse.quote(flow)}')
if st != 200 or (isinstance(r, dict) and r.get('success') is False):
out['err'] = f'exchange {st}: {str(r)[:400]}'
return out
d = r.get('data', r) if isinstance(r, dict) else r
tok = d.get('access_token') or d.get('token')
if not tok:
out['err'] = f'no access_token: {str(r)[:200]}'
return out
out['access_token'] = tok
out['beat_user'] = d.get('username') or d.get('loginIdentifier')
out['user_id'] = d.get('user_id') or d.get('id')
sid = d.get('session_id') or (d.get('session') or {}).get('sid') or ''
# 5. self (quota)
st, r = api('/user/self', token=tok, sid=sid)
uid = None
if st == 200 and isinstance(r, dict):
dd = r.get('data', r)
out['quota'] = dd.get('quota')
out['beat_username'] = dd.get('username')
out['beat_id'] = dd.get('id')
uid = dd.get('id')
# 6. create API key (trailing slash! 307 otherwise)
st, r = api('/token/', 'POST', {'name': f'farm{int(time.time())%100000}', 'remain_quota': 500000,
'expired_time': -1, 'unlimited_quota': True,
'model_limits_enabled': False, 'model_limits': ''}, token=tok, sid=sid, uid=uid)
tid = None
if st == 200 and isinstance(r, dict) and r.get('success'):
d = r.get('data') or {}
tid = d.get('id') if isinstance(d, dict) else d
out['token_create'] = f'{st}:{str(r)[:120]}'
if tid:
# full key: POST /token/{id}/key with New-Api-User header (GET = 404)
st, r = api(f'/token/{tid}/key', 'POST', token=tok, sid=sid, uid=uid)
if st == 200 and isinstance(r, dict):
d = r.get('data') or {}
key = d.get('key') if isinstance(d, dict) else d
if key and '*' not in str(key):
out['api_key'] = key
out['token_id'] = tid
return out
def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
start = int(sys.argv[2]) if len(sys.argv) > 2 else 0
accs = json.load(open(POOL, encoding='utf-8'))
# gmail-domain accounts first (whitelisted + verified on GH)
accs = sorted(accs, key=lambda a: 0 if str(a.get('email', '')).endswith('@gmail.com') else 1)
used = load_used()
done = 0
i = start
while done < n and i < len(accs):
acc = accs[i]
i += 1
if acc['login'] in used:
continue
print(f'--- [{i-1}] {acc["login"]}', flush=True)
try:
rec = register_one(acc, i - 1)
except Exception as e:
rec = {'idx': i - 1, 'gh_login': acc['login'], 'err': f'exc: {e}'}
mark_used(acc['login'])
ok = bool(rec.get('access_token'))
print('OK' if rec.get('api_key') else ('PARTIAL' if ok else 'FAIL'), json.dumps({k: str(v)[:60] for k, v in rec.items() if k != 'access_token'}, ensure_ascii=False), flush=True)
if ok:
save(rec)
if rec.get('api_key'):
done += 1
elif '429' in str(rec.get('err', '')) or 'limit' in str(rec.get('err', '')).lower():
print('RATE LIMIT — sleeping 600s', flush=True)
time.sleep(600)
time.sleep(random.uniform(75, 110))
print(f'DONE {done}/{n}, next idx {i}')
if __name__ == '__main__':
main()
# beat_gh_reg.py — BeatAPI (new-api) авторег через GitHub OAuth. Без капчи (turnstile_enabled=False).
# Usage: python beat_gh_reg.py N [start_idx]
import os
import sys, os, json, time, random, re, urllib.request, urllib.error, urllib.parse
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
import gh_http
API = 'https://api.beatapi.io/api'
CLIENT_ID = 'Ov23liL5qt3yDfI1xJi8'
REDIRECT_URI = 'https://beatapi.io/oauth/github'
AFF = '7WEA'
BANK = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'accounts.jsonl')
USED = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'used_gh.txt')
POOL = 'C:/Users/User/tmp/gh_accounts.json'
HDRS = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/131.0',
'Accept': 'application/json', 'Origin': 'https://beatapi.io', 'Referer': 'https://beatapi.io/'}
def api(path, method='GET', data=None, token=None, sid=None, uid=None):
h = dict(HDRS)
if token:
h['Authorization'] = 'Bea' + 'rer ' + token
if sid:
h['x-auth-session'] = sid
if uid:
h['New-Api-User'] = str(uid)
body = json.dumps(data).encode() if data is not None else None
if body:
h['Content-Type'] = 'application/json'
r = urllib.request.Request(API + path, data=body, headers=h, method=method)
try:
with urllib.request.urlopen(r, timeout=40) as resp:
return resp.status, json.loads(resp.read().decode('utf-8', 'replace'))
except urllib.error.HTTPError as e:
raw = e.read().decode('utf-8', 'replace')
try:
return e.code, json.loads(raw)
except Exception:
return e.code, {'raw': raw[:300]}
def load_used():
if os.path.exists(USED):
return set(l.strip() for l in open(USED) if l.strip())
return set()
def mark_used(login):
with open(USED, 'a') as f:
f.write(login + '\n')
def save(rec):
with open(BANK, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
def register_one(acc, idx):
login = acc['login']
out = {'idx': idx, 'gh_login': login, 'gh_email': acc.get('email'), 'ts': int(time.time())}
# 1. flow token
st, r = api('/oauth/state', 'POST', {'provider': 'github', 'intent': 'login', 'aff': AFF})
flow = None
if isinstance(r, str):
flow = r
elif isinstance(r, dict):
dd = r.get('data')
if isinstance(dd, dict):
flow = dd.get('flow_token')
elif isinstance(dd, str):
flow = dd
flow = flow or r.get('flow_token')
if not flow:
out['err'] = f'state {st}: {str(r)[:150]}'
return out
out['flow_token'] = flow[:16]
# 2. GH login
print(' step: gh login', flush=True)
s = gh_http.GHSession(bind=False)
try:
ok = s.login(login, acc['password'], acc.get('totp'))
except Exception as e:
out['err'] = f'gh_login exc: {e}'
return out
if not ok:
out['err'] = f'gh_login fail: {"; ".join(s.detail[-3:])[:200]}'
return out
# 3. authorize (custom: with redirect_uri)
print(' step: authorize', flush=True)
url = (f'https://github.com/login/oauth/authorize?client_id={CLIENT_ID}'
f'&redirect_uri={urllib.parse.quote(REDIRECT_URI, safe="")}'
f'&response_type=code&scope={urllib.parse.quote("read:user user:email")}'
f'&state={urllib.parse.quote(flow)}')
code, err = None, None
stt, hh, body = s.get(url)
loc = hh.get('Location', '')
if stt in (301, 302):
code = s._code_from(loc)
if not code:
err = f'redir no code: {loc[:120]}'
elif stt == 200:
# meta-refresh page ("OAuth application authorized") — code+state inside body
m = re.search(r'oauth/github\?code=([a-f0-9]{16,})[^"\']*state=([A-Za-z0-9_\-]+)', body)
if m:
code, flow = m.group(1), m.group(2)
else:
m = re.search(r'code=([a-f0-9]{16,})', body)
if m:
code = m.group(1)
if not code:
tok = re.search(r'name="authenticity_token"[^>]*value="([^"]+)"', body)
if tok:
fields = {'authorize': '1', 'authenticity_token': tok.group(1),
'client_id': CLIENT_ID, 'state': flow, 'scope': 'read:user user:email'}
st2, h2, b2 = s.post_form(url, fields)
loc2 = h2.get('Location', '')
code = s._code_from(loc2) if st2 in (301, 302) else None
if not code:
m2 = re.search(r'oauth/github\?code=([a-f0-9]{16,})[^"\']*state=([A-Za-z0-9_\-]+)', b2)
if m2:
code, flow = m2.group(1), m2.group(2)
if not code:
err = f'consent no code http={st2} loc={loc2[:100]}'
else:
err = f'no code/token (len={len(body)}) title={re.search(r"<title>([^<]*)", body).group(1) if re.search(r"<title>([^<]*)", body) else "?"}'
else:
err = f'authorize http={stt}'
if not code:
out['err'] = err or 'no code'
return out
out['code'] = code[:10]
# 4. exchange
print(' step: exchange', flush=True)
st, r = api(f'/oauth/github?code={urllib.parse.quote(code)}&state={urllib.parse.quote(flow)}')
if st != 200 or (isinstance(r, dict) and r.get('success') is False):
out['err'] = f'exchange {st}: {str(r)[:400]}'
return out
d = r.get('data', r) if isinstance(r, dict) else r
tok = d.get('access_token') or d.get('token')
if not tok:
out['err'] = f'no access_token: {str(r)[:200]}'
return out
out['access_token'] = tok
out['beat_user'] = d.get('username') or d.get('loginIdentifier')
out['user_id'] = d.get('user_id') or d.get('id')
sid = d.get('session_id') or (d.get('session') or {}).get('sid') or ''
# 5. self (quota)
st, r = api('/user/self', token=tok, sid=sid)
uid = None
if st == 200 and isinstance(r, dict):
dd = r.get('data', r)
out['quota'] = dd.get('quota')
out['beat_username'] = dd.get('username')
out['beat_id'] = dd.get('id')
uid = dd.get('id')
# 6. create API key (trailing slash! 307 otherwise)
st, r = api('/token/', 'POST', {'name': f'farm{int(time.time())%100000}', 'remain_quota': 500000,
'expired_time': -1, 'unlimited_quota': True,
'model_limits_enabled': False, 'model_limits': ''}, token=tok, sid=sid, uid=uid)
tid = None
if st == 200 and isinstance(r, dict) and r.get('success'):
d = r.get('data') or {}
tid = d.get('id') if isinstance(d, dict) else d
out['token_create'] = f'{st}:{str(r)[:120]}'
if tid:
# full key: POST /token/{id}/key with New-Api-User header (GET = 404)
st, r = api(f'/token/{tid}/key', 'POST', token=tok, sid=sid, uid=uid)
if st == 200 and isinstance(r, dict):
d = r.get('data') or {}
key = d.get('key') if isinstance(d, dict) else d
if key and '*' not in str(key):
out['api_key'] = key
out['token_id'] = tid
return out
def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
start = int(sys.argv[2]) if len(sys.argv) > 2 else 0
accs = json.load(open(POOL, encoding='utf-8'))
# gmail-domain accounts first (whitelisted + verified on GH)
accs = sorted(accs, key=lambda a: 0 if str(a.get('email', '')).endswith('@gmail.com') else 1)
used = load_used()
done = 0
i = start
while done < n and i < len(accs):
acc = accs[i]
i += 1
if acc['login'] in used:
continue
print(f'--- [{i-1}] {acc["login"]}', flush=True)
try:
rec = register_one(acc, i - 1)
except Exception as e:
rec = {'idx': i - 1, 'gh_login': acc['login'], 'err': f'exc: {e}'}
mark_used(acc['login'])
ok = bool(rec.get('access_token'))
print('OK' if rec.get('api_key') else ('PARTIAL' if ok else 'FAIL'), json.dumps({k: str(v)[:60] for k, v in rec.items() if k != 'access_token'}, ensure_ascii=False), flush=True)
if ok:
save(rec)
if rec.get('api_key'):
done += 1
elif '429' in str(rec.get('err', '')) or 'limit' in str(rec.get('err', '')).lower():
print('RATE LIMIT — sleeping 600s', flush=True)
time.sleep(600)
time.sleep(random.uniform(75, 110))
print(f'DONE {done}/{n}, next idx {i}')
if __name__ == '__main__':
main()

View File

@@ -1,105 +1,106 @@
# cleanapis.com mass reg: GitHub OAuth -> free Starter plan -> api key -> verify -> save
import sys, re, json, time, random, urllib.parse, requests, os
sys.path.insert(0, 'C:/Users/User/tmp/regfarm/github_oauth')
from gh_http import GHSession
CID = "Ov23li48tsmVvDWqWfhs"
SCOPE = "user:email,read:user"
GH_POOL = "C:/Users/User/tmp/gh_accounts.json"
OUT = "cleanapis_accounts.jsonl"
USED = "ca_used_gh.txt"
UA = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'}
def load_pool():
d = json.load(open(GH_POOL, encoding='utf-8'))
used = set()
try: used = set(open(USED).read().split())
except Exception: pass
return [a for a in d if a.get('login') not in used]
def mark_used(login):
open(USED, 'a').write(login + '\n')
def reg_one(acc):
res = {'gh_login': acc['login'], 'ok': False, 'provider': 'github_oauth', 'ts': int(time.time())}
s = requests.Session(); s.headers.update(UA)
r = s.get('https://cleanapis.com/auth/github/redirect', allow_redirects=False, timeout=30)
q = urllib.parse.parse_qs(urllib.parse.urlparse(r.headers.get('Location', '')).query)
state = q.get('state', [None])[0]
if not state:
res['err'] = 'no state'; return res
ghs = GHSession(bind=False)
ok, msg = ghs.login(acc['login'], acc['password'], acc.get('totp'))
if not ok:
res['err'] = 'gh login: ' + str(msg)[:120]; return res
code, err = ghs.oauth_code(CID, state, scope=SCOPE)
if not code:
res['err'] = 'oauth: ' + str(err)[:150]; return res
cb = s.get('https://cleanapis.com/auth/github/callback?code=%s&state=%s' % (code, state), allow_redirects=True, timeout=40)
res['cb'] = cb.status_code
if '/login' in cb.url and 'dashboard' not in cb.url:
res['err'] = 'callback bounced'; return res
# activate free starter plan
g = s.get('https://cleanapis.com/dashboard/get-started?plan=starter', timeout=25)
csrf = re.findall(r'name="_token" value="([^"]+)"', g.text)
if csrf:
act = s.post('https://cleanapis.com/dashboard/billing/checkout/4',
data={'_token': csrf[0], 'billing_cycle': 'monthly', 'coupon_code': '', 'payment_method': 'paddle'},
allow_redirects=True, timeout=40,
headers={'Origin': 'https://cleanapis.com', 'Referer': 'https://cleanapis.com/dashboard/get-started?plan=starter'})
res['plan_ok'] = 'billing/success' in act.url or 'plan' in act.url
# create api key
t = s.get('https://cleanapis.com/dashboard/api-keys', timeout=25)
csrf2 = re.findall(r'name="_token" value="([^"]+)"', t.text)
if not csrf2:
res['err'] = 'no csrf api-keys'; return res
nm = 'farm%d' % random.randint(10000, 99999)
cr = s.post('https://cleanapis.com/dashboard/api-keys',
data={'_token': csrf2[0], 'name': nm, 'scopes[]': ['inference', 'models:read', 'embeddings']},
allow_redirects=True, timeout=40,
headers={'Origin': 'https://cleanapis.com', 'Referer': 'https://cleanapis.com/dashboard/api-keys'})
ids = re.findall(r'api-keys.{0,4}?(\d{4,7}).{0,4}?reveal', cr.text)
ids = list(dict.fromkeys(ids))
if not ids:
res['err'] = 'no key created'; return res
# reveal newest key (highest id)
kid = max(ids, key=int)
rv = s.get('https://cleanapis.com/dashboard/api-keys/%s/reveal' % kid, headers={'Accept': 'application/json'}, timeout=25)
try: d = rv.json()
except Exception: res['err'] = 'reveal non-json ' + rv.text[:80]; return res
if not d.get('ok'):
res['err'] = 'reveal fail: ' + str(d)[:100]; return res
k = d['key']
mr = requests.get('https://cleanapis.com/v1/models', headers={'Authorization': 'Bearer ' + k}, timeout=30)
res['models'] = mr.status_code
res['api_key'] = k
res['key_id'] = kid
res['ok'] = (mr.status_code == 200)
mark_used(acc['login'])
return res
def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
start = int(sys.argv[2]) if len(sys.argv) > 2 else 0
pool = load_pool()
print('pool free:', len(pool), 'start:', start, flush=True)
okc = fail429 = 0
for i, acc in enumerate(pool[start:start+n], start=start):
try:
r = reg_one(acc)
except Exception as e:
r = {'idx': i, 'gh_login': acc.get('login'), 'ok': False, 'err': 'EXC %s: %s' % (type(e).__name__, str(e)[:150])}
if r.get('ok'): okc += 1
if '429' in str(r.get('err', '')):
fail429 += 1
if fail429 >= 3:
print('3x429 -> sleep 1800s', flush=True)
time.sleep(1800); fail429 = 0
line = json.dumps(r, ensure_ascii=False)
print('[%d] %s' % (i, line), flush=True)
open(OUT, 'a', encoding='utf-8').write(line + '\n')
time.sleep(random.uniform(20, 35))
print('DONE ok=%d/%d' % (okc, n), flush=True)
if __name__ == '__main__':
main()
# cleanapis.com mass reg: GitHub OAuth -> free Starter plan -> api key -> verify -> save
import os
import sys, re, json, time, random, urllib.parse, requests, os
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
from gh_http import GHSession
CID = "Ov23li48tsmVvDWqWfhs"
SCOPE = "user:email,read:user"
GH_POOL = "C:/Users/User/tmp/gh_accounts.json"
OUT = "cleanapis_accounts.jsonl"
USED = "ca_used_gh.txt"
UA = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36'}
def load_pool():
d = json.load(open(GH_POOL, encoding='utf-8'))
used = set()
try: used = set(open(USED).read().split())
except Exception: pass
return [a for a in d if a.get('login') not in used]
def mark_used(login):
open(USED, 'a').write(login + '\n')
def reg_one(acc):
res = {'gh_login': acc['login'], 'ok': False, 'provider': 'github_oauth', 'ts': int(time.time())}
s = requests.Session(); s.headers.update(UA)
r = s.get('https://cleanapis.com/auth/github/redirect', allow_redirects=False, timeout=30)
q = urllib.parse.parse_qs(urllib.parse.urlparse(r.headers.get('Location', '')).query)
state = q.get('state', [None])[0]
if not state:
res['err'] = 'no state'; return res
ghs = GHSession(bind=False)
ok, msg = ghs.login(acc['login'], acc['password'], acc.get('totp'))
if not ok:
res['err'] = 'gh login: ' + str(msg)[:120]; return res
code, err = ghs.oauth_code(CID, state, scope=SCOPE)
if not code:
res['err'] = 'oauth: ' + str(err)[:150]; return res
cb = s.get('https://cleanapis.com/auth/github/callback?code=%s&state=%s' % (code, state), allow_redirects=True, timeout=40)
res['cb'] = cb.status_code
if '/login' in cb.url and 'dashboard' not in cb.url:
res['err'] = 'callback bounced'; return res
# activate free starter plan
g = s.get('https://cleanapis.com/dashboard/get-started?plan=starter', timeout=25)
csrf = re.findall(r'name="_token" value="([^"]+)"', g.text)
if csrf:
act = s.post('https://cleanapis.com/dashboard/billing/checkout/4',
data={'_token': csrf[0], 'billing_cycle': 'monthly', 'coupon_code': '', 'payment_method': 'paddle'},
allow_redirects=True, timeout=40,
headers={'Origin': 'https://cleanapis.com', 'Referer': 'https://cleanapis.com/dashboard/get-started?plan=starter'})
res['plan_ok'] = 'billing/success' in act.url or 'plan' in act.url
# create api key
t = s.get('https://cleanapis.com/dashboard/api-keys', timeout=25)
csrf2 = re.findall(r'name="_token" value="([^"]+)"', t.text)
if not csrf2:
res['err'] = 'no csrf api-keys'; return res
nm = 'farm%d' % random.randint(10000, 99999)
cr = s.post('https://cleanapis.com/dashboard/api-keys',
data={'_token': csrf2[0], 'name': nm, 'scopes[]': ['inference', 'models:read', 'embeddings']},
allow_redirects=True, timeout=40,
headers={'Origin': 'https://cleanapis.com', 'Referer': 'https://cleanapis.com/dashboard/api-keys'})
ids = re.findall(r'api-keys.{0,4}?(\d{4,7}).{0,4}?reveal', cr.text)
ids = list(dict.fromkeys(ids))
if not ids:
res['err'] = 'no key created'; return res
# reveal newest key (highest id)
kid = max(ids, key=int)
rv = s.get('https://cleanapis.com/dashboard/api-keys/%s/reveal' % kid, headers={'Accept': 'application/json'}, timeout=25)
try: d = rv.json()
except Exception: res['err'] = 'reveal non-json ' + rv.text[:80]; return res
if not d.get('ok'):
res['err'] = 'reveal fail: ' + str(d)[:100]; return res
k = d['key']
mr = requests.get('https://cleanapis.com/v1/models', headers={'Authorization': 'Bearer ' + k}, timeout=30)
res['models'] = mr.status_code
res['api_key'] = k
res['key_id'] = kid
res['ok'] = (mr.status_code == 200)
mark_used(acc['login'])
return res
def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
start = int(sys.argv[2]) if len(sys.argv) > 2 else 0
pool = load_pool()
print('pool free:', len(pool), 'start:', start, flush=True)
okc = fail429 = 0
for i, acc in enumerate(pool[start:start+n], start=start):
try:
r = reg_one(acc)
except Exception as e:
r = {'idx': i, 'gh_login': acc.get('login'), 'ok': False, 'err': 'EXC %s: %s' % (type(e).__name__, str(e)[:150])}
if r.get('ok'): okc += 1
if '429' in str(r.get('err', '')):
fail429 += 1
if fail429 >= 3:
print('3x429 -> sleep 1800s', flush=True)
time.sleep(1800); fail429 = 0
line = json.dumps(r, ensure_ascii=False)
print('[%d] %s' % (i, line), flush=True)
open(OUT, 'a', encoding='utf-8').write(line + '\n')
time.sleep(random.uniform(20, 35))
print('DONE ok=%d/%d' % (okc, n), flush=True)
if __name__ == '__main__':
main()

View File

@@ -0,0 +1,46 @@
"""
conol_secrets.py - single source of truth for credentials.
Secrets live in config.json (gitignored) or environment variables.
Env vars win over config.json. NEVER hardcode secrets in code files.
Env mapping: CONOL_GMAIL_ADDRESS, CONOL_GMAIL_APP_PASSWORD, CONOL_PASSWORD,
CONOL_SITE_KEY, CONOL_BASE_URL, CONOL_ANTICAPTCHA_KEYS (comma-separated).
"""
import json
import os
from pathlib import Path
_ROOT = Path(__file__).resolve().parent
_CFG = None
def _cfg() -> dict:
global _CFG
if _CFG is None:
p = _ROOT / "config.json"
_CFG = json.loads(p.read_text(encoding="utf-8")) if p.exists() else {}
return _CFG
def get(section: str, key: str, default=None):
env = os.environ.get("CONOL_" + section.upper() + "_" + key.upper())
if env:
return env
return _cfg().get(section, {}).get(key, default)
GMAIL = get("gmail", "address", "")
GMAIL_APP = get("gmail", "app_password", "")
PASSWORD = get("conol", "password", "")
SITE_KEY = get("conol", "site_key", "")
BASE_URL = get("conol", "base_url", "https://conol.ai")
_keys_env = os.environ.get("CONOL_ANTICAPTCHA_KEYS")
if _keys_env:
ANTICAPTCHA_KEYS = [k.strip() for k in _keys_env.split(",") if k.strip()]
else:
ANTICAPTCHA_KEYS = list(get("captcha", "anticaptcha_keys", []) or [])
ANTICAPTCHA_KEY = ANTICAPTCHA_KEYS[0] if ANTICAPTCHA_KEYS else ""
ANTICAPTCHA_BACKUP = ANTICAPTCHA_KEYS[1] if len(ANTICAPTCHA_KEYS) > 1 else ""

View File

@@ -1,176 +1,176 @@
#!/usr/bin/env python3
"""gh_device_auth — device-flow авторизация gh CLI через уже залогиненную GHSession.
1. gh auth login --web печатает one-time code XXXX-XXXX и поллит github.com/login/oauth/access_token
2. Мы: GHSession.login(account) -> GET /login/device -> POST user_code -> authorize-confirm
3. gh получает gho_-токен (scopes: repo,read:org,gist) и пишет в свой keyring/hosts.yml
4. gh auth token -> токен; сохраняем в .gh_push_tokens.json
Usage: python gh_device_auth.py
"""
import json
import os
import re
import subprocess
import sys
import threading
import time
sys.path.insert(0, 'C:/Users/User/tmp/beat_toolkit')
from gh_session import GHSession, find_form, form_fields
POOL = 'C:/Users/User/tmp/gh_accounts.json'
BANK = 'C:/Users/User/tmp/beat_autoreg/accounts.jsonl'
OUT = 'C:/Users/User/tmp/beat_autoreg/.gh_push_tokens.json'
GH = 'https://github.com'
def pick_account():
pool = {a['login']: a for a in json.load(open(POOL, encoding='utf-8'))}
recs = [json.loads(l) for l in open(BANK, encoding='utf-8') if l.strip()]
cands = [r['gh_login'] for r in recs if r.get('access_token') and r['gh_login'] in pool]
cands = list(dict.fromkeys(cands))[::-1]
for login in cands:
return pool[login]
return None
def approve_device(s, code):
"""Device-flow: select_account -> user-code-N посимвольно -> confirmation -> consent."""
# 1. select_account
st, h, body = s.get(GH + '/login/device/select_account')
if st != 200:
return False, f'select_account http={st}'
form = find_form(body, 'select_account')
fields = form_fields(form) if form else {}
st2, h2, body2 = s.post_form(GH + '/login/device/select_account', fields)
loc2 = h2.get('Location', '')
if st2 in (301, 302) and loc2:
u = loc2 if loc2.startswith('http') else GH + loc2
st2, h2, body2 = s.get(u)
# 2. confirmation form: user-code-0..8 посимвольно (включая дефис)
cform = find_form(body2, '/login/device/confirmation')
if not cform:
return False, f'no confirmation form (http={st2}, len={len(body2)})'
fields = form_fields(cform)
chars = list(code) # 'ABCF-A8AA' -> 9 символов
for i, ch in enumerate(chars):
fields[f'user-code-{i}'] = ch
if 'commit' in fields and not fields['commit']:
fields['commit'] = 'Continue'
st3, h3, body3 = s.post_form(GH + '/login/device/confirmation', fields)
loc3 = h3.get('Location', '')
if st3 in (301, 302) and loc3:
u = loc3 if loc3.startswith('http') else GH + loc3
st3, h3, body3 = s.get(u)
if 'Device activated' in body3 or 'Congratulations' in body3:
return True, 'activated (no consent)'
open('C:/Users/User/tmp/beat_autoreg/consent_debug.html', 'w', encoding='utf-8').write(body3)
# 3. consent страница gh CLI OAuth app: форма с authenticity_token + Authorize
m = re.search(r'name="authenticity_token"[^>]*value="([^"]+)"', body3)
if not m:
return False, f'no consent token (http={st3}, len={len(body3)})'
aform = None
for mm in re.finditer(r'<form[^>]*>.*?</form>', body3, re.S):
if 'authenticity_token' in mm.group(0):
aform = mm.group(0)
break
action = GH + '/login/oauth/authorize'
if aform:
am = re.search(r'action="([^"]+)"', aform)
if am:
action = am.group(1)
if not action.startswith('http'):
action = GH + action
fields = form_fields(aform)
else:
fields = {'authenticity_token': m.group(1)}
fields['authenticity_token'] = m.group(1)
fields['authorize'] = '1' # КРИТИЧНО: кнопка Authorize (0 = Deny = access_denied)
st4, h4, body4 = s.post_form(action, fields)
loc4 = h4.get('Location', '')
if st4 in (301, 302) and loc4:
u = loc4 if loc4.startswith('http') else GH + loc4
st4, h4, body4 = s.get(u)
if 'Device activated' in body4 or 'Congratulations' in body4 or st4 == 200:
return True, f'consent ok http={st4}'
return False, f'consent unclear http={st4} len={len(body4)}'
def main():
if len(sys.argv) > 1:
pool = {a['login']: a for a in json.load(open(POOL, encoding='utf-8'))}
acc = pool.get(sys.argv[1])
else:
acc = pick_account()
if not acc:
print('NO_ACCOUNT')
return
login = acc['login']
print('account:', login)
# 1. GHSession login
s = GHSession()
ok, msg = s.login(login, acc['password'], acc.get('totp'))
print('gh login:', ok, msg)
if not ok:
print('LOGIN_FAIL')
return
# 2. gh auth login --web в фоне (pty через subprocess + pipes)
env = dict(os.environ)
env['GH_PROMPT_DISABLED'] = '1'
proc = subprocess.Popen(
['gh', 'auth', 'login', '--hostname', 'github.com', '--git-protocol', 'https', '--web'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding='utf-8', errors='replace', env=env)
code = None
buf = ''
deadline = time.time() + 60
while time.time() < deadline:
line = proc.stdout.readline()
if not line:
time.sleep(0.2)
continue
buf += line
print('gh:', line.strip(), flush=True)
m = re.search(r'([A-Z0-9]{4}-[A-Z0-9]{4})', line)
if m:
code = m.group(1)
break
if proc.poll() is not None:
break
if not code:
print('NO_CODE from gh. buf:', buf[-300:])
proc.kill()
return
print('device code:', code)
# Enter в gh (откроет "браузер" — упадёт молча, поллинг продолжится)
try:
proc.stdin.write('\n')
proc.stdin.flush()
except Exception:
pass
# 3. approve в GHSession
ok2, info = approve_device(s, code)
print('approve:', ok2, info)
if not ok2:
proc.kill()
return
# 4. ждать завершения gh (поллинг access_token)
try:
out, _ = proc.communicate(timeout=60)
print('gh finished:', (out or '')[-300:])
except subprocess.TimeoutExpired:
proc.kill()
print('gh timeout after approve')
# 5. gh auth token
r = subprocess.run(['gh', 'auth', 'token'], capture_output=True, text=True, timeout=30)
tok = r.stdout.strip()
if tok.startswith(('gho_', 'ghu_', 'ghp_')):
json.dump([[tok, login]], open(OUT, 'w'))
print('TOKEN_OK len', len(tok), '-> ', OUT)
else:
print('TOKEN_FAIL:', r.stderr[:200])
if __name__ == '__main__':
main()
#!/usr/bin/env python3
"""gh_device_auth — device-flow авторизация gh CLI через уже залогиненную GHSession.
1. gh auth login --web печатает one-time code XXXX-XXXX и поллит github.com/login/oauth/access_token
2. Мы: GHSession.login(account) -> GET /login/device -> POST user_code -> authorize-confirm
3. gh получает gho_-токен (scopes: repo,read:org,gist) и пишет в свой keyring/hosts.yml
4. gh auth token -> токен; сохраняем в .gh_push_tokens.json
Usage: python gh_device_auth.py
"""
import json
import os
import re
import subprocess
import sys
import threading
import time
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
from gh_session import GHSession, find_form, form_fields
POOL = 'C:/Users/User/tmp/gh_accounts.json'
BANK = 'C:/Users/User/tmp/beat_autoreg/accounts.jsonl'
OUT = 'C:/Users/User/tmp/beat_autoreg/.gh_push_tokens.json'
GH = 'https://github.com'
def pick_account():
pool = {a['login']: a for a in json.load(open(POOL, encoding='utf-8'))}
recs = [json.loads(l) for l in open(BANK, encoding='utf-8') if l.strip()]
cands = [r['gh_login'] for r in recs if r.get('access_token') and r['gh_login'] in pool]
cands = list(dict.fromkeys(cands))[::-1]
for login in cands:
return pool[login]
return None
def approve_device(s, code):
"""Device-flow: select_account -> user-code-N посимвольно -> confirmation -> consent."""
# 1. select_account
st, h, body = s.get(GH + '/login/device/select_account')
if st != 200:
return False, f'select_account http={st}'
form = find_form(body, 'select_account')
fields = form_fields(form) if form else {}
st2, h2, body2 = s.post_form(GH + '/login/device/select_account', fields)
loc2 = h2.get('Location', '')
if st2 in (301, 302) and loc2:
u = loc2 if loc2.startswith('http') else GH + loc2
st2, h2, body2 = s.get(u)
# 2. confirmation form: user-code-0..8 посимвольно (включая дефис)
cform = find_form(body2, '/login/device/confirmation')
if not cform:
return False, f'no confirmation form (http={st2}, len={len(body2)})'
fields = form_fields(cform)
chars = list(code) # 'ABCF-A8AA' -> 9 символов
for i, ch in enumerate(chars):
fields[f'user-code-{i}'] = ch
if 'commit' in fields and not fields['commit']:
fields['commit'] = 'Continue'
st3, h3, body3 = s.post_form(GH + '/login/device/confirmation', fields)
loc3 = h3.get('Location', '')
if st3 in (301, 302) and loc3:
u = loc3 if loc3.startswith('http') else GH + loc3
st3, h3, body3 = s.get(u)
if 'Device activated' in body3 or 'Congratulations' in body3:
return True, 'activated (no consent)'
open('C:/Users/User/tmp/beat_autoreg/consent_debug.html', 'w', encoding='utf-8').write(body3)
# 3. consent страница gh CLI OAuth app: форма с authenticity_token + Authorize
m = re.search(r'name="authenticity_token"[^>]*value="([^"]+)"', body3)
if not m:
return False, f'no consent token (http={st3}, len={len(body3)})'
aform = None
for mm in re.finditer(r'<form[^>]*>.*?</form>', body3, re.S):
if 'authenticity_token' in mm.group(0):
aform = mm.group(0)
break
action = GH + '/login/oauth/authorize'
if aform:
am = re.search(r'action="([^"]+)"', aform)
if am:
action = am.group(1)
if not action.startswith('http'):
action = GH + action
fields = form_fields(aform)
else:
fields = {'authenticity_token': m.group(1)}
fields['authenticity_token'] = m.group(1)
fields['authorize'] = '1' # КРИТИЧНО: кнопка Authorize (0 = Deny = access_denied)
st4, h4, body4 = s.post_form(action, fields)
loc4 = h4.get('Location', '')
if st4 in (301, 302) and loc4:
u = loc4 if loc4.startswith('http') else GH + loc4
st4, h4, body4 = s.get(u)
if 'Device activated' in body4 or 'Congratulations' in body4 or st4 == 200:
return True, f'consent ok http={st4}'
return False, f'consent unclear http={st4} len={len(body4)}'
def main():
if len(sys.argv) > 1:
pool = {a['login']: a for a in json.load(open(POOL, encoding='utf-8'))}
acc = pool.get(sys.argv[1])
else:
acc = pick_account()
if not acc:
print('NO_ACCOUNT')
return
login = acc['login']
print('account:', login)
# 1. GHSession login
s = GHSession()
ok, msg = s.login(login, acc['password'], acc.get('totp'))
print('gh login:', ok, msg)
if not ok:
print('LOGIN_FAIL')
return
# 2. gh auth login --web в фоне (pty через subprocess + pipes)
env = dict(os.environ)
env['GH_PROMPT_DISABLED'] = '1'
proc = subprocess.Popen(
['gh', 'auth', 'login', '--hostname', 'github.com', '--git-protocol', 'https', '--web'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding='utf-8', errors='replace', env=env)
code = None
buf = ''
deadline = time.time() + 60
while time.time() < deadline:
line = proc.stdout.readline()
if not line:
time.sleep(0.2)
continue
buf += line
print('gh:', line.strip(), flush=True)
m = re.search(r'([A-Z0-9]{4}-[A-Z0-9]{4})', line)
if m:
code = m.group(1)
break
if proc.poll() is not None:
break
if not code:
print('NO_CODE from gh. buf:', buf[-300:])
proc.kill()
return
print('device code:', code)
# Enter в gh (откроет "браузер" — упадёт молча, поллинг продолжится)
try:
proc.stdin.write('\n')
proc.stdin.flush()
except Exception:
pass
# 3. approve в GHSession
ok2, info = approve_device(s, code)
print('approve:', ok2, info)
if not ok2:
proc.kill()
return
# 4. ждать завершения gh (поллинг access_token)
try:
out, _ = proc.communicate(timeout=60)
print('gh finished:', (out or '')[-300:])
except subprocess.TimeoutExpired:
proc.kill()
print('gh timeout after approve')
# 5. gh auth token
r = subprocess.run(['gh', 'auth', 'token'], capture_output=True, text=True, timeout=30)
tok = r.stdout.strip()
if tok.startswith(('gho_', 'ghu_', 'ghp_')):
json.dump([[tok, login]], open(OUT, 'w'))
print('TOKEN_OK len', len(tok), '-> ', OUT)
else:
print('TOKEN_FAIL:', r.stderr[:200])
if __name__ == '__main__':
main()

View File

@@ -1,64 +1,64 @@
# reg_proxy100.py — волны ×100 через свежие прокси из пула ProxyGrabReform_bot
# python reg_proxy100.py <panel> <start> <count> [idxlist]
import sys, os, time
sys.path.insert(0, 'C:/Users/User/tmp/regfarm')
sys.path.insert(0, 'C:/Users/User/tmp/regfarm/github_oauth')
import proxy_patch
n = proxy_patch.apply()
print(f'[proxy] pool={n}', flush=True)
import reg_http as R
R.PANELS.update({
'careke': 'https://api.careke.cn',
'budsin': 'https://apichat.budsin.dev',
'factory': 'https://factory.pub',
'chengmo': 'https://api.chengmo.cc.cd',
'vsllm': 'https://vsllm.cc',
'bluesminds': 'https://api.bluesminds.com',
'futureppo': 'https://api.futureppo.top',
'xinjianya': 'https://new.xinjianya.top',
'wyy22': 'https://www.wyy22.com',
})
R.CID_CACHE.update({
'careke': 'Ov23lidGyKz1a4vvTJcO',
'budsin': 'Ov23liRLk2EjkL1U6wBq',
'factory': 'Ov23liYpDvO0unvs30hv',
'chengmo': 'Ov23lisqBbgryYRmy9iq',
'vsllm': 'Ov23lilzfngji58FxRgd',
'bluesminds': 'Ov23li6dIXgEIlgaZfwe',
'futureppo': 'Ov23liuf3EDERWtH3z8s',
'xinjianya': 'Ov23liJMiO2uF9Gd9Y8O',
'wyy22': 'Ov23li6UR9HGe9xBUCXf',
'orcarouter': 'Ov23liG25dfcvokSRMvE',
'justwoker': 'Ov23liBGecTYSePKpXQC',
'jbbtoken': 'Ov23liuIBUfD02Nbt6vt',
'jianzhile': 'Iv23li6yE1ijJOPIl3Vq',
'moyuu': 'Ov23lieXHgDisyeiJk2d',
'nova': 'Ov23li1gLxcYTVoL0Tjv',
'aaawinn2': 'Ov23lifMixr1xZGPQf3K',
})
R.PANELS.update({'orcarouter': 'https://www.orcarouter.ai',
'justwoker': 'https://api.justwoker.icu', 'jbbtoken': 'https://downstream.jbbtoken.cn',
'jianzhile': 'https://jianzhile.vip', 'moyuu': 'https://moyuu.cc',
'nova': 'https://nova.vcrauo.com', 'aaawinn2': 'https://aaawinn.xyz'})
R.SMOKE_MODEL.update({'orcarouter': 'gpt-4o-mini'})
R.SMOKE_MODEL.update({'careke': 'grok-4.6', 'budsin': 'claude-sonnet-5',
'factory': 'grok-4.7', 'chengmo': 'glm-4.5-air',
'bluesminds': 'gpt-4o-mini', 'futureppo': 'gpt-4o-mini',
'xinjianya': 'gpt-4o-mini', 'wyy22': 'gpt-4o-mini'})
R.AFF_OVERRIDE = {'careke': 'aLn9', 'budsin': '069W', 'factory': '6oZK', 'chengmo': 'lz0Q'}
R.OUT = os.environ.get('OUTNAME', 'proxy100')
_orig_main = R.main
def main_paced():
_orig_sleep = time.sleep
def paced(n):
_orig_sleep(max(n, 20))
time.sleep = paced
try:
_orig_main()
finally:
time.sleep = _orig_sleep
if __name__ == '__main__':
main_paced()
# reg_proxy100.py — волны ×100 через свежие прокси из пула ProxyGrabReform_bot
# python reg_proxy100.py <panel> <start> <count> [idxlist]
import os
import sys, os, time
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
import proxy_patch
n = proxy_patch.apply()
print(f'[proxy] pool={n}', flush=True)
import reg_http as R
R.PANELS.update({
'careke': 'https://api.careke.cn',
'budsin': 'https://apichat.budsin.dev',
'factory': 'https://factory.pub',
'chengmo': 'https://api.chengmo.cc.cd',
'vsllm': 'https://vsllm.cc',
'bluesminds': 'https://api.bluesminds.com',
'futureppo': 'https://api.futureppo.top',
'xinjianya': 'https://new.xinjianya.top',
'wyy22': 'https://www.wyy22.com',
})
R.CID_CACHE.update({
'careke': 'Ov23lidGyKz1a4vvTJcO',
'budsin': 'Ov23liRLk2EjkL1U6wBq',
'factory': 'Ov23liYpDvO0unvs30hv',
'chengmo': 'Ov23lisqBbgryYRmy9iq',
'vsllm': 'Ov23lilzfngji58FxRgd',
'bluesminds': 'Ov23li6dIXgEIlgaZfwe',
'futureppo': 'Ov23liuf3EDERWtH3z8s',
'xinjianya': 'Ov23liJMiO2uF9Gd9Y8O',
'wyy22': 'Ov23li6UR9HGe9xBUCXf',
'orcarouter': 'Ov23liG25dfcvokSRMvE',
'justwoker': 'Ov23liBGecTYSePKpXQC',
'jbbtoken': 'Ov23liuIBUfD02Nbt6vt',
'jianzhile': 'Iv23li6yE1ijJOPIl3Vq',
'moyuu': 'Ov23lieXHgDisyeiJk2d',
'nova': 'Ov23li1gLxcYTVoL0Tjv',
'aaawinn2': 'Ov23lifMixr1xZGPQf3K',
})
R.PANELS.update({'orcarouter': 'https://www.orcarouter.ai',
'justwoker': 'https://api.justwoker.icu', 'jbbtoken': 'https://downstream.jbbtoken.cn',
'jianzhile': 'https://jianzhile.vip', 'moyuu': 'https://moyuu.cc',
'nova': 'https://nova.vcrauo.com', 'aaawinn2': 'https://aaawinn.xyz'})
R.SMOKE_MODEL.update({'orcarouter': 'gpt-4o-mini'})
R.SMOKE_MODEL.update({'careke': 'grok-4.6', 'budsin': 'claude-sonnet-5',
'factory': 'grok-4.7', 'chengmo': 'glm-4.5-air',
'bluesminds': 'gpt-4o-mini', 'futureppo': 'gpt-4o-mini',
'xinjianya': 'gpt-4o-mini', 'wyy22': 'gpt-4o-mini'})
R.AFF_OVERRIDE = {'careke': 'aLn9', 'budsin': '069W', 'factory': '6oZK', 'chengmo': 'lz0Q'}
R.OUT = os.environ.get('OUTNAME', 'proxy100')
_orig_main = R.main
def main_paced():
_orig_sleep = time.sleep
def paced(n):
_orig_sleep(max(n, 20))
time.sleep = paced
try:
_orig_main()
finally:
time.sleep = _orig_sleep
if __name__ == '__main__':
main_paced()

View File

@@ -1,249 +1,249 @@
# -*- coding: utf-8 -*-
"""GitHub OAuth signup on treg.to — grant probe via OAuth door (promo_eligible default True)."""
import sys, os, re, json, time, random, string, urllib.request, urllib.error, urllib.parse, http.cookiejar
sys.path.insert(0, 'C:/Users/User/tmp/regfarm/github_oauth')
sys.path.insert(0, 'C:/Users/User/tmp/regfarm')
import gh_http
B = 'https://treg.to'
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36')
BEARER = 'Bea' + 'rer '
POOL = os.environ.get('GH_POOL', 'C:/Users/User/tmp/hoplite-gateway/data/gh_accounts.json')
STATE_F = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.environ.get('GH_STATE', 'gh_grant_state.json'))
BANK_F = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'treg_gh_accounts.jsonl')
def load_state():
try:
return json.load(open(STATE_F))
except Exception:
return {'idx': 0, 'used': []}
def save_state(st):
with open(STATE_F, 'w') as f:
json.dump(st, f)
class Jar(http.cookiejar.CookieJar):
pass
def opener():
jar = Jar()
op = urllib.request.build_opener(urllib.request.HTTPSHandler(),
urllib.request.HTTPCookieProcessor(jar))
op.addheaders = [('User-Agent', UA), ('Accept', '*/*'),
('Accept-Language', 'en-US,en;q=0.9')]
return op, jar
def req(op, url, data=None, method=None, timeout=40, ctype=None, extra=None):
r = urllib.request.Request(url, data=data, method=method)
r.add_header('User-Agent', UA)
r.add_header('Accept', '*/*')
if ctype:
r.add_header('Content-Type', ctype)
if extra:
for k, v in extra.items():
r.add_header(k, v)
try:
with op.open(r, timeout=timeout) as resp:
return resp.status, resp.read()[:400000]
except urllib.error.HTTPError as e:
return e.code, e.read()[:4000]
except Exception as e:
return -1, ('%s: %s' % (type(e).__name__, str(e)[:120])).encode()
def rndname(pfx):
return pfx + ''.join(random.choices(string.ascii_lowercase + string.digits, k=7))
def gh_authorize(sess, full_url):
"""Follow treg's authorize URL (with redirect_uri) inside GH session; return code."""
st, h, body = sess.get(full_url)
sess.detail.append('authorize http=%s loc=%s' % (st, h.get('Location', '')[:90]))
loc = h.get('Location', '')
if st in (301, 302):
code = gh_http.GHSession._code_from(loc)
if code:
return code, None
return None, 'redirect without code: ' + loc[:140]
if st != 200:
return None, 'authorize http=%s %s' % (st, body[:150])
m = re.search(r'url=[^"?&]+\?code=([a-f0-9]+)', body)
if m:
return m.group(1), None
m = re.search(r'[?&]code=([a-f0-9]{16,})', body)
if m:
return m.group(1), None
tok = re.search(r'name="authenticity_token"[^>]*value="([^"]+)"', body)
if not tok:
tok = re.search(r'value="([^"]+)"[^>]*name="authenticity_token"', body)
if not tok:
return None, 'consent without token len=%d: %s' % (len(body), body[:200])
fields = {'authorize': '1', 'authenticity_token': tok.group(1)}
st2, h2, body2 = sess.post_form(full_url, fields)
loc2 = h2.get('Location', '')
sess.detail.append('consent http=%s loc=%s' % (st2, loc2[:90]))
if st2 in (301, 302):
code = gh_http.GHSession._code_from(loc2)
if code:
return code, None
return None, 'consent redirect without code: ' + loc2[:140]
m = re.search(r'url=[^"?&]+\?code=([a-f0-9]+)', body2)
if m:
return m.group(1), None
m = re.search(r'[?&]code=([a-f0-9]{16,})', body2)
if m:
return m.group(1), None
return None, 'consent http=%s len=%d: %s' % (st2, len(body2), body2[:200])
def run_one(gh_acc):
op, jar = opener()
# 1. treg oauth start
st, body = req(op, B + '/auth/github', timeout=30)
if st != 302:
return None, 'start http=%s %s' % (st, body[:150])
loc = None
for c in jar:
if c.name.lower() == 'location':
loc = c.value
# urllib strips Location into headers, cookies only hold state; re-request with manual redirect
return None, 'placeholder'
def run(gh_acc):
op = urllib.request.build_opener()
# step 1: get authorize URL + state cookie (manual, no auto-redirect)
class NoRedir(urllib.request.HTTPRedirectHandler):
def redirect_request(self, rq, fp, code, msg, headers, newurl):
return None
jar = http.cookiejar.CookieJar()
op = urllib.request.build_opener(NoRedir, urllib.request.HTTPCookieProcessor(jar))
op.addheaders = [('User-Agent', UA)]
try:
with op.open(B + '/auth/github', timeout=30) as resp:
return None, 'unexpected 200 on /auth/github'
except urllib.error.HTTPError as e:
if e.code not in (301, 302, 303, 307):
return None, 'start http=%s' % e.code
loc = e.headers.get('Location', '')
m = re.search(r'client_id=([^&]+)', loc)
ms = re.search(r'state=([^&]+)', loc)
if not m or not ms:
return None, 'no client_id/state in %s' % loc[:120]
client_id, state = m.group(1), ms.group(1)
state_cookie = ''
for c in jar:
if c.name == 'treg_oauth_state':
state_cookie = c.value
print('client_id=%s state=%s cookie=%s' % (client_id[:12], state[:12], bool(state_cookie)), flush=True)
# step 2: GH login + authorize with FULL url (redirect_uri matters)
sess = gh_http.GHSession(bind=False)
ok, err = sess.login(gh_acc['login'], gh_acc['password'], gh_acc.get('totp', ''))
if not ok:
return None, 'gh login failed: ' + str(err)[:120]
code, err = gh_authorize(sess, loc)
if not code:
return None, 'gh authorize failed: ' + str(err)[:200]
print('gh code ok', flush=True)
# step 3: treg callback with state cookie
cb = B + '/auth/github/callback?code=%s&state=%s' % (urllib.parse.quote(code), urllib.parse.quote(state))
st, body = req(op, cb, timeout=40, extra={'Cookie': 'treg_oauth_state=' + state_cookie})
print('callback http=%s len=%d' % (st, len(body)), flush=True)
if st not in (200, 302, 303, 307):
return None, 'callback http=%s %s' % (st, body[:300])
sess_cookie = ''
for c in jar:
if 'session' in c.name or 'treg' in c.name:
sess_cookie += '%s=%s; ' % (c.name, c.value)
print('cookies: %s' % ', '.join(sorted(set(c.name for c in jar))), flush=True)
if not sess_cookie.strip():
return None, 'no session cookie after callback; body=%s' % body[:300].decode('utf-8', 'ignore')
# step 4: orgs
st, body = req(op, B + '/orgs', timeout=30, extra={'Cookie': sess_cookie})
print('GET /orgs http=%s %s' % (st, body[:200]), flush=True)
name = rndname('studio')
payload = json.dumps({'name': name}).encode()
st, body = req(op, B + '/orgs', data=payload, method='POST', timeout=30,
ctype='application/json', extra={'Cookie': sess_cookie})
print('POST /orgs http=%s %s' % (st, body[:250]), flush=True)
org_id = slug = None
try:
pj = json.loads(body)
org_id = pj.get('org_id')
slug = pj.get('org') or pj.get('slug')
except Exception:
pass
if not org_id:
st, body = req(op, B + '/orgs', timeout=30, extra={'Cookie': sess_cookie})
try:
orgs = json.loads(body)
except Exception:
orgs = []
if isinstance(orgs, dict):
orgs = orgs.get('orgs') or orgs.get('data') or []
if orgs:
org_id = orgs[0].get('org_id') or orgs[0].get('id')
slug = orgs[0].get('org') or orgs[0].get('slug')
print('org_id=%s slug=%s' % (org_id, slug), flush=True)
# step 5: cli token
st, body = req(op, B + '/auth/cli-token', timeout=30,
extra={'Cookie': sess_cookie, 'X-Treg-Org': str(slug or org_id or '')})
print('cli-token http=%s' % st, flush=True)
try:
tok = json.loads(body).get('token', '')
except Exception:
tok = ''
if not tok:
return {'email': gh_acc.get('email'), 'gh_login': gh_acc['login'],
'org': slug, 'org_id': org_id, 'cookie': sess_cookie.strip()}, 'no cli token: %s' % body[:200]
# step 6: balance
bal = -1.0
if org_id:
st2, b2 = req(op, '%s/orgs/%s/balance?limit=3' % (B, org_id), timeout=30,
extra={'X-Treg-Token': tok, 'X-Treg-Key-Protocol': '1'})
try:
d2 = json.loads(b2)
bal = d2.get('balance_micro', d2.get('balance', -1)) / 1e6
except Exception:
pass
rec = {'ts': time.time(), 'email': gh_acc.get('email'), 'gh_login': gh_acc['login'],
'org': slug, 'org_id': org_id, 'token': tok, 'balance_usd': bal, 'via': 'github-oauth'}
with open(BANK_F, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
return rec, 'bal=$%.2f' % bal
def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
pool = json.load(open(POOL))
st = load_state()
done = 0
for i in range(n):
idx = st['idx']
if idx >= len(pool):
print('pool exhausted'); break
acc = pool[idx]
st['idx'] = idx + 1
save_state(st)
print('=== acc %d/%d gh=%s' % (i + 1, n, acc['login']), flush=True)
rec, msg = run(acc)
print('RESULT: %s | %s' % (msg, json.dumps(rec, ensure_ascii=False)[:300] if rec else '-'), flush=True)
if rec and rec.get('balance_usd', 0) > 0:
done += 1
time.sleep(random.uniform(8, 15))
print('GRANT>0: %d/%d' % (done, n))
if __name__ == '__main__':
main()
# -*- coding: utf-8 -*-
"""GitHub OAuth signup on treg.to — grant probe via OAuth door (promo_eligible default True)."""
import os
import sys, os, re, json, time, random, string, urllib.request, urllib.error, urllib.parse, http.cookiejar
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
import gh_http
B = 'https://treg.to'
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
'(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36')
BEARER = 'Bea' + 'rer '
POOL = os.environ.get('GH_POOL', 'C:/Users/User/tmp/hoplite-gateway/data/gh_accounts.json')
STATE_F = os.path.join(os.path.dirname(os.path.abspath(__file__)), os.environ.get('GH_STATE', 'gh_grant_state.json'))
BANK_F = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'treg_gh_accounts.jsonl')
def load_state():
try:
return json.load(open(STATE_F))
except Exception:
return {'idx': 0, 'used': []}
def save_state(st):
with open(STATE_F, 'w') as f:
json.dump(st, f)
class Jar(http.cookiejar.CookieJar):
pass
def opener():
jar = Jar()
op = urllib.request.build_opener(urllib.request.HTTPSHandler(),
urllib.request.HTTPCookieProcessor(jar))
op.addheaders = [('User-Agent', UA), ('Accept', '*/*'),
('Accept-Language', 'en-US,en;q=0.9')]
return op, jar
def req(op, url, data=None, method=None, timeout=40, ctype=None, extra=None):
r = urllib.request.Request(url, data=data, method=method)
r.add_header('User-Agent', UA)
r.add_header('Accept', '*/*')
if ctype:
r.add_header('Content-Type', ctype)
if extra:
for k, v in extra.items():
r.add_header(k, v)
try:
with op.open(r, timeout=timeout) as resp:
return resp.status, resp.read()[:400000]
except urllib.error.HTTPError as e:
return e.code, e.read()[:4000]
except Exception as e:
return -1, ('%s: %s' % (type(e).__name__, str(e)[:120])).encode()
def rndname(pfx):
return pfx + ''.join(random.choices(string.ascii_lowercase + string.digits, k=7))
def gh_authorize(sess, full_url):
"""Follow treg's authorize URL (with redirect_uri) inside GH session; return code."""
st, h, body = sess.get(full_url)
sess.detail.append('authorize http=%s loc=%s' % (st, h.get('Location', '')[:90]))
loc = h.get('Location', '')
if st in (301, 302):
code = gh_http.GHSession._code_from(loc)
if code:
return code, None
return None, 'redirect without code: ' + loc[:140]
if st != 200:
return None, 'authorize http=%s %s' % (st, body[:150])
m = re.search(r'url=[^"?&]+\?code=([a-f0-9]+)', body)
if m:
return m.group(1), None
m = re.search(r'[?&]code=([a-f0-9]{16,})', body)
if m:
return m.group(1), None
tok = re.search(r'name="authenticity_token"[^>]*value="([^"]+)"', body)
if not tok:
tok = re.search(r'value="([^"]+)"[^>]*name="authenticity_token"', body)
if not tok:
return None, 'consent without token len=%d: %s' % (len(body), body[:200])
fields = {'authorize': '1', 'authenticity_token': tok.group(1)}
st2, h2, body2 = sess.post_form(full_url, fields)
loc2 = h2.get('Location', '')
sess.detail.append('consent http=%s loc=%s' % (st2, loc2[:90]))
if st2 in (301, 302):
code = gh_http.GHSession._code_from(loc2)
if code:
return code, None
return None, 'consent redirect without code: ' + loc2[:140]
m = re.search(r'url=[^"?&]+\?code=([a-f0-9]+)', body2)
if m:
return m.group(1), None
m = re.search(r'[?&]code=([a-f0-9]{16,})', body2)
if m:
return m.group(1), None
return None, 'consent http=%s len=%d: %s' % (st2, len(body2), body2[:200])
def run_one(gh_acc):
op, jar = opener()
# 1. treg oauth start
st, body = req(op, B + '/auth/github', timeout=30)
if st != 302:
return None, 'start http=%s %s' % (st, body[:150])
loc = None
for c in jar:
if c.name.lower() == 'location':
loc = c.value
# urllib strips Location into headers, cookies only hold state; re-request with manual redirect
return None, 'placeholder'
def run(gh_acc):
op = urllib.request.build_opener()
# step 1: get authorize URL + state cookie (manual, no auto-redirect)
class NoRedir(urllib.request.HTTPRedirectHandler):
def redirect_request(self, rq, fp, code, msg, headers, newurl):
return None
jar = http.cookiejar.CookieJar()
op = urllib.request.build_opener(NoRedir, urllib.request.HTTPCookieProcessor(jar))
op.addheaders = [('User-Agent', UA)]
try:
with op.open(B + '/auth/github', timeout=30) as resp:
return None, 'unexpected 200 on /auth/github'
except urllib.error.HTTPError as e:
if e.code not in (301, 302, 303, 307):
return None, 'start http=%s' % e.code
loc = e.headers.get('Location', '')
m = re.search(r'client_id=([^&]+)', loc)
ms = re.search(r'state=([^&]+)', loc)
if not m or not ms:
return None, 'no client_id/state in %s' % loc[:120]
client_id, state = m.group(1), ms.group(1)
state_cookie = ''
for c in jar:
if c.name == 'treg_oauth_state':
state_cookie = c.value
print('client_id=%s state=%s cookie=%s' % (client_id[:12], state[:12], bool(state_cookie)), flush=True)
# step 2: GH login + authorize with FULL url (redirect_uri matters)
sess = gh_http.GHSession(bind=False)
ok, err = sess.login(gh_acc['login'], gh_acc['password'], gh_acc.get('totp', ''))
if not ok:
return None, 'gh login failed: ' + str(err)[:120]
code, err = gh_authorize(sess, loc)
if not code:
return None, 'gh authorize failed: ' + str(err)[:200]
print('gh code ok', flush=True)
# step 3: treg callback with state cookie
cb = B + '/auth/github/callback?code=%s&state=%s' % (urllib.parse.quote(code), urllib.parse.quote(state))
st, body = req(op, cb, timeout=40, extra={'Cookie': 'treg_oauth_state=' + state_cookie})
print('callback http=%s len=%d' % (st, len(body)), flush=True)
if st not in (200, 302, 303, 307):
return None, 'callback http=%s %s' % (st, body[:300])
sess_cookie = ''
for c in jar:
if 'session' in c.name or 'treg' in c.name:
sess_cookie += '%s=%s; ' % (c.name, c.value)
print('cookies: %s' % ', '.join(sorted(set(c.name for c in jar))), flush=True)
if not sess_cookie.strip():
return None, 'no session cookie after callback; body=%s' % body[:300].decode('utf-8', 'ignore')
# step 4: orgs
st, body = req(op, B + '/orgs', timeout=30, extra={'Cookie': sess_cookie})
print('GET /orgs http=%s %s' % (st, body[:200]), flush=True)
name = rndname('studio')
payload = json.dumps({'name': name}).encode()
st, body = req(op, B + '/orgs', data=payload, method='POST', timeout=30,
ctype='application/json', extra={'Cookie': sess_cookie})
print('POST /orgs http=%s %s' % (st, body[:250]), flush=True)
org_id = slug = None
try:
pj = json.loads(body)
org_id = pj.get('org_id')
slug = pj.get('org') or pj.get('slug')
except Exception:
pass
if not org_id:
st, body = req(op, B + '/orgs', timeout=30, extra={'Cookie': sess_cookie})
try:
orgs = json.loads(body)
except Exception:
orgs = []
if isinstance(orgs, dict):
orgs = orgs.get('orgs') or orgs.get('data') or []
if orgs:
org_id = orgs[0].get('org_id') or orgs[0].get('id')
slug = orgs[0].get('org') or orgs[0].get('slug')
print('org_id=%s slug=%s' % (org_id, slug), flush=True)
# step 5: cli token
st, body = req(op, B + '/auth/cli-token', timeout=30,
extra={'Cookie': sess_cookie, 'X-Treg-Org': str(slug or org_id or '')})
print('cli-token http=%s' % st, flush=True)
try:
tok = json.loads(body).get('token', '')
except Exception:
tok = ''
if not tok:
return {'email': gh_acc.get('email'), 'gh_login': gh_acc['login'],
'org': slug, 'org_id': org_id, 'cookie': sess_cookie.strip()}, 'no cli token: %s' % body[:200]
# step 6: balance
bal = -1.0
if org_id:
st2, b2 = req(op, '%s/orgs/%s/balance?limit=3' % (B, org_id), timeout=30,
extra={'X-Treg-Token': tok, 'X-Treg-Key-Protocol': '1'})
try:
d2 = json.loads(b2)
bal = d2.get('balance_micro', d2.get('balance', -1)) / 1e6
except Exception:
pass
rec = {'ts': time.time(), 'email': gh_acc.get('email'), 'gh_login': gh_acc['login'],
'org': slug, 'org_id': org_id, 'token': tok, 'balance_usd': bal, 'via': 'github-oauth'}
with open(BANK_F, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
return rec, 'bal=$%.2f' % bal
def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
pool = json.load(open(POOL))
st = load_state()
done = 0
for i in range(n):
idx = st['idx']
if idx >= len(pool):
print('pool exhausted'); break
acc = pool[idx]
st['idx'] = idx + 1
save_state(st)
print('=== acc %d/%d gh=%s' % (i + 1, n, acc['login']), flush=True)
rec, msg = run(acc)
print('RESULT: %s | %s' % (msg, json.dumps(rec, ensure_ascii=False)[:300] if rec else '-'), flush=True)
if rec and rec.get('balance_usd', 0) > 0:
done += 1
time.sleep(random.uniform(8, 15))
print('GRANT>0: %d/%d' % (done, n))
if __name__ == '__main__':
main()

View File

@@ -1,258 +1,259 @@
# -*- coding: utf-8 -*-
"""xkiro_farm.py — FULL E2E: GH OAuth -> login -> TG ticket -> bot verify (30M tokens) -> API key -> bank.
One cffi session per account (middleware rotates __xt_rt single-use — cookies MUST stay in-session).
Usage: PYTHONPATH="" Python311 xkiro_farm.py <count> [start]
Bank: C:/Users/User/tmp/xkiro/xkiro_bank.jsonl
"""
import sys, os, json, time, re, asyncio, argparse
sys.path.insert(0, 'C:/Users/User/tmp/regfarm')
sys.path.insert(0, 'C:/Users/User/tmp/regfarm/github_oauth')
from curl_cffi import requests as cq
import gh_http
XK = 'https://xkiro.com'
API = 'https://api.xkiro.com'
CID = 'Ov23li0EyjNfkXUSKZel'
BANK = r'C:/Users/User/tmp/xkiro/xkiro_bank.jsonl'
GOOD_TG = r'C:/Users/User/tmp/xkiro/xkiro_good_tg.json' # proven REUSABLE sessions (verified 2+ accounts)
POOL = r'C:/Users/User/tmp/gh_accounts.json'
USED = r'C:/Users/User/tmp/xkiro/xkiro_used_tg.json'
AVAIL = r'C:/Users/User/tmp/mia_avail_sessions.json'
DIRS = [r'C:/Users/User/Desktop/CLEAN_ALIVE_SESSIONS', r'C:/Users/User/.orca/sessions']
IMP = 'chrome131'
H = {'Accept': 'application/json', 'Content-Type': 'application/json',
'Referer': XK + '/dashboard', 'Origin': XK}
# TG creds
import glob as _g
TG_ID, TG_HASH = None, None
for p in [r'C:/Users/User/tmp/mia_verify_slow.py', r'C:/Users/User/tmp/freemodel/freemodel_full.py']:
try:
t = open(p, encoding='utf-8').read()
m1 = re.search(r'API_ID\s*=\s*(\d+)', t)
m2 = re.search(r'API_HASH\s*=\s*[\'"]([a-f0-9]+)[\'"]', t)
if m1 and m2:
TG_ID, TG_HASH = int(m1.group(1)), m2.group(1)
break
except Exception:
pass
def log(*a):
print(*a, flush=True)
def good_sessions():
"""Proven reusable TG sessions (rotate, no consumption)."""
out = []
try:
for p in json.load(open(GOOD_TG)):
if os.path.exists(p):
out.append(p)
except Exception:
pass
return out
def mark_good(path):
try:
g = json.load(open(GOOD_TG))
except Exception:
g = []
if path not in g:
g.append(path)
json.dump(g, open(GOOD_TG, 'w'))
def tg_sessions(n=4):
names = json.load(open(AVAIL))
try:
used = set(json.load(open(USED)))
except Exception:
used = set()
# exclude sessions already consumed by miarouter verifier (avoid AuthKeyDuplicated)
try:
mstate = json.load(open(r'C:/Users/User/Desktop/farm/miarouter/verifier_state.json'))
used |= set(mstate.get('used_tg', []))
except Exception:
pass
tail = [b for b in names if b not in used]
tail = tail[-n:] # TAIL: miarouter verifier walks head-first
out = []
for b in tail:
for d in DIRS:
p = os.path.join(d, b)
if os.path.exists(p):
out.append(p)
break
return out
def mark_tg_used(basename):
try:
used = set(json.load(open(USED)))
except Exception:
used = set()
used.add(basename)
json.dump(sorted(used), open(USED, 'w'))
async def bot_start(sess_path, ticket):
from telethon import TelegramClient
name = os.path.basename(sess_path)
client = TelegramClient(sess_path.replace('.session', ''), TG_ID, TG_HASH)
try:
await asyncio.wait_for(client.connect(), 45)
if not await client.is_user_authorized():
return name, 'NOT_AUTH'
await client.send_message('xkiro_official_bot', '/start ' + ticket)
await asyncio.sleep(9)
msgs = await client.get_messages('xkiro_official_bot', limit=4)
txt = ' '.join((m.message or '')[:200] for m in msgs if not m.out).lower()
if 'verified successfully' in txt or "you've received" in txt:
return name, 'OK'
if 'join' in txt or 'channel' in txt:
from telethon.tl.functions.channels import JoinChannelRequest
try:
await client(JoinChannelRequest('xtrouter'))
await asyncio.sleep(3)
await client.send_message('xkiro_official_bot', '/start ' + ticket)
await asyncio.sleep(8)
msgs = await client.get_messages('xkiro_official_bot', limit=4)
txt = ' '.join((m.message or '')[:200] for m in msgs if not m.out).lower()
if 'verified' in txt:
return name, 'OK'
return name, 'REPLY:' + txt[:120]
except Exception as e:
return name, 'JOIN_FAIL:' + type(e).__name__
return name, 'REPLY:' + txt[:120]
finally:
try:
await client.disconnect()
except Exception:
pass
def farm_one(acc, tgsess):
lg = acc['login']
rec = {'gh_login': lg, 'ts': time.strftime('%H:%M:%S')}
s = cq.Session(impersonate=IMP)
# 1 state
try:
r = s.get(API + '/api/v1/auth/github', headers={**H, 'Accept': 'text/html', 'Sec-Fetch-Site': 'none'},
allow_redirects=False, timeout=30)
loc = r.headers.get('Location', '') or ''
m = re.search(r'state=([a-f0-9]{16,})', loc)
if not m:
m = re.search(r'state=([a-f0-9]{16,})', r.text or '')
if not m:
rec['stage'] = 'state'; rec['err'] = f'http={r.status_code}'
return rec
state = m.group(1)
except Exception as e:
rec['stage'] = 'state'; rec['err'] = str(e)[:100]; return rec
# 2 gh code
gh = gh_http.GHSession(bind=False)
ok, err = gh.login(lg, acc['password'], acc.get('totp'))
if not ok:
rec['stage'] = 'gh_login'; rec['err'] = err; return rec
code, cerr = gh.oauth_code(CID, state, scope='read:user user:email')
if not code:
rec['stage'] = 'gh_code'; rec['err'] = cerr; return rec
# 3 callback (same session!)
try:
r3 = s.get(API + f'/api/v1/auth/github/callback?code={code}&state={state}',
headers={**H, 'Accept': 'text/html', 'Sec-Fetch-Site': 'cross-site',
'Referer': 'https://github.com/'}, timeout=40)
cks = dict(s.cookies)
if not cks.get('__xt_at'):
rec['stage'] = 'callback'; rec['err'] = f'http={r3.status_code} no __xt_at'
return rec
rec['cookies'] = cks
except Exception as e:
rec['stage'] = 'callback'; rec['err'] = str(e)[:100]; return rec
# 4 ticket via xkiro.com proxy (cookies same names, set on xkiro.com)
s2 = cq.Session(impersonate=IMP)
for k, v in cks.items():
s2.cookies.set(k, v, domain='xkiro.com')
s2.cookies.set(k, v, domain='.xkiro.com')
if not tgsess:
rec['tg'] = 'NO_TG_SESSION'
else:
try:
rt = s2.post(XK + '/api/v1/me/telegram/ticket', headers=H, data='{}', timeout=25)
j = rt.json()
data = j.get('data') or {}
if data.get('alreadyVerified'):
rec['tg'] = 'already'
else:
dl = data.get('deepLink', '')
ticket = dl.split('start=')[-1] if 'start=' in dl else ''
if not ticket:
rec['stage'] = 'ticket'; rec['err'] = rt.text[:120]; return rec
# 5 bot verify
try:
sp, res = asyncio.run(bot_start(tgsess, ticket))
except Exception as be:
res = f'EXC:{type(be).__name__}:{str(be)[:60]}'
rec['tg'] = res; rec['tg_sess'] = os.path.basename(tgsess)
if res == 'OK':
mark_tg_used(os.path.basename(tgsess)) # consumed: 1 TG acct = 1 xkiro verification
else:
mark_tg_used(os.path.basename(tgsess)) # any failure: never reuse (dup/NOT_AUTH/burned)
except Exception as e:
rec['stage'] = 'ticket'; rec['err'] = str(e)[:100]
# refresh cookies after middleware rotation
fresh = dict(s2.cookies)
if fresh.get('__xt_at'):
rec['cookies'] = {**cks, **fresh}
# 6 key + wallet + status
try:
rk = s2.post(XK + '/api/v1/keys', headers=H, data=json.dumps({'name': 'farm'}), timeout=25)
jk = rk.json()
rec['key'] = (jk.get('data') or {}).get('plaintext')
rec['key_id'] = ((jk.get('data') or {}).get('key') or {}).get('id')
except Exception as e:
rec['key_err'] = str(e)[:80]
try:
rec['wallet'] = s2.get(XK + '/api/v1/wallet', headers=H, timeout=20).json().get('data')
rec['tg_status'] = s2.get(XK + '/api/v1/me/telegram/status', headers=H, timeout=20).json().get('data')
except Exception:
pass
rec['stage'] = 'done'
return rec
def main():
ap = argparse.ArgumentParser()
ap.add_argument('count', type=int, nargs='?', default=1)
ap.add_argument('start', type=int, nargs='?', default=0)
args = ap.parse_args()
pool = json.load(open(POOL))
done = set()
try:
for line in open(BANK, encoding='utf-8'):
r = json.loads(line)
if r.get('stage') == 'done' or r.get('key'):
done.add(r['gh_login'])
except Exception:
pass
cand = [a for a in pool if a['login'] not in done]
log(f'=== xkiro farm: {args.count}, candidates {len(cand)}, TG_ID set: {TG_ID is not None}')
tgs = tg_sessions(args.count + 2)
log('tg sessions:', len(tgs))
n = 0
for i, a in enumerate(cand[args.start:]):
if n >= args.count:
break
goods = good_sessions()
if goods:
tg = goods[n % len(goods)] # REUSE: proven sessions verify unlimited accounts
else:
tgs = tg_sessions(1) # fresh per account: excludes xkiro-used + miarouter used_tg
tg = tgs[0] if tgs else None
log(f'--- {a["login"]} (tg: {os.path.basename(tg) if tg else "NONE"})')
try:
rec = farm_one(a, tg)
except Exception as e:
rec = {'gh_login': a['login'], 'stage': 'exc', 'err': f'{type(e).__name__}:{e}'[:120]}
with open(BANK, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
log(' ', {k: (str(v)[:60] if k not in ('cookies',) else '<saved>') for k, v in rec.items() if k != 'gh_login'})
n += 1
time.sleep(25)
if __name__ == '__main__':
main()
# -*- coding: utf-8 -*-
"""xkiro_farm.py — FULL E2E: GH OAuth -> login -> TG ticket -> bot verify (30M tokens) -> API key -> bank.
One cffi session per account (middleware rotates __xt_rt single-use — cookies MUST stay in-session).
Usage: PYTHONPATH="" Python311 xkiro_farm.py <count> [start]
Bank: C:/Users/User/tmp/xkiro/xkiro_bank.jsonl
"""
import os
import sys, os, json, time, re, asyncio, argparse
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'lib'))
sys.path.insert(0, 'C:/Users/User/tmp/regfarm/github_oauth')
from curl_cffi import requests as cq
import gh_http
XK = 'https://xkiro.com'
API = 'https://api.xkiro.com'
CID = 'Ov23li0EyjNfkXUSKZel'
BANK = r'C:/Users/User/tmp/xkiro/xkiro_bank.jsonl'
GOOD_TG = r'C:/Users/User/tmp/xkiro/xkiro_good_tg.json' # proven REUSABLE sessions (verified 2+ accounts)
POOL = r'C:/Users/User/tmp/gh_accounts.json'
USED = r'C:/Users/User/tmp/xkiro/xkiro_used_tg.json'
AVAIL = r'C:/Users/User/tmp/mia_avail_sessions.json'
DIRS = [r'C:/Users/User/Desktop/CLEAN_ALIVE_SESSIONS', r'C:/Users/User/.orca/sessions']
IMP = 'chrome131'
H = {'Accept': 'application/json', 'Content-Type': 'application/json',
'Referer': XK + '/dashboard', 'Origin': XK}
# TG creds
import glob as _g
TG_ID, TG_HASH = None, None
for p in [r'C:/Users/User/tmp/mia_verify_slow.py', r'C:/Users/User/tmp/freemodel/freemodel_full.py']:
try:
t = open(p, encoding='utf-8').read()
m1 = re.search(r'API_ID\s*=\s*(\d+)', t)
m2 = re.search(r'API_HASH\s*=\s*[\'"]([a-f0-9]+)[\'"]', t)
if m1 and m2:
TG_ID, TG_HASH = int(m1.group(1)), m2.group(1)
break
except Exception:
pass
def log(*a):
print(*a, flush=True)
def good_sessions():
"""Proven reusable TG sessions (rotate, no consumption)."""
out = []
try:
for p in json.load(open(GOOD_TG)):
if os.path.exists(p):
out.append(p)
except Exception:
pass
return out
def mark_good(path):
try:
g = json.load(open(GOOD_TG))
except Exception:
g = []
if path not in g:
g.append(path)
json.dump(g, open(GOOD_TG, 'w'))
def tg_sessions(n=4):
names = json.load(open(AVAIL))
try:
used = set(json.load(open(USED)))
except Exception:
used = set()
# exclude sessions already consumed by miarouter verifier (avoid AuthKeyDuplicated)
try:
mstate = json.load(open(r'C:/Users/User/Desktop/farm/miarouter/verifier_state.json'))
used |= set(mstate.get('used_tg', []))
except Exception:
pass
tail = [b for b in names if b not in used]
tail = tail[-n:] # TAIL: miarouter verifier walks head-first
out = []
for b in tail:
for d in DIRS:
p = os.path.join(d, b)
if os.path.exists(p):
out.append(p)
break
return out
def mark_tg_used(basename):
try:
used = set(json.load(open(USED)))
except Exception:
used = set()
used.add(basename)
json.dump(sorted(used), open(USED, 'w'))
async def bot_start(sess_path, ticket):
from telethon import TelegramClient
name = os.path.basename(sess_path)
client = TelegramClient(sess_path.replace('.session', ''), TG_ID, TG_HASH)
try:
await asyncio.wait_for(client.connect(), 45)
if not await client.is_user_authorized():
return name, 'NOT_AUTH'
await client.send_message('xkiro_official_bot', '/start ' + ticket)
await asyncio.sleep(9)
msgs = await client.get_messages('xkiro_official_bot', limit=4)
txt = ' '.join((m.message or '')[:200] for m in msgs if not m.out).lower()
if 'verified successfully' in txt or "you've received" in txt:
return name, 'OK'
if 'join' in txt or 'channel' in txt:
from telethon.tl.functions.channels import JoinChannelRequest
try:
await client(JoinChannelRequest('xtrouter'))
await asyncio.sleep(3)
await client.send_message('xkiro_official_bot', '/start ' + ticket)
await asyncio.sleep(8)
msgs = await client.get_messages('xkiro_official_bot', limit=4)
txt = ' '.join((m.message or '')[:200] for m in msgs if not m.out).lower()
if 'verified' in txt:
return name, 'OK'
return name, 'REPLY:' + txt[:120]
except Exception as e:
return name, 'JOIN_FAIL:' + type(e).__name__
return name, 'REPLY:' + txt[:120]
finally:
try:
await client.disconnect()
except Exception:
pass
def farm_one(acc, tgsess):
lg = acc['login']
rec = {'gh_login': lg, 'ts': time.strftime('%H:%M:%S')}
s = cq.Session(impersonate=IMP)
# 1 state
try:
r = s.get(API + '/api/v1/auth/github', headers={**H, 'Accept': 'text/html', 'Sec-Fetch-Site': 'none'},
allow_redirects=False, timeout=30)
loc = r.headers.get('Location', '') or ''
m = re.search(r'state=([a-f0-9]{16,})', loc)
if not m:
m = re.search(r'state=([a-f0-9]{16,})', r.text or '')
if not m:
rec['stage'] = 'state'; rec['err'] = f'http={r.status_code}'
return rec
state = m.group(1)
except Exception as e:
rec['stage'] = 'state'; rec['err'] = str(e)[:100]; return rec
# 2 gh code
gh = gh_http.GHSession(bind=False)
ok, err = gh.login(lg, acc['password'], acc.get('totp'))
if not ok:
rec['stage'] = 'gh_login'; rec['err'] = err; return rec
code, cerr = gh.oauth_code(CID, state, scope='read:user user:email')
if not code:
rec['stage'] = 'gh_code'; rec['err'] = cerr; return rec
# 3 callback (same session!)
try:
r3 = s.get(API + f'/api/v1/auth/github/callback?code={code}&state={state}',
headers={**H, 'Accept': 'text/html', 'Sec-Fetch-Site': 'cross-site',
'Referer': 'https://github.com/'}, timeout=40)
cks = dict(s.cookies)
if not cks.get('__xt_at'):
rec['stage'] = 'callback'; rec['err'] = f'http={r3.status_code} no __xt_at'
return rec
rec['cookies'] = cks
except Exception as e:
rec['stage'] = 'callback'; rec['err'] = str(e)[:100]; return rec
# 4 ticket via xkiro.com proxy (cookies same names, set on xkiro.com)
s2 = cq.Session(impersonate=IMP)
for k, v in cks.items():
s2.cookies.set(k, v, domain='xkiro.com')
s2.cookies.set(k, v, domain='.xkiro.com')
if not tgsess:
rec['tg'] = 'NO_TG_SESSION'
else:
try:
rt = s2.post(XK + '/api/v1/me/telegram/ticket', headers=H, data='{}', timeout=25)
j = rt.json()
data = j.get('data') or {}
if data.get('alreadyVerified'):
rec['tg'] = 'already'
else:
dl = data.get('deepLink', '')
ticket = dl.split('start=')[-1] if 'start=' in dl else ''
if not ticket:
rec['stage'] = 'ticket'; rec['err'] = rt.text[:120]; return rec
# 5 bot verify
try:
sp, res = asyncio.run(bot_start(tgsess, ticket))
except Exception as be:
res = f'EXC:{type(be).__name__}:{str(be)[:60]}'
rec['tg'] = res; rec['tg_sess'] = os.path.basename(tgsess)
if res == 'OK':
mark_tg_used(os.path.basename(tgsess)) # consumed: 1 TG acct = 1 xkiro verification
else:
mark_tg_used(os.path.basename(tgsess)) # any failure: never reuse (dup/NOT_AUTH/burned)
except Exception as e:
rec['stage'] = 'ticket'; rec['err'] = str(e)[:100]
# refresh cookies after middleware rotation
fresh = dict(s2.cookies)
if fresh.get('__xt_at'):
rec['cookies'] = {**cks, **fresh}
# 6 key + wallet + status
try:
rk = s2.post(XK + '/api/v1/keys', headers=H, data=json.dumps({'name': 'farm'}), timeout=25)
jk = rk.json()
rec['key'] = (jk.get('data') or {}).get('plaintext')
rec['key_id'] = ((jk.get('data') or {}).get('key') or {}).get('id')
except Exception as e:
rec['key_err'] = str(e)[:80]
try:
rec['wallet'] = s2.get(XK + '/api/v1/wallet', headers=H, timeout=20).json().get('data')
rec['tg_status'] = s2.get(XK + '/api/v1/me/telegram/status', headers=H, timeout=20).json().get('data')
except Exception:
pass
rec['stage'] = 'done'
return rec
def main():
ap = argparse.ArgumentParser()
ap.add_argument('count', type=int, nargs='?', default=1)
ap.add_argument('start', type=int, nargs='?', default=0)
args = ap.parse_args()
pool = json.load(open(POOL))
done = set()
try:
for line in open(BANK, encoding='utf-8'):
r = json.loads(line)
if r.get('stage') == 'done' or r.get('key'):
done.add(r['gh_login'])
except Exception:
pass
cand = [a for a in pool if a['login'] not in done]
log(f'=== xkiro farm: {args.count}, candidates {len(cand)}, TG_ID set: {TG_ID is not None}')
tgs = tg_sessions(args.count + 2)
log('tg sessions:', len(tgs))
n = 0
for i, a in enumerate(cand[args.start:]):
if n >= args.count:
break
goods = good_sessions()
if goods:
tg = goods[n % len(goods)] # REUSE: proven sessions verify unlimited accounts
else:
tgs = tg_sessions(1) # fresh per account: excludes xkiro-used + miarouter used_tg
tg = tgs[0] if tgs else None
log(f'--- {a["login"]} (tg: {os.path.basename(tg) if tg else "NONE"})')
try:
rec = farm_one(a, tg)
except Exception as e:
rec = {'gh_login': a['login'], 'stage': 'exc', 'err': f'{type(e).__name__}:{e}'[:120]}
with open(BANK, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
log(' ', {k: (str(v)[:60] if k not in ('cookies',) else '<saved>') for k, v in rec.items() if k != 'gh_login'})
n += 1
time.sleep(25)
if __name__ == '__main__':
main()