HF-MLH Toolkit v2 — stdlib OAuth/claim pipeline, resumable JSONL bank, config.json setup
This commit is contained in:
+297
@@ -0,0 +1,297 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Hacktoberfest promos: re-auth MLH account via magic link -> OAuth hacktoberfest-api -> offers/claim.
|
||||
Usage: python hf_promos.py <idx> [--claim]
|
||||
Reads mlh_farm_accounts.jsonl, refreshes cookies, saves hf_promo_accounts.jsonl
|
||||
"""
|
||||
# __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, time, re, sys, os, random, string
|
||||
import urllib.request, urllib.parse, urllib.error, http.cookiejar
|
||||
import imaplib, email as emaillib
|
||||
sys.path.insert(0, str(_REPO))
|
||||
import hf_config as CFG
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
TMP = str(CFG.DATA)
|
||||
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"
|
||||
SIDE = CFG.SIDECAR
|
||||
SITEKEY = CFG.SITEKEY
|
||||
API = CFG.API
|
||||
OUT = CFG.data_file("hf_promo_accounts.jsonl")
|
||||
K2 = None # 2captcha fallback key (lazy)
|
||||
|
||||
def log(*a): print(time.strftime("%H:%M:%S"), *a, flush=True)
|
||||
|
||||
def k2key():
|
||||
global K2
|
||||
if K2 is None:
|
||||
K2 = CFG.two_captcha_key()
|
||||
if not K2:
|
||||
log("2captcha key not configured (TWO_CAPTCHA_KEY / data/captcha_keys_2captcha.json)")
|
||||
return K2
|
||||
|
||||
def http_json(url, payload, timeout=200):
|
||||
req = urllib.request.Request(url, data=json.dumps(payload).encode(),
|
||||
headers={"Content-Type": "application/json"})
|
||||
return json.loads(urllib.request.urlopen(req, timeout=timeout).read())
|
||||
|
||||
def solve_turnstile(action="authentication"):
|
||||
# MLH siteverify REJECTS plain sidecar tokens (invalid-input-response) —
|
||||
# only real_page (camoufox) works. Fallback: 2captcha.
|
||||
for attempt in range(2):
|
||||
try:
|
||||
r = http_json(SIDE + "/solve", {"type": "turnstile", "sitekey": SITEKEY,
|
||||
"url": "https://www.mlh.com/signin", "action": action,
|
||||
"real_page": True, "timeout_s": 180}, timeout=220)
|
||||
if isinstance(r, dict) and r.get("solved") and r.get("token"):
|
||||
log("turnstile OK (sidecar real_page)")
|
||||
return r["token"]
|
||||
log("sidecar miss:", json.dumps(r)[:150])
|
||||
except Exception as e:
|
||||
log("sidecar err:", str(e)[:120])
|
||||
time.sleep(5)
|
||||
# 2captcha fallback
|
||||
try:
|
||||
kk = k2key()
|
||||
if not kk:
|
||||
return None
|
||||
def api(url, data):
|
||||
req = urllib.request.Request(url, data=urllib.parse.urlencode(data).encode())
|
||||
return json.loads(urllib.request.urlopen(req, timeout=30).read())
|
||||
r = api("https://api.2captcha.com/in.php", {"key": kk, "method": "turnstile",
|
||||
"sitekey": SITEKEY, "pageurl": "https://www.mlh.com/", "action": action, "json": 1})
|
||||
if r.get("status") != 1:
|
||||
log("2captcha in fail:", r); return None
|
||||
tid = r["request"]
|
||||
for _ in range(90):
|
||||
time.sleep(3)
|
||||
rr = api("https://api.2captcha.com/res.php", {"key": kk, "action": "get", "id": tid, "json": 1})
|
||||
if rr.get("status") == 1:
|
||||
log("turnstile OK (2captcha)"); return rr["request"]
|
||||
if rr.get("request") != "CAPCHA_NOT_READY":
|
||||
log("2captcha fail:", rr); return None
|
||||
except Exception as e:
|
||||
log("2captcha err:", str(e)[:120])
|
||||
return None
|
||||
|
||||
def wait_magic(tag, timeout=300):
|
||||
t0 = time.time()
|
||||
IMAP_USER, IMAP_PASS = CFG.imap_creds()
|
||||
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)])")
|
||||
hs = hd[0][1].decode(errors="replace").lower()
|
||||
if tag not in hs: continue
|
||||
if "verify your identity" not in hs and "sign in" not in hs and "magic" not in hs: continue
|
||||
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":
|
||||
b2 = p.get_payload(decode=True).decode(errors="replace"); break
|
||||
lab = re.findall(r'Sign in\s*\(?\s*(https://transactional\.mlh\.io/[^)\s>]+)', b2)
|
||||
if not lab:
|
||||
lab = re.findall(r'(https://transactional\.mlh\.io/ls/click[^\s<>"\']+)', b2)
|
||||
M.logout()
|
||||
if lab: return lab[0]
|
||||
M.logout()
|
||||
except Exception as e:
|
||||
log("imap err:", str(e)[:80])
|
||||
time.sleep(6)
|
||||
return None
|
||||
|
||||
def jar_from(cookies):
|
||||
cj = http.cookiejar.CookieJar()
|
||||
for part in cookies.split("; "):
|
||||
if "=" in part:
|
||||
n, v = part.split("=", 1)
|
||||
cj.set_cookie(http.cookiejar.Cookie(0, n, v, None, False, ".mlh.com", True, False,
|
||||
"/", True, True, None, False, None, None, {}))
|
||||
return cj
|
||||
|
||||
def ck_str(cj):
|
||||
return "; ".join(f"{c.name}={c.value}" for c in cj)
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
def reauth(acc):
|
||||
"""Fresh MLH session via signin POST + magic link."""
|
||||
tag = acc["email"].split("+")[1].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)
|
||||
csrf = re.search(r'name="csrf-token" content="([^"]+)"', html)
|
||||
if not ver or not csrf:
|
||||
return None, "no_ver_csrf"
|
||||
tok = solve_turnstile()
|
||||
if not tok: return None, "no_turnstile"
|
||||
body = json.dumps({"email": acc["email"], "return_to": "", "cf-turnstile-response": tok}).encode()
|
||||
req = urllib.request.Request("https://www.mlh.com/signin", data=body, method="POST")
|
||||
for k, v in {"Content-Type": "application/json", "Accept": "text/html,application/xhtml+xml",
|
||||
"X-Inertia": "true", "X-Inertia-Version": ver.group(1), "X-CSRF-Token": csrf.group(1),
|
||||
"Referer": "https://www.mlh.com/signin", "Origin": "https://www.mlh.com"}.items():
|
||||
req.add_header(k, v)
|
||||
try:
|
||||
resp = op.open(req, timeout=45); d0 = resp.read().decode(errors="replace")
|
||||
log("signin POST:", resp.status, resp.url[:90])
|
||||
if "error" in d0[:4000].lower():
|
||||
m = re.search(r'"errors":\s*({[^}]*})', d0)
|
||||
if m: log("signin errors:", m.group(1)[:200])
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, "signin_%s" % e.code
|
||||
link = wait_magic(tag)
|
||||
if not link: return None, "no_magic"
|
||||
r = op.open(link, timeout=60); d = r.read().decode(errors="replace")
|
||||
signed = '"isSignedIn":true' in d
|
||||
log("magic:", r.status, "signed:", signed)
|
||||
if not signed: return None, "not_signed"
|
||||
return ck_str(cj), None
|
||||
|
||||
def hf_token(cookies):
|
||||
"""OAuth code -> hacktoberfest API token."""
|
||||
cj = jar_from(cookies)
|
||||
op = urllib.request.build_opener(NoRedirect, urllib.request.HTTPCookieProcessor(cj))
|
||||
op.addheaders = [("User-Agent", UA), ("Accept", "text/html,application/xhtml+xml")]
|
||||
url = API + "/oauth/mlh"
|
||||
code = None
|
||||
for step in range(12):
|
||||
try:
|
||||
r = op.open(urllib.request.Request(url), timeout=40)
|
||||
d = r.read().decode(errors="replace")
|
||||
# callback page may contain code in URL query
|
||||
q = urllib.parse.parse_qs(urllib.parse.urlsplit(r.url).query)
|
||||
if "code" in q: code = q["code"][0]
|
||||
log("step%d %s %s len=%d" % (step, r.status, r.url[:110], len(d)))
|
||||
if code: break
|
||||
# maybe consent page: look for authorize form / button
|
||||
m = re.search(r'name="csrf-token" content="([^"]+)"', d)
|
||||
ver = re.search(r'"version":"([a-f0-9]+)"', d)
|
||||
if "oauth" in r.url and m:
|
||||
# POST authorize approve (Inertia)
|
||||
body = json.dumps({}).encode()
|
||||
rq = urllib.request.Request(url, data=body, method="POST")
|
||||
for k, v in {"Content-Type": "application/json", "X-Inertia": "true",
|
||||
"X-Inertia-Version": ver.group(1) if ver else "",
|
||||
"X-CSRF-Token": m.group(1), "Origin": "https://www.mlh.com",
|
||||
"Referer": url, "Accept": "application/json, text/html"}.items():
|
||||
rq.add_header(k, v)
|
||||
try:
|
||||
rr = op.open(rq, timeout=40); rr.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
loc = e.headers.get("Location", "")
|
||||
log("consent POST:", e.code, loc[:150])
|
||||
if loc: url = urllib.parse.urljoin(url, loc); continue
|
||||
return None, "consent_%s" % e.code
|
||||
continue
|
||||
return None, "stuck_%s" % r.url[:80]
|
||||
except urllib.error.HTTPError as e:
|
||||
loc = e.headers.get("Location", "")
|
||||
log("step%d %s -> %s" % (step, e.code, loc[:150]))
|
||||
if not loc: return None, "http_%s" % e.code
|
||||
q = urllib.parse.parse_qs(urllib.parse.urlsplit(loc).query)
|
||||
if "code" in q: code = q["code"][0]; break
|
||||
url = urllib.parse.urljoin(url, loc)
|
||||
if not code: return None, "no_code"
|
||||
r = http_json(API + "/auth/token", {"code": code}, timeout=40)
|
||||
at = r.get("accessToken")
|
||||
if not at: return None, "no_token:%s" % json.dumps(r)[:150]
|
||||
return r, None
|
||||
|
||||
def api_get(path, token):
|
||||
req = urllib.request.Request(API + path, headers={"User-Agent": UA, "Accept": "application/json",
|
||||
"Authorization": "Bearer " + token,
|
||||
"Origin": "https://hacktoberfest.com",
|
||||
"Referer": "https://hacktoberfest.com/"})
|
||||
return json.loads(urllib.request.urlopen(req, timeout=40).read())
|
||||
|
||||
def api_post(path, payload, token):
|
||||
req = urllib.request.Request(API + path, data=json.dumps(payload).encode(), method="POST",
|
||||
headers={"User-Agent": UA, "Content-Type": "application/json",
|
||||
"Accept": "application/json", "Authorization": "Bearer " + token,
|
||||
"Origin": "https://hacktoberfest.com",
|
||||
"Referer": "https://hacktoberfest.com/my/promos/"})
|
||||
return json.loads(urllib.request.urlopen(req, timeout=40).read())
|
||||
|
||||
def main():
|
||||
idx = int(sys.argv[1]) if len(sys.argv) > 1 else 0
|
||||
do_claim = "--claim" in sys.argv
|
||||
rows = [json.loads(l) for l in open(CFG.data_file("mlh_farm_accounts.jsonl"), encoding="utf-8") if l.strip()]
|
||||
acc = rows[idx]
|
||||
log("ACC", idx, acc["email"])
|
||||
cookies, err = reauth(acc)
|
||||
if not cookies:
|
||||
log("REAUTH FAIL:", err); sys.exit(2)
|
||||
tok, err = hf_token(cookies)
|
||||
if not tok:
|
||||
log("HF TOKEN FAIL:", err)
|
||||
# save fresh mlh cookies anyway
|
||||
rec = {"email": acc["email"], "mlh_cookies": cookies, "hf_err": err}
|
||||
with open(OUT, "a", encoding="utf-8") as f: f.write(json.dumps(rec) + "\n")
|
||||
sys.exit(3)
|
||||
at = tok["accessToken"]
|
||||
log("HF TOKEN OK user:", json.dumps(tok.get("user", {}))[:200])
|
||||
offers = api_get("/api/me/offers", at)
|
||||
print(json.dumps(offers, indent=1)[:4000], flush=True)
|
||||
open(CFG.data_file("hf_offers_%d.json" % idx), "w", encoding="utf-8").write(json.dumps(offers, indent=1))
|
||||
rec = {"email": acc["email"], "mlh_cookies": cookies, "access_token": at,
|
||||
"refresh_token": tok.get("refreshToken"), "user": tok.get("user"), "ts": int(time.time()),
|
||||
"offers": offers}
|
||||
# claim links for promos whose requirements are met
|
||||
if isinstance(offers, list):
|
||||
for off in offers:
|
||||
promo = off.get("promo")
|
||||
if not promo: continue
|
||||
reqs = {r["kind"]: r.get("met") for r in promo.get("requirements", [])}
|
||||
name = off.get("company", {}).get("name")
|
||||
if all(v for v in reqs.values()) or not reqs:
|
||||
if do_claim:
|
||||
try:
|
||||
cl = api_post("/api/me/offers/claim-link", {"poolId": promo["poolId"], "eventId": promo["eventId"]}, at)
|
||||
log("CLAIM", name, "->", json.dumps(cl)[:300])
|
||||
rec.setdefault("claims", {})[name] = cl
|
||||
except urllib.error.HTTPError as e:
|
||||
log("CLAIM ERR", name, e.code, e.read().decode(errors="replace")[:200])
|
||||
else:
|
||||
log("SKIP", name, "reqs:", reqs)
|
||||
with open(OUT, "a", encoding="utf-8") as f: f.write(json.dumps(rec) + "\n")
|
||||
log("DONE")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user