HF-MLH Toolkit v2 — stdlib OAuth/claim pipeline, resumable JSONL bank, config.json setup
This commit is contained in:
+245
@@ -0,0 +1,245 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""MLH re-auth via OTP flow (Oct 2026):
|
||||
1. GET /signin -> version+csrf
|
||||
2. POST /signin {email, return_to, cf-turnstile-response} (real_page token!) -> Inertia OTP page w/ otpId
|
||||
3. IMAP: "One-Time Login Code is NNNNNN" for tag
|
||||
4. POST /signin {otp_id, otp, email, return_to, cf-turnstile-response} -> signed session
|
||||
Usage: python hf_reauth2.py <tag_or_email> [wait_sec]
|
||||
State: hf_mlh_sessions.json"""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import json, re, sys, os, time, urllib.request, urllib.parse, urllib.error, http.cookiejar
|
||||
import imaplib, email as emaillib, quopri
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from hf_promos import solve_turnstile, ck_str, UA
|
||||
import hf_config as CFG
|
||||
|
||||
STATE = CFG.data_file("hf_mlh_sessions.json")
|
||||
IMAP_USER, IMAP_PASS = os.environ.get("IMAP_USER",""), os.environ.get("IMAP_PASS","")
|
||||
|
||||
def log(*a): print(time.strftime("%H:%M:%S"), *a, flush=True)
|
||||
|
||||
def load_state():
|
||||
try: return json.load(open(STATE, encoding="utf-8"))
|
||||
except Exception: return {}
|
||||
|
||||
def save_state(st): json.dump(st, open(STATE, "w", encoding="utf-8"), indent=1)
|
||||
|
||||
def inertia_headers(ver, csrf):
|
||||
return {"Content-Type": "application/json", "Accept": "application/json, text/html",
|
||||
"X-Inertia": "true", "X-Inertia-Version": ver, "X-CSRF-Token": csrf,
|
||||
"Referer": "https://www.mlh.com/signin", "Origin": "https://www.mlh.com",
|
||||
"User-Agent": UA}
|
||||
|
||||
def wait_otp(tag, since_ts, timeout=240):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
try:
|
||||
M = imaplib.IMAP4_SSL("imap.gmail.com"); M.login(IMAP_USER, IMAP_PASS); M.select("INBOX")
|
||||
M.noop()
|
||||
typ, data = M.search(None, "ALL")
|
||||
ids = data[0].split()[-40:]
|
||||
for i in reversed(ids):
|
||||
typ, hd = M.fetch(i, "(BODY.PEEK[HEADER.FIELDS (TO SUBJECT DATE)])")
|
||||
raw = hd[0][1] if isinstance(hd[0], tuple) else hd[0]
|
||||
hs = raw.decode(errors="replace") if isinstance(raw, bytes) else str(raw)
|
||||
low = hs.lower()
|
||||
if tag not in low: continue
|
||||
if "one-time" not in low and "verify your identity" not in low and "login code" not in low: continue
|
||||
dm = re.search(r'Date: (.+)', hs)
|
||||
if dm:
|
||||
try:
|
||||
from email.utils import parsedate_to_datetime
|
||||
if parsedate_to_datetime(dm.group(1).strip()).timestamp() < since_ts - 60: continue
|
||||
except Exception: pass
|
||||
typ, full = M.fetch(i, "(BODY.PEEK[])")
|
||||
msg = emaillib.message_from_bytes(full[0][1]); b2 = ""
|
||||
for p in msg.walk():
|
||||
if p.get_content_type() == "text/plain":
|
||||
pl = p.get_payload(decode=True)
|
||||
b2 = pl.decode(errors="replace") if isinstance(pl, bytes) else str(pl)
|
||||
break
|
||||
if not b2:
|
||||
for p in msg.walk():
|
||||
if p.get_content_type() == "text/html":
|
||||
pl = p.get_payload(decode=True)
|
||||
b2 = pl.decode(errors="replace") if isinstance(pl, bytes) else str(pl)
|
||||
break
|
||||
b2 = quopri.decodestring(b2.encode(errors="replace")).decode(errors="replace")
|
||||
M.logout()
|
||||
m = re.search(r'Login Code is\s*(\d{6})', b2)
|
||||
if not m: m = re.search(r'\b(\d{6})\b', b2[:600])
|
||||
if m: return m.group(1)
|
||||
M.logout()
|
||||
except Exception as e:
|
||||
log("imap err:", str(e)[:80])
|
||||
time.sleep(5)
|
||||
return None
|
||||
|
||||
def check_signed(html):
|
||||
return ('"isSignedIn":true' in html) or ('isSignedIn":true' in html) or ('isSignedIn\\":true' in html)
|
||||
|
||||
def reauth(email_addr, wait=240):
|
||||
tag = email_addr.split("+")[1].split("@")[0] if "+" in email_addr else email_addr.split("@")[0]
|
||||
cj = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
|
||||
op.addheaders = [("User-Agent", UA)]
|
||||
g = op.open("https://www.mlh.com/signin", timeout=40)
|
||||
html = g.read().decode(errors="replace")
|
||||
ver = re.search(r'"version":"([a-f0-9]+)"', html).group(1)
|
||||
csrf = re.search(r'name="csrf-token" content="([^"]+)"', html).group(1)
|
||||
t0 = time.time()
|
||||
tok = solve_turnstile()
|
||||
if not tok: return None, "no_turnstile"
|
||||
body = json.dumps({"email": email_addr, "return_to": "", "cf-turnstile-response": tok}).encode()
|
||||
req = urllib.request.Request("https://www.mlh.com/signin", data=body, method="POST")
|
||||
for k, v in inertia_headers(ver, csrf).items(): req.add_header(k, v)
|
||||
try:
|
||||
resp = op.open(req, timeout=45); d = resp.read().decode(errors="replace")
|
||||
url1 = resp.url
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, "post1_%s" % e.code
|
||||
log("post1 url:", url1)
|
||||
comp = re.search(r'"component":"([^"]+)"', d)
|
||||
flash = re.search(r'"flash":\s*\{"error":\s*\{[^}]*"message":\s*"([^"]+)"', d)
|
||||
otpid = re.search(r'"otpId":\s*"?([A-Za-z0-9_\-]+)', d)
|
||||
pm = re.search(r'"props":\{(.{0,300})', d)
|
||||
log("post1 comp:", comp.group(1) if comp else "?", "otpId:", otpid.group(1) if otpid else None)
|
||||
if pm: log("props:", pm.group(1)[:250])
|
||||
if flash:
|
||||
return None, "flash:" + flash.group(1)
|
||||
if comp and "Success" in comp.group(1):
|
||||
return ck_str(cj), None # already signed in
|
||||
if not otpid:
|
||||
# maybe OTP page without id, or email-not-found silent re-render
|
||||
if comp and "OTP" in comp.group(1):
|
||||
otpid_val = ""
|
||||
else:
|
||||
open(str(CFG.WORK / "hf_post1_resp.json"), "w", encoding="utf-8").write(d)
|
||||
return None, "no_otpid_comp=%s" % (comp.group(1) if comp else "?")
|
||||
else:
|
||||
otpid_val = otpid.group(1)
|
||||
# new version may have changed after POST
|
||||
vm = re.search(r'"version":"([a-f0-9]+)"', d)
|
||||
ver2 = vm.group(1) if vm else ver
|
||||
otp = wait_otp(tag, t0, timeout=wait)
|
||||
if not otp: return None, "no_otp_email"
|
||||
log("OTP:", otp)
|
||||
tok2 = solve_turnstile()
|
||||
if not tok2: return None, "no_turnstile2"
|
||||
otp_url = "https://www.mlh.com/signin/%s/otp" % otpid_val
|
||||
# GET otp page first: fresh Inertia version (POST with stale version = 409)
|
||||
try:
|
||||
gp = op.open(otp_url, timeout=40); hp = gp.read().decode(errors="replace")
|
||||
vm2 = re.search(r'"version":"([a-f0-9]+)"', hp)
|
||||
if vm2: ver2 = vm2.group(1)
|
||||
cm = re.search(r'name="csrf-token" content="([^"]+)"', hp)
|
||||
if cm: csrf = cm.group(1)
|
||||
log("otp page GET ok, ver:", ver2[:12])
|
||||
except Exception as e:
|
||||
log("otp page GET err:", str(e)[:80])
|
||||
hdr2 = inertia_headers(ver2, csrf)
|
||||
hdr2["Referer"] = otp_url
|
||||
body2 = json.dumps({"otp_id": otpid_val, "otp": otp, "email": email_addr,
|
||||
"return_to": "", "cf-turnstile-response": tok2}).encode()
|
||||
req2 = urllib.request.Request(otp_url, data=body2, method="POST")
|
||||
for k, v in hdr2.items(): req2.add_header(k, v)
|
||||
try:
|
||||
r2 = op.open(req2, timeout=45); d2 = r2.read().decode(errors="replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode(errors="replace")
|
||||
log("post2 %s hdrs: %s" % (e.code, dict(e.headers)))
|
||||
log("post2 body:", body[:400])
|
||||
if e.code == 409:
|
||||
loc = e.headers.get("X-Inertia-Location", "")
|
||||
log("inertia loc:", loc[:150])
|
||||
# 409 may come AFTER otp consumption+signin — check session first!
|
||||
try:
|
||||
rc = op.open("https://www.mlh.com/", timeout=40); hc = rc.read().decode(errors="replace")
|
||||
if check_signed(hc):
|
||||
log("409 but SIGNED (otp consumed pre-conflict)")
|
||||
return ck_str(cj), None
|
||||
except Exception:
|
||||
pass
|
||||
# retry once: fresh GET of otp page, re-solve, POST again
|
||||
try:
|
||||
gp2 = op.open(otp_url, timeout=40); hp2 = gp2.read().decode(errors="replace")
|
||||
ver3 = re.search(r'"version":"([a-f0-9]+)"', hp2).group(1)
|
||||
cs3 = re.search(r'name="csrf-token" content="([^"]+)"', hp2)
|
||||
csrf3 = cs3.group(1) if cs3 else csrf
|
||||
tok3 = solve_turnstile()
|
||||
hdr3 = inertia_headers(ver3, csrf3); hdr3["Referer"] = otp_url
|
||||
body3 = json.dumps({"otp_id": otpid_val, "otp": otp, "email": email_addr,
|
||||
"return_to": "", "cf-turnstile-response": tok3}).encode()
|
||||
req3 = urllib.request.Request(otp_url, data=body3, method="POST")
|
||||
for k, v in hdr3.items(): req3.add_header(k, v)
|
||||
r2 = op.open(req3, timeout=45); d2 = r2.read().decode(errors="replace")
|
||||
log("retry post2:", r2.status)
|
||||
except urllib.error.HTTPError as e2:
|
||||
return None, "post2retry_%s" % e2.code
|
||||
else:
|
||||
return None, "post2_%s" % e.code
|
||||
comp2 = re.search(r'"component":"([^"]+)"', d2)
|
||||
flash2 = re.search(r'"flash":\s*\{"error":\s*\{[^}]*"message":\s*"([^"]+)"', d2)
|
||||
signed = check_signed(d2)
|
||||
log("post2 comp:", comp2.group(1) if comp2 else "?", "signed:", signed)
|
||||
if flash2: log("flash2:", flash2.group(1))
|
||||
if not signed:
|
||||
try:
|
||||
r3 = op.open("https://www.mlh.com/", timeout=40); h3 = r3.read().decode(errors="replace")
|
||||
signed = check_signed(h3)
|
||||
uid = re.search(r'currentUser.{0,200}?"id":"?([a-z0-9\-]+)', h3)
|
||||
log("home signed:", signed, "uid:", uid.group(1) if uid else None)
|
||||
except Exception as e:
|
||||
log("home err", str(e)[:80])
|
||||
open(str(CFG.WORK / "hf_post2_resp.json"), "w", encoding="utf-8").write(d2[:20000])
|
||||
if not signed:
|
||||
return None, "not_signed"
|
||||
return ck_str(cj), None
|
||||
|
||||
def main():
|
||||
arg = sys.argv[1]
|
||||
wait = int(sys.argv[2]) if len(sys.argv) > 2 else 240
|
||||
email_addr = arg if "@" in arg else CFG.alias_email(arg)
|
||||
st = load_state()
|
||||
log("== reauth2", email_addr)
|
||||
cookies, err = reauth(email_addr, wait)
|
||||
if not cookies:
|
||||
log("FAIL:", err)
|
||||
st[email_addr] = {"status": err, "ts": int(time.time())}
|
||||
save_state(st); sys.exit(2)
|
||||
st[email_addr] = {"cookies": cookies, "signed": True, "ts": int(time.time()), "status": "ok"}
|
||||
save_state(st)
|
||||
log("OK session saved")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user