181 lines
7.6 KiB
Python
181 lines
7.6 KiB
Python
"""ModelOC — регистрация аккаунта через GitHub OAuth (чистый HTTP, без браузера).
|
|
|
|
Флоу:
|
|
invite-cookie (/i/<INVITE>) -> /auth/oauth/github -> github.com/session (пароль+TOTP)
|
|
-> authorize -> callback -> GET /pool/balance (credits) -> POST /pool/keys (pk_*)
|
|
|
|
Использование как модуля:
|
|
import reg
|
|
res = reg.reg({'login': 'user', 'password': 'pw', 'totp': 'BASE32SECRET'})
|
|
# {'login', 'ok', 'credits', 'key', 'error'}
|
|
|
|
CLI:
|
|
python reg.py <pool.json> <index>
|
|
"""
|
|
import html
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
from urllib.parse import urljoin
|
|
|
|
import requests
|
|
import pyotp
|
|
|
|
UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
|
'(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36')
|
|
MC = os.environ.get('MODELOC_BASE', 'https://modeloc.com')
|
|
INVITE = os.environ.get('MODELOC_INVITE', 'F78Q8Y46')
|
|
KEY_NAME_PREFIX = os.environ.get('MODELOC_KEY_PREFIX', 'eni-')
|
|
|
|
FUNDED_ZERO = ('', '0', '0.0', '0E+4', '0.0000', 'None')
|
|
|
|
|
|
def hidden(page):
|
|
out = {}
|
|
for tag in re.findall(r'<input[^>]*type="hidden"[^>]*>', page):
|
|
n = re.search(r'name="([^"]+)"', tag)
|
|
v = re.search(r'value="([^"]*)"', tag)
|
|
if n:
|
|
out[n.group(1)] = html.unescape(v.group(1)) if v else ''
|
|
return out
|
|
|
|
|
|
def gh_login(s, acc):
|
|
"""Логин в GitHub с TOTP. Возвращает None при успехе или строку-ошибку."""
|
|
r = s.get('https://github.com/login', timeout=30)
|
|
h = hidden(r.text)
|
|
data = {'authenticity_token': h.get('authenticity_token', ''), 'login': acc['login'],
|
|
'password': acc['password'], 'webauthn-conditional': 'undefined',
|
|
'javascript-support': 'enabled', 'webauthn-support': 'supported',
|
|
'webauthn-iuvpaa-support': 'unknown', 'return_to': '', 'allow_signup': '',
|
|
'client_id': h.get('client_id', ''), 'integration': '', 'commit': 'Sign in'}
|
|
if 'timestamp' in h:
|
|
data['timestamp'] = h['timestamp']
|
|
data['timestamp_secret'] = h.get('timestamp_secret', '')
|
|
for k in h:
|
|
if k.startswith('required_field_'):
|
|
data[k] = ''
|
|
r = s.post('https://github.com/session', data=data, allow_redirects=False, timeout=30)
|
|
if r.status_code == 200:
|
|
m = re.search(r'<div[^>]*flash-error[^>]*>(.*?)</div>', r.text, re.S)
|
|
return 'login: ' + (re.sub(r'<[^>]+>', ' ', m.group(1)).strip()[:60] if m else 'no_redirect')
|
|
loc = r.headers.get('Location', '')
|
|
if 'two-factor' in loc or 'verified-device' in loc:
|
|
if not acc.get('totp'):
|
|
return 'need_2fa'
|
|
r2 = s.get(urljoin('https://github.com', loc), timeout=30)
|
|
h2 = hidden(r2.text)
|
|
code = pyotp.TOTP(acc['totp'].replace(' ', '')).now()
|
|
field = 'app_otp' if 'app_otp' in r2.text else 'otp'
|
|
# action формы 2FA: /sessions/two-factor (не /app!) — иначе 422
|
|
mact = re.search(r'<form[^>]+action="([^"]+)"', r2.text)
|
|
action = urljoin('https://github.com', mact.group(1)) if mact else 'https://github.com/sessions/two-factor'
|
|
r2 = s.post(action, data={'authenticity_token': h2.get('authenticity_token', ''), field: code},
|
|
allow_redirects=False, timeout=30,
|
|
headers={'Referer': r2.url, 'Origin': 'https://github.com'})
|
|
if '/sessions/verified-device' in r2.headers.get('Location', ''):
|
|
return 'device_verify'
|
|
if r2.status_code == 200:
|
|
return '2fa_fail'
|
|
p = s.get('https://github.com/settings/profile', timeout=30, allow_redirects=False)
|
|
if p.status_code != 200:
|
|
return 'not_logged_in_%s' % p.status_code
|
|
return None
|
|
|
|
|
|
def oauth(s, auth_url):
|
|
"""Проходим экран согласия OAuth. Возвращает (callback_url, error)."""
|
|
r = s.get(auth_url, allow_redirects=False, timeout=30)
|
|
if r.status_code in (301, 302, 303, 307, 308):
|
|
return r.headers.get('Location', ''), None
|
|
low = r.text.lower()
|
|
if 'cannot authorize a third party' in low:
|
|
return None, 'gh_flagged'
|
|
if 'page not found' in low:
|
|
return None, 'app_404'
|
|
h = hidden(r.text)
|
|
if not h.get('authenticity_token'):
|
|
return None, 'no_csrf'
|
|
h['authorize'] = '1'
|
|
r = s.post('https://github.com/login/oauth/authorize', data=h, allow_redirects=False, timeout=30)
|
|
loc = r.headers.get('Location', '')
|
|
if not loc:
|
|
m = re.search(r'url=([^"\']+)', r.text)
|
|
loc = html.unescape(m.group(1)) if m else ''
|
|
return (loc, None) if loc else (None, 'auth_post_%s' % r.status_code)
|
|
|
|
|
|
def follow(s, url, hops=8):
|
|
cur = url
|
|
for _ in range(hops):
|
|
r = s.get(cur, allow_redirects=False, timeout=40)
|
|
if r.status_code in (301, 302, 303, 307, 308):
|
|
loc = r.headers.get('Location', '')
|
|
if not loc:
|
|
return None
|
|
cur = urljoin(r.url, loc)
|
|
continue
|
|
return r
|
|
return None
|
|
|
|
|
|
def reg(acc, name=None):
|
|
s = requests.Session()
|
|
s.headers.update({'User-Agent': UA, 'Accept-Language': 'en-US,en;q=0.9'})
|
|
# приглашение должно лечь в cookie ДО создания аккаунта, иначе 0 кредитов
|
|
try:
|
|
s.get(MC + '/i/' + INVITE, timeout=30)
|
|
except Exception:
|
|
pass
|
|
r = s.get(MC + '/auth/oauth/github', allow_redirects=False, timeout=30)
|
|
loc = r.headers.get('Location', '')
|
|
if 'github.com' not in loc:
|
|
return {'login': acc['login'], 'ok': False, 'error': 'start_%s' % r.status_code}
|
|
err = gh_login(s, acc)
|
|
if err:
|
|
return {'login': acc['login'], 'ok': False, 'error': err}
|
|
cb, err = oauth(s, loc)
|
|
if err:
|
|
return {'login': acc['login'], 'ok': False, 'error': err}
|
|
page = follow(s, urljoin(MC, cb))
|
|
if page is None:
|
|
return {'login': acc['login'], 'ok': False, 'error': 'callback_dead'}
|
|
b = s.get(MC + '/pool/balance', timeout=30)
|
|
if b.status_code != 200:
|
|
return {'login': acc['login'], 'ok': False, 'error': 'balance_%s' % b.status_code}
|
|
credits = b.json().get('credits')
|
|
nm = name or (KEY_NAME_PREFIX + acc['login'][:14])
|
|
k = s.post(MC + '/pool/keys', json={'name': nm, 'scope': 'all', 'sharer_scope': 'all'}, timeout=60)
|
|
key = None
|
|
if k.status_code in (200, 201):
|
|
d = k.json()
|
|
key = d.get('key') or (d.get('data') or {}).get('key')
|
|
if not key:
|
|
try:
|
|
ks = s.get(MC + '/pool/keys', timeout=30).json()
|
|
items = ks if isinstance(ks, list) else (ks.get('keys') or ks.get('items') or [])
|
|
if items:
|
|
key = items[-1].get('key')
|
|
except Exception:
|
|
pass
|
|
ok = bool(key) and float(credits or 0) > 0
|
|
return {'login': acc['login'], 'ok': ok, 'credits': credits, 'key': key,
|
|
'error': None if ok else 'no_key_%s' % k.status_code}
|
|
|
|
|
|
def probe(key, model=None, base=None):
|
|
"""Живость ключа: 200 на chat/completions. Возвращает (http_code, текстовый срез)."""
|
|
base = (base or MC).rstrip('/')
|
|
model = model or os.environ.get('MODELOC_PROBE_MODEL', 'kr/claude-sonnet-4.5')
|
|
r = requests.post(base + '/pool/v1/chat/completions',
|
|
headers={'Authorization': 'Bearer ' + key, 'Content-Type': 'application/json'},
|
|
json={'model': model, 'messages': [{'role': 'user', 'content': 'hi'}], 'max_tokens': 5},
|
|
timeout=40)
|
|
return r.status_code, r.text[:200]
|
|
|
|
|
|
if __name__ == '__main__':
|
|
pool = json.load(open(sys.argv[1], encoding='utf-8'))
|
|
print(json.dumps(reg(pool[int(sys.argv[2])]), ensure_ascii=False)) |