Files

436 lines
17 KiB
Python
Executable File

#!/usr/bin/env python3
"""modeloc-autoreg — bring-your-own-credentials client for the modeloc.com compute pool.
What it does (one account per call, pure HTTP, no browser):
1. GH — loads a GitHub web session (cookie string from your own browser) and
proves it is alive via /settings/profile.
2. INVITE— GET https://modeloc.com/i/<invite> so the server drops the `ara_invite`
cookie. This is the step that decides whether the account gets the
onboarding credit grant at all.
3. OAUTH — GET /auth/oauth/github -> github.com/login/oauth/authorize ->
consent form POST (two `authorize` buttons: 0 = cancel, 1 = allow) ->
modeloc callback -> `ara_session` cookie.
4. POOL — /pool/balance, /pool/enroll, POST /pool/keys (JSON!), then
/pool/v1/models and one cheap /pool/v1/chat/completions.
Design notes / traps this code already handles:
* gh_http-style clients that install a NoRedirect handler break OAuth: GitHub
answers 200 "already authorized" instead of the ?code= redirect. We keep a
second opener bound to the *same* cookie jar that follows redirects.
* Header lookups must be case-insensitive (`location` vs `Location`).
* The consent page carries two submit buttons with name="authorize":
value="0" is Cancel, value="1" is Authorize. Picking the first one by DOM
order sends you to a 404.
* POST /pool/keys with a body FastAPI does not recognise as JSON returns
`422 {"detail":[{"type":"dict_type"}]}`; send explicit Content-Type.
* Cloudflare in front of /pool/v1 rejects bare python urllib by TLS
fingerprint (`403 error code 1010`). curl_cffi with impersonate="chrome"
works. Install it: `pip install curl_cffi`.
* Balance strings may arrive as "0E+4" — that is a real zero, not 10000.
* A key can exist with zero spendable balance: /models returns 200 while
chat returns 402/429.
BYOK only: this tool never ships, embeds or harvests credentials. You supply
your own GitHub session cookie (and optionally an invite code you are entitled
to use). Nothing is uploaded anywhere except the requests to modeloc.com and
github.com that the flow itself requires.
"""
from __future__ import annotations
import argparse
import html as htmlmod
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from http.cookiejar import CookieJar
BASE = "https://modeloc.com"
GH = "https://github.com"
UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36")
try: # Cloudflare-friendly HTTP client
from curl_cffi import requests as cffi_requests
except Exception: # pragma: no cover - optional
cffi_requests = None
# --------------------------------------------------------------------------- #
# helpers
# --------------------------------------------------------------------------- #
def log(msg: str) -> None:
print(msg, flush=True)
def hget(headers, name: str, default: str = "") -> str:
"""Case-insensitive header lookup (dict or HTTPMessage)."""
name = name.lower()
try:
items = headers.items()
except AttributeError:
return default
for k, v in items:
if k.lower() == name:
return v
return default
def cookie_dict(jar: CookieJar) -> dict:
return {c.name: c.value for c in jar}
def parse_cookie_string(raw: str) -> dict:
out = {}
for part in raw.split(";"):
part = part.strip()
if not part or "=" not in part:
continue
k, v = part.split("=", 1)
out[k.strip()] = v.strip()
return out
class Session:
"""Cookie jar + redirect-capable opener shared by GitHub and modeloc."""
def __init__(self, proxy: str | None = None):
self.jar = CookieJar()
handlers = [urllib.request.HTTPCookieProcessor(self.jar),
urllib.request.HTTPSHandler(), urllib.request.HTTPHandler()]
if proxy:
handlers.insert(0, urllib.request.ProxyHandler({"http": proxy, "https": proxy}))
self.op = urllib.request.build_opener(*handlers)
self.op.addheaders = [("User-Agent", UA),
("Accept", "text/html,application/xhtml+xml,application/json;q=0.9,*/*;q=0.8"),
("Accept-Language", "en-US,en;q=0.9")]
def request(self, url: str, data: bytes | None = None, headers: dict | None = None,
follow: bool = True):
req = urllib.request.Request(url, data=data, headers=headers or {})
opener = self.op if follow else urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(self.jar), _no_redirect())
try:
with opener.open(req, timeout=60) as r:
return r.status, dict(r.headers), r.read().decode("utf-8", "ignore"), r.geturl()
except urllib.error.HTTPError as e:
return e.code, dict(e.headers or {}), e.read().decode("utf-8", "ignore"), url
def set_cookie(self, name: str, value: str, domain: str) -> None:
from http.cookiejar import Cookie
c = Cookie(0, name, value, None, False, domain, False, False, "/", True,
False, None, True, None, None, {})
self.jar.set_cookie(c)
def _no_redirect():
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *a, **kw):
return None
return NoRedirect()
def gh_cookie_session(cookie_string: str, proxy: str | None = None) -> Session:
"""Build a Session carrying a GitHub web session cookie (user_logged_in etc.)."""
s = Session(proxy)
for k, v in parse_cookie_string(cookie_string).items():
s.set_cookie(k, v, ".github.com")
return s
# --------------------------------------------------------------------------- #
# 1. GitHub liveness
# --------------------------------------------------------------------------- #
def gh_check(s: Session) -> tuple[bool, str]:
st, _h, body, final = s.request(GH + "/settings/profile")
if st == 200 and ("/login" not in final) and "Sign in to GitHub" not in body:
m = re.search(r'data-login="([^"]+)"', body) or re.search(r'"login":"([^"]+)"', body)
return True, (m.group(1) if m else "?")
return False, "not authenticated (cookie expired?)"
# --------------------------------------------------------------------------- #
# 2. invite cookie
# --------------------------------------------------------------------------- #
def drop_invite(s: Session, invite: str) -> dict:
url = f"{BASE}/i/{invite}" if invite else f"{BASE}/"
st, _h, _b, _f = s.request(url)
return {"status": st, "cookies": list(cookie_dict(s.jar).keys())}
# --------------------------------------------------------------------------- #
# 3. OAuth chain with consent handling
# --------------------------------------------------------------------------- #
def _forms(body: str) -> list[dict]:
out = []
for m in re.finditer(r"<form[^>]*>.*?</form>", body, re.S):
f = m.group(0)
am = re.search(r'action="([^"]*)"', f)
mm = re.search(r'method="([^"]*)"', f)
fields: dict[str, str] = {}
for im in re.finditer(r"<input[^>]*>", f):
tag = im.group(0)
nm = re.search(r'name="([^"]+)"', tag)
vl = re.search(r'value="([^"]*)"', tag)
if nm:
fields[nm.group(1)] = htmlmod.unescape(vl.group(1)) if vl else ""
for bm in re.finditer(r"<(?:button|input)[^>]*>", f):
tag = bm.group(0)
if "submit" not in tag.lower():
continue
nm = re.search(r'name="([^"]+)"', tag)
vl = re.search(r'value="([^"]*)"', tag)
if nm:
name = nm.group(1)
val = htmlmod.unescape(vl.group(1)) if vl else ""
# consent: two buttons named `authorize` — prefer the allow one
if name in fields:
if val == "1":
fields[name] = val
else:
fields[name] = val
out.append({"action": am.group(1) if am else "",
"method": (mm.group(1) if mm else "get").lower(),
"fields": fields})
return out
def oauth_login(s: Session, max_hops: int = 12) -> dict:
st, h, _b, _f = s.request(BASE + "/auth/oauth/github")
loc = hget(h, "location")
cur = urllib.parse.urljoin(BASE, loc) if loc else None
chain = [("start", st, (loc or "")[:80])]
if st not in (301, 302, 303, 307) or not cur:
if "ara_session" in cookie_dict(s.jar):
return {"ok": True, "chain": chain}
return {"ok": False, "chain": chain, "error": f"no oauth redirect (http {st})"}
final = cur
for _ in range(max_hops):
st, h, body, final = s.request(cur)
chain.append(("get", st, cur[:80]))
nxt = hget(h, "location")
if st in (301, 302, 303, 307) and nxt:
cur = urllib.parse.urljoin(cur, nxt)
continue
# consent page
if st == 200 and "oauth/authorize" in cur:
acted = False
for form in _forms(body):
if form["method"] != "post":
continue
post_url = urllib.parse.urljoin(cur, form["action"] or cur)
data = urllib.parse.urlencode(form["fields"]).encode()
st2, h2, body2, final2 = s.request(post_url, data=data)
chain.append(("POST consent", st2, post_url[:80]))
nxt2 = hget(h2, "location")
if st2 in (301, 302, 303) and nxt2:
cur = urllib.parse.urljoin(post_url, nxt2)
acted = True
break
if st2 == 200:
cur, body, final = post_url, body2, final2
acted = True
break
if acted:
continue
break
ok = "ara_session" in cookie_dict(s.jar)
return {"ok": ok, "chain": chain,
"error": None if ok else f"no ara_session (last {st} {final[:60]})"}
# --------------------------------------------------------------------------- #
# 4. pool: balance / enroll / key / probe
# --------------------------------------------------------------------------- #
def pool_balance(s: Session) -> dict:
st, _h, body, _f = s.request(BASE + "/pool/balance",
headers={"Accept": "application/json"})
if st != 200:
return {"http": st}
try:
return json.loads(body)
except Exception:
return {"http": st, "raw": body[:120]}
def pool_enroll(s: Session) -> dict:
data = json.dumps({}).encode()
st, _h, body, _f = s.request(BASE + "/pool/enroll", data=data,
headers={"Content-Type": "application/json",
"Accept": "application/json"})
return {"http": st, "body": body[:160]}
def invite_summary(s: Session) -> dict:
"""Own referral link + counters (the page does exactly this fetch)."""
st, _h, body, _f = s.request(BASE + "/invite/summary",
headers={"Accept": "application/json"})
if st != 200:
return {"http": st, "raw": body[:120]}
try:
return json.loads(body)
except Exception:
return {"http": st, "raw": body[:120]}
def create_key(s: Session, name: str = "auto") -> dict:
payload = {"name": name, "filter_mode": "all", "allowed_models": []}
st, _h, body, _f = s.request(BASE + "/pool/keys", data=json.dumps(payload).encode(),
headers={"Content-Type": "application/json",
"Accept": "application/json"})
key = None
try:
key = json.loads(body).get("key")
except Exception:
pass
return {"http": st, "key": key, "body": body[:160]}
def to_float(v) -> float:
try:
return float(str(v).replace("E+4", "e4"))
except Exception:
return 0.0
def probe(api_key: str, model: str = "deepseek-v4-flash") -> dict:
"""ModelOC sits behind Cloudflare: bare urllib is dying on TLS fingerprint."""
url = BASE + "/pool/v1/chat/completions"
payload = {"model": model, "messages": [{"role": "user", "content": "ok"}], "max_tokens": 4}
headers = {"Authorization": "Bearer " + api_key, "Content-Type": "application/json"}
if cffi_requests:
try:
r = cffi_requests.post(url, json=payload, headers=headers,
impersonate="chrome", timeout=90)
return {"http": r.status_code, "body": r.text[:160]}
except Exception as e:
return {"http": 0, "error": f"{type(e).__name__}: {e}"}
req = urllib.request.Request(url, data=json.dumps(payload).encode(), headers=headers)
try:
with urllib.request.urlopen(req, timeout=90) as r:
return {"http": r.status, "body": r.read().decode()[:160]}
except urllib.error.HTTPError as e:
return {"http": e.code, "body": e.read().decode()[:160]}
except Exception as e:
return {"http": 0, "error": f"{type(e).__name__}: {e}"}
def list_models(api_key: str) -> dict:
url = BASE + "/pool/v1/models"
headers = {"Authorization": "Bearer " + api_key}
if cffi_requests:
try:
r = cffi_requests.get(url, headers=headers, impersonate="chrome", timeout=60)
ids = [m.get("id") for m in (r.json().get("data") or [])] if r.status_code == 200 else []
return {"http": r.status_code, "models": len(ids), "sample": ids[:6]}
except Exception as e:
return {"http": 0, "error": str(e)[:80]}
return {"http": 0, "error": "curl_cffi not installed"}
# --------------------------------------------------------------------------- #
# one account
# --------------------------------------------------------------------------- #
def run_account(cookie: str, invite: str = "", proxy: str | None = None,
want_key: bool = True, model: str = "deepseek-v4-flash",
want_invite: bool = False) -> dict:
s = gh_cookie_session(cookie, proxy)
t0 = time.time()
res: dict = {"ok": False}
alive, login = gh_check(s)
res["gh_login"] = login
if not alive:
res["error"] = "github cookie is not authenticated"
return res
if invite:
res["invite"] = drop_invite(s, invite)
oa = oauth_login(s)
res["oauth"] = oa
if not oa["ok"]:
res["error"] = oa["error"]
return res
bal = pool_balance(s)
res["balance"] = bal
if not bal.get("enrolled", True):
pool_enroll(s)
bal = pool_balance(s)
res["balance_after_enroll"] = bal
res["spendable"] = bal.get("spendable")
if want_invite:
res["my_invite"] = invite_summary(s)
if want_key:
k = create_key(s)
res["key_http"] = k["http"]
if k["key"]:
res["key"] = k["key"]
res["models"] = list_models(k["key"])
res["probe"] = probe(k["key"], model)
res["ok"] = res["probe"].get("http") == 200
else:
res["key_body"] = k["body"]
else:
res["ok"] = True
res["secs"] = round(time.time() - t0, 1)
return res
def main() -> int:
ap = argparse.ArgumentParser(description="modeloc.com account runner (BYOK, pure HTTP)")
ap.add_argument("--cookie", default=os.environ.get("GH_COOKIE", ""),
help="GitHub session cookie string (user_session=...; ...)")
ap.add_argument("--cookie-file", default="", help="file with one cookie string")
ap.add_argument("--invite", default=os.environ.get("MODELOC_INVITE", ""),
help="invite code from an /i/<code> link you are entitled to use")
ap.add_argument("--proxy", default=os.environ.get("HTTPS_PROXY", ""))
ap.add_argument("--model", default="deepseek-v4-flash")
ap.add_argument("--no-key", action="store_true", help="stop after balance")
ap.add_argument("--my-invite", action="store_true",
help="also print your own /i/<code> referral link (GET /invite/summary)")
ap.add_argument("--json", action="store_true")
args = ap.parse_args()
cookies = []
if args.cookie:
cookies.append(args.cookie)
if args.cookie_file:
with open(args.cookie_file, encoding="utf-8") as fh:
cookies += [ln.strip() for ln in fh if ln.strip() and "=" in ln]
if not cookies:
ap.print_help()
log("\nNeed --cookie or --cookie-file (GitHub web session, your own account).")
return 2
rc = 0
for i, c in enumerate(cookies, 1):
res = run_account(c, args.invite, args.proxy or None, not args.no_key, args.model,
args.my_invite)
if args.json:
print(json.dumps(res))
else:
bal = res.get("balance") or {}
log(f"[{i}/{len(cookies)}] {res.get('gh_login')} "
f"spendable={bal.get('spendable')} ok={res.get('ok')} "
f"key={'yes' if res.get('key') else 'no'} "
f"err={str(res.get('error'))[:70]}")
rc += 0 if res.get("ok") else 1
return 1 if rc else 0
if __name__ == "__main__":
sys.exit(main())