HF-MLH Toolkit v2 — stdlib OAuth/claim pipeline, resumable JSONL bank, config.json setup

This commit is contained in:
aaronjaworski710
2026-10-18 09:24:36 +03:00
commit f53aaf285b
10 changed files with 1406 additions and 0 deletions
+12
View File
@@ -0,0 +1,12 @@
config.json
data/
_work/
__pycache__/
*.pyc
# legacy flat-file locations (pre-config versions wrote these next to the scripts)
hf_mlh_sessions.json
hf_hf_tokens.json
hf_claim_bank.jsonl
hf_promo_accounts.jsonl
mlh_farm_accounts.jsonl
captcha_keys_2captcha.json
+72
View File
@@ -0,0 +1,72 @@
# HF-MLH Toolkit
Raw-HTTP pipeline for MLH Hacktoberfest 2026 developer perks — no browser, no Selenium/Playwright for the claim flow. Pure `urllib` + Inertia.js protocol.
## Setup
```bash
cp config.example.json config.json # fill in IMAP_USER / IMAP_PASS
# or via env:
export IMAP_USER=you@gmail.com IMAP_PASS=<gmail app password>
export MAIL_ALIAS_BASE=you@gmail.com # base for +tag alias accounts
```
`config.json` is gitignored. Resolution order: env var → config.json → default.
All state lives under `./data/` (override with `TOOLKIT_DATA`); debug dumps under `./_work/`.
| File (under `data/`) | Purpose |
|---|---|
| `mlh_farm_accounts.jsonl` | input: one `{"email": ...}` per line |
| `hf_mlh_sessions.json` | MLH session cookies per email |
| `hf_hf_tokens.json` | Hacktoberfest API access/refresh tokens cache |
| `hf_claim_bank.jsonl` | results bank, resumable per email+sponsor |
## Scripts
1. **`hf_reauth2.py <tag_or_email> [wait_sec]`** — MLH re-auth via OTP: Turnstile (real-page solver) → `POST /signin` → `otpId` → 6-digit code from IMAP → `POST /signin/{otpId}/otp` → saves cookies to `hf_mlh_sessions.json`. (`hf_reauth.py` is the older magic-link variant.)
2. **`hf_refresh.py [email]`** — refresh cached HF API tokens via `POST /auth/refresh`. **No MLH auth, no browser, no email** — as long as a `refreshToken` is cached, this keeps the pipeline alive. Run before a claim wave. Exit 0 = at least one refreshed, 2 = all failed.
3. **`hf_raw_claim.py [start] [count]`** — full claim chain per account:
- `mlh_token` from sessions (else OTP reauth fallback, cookies are persisted back)
- OAuth: `GET hacktoberfest-api.mlh.com/oauth/mlh` → Inertia `authorize` POST on `www.mlh.com` → **409 + `x-inertia-location`** (lowercase header) = external code → callback 302 → **internal 64-hex code** → `POST /auth/token`
- `GET /api/me/offers` → per-sponsor `claim-link` → redeem page props (`token`, `redeemUrl`, `unmetClaimRequirements`) → Inertia POST redeem → `promoCode`
- Bank is resumable: claimed/blocked entries are skipped on re-run.
4. **`hf_promos.py <idx> [--claim]`** — legacy single-account variant (magic-link reauth + offers dump).
Typical wave:
```bash
python hf_refresh.py # revive all cached tokens
python hf_raw_claim.py 0 26 # claim everything unblocked for accounts 0..25
```
## Perks status (26 tested accounts)
| Sponsor | Value | Status |
|---|---|---|
| Backboard | $5 | auto-claimed 26/26 (redeem code on backboard.io) |
| Render | $50 | auto-claimed 26/26 (credits portal, claim by Nov 15) |
| .tech domain | 1 yr free | blocked: `verified_phone` + `github_oauth` |
| Thinking Machines (Tinker) | $10 | blocked: `verified_phone` + `github_oauth` |
| ElevenLabs / SpaceXAI | challenges | no promo pool — challenge-only offers |
The `verified_phone` gate is **not** bypassed by this toolkit — phone-gated perks stay `blocked` in the bank. Note: Thinking Machines credits are for **Tinker** (their open-weight hosting), not an Anthropic/Claude API.
## Key protocol findings
- The `authorize` POST answers **409 with `x-inertia-location`** (lowercase!) containing the external OAuth code — not an error, it's Inertia's external-redirect convention.
- The callback URL's code is **not** the token-exchange code: `GET .../oauth/mlh/callback?code=<ext>` → 302 `hacktoberfest.com/auth/callback?code=<internal 64-hex>`; only the internal code works on `POST /auth/token`.
- Seed **only** `mlh_token` into a fresh cookie jar — stale session cookies cause `422 transaction-invalid`.
- Stale `X-Inertia-Version` on any Inertia POST → bare 409 with no Location: re-GET the page first.
- OTP POST can return 409 **after** the code was consumed and the session signed — re-check `isSignedIn` before retrying.
- HF `accessToken` expires in ~days; `refreshToken` survives much longer — `hf_refresh.py` revives a whole farm without touching MLH.
## Requirements
- Python 3.11+, **stdlib only** (`urllib`, `imaplib`, `quopri`, `json`).
- A Gmail mailbox with an [app password](https://myaccount.google.com/apppasswords) (farm accounts are `+tag` aliases of it).
- Turnstile solving (reauth step only): local real-page solver on `127.0.0.1:8877` (`SIDECAR_URL`), optional 2captcha fallback (`TWO_CAPTCHA_KEY` or `data/captcha_keys_2captcha.json`). MLH's siteverify rejects plain headless tokens — `real_page: true` is mandatory.
## Farm notes
- MLH bans plus-tag alias farms in batches; pace waves and expect attrition.
- Bank records keyed by `(email, sponsor)` — safe to re-run any wave.
+9
View File
@@ -0,0 +1,9 @@
{
"IMAP_USER": "you@gmail.com",
"IMAP_PASS": "your-16-char-gmail-app-password",
"MAIL_ALIAS_BASE": "you@gmail.com",
"TWO_CAPTCHA_KEY": "",
"SIDECAR_URL": "http://127.0.0.1:8877",
"TOOLKIT_DATA": "",
"TOOLKIT_WORK": ""
}
+111
View File
@@ -0,0 +1,111 @@
# -*- coding: utf-8 -*-
"""Shared config for hf-mlh-toolkit.
Resolution order for every setting: environment variable > config.json (repo root,
gitignored) > built-in default. No secrets are stored in this repo.
Keys (env var name == config.json key):
IMAP_USER Gmail address used to read OTP / magic-link emails
IMAP_PASS Gmail app password (NOT the account password)
MAIL_ALIAS_BASE base email for +tag aliases (default: IMAP_USER)
TWO_CAPTCHA_KEY optional 2captcha fallback key for Turnstile
SIDECAR_URL local real-page Turnstile solver (default http://127.0.0.1:8877)
MLH_SITEKEY Turnstile sitekey (public value, safe default baked in)
TOOLKIT_DATA data dir (default <repo>/data) - banks, sessions, accounts
TOOLKIT_WORK work dir (default <repo>/_work) - debug dumps
HF_TOOLKIT_CONFIG path to config.json (default <repo>/config.json)
Data files (all under TOOLKIT_DATA):
mlh_farm_accounts.jsonl input: {"email": "..."} per line
hf_mlh_sessions.json MLH cookies per email (written by reauth scripts)
hf_hf_tokens.json HF OAuth tokens cache per email
hf_claim_bank.jsonl resumable claim results (email+sponsor keyed)
hf_promo_accounts.jsonl hf_promos.py output
captcha_keys_2captcha.json optional fallback key file
"""
import json
import os
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
_cfg = {}
_cfg_path = Path(os.environ.get("HF_TOOLKIT_CONFIG", str(ROOT / "config.json")))
if _cfg_path.exists():
try:
_cfg = json.loads(_cfg_path.read_text(encoding="utf-8"))
except Exception as e:
print("hf_config: config.json parse error:", e, file=sys.stderr)
def get(key, default=None):
"""env > config.json > default. Empty strings count as unset."""
v = os.environ.get(key)
if v is None or v == "":
v = _cfg.get(key)
if v is None or v == "":
return default
return v
DATA = Path(get("TOOLKIT_DATA", str(ROOT / "data")))
WORK = Path(get("TOOLKIT_WORK", str(ROOT / "_work")))
try:
DATA.mkdir(parents=True, exist_ok=True)
WORK.mkdir(parents=True, exist_ok=True)
except Exception:
pass
SIDECAR = get("SIDECAR_URL", "http://127.0.0.1:8877")
SITEKEY = get("MLH_SITEKEY", "0x4AAAAAAARi-8xgLgfKOXIb") # public sitekey
API = "https://hacktoberfest-api.mlh.com"
def imap_creds():
"""(user, app_password) or exit with a clear message."""
user = get("IMAP_USER")
pw = get("IMAP_PASS")
if not user or not pw:
sys.exit("hf_config ERROR: IMAP_USER / IMAP_PASS not set.\n"
" export IMAP_USER=you@gmail.com IMAP_PASS=<16-char app password>\n"
" or copy config.example.json -> config.json and fill it in.\n"
" Needed to read MLH OTP / magic-link emails.")
return user, pw
def alias_base():
return get("MAIL_ALIAS_BASE") or get("IMAP_USER") or ""
def alias_email(tag):
"""user+tag@domain from MAIL_ALIAS_BASE (falls back to IMAP_USER)."""
base = alias_base()
if not base or "@" not in base:
sys.exit("hf_config ERROR: MAIL_ALIAS_BASE / IMAP_USER not set - "
"cannot build alias email for tag %r" % tag)
local, domain = base.split("@", 1)
return "%s+%s@%s" % (local, tag, domain)
def two_captcha_key():
"""2captcha key: env/config first, then data/captcha_keys_2captcha.json, else None."""
k = get("TWO_CAPTCHA_KEY")
if k:
return k
f = DATA / "captcha_keys_2captcha.json"
if f.exists():
try:
d = json.loads(f.read_text(encoding="utf-8"))
if isinstance(d, dict) and "keys" in d:
return d["keys"][0]["key"]
if isinstance(d, list) and d:
return d[0]
except Exception:
pass
return None
def data_file(name):
"""Absolute path string for a file under the data dir."""
return str(DATA / name)
+297
View File
@@ -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()
+320
View File
@@ -0,0 +1,320 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Hacktoberfest 2026 (MLH) raw-HTTP promo claim pipeline. No browser needed.
Flow per account (all raw urllib):
1. mlh_token from hf_mlh_sessions.json (else hf_reauth2.reauth via OTP email)
2. GET hacktoberfest-api.mlh.com/oauth/mlh -> Inertia authorize page (tid/state/scopes)
3. POST www.mlh.com/oauth/authorize (Inertia JSON) -> 409 + x-inertia-location (LOWERCASE hdr!) = ext code
4. GET api/oauth/mlh/callback?code=ext&state -> 302 Location hacktoberfest.com/auth/callback?code=INTERNAL(64hex)
5. POST api/auth/token {code: internal} -> accessToken/refreshToken
6. GET api/api/me/offers (Bearer) -> promos; POST api/api/me/offers/claim-link {poolId,eventId} -> claimLink
7. GET claimLink (www.mlh.com, mlh cookies) -> props {token, redeemUrl, unmetClaimRequirements, promoCode}
8. If unmet empty: Inertia POST www.mlh.com{redeemUrl} {token} -> promoCode in props (or follow x-inertia-location)
Bank: hf_claim_bank.jsonl (resumable per email+sponsor).
Usage: hf_raw_claim.py [start [count]]
"""
import json, re, html, sys, time, os, urllib.request, urllib.parse, urllib.error, http.cookiejar
BASE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, BASE)
import hf_config as CFG
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
UA = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36'
API = CFG.API
BANK = CFG.data_file('hf_claim_bank.jsonl')
SESS = CFG.data_file('hf_mlh_sessions.json')
ACCTS = CFG.data_file('mlh_farm_accounts.jsonl')
TOKENS = CFG.data_file('hf_hf_tokens.json') # email -> HF tokens cache
def log(*a):
print(time.strftime('%H:%M:%S'), *a, flush=True)
def hdr(hdrs, name):
for k, v in hdrs.items():
if k.lower() == name.lower():
return v
return None
def parse_pg(h):
cands = re.findall(r'data-page="([^"]+)"', h) + \
re.findall(r'type="application/json">(.*?)</script>', h, re.S)
for c in cands:
try:
return json.loads(html.unescape(c))
except Exception:
pass
return None
class NoRedir(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *a, **k):
return None
def mkjar(mlh_token=None):
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
op.addheaders = [('User-Agent', UA)]
op3 = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj), NoRedir())
op3.addheaders = [('User-Agent', UA), ('Accept', 'text/html')]
if mlh_token:
cj.set_cookie(http.cookiejar.Cookie(0, 'mlh_token', mlh_token, None, False,
'.mlh.com', True, True, '/', True, True, None, False, None, None, {}))
return cj, op, op3
def inertia_post(op, cj, url, data, referer, version=None, extra_hdrs=None):
xsrf = [c.value for c in cj if c.name == 'XSRF-TOKEN']
rq = urllib.request.Request(url, data=json.dumps(data).encode(), method='POST')
rq.add_header('Content-Type', 'application/json')
rq.add_header('Accept', 'text/html, application/xhtml+xml')
rq.add_header('X-Inertia', 'true')
rq.add_header('X-Requested-With', 'XMLHttpRequest')
rq.add_header('Referer', referer)
if version:
rq.add_header('X-Inertia-Version', version)
if xsrf:
rq.add_header('X-XSRF-TOKEN', urllib.parse.unquote(xsrf[-1]))
for k, v in (extra_hdrs or {}).items():
rq.add_header(k, v)
try:
r = op.open(rq, timeout=60)
return r.status, r.geturl(), r.read().decode(errors='replace'), dict(r.headers)
except urllib.error.HTTPError as e:
b = e.read().decode(errors='replace') if e.fp else ''
return e.code, url, b, dict(e.headers or {})
def get_mlh_token(email):
try:
st = json.load(open(SESS, encoding='utf-8'))
except Exception:
return None
ent = st.get(email)
if not ent:
return None
ck = ent['cookies']
if isinstance(ck, dict):
return ck.get('mlh_token')
for kv in str(ck).split('; '):
if kv.startswith('mlh_token='):
return kv.split('=', 1)[1]
return None
def hf_oauth(op, op3, cj):
"""returns (tokens dict, err)"""
r = op.open(API + '/oauth/mlh', timeout=60)
h = r.read().decode(errors='replace')
pg = parse_pg(h)
if not pg or 'authorizationTransactionId' not in pg.get('props', {}):
return None, 'no authorize page'
pr = pg['props']
sd = pr.get('scopesDetail') or []
body = {'redirect_uri': pr.get('redirectUri'), 'response_type': 'code',
'scope': ' '.join(s['id'] for s in sd), 'state': pr.get('state', ''),
'authorization_transaction_id': pr['authorizationTransactionId'],
'consented_scopes': [s['id'] for s in sd if s.get('consented')],
'auth_token': ''}
code, u2, resp, hdrs = inertia_post(op, cj, 'https://www.mlh.com/oauth/authorize',
body, 'https://www.mlh.com/oauth/authorize')
cb = hdr(hdrs, 'X-Inertia-Location')
if not cb:
m = re.search(r'"error_description":"(.*?)"', resp)
return None, 'authorize %s %s' % (code, m.group(1) if m else resp[:120])
q = urllib.parse.urlparse(cb)
qs = urllib.parse.parse_qs(q.query)
if not qs.get('code'):
return None, 'no code in cb: %s' % cb[:120]
ext, state = qs['code'][0], qs.get('state', [''])[0]
apicb = API + '/oauth/mlh/callback?' + urllib.parse.urlencode({'code': ext, 'state': state})
internal = None
try:
r3 = op3.open(apicb, timeout=60)
loc = r3.headers.get('Location')
except urllib.error.HTTPError as e:
loc = e.headers.get('Location')
if loc:
lq = urllib.parse.parse_qs(urllib.parse.urlparse(loc).query)
internal = (lq.get('code') or [None])[0]
if not internal:
return None, 'no internal code (loc=%s)' % (loc or '')[:100]
rq = urllib.request.Request(API + '/auth/token', data=json.dumps({'code': internal}).encode(), method='POST')
rq.add_header('Content-Type', 'application/json')
rq.add_header('Origin', 'https://hacktoberfest.com')
rq.add_header('Referer', 'https://hacktoberfest.com/')
try:
rr = op.open(rq, timeout=60)
return json.loads(rr.read().decode()), None
except urllib.error.HTTPError as e:
return None, 'token exchange %s %s' % (e.code, e.read().decode()[:150])
def api_get(op, tok, path, data=None):
rq = urllib.request.Request(API + path, data=json.dumps(data).encode() if data else None,
method='POST' if data else 'GET')
rq.add_header('Content-Type', 'application/json')
rq.add_header('Authorization', 'Bearer ' + tok)
try:
r = op.open(rq, timeout=60)
return r.status, json.loads(r.read().decode())
except urllib.error.HTTPError as e:
return e.code, e.read().decode(errors='replace')[:250]
def promo_ids(o):
"""extract poolId/eventId from offer struct (varies)"""
out = {}
def walk(x):
if isinstance(x, dict):
for k, v in x.items():
if k == 'poolId' and isinstance(v, str):
out['poolId'] = v
elif k == 'eventId' and isinstance(v, (str, int)) and 'eventId' not in out:
out['eventId'] = v
walk(v)
elif isinstance(x, list):
for i in x:
walk(i)
walk(o)
return out
def load_bank():
done = {}
if os.path.exists(BANK):
for ln in open(BANK, encoding='utf-8'):
try:
r = json.loads(ln)
if r.get('status') in ('claimed', 'blocked'):
done[(r['email'], r['sponsor'])] = r
except Exception:
pass
return done
def bank(rec):
with open(BANK, 'a', encoding='utf-8') as f:
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
log(' BANK:', rec.get('sponsor'), rec.get('status'),
rec.get('promoCode') or rec.get('unmet') or str(rec.get('err', ''))[:80])
def redeem(op, cj, claim_url):
r = op.open(claim_url, timeout=60)
h = r.read().decode(errors='replace')
pg = parse_pg(h)
if not pg:
return {'status': 'parse_fail'}
pr = pg['props']
tok = pr.get('token')
redeem_url = pr.get('redeemUrl')
unmet = pr.get('unmetClaimRequirements') or []
if pr.get('promoCode'):
return {'status': 'claimed', 'promoCode': pr['promoCode']}
if unmet:
return {'status': 'blocked',
'unmet': [u.get('kind') if isinstance(u, dict) else u for u in unmet]}
if not (tok and redeem_url):
return {'status': 'no_token', 'keys': list(pr.keys())[:12]}
full = 'https://www.mlh.com' + redeem_url
code, u2, resp, hdrs = inertia_post(op, cj, full, {'token': tok}, full, version=pg['version'])
loc = hdr(hdrs, 'X-Inertia-Location')
if loc:
r2 = op.open(urllib.parse.urljoin(full, loc), timeout=60)
resp = r2.read().decode(errors='replace')
m = re.search(r'"promoCode":"([^"]+)"', resp)
if m:
return {'status': 'claimed', 'promoCode': m.group(1)}
try:
j = json.loads(resp) if resp.strip().startswith('{') else parse_pg(resp)
pr2 = (j or {}).get('props', {})
if pr2.get('promoCode'):
return {'status': 'claimed', 'promoCode': pr2['promoCode']}
u2m = pr2.get('unmetClaimRequirements') or []
if u2m:
return {'status': 'blocked', 'unmet': [u.get('kind') if isinstance(u, dict) else u for u in u2m]}
except Exception:
pass
return {'status': 'redeem_unclear', 'http': code, 'head': resp[:150]}
SLUG_KWS = ('backboard', 'render', 'getdottech', 'dottech', 'thinkingmachines',
'thinking-machines', 'tinker', 'eyntk', 'digitalocean', 'namecheap', 'balsamiq')
def save_mlh_token(email, cookies):
"""Persist fresh cookies into SESS so get_mlh_token() finds them next run."""
try:
st = json.load(open(SESS, encoding='utf-8'))
except Exception:
st = {}
st[email] = {'cookies': cookies, 'signed': True, 'ts': int(time.time()), 'status': 'ok'}
json.dump(st, open(SESS, 'w', encoding='utf-8'), indent=1)
def process(email):
mlh_tok = get_mlh_token(email)
if not mlh_tok:
log(' reauth OTP...')
import hf_reauth2
try:
cookies, err = hf_reauth2.reauth(email)
if cookies:
save_mlh_token(email, cookies)
else:
log(' reauth fail:', err)
except Exception as e:
log(' reauth exc:', str(e)[:100])
mlh_tok = get_mlh_token(email)
if not mlh_tok:
bank({'email': email, 'sponsor': '*', 'status': 'reauth_fail'})
return
cj, op, op3 = mkjar(mlh_tok)
toks, err = hf_oauth(op, op3, cj)
if not toks:
bank({'email': email, 'sponsor': '*', 'status': 'oauth_fail', 'err': err})
return
log(' HF tokens OK:', toks.get('user', {}).get('email'))
cache = {}
if os.path.exists(TOKENS):
try:
cache = json.load(open(TOKENS, encoding='utf-8'))
except Exception:
cache = {}
cache[email] = toks
json.dump(cache, open(TOKENS, 'w', encoding='utf-8'))
s, offers = api_get(op, toks['accessToken'], '/api/me/offers')
if not isinstance(offers, list):
bank({'email': email, 'sponsor': '*', 'status': 'offers_fail', 'err': '%s %s' % (s, str(offers)[:100])})
return
log(' offers:', len(offers))
done = load_bank()
for o in offers:
ids = promo_ids(o)
blob = json.dumps(o).lower()
slug = next((kw for kw in SLUG_KWS if kw in blob), None) or ('pool_' + (ids.get('poolId') or 'x')[:8])
if (email, slug) in done:
log(' skip (banked):', slug)
continue
pool, ev = ids.get('poolId'), ids.get('eventId')
if not pool:
bank({'email': email, 'sponsor': slug, 'status': 'no_pool'})
continue
payload = {'poolId': pool}
if ev:
payload['eventId'] = ev
s2, cl = api_get(op, toks['accessToken'], '/api/me/offers/claim-link', payload)
link = None
if isinstance(cl, dict):
link = cl.get('claimLink') or cl.get('claim_link') or cl.get('url')
if not link:
bank({'email': email, 'sponsor': slug, 'status': 'claimlink_fail', 'err': '%s %s' % (s2, str(cl)[:120])})
continue
res = redeem(op, cj, link)
bank({'email': email, 'sponsor': slug, 'poolId': pool, **res})
time.sleep(2)
def main():
start = int(sys.argv[1]) if len(sys.argv) > 1 else 0
count = int(sys.argv[2]) if len(sys.argv) > 2 else 2
rows = [json.loads(l) for l in open(ACCTS, encoding='utf-8') if l.strip()]
log('accounts total:', len(rows), '| processing', start, '..', start + count - 1)
for i, acc in enumerate(rows[start:start + count], start):
log('ACC', i, acc['email'])
try:
process(acc['email'])
except Exception as e:
bank({'email': acc['email'], 'sponsor': '*', 'status': 'exc', 'err': str(e)[:200]})
log('DONE')
if __name__ == '__main__':
main()
+245
View File
@@ -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&quot;: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()
+245
View File
@@ -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")
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()
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)])")
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&quot;: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()
+92
View File
@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
"""Refresh cached Hacktoberfest API tokens WITHOUT touching MLH at all.
hf_raw_claim.py stores {email: {accessToken, refreshToken, user, ...}} in
hf_hf_tokens.json. The refreshToken outlives the accessToken, so a whole
claim wave can run browser-free and OTP-free as long as refresh works.
Usage:
python hf_refresh.py # refresh every cached token, rewrite the cache
python hf_refresh.py <email> # refresh one account
Exit code 0 if at least one token refreshed (or cache empty), 2 if all failed.
"""
import json
import sys
import time
import urllib.error
import urllib.request
sys.path.insert(0, __import__("os").path.dirname(__import__("os").path.abspath(__file__)))
import hf_config as CFG
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"
def log(*a):
print(time.strftime("%H:%M:%S"), *a, flush=True)
def load_cache():
try:
return json.load(open(CFG.data_file("hf_hf_tokens.json"), encoding="utf-8"))
except Exception:
return {}
def save_cache(cache):
json.dump(cache, open(CFG.data_file("hf_hf_tokens.json"), "w", encoding="utf-8"), indent=1)
def refresh(refresh_token):
"""POST /auth/refresh -> new token dict, or (None, err)."""
body = json.dumps({"refreshToken": refresh_token}).encode()
rq = urllib.request.Request(CFG.API + "/auth/refresh", data=body, method="POST")
rq.add_header("Content-Type", "application/json")
rq.add_header("User-Agent", UA)
rq.add_header("Origin", "https://hacktoberfest.com")
rq.add_header("Referer", "https://hacktoberfest.com/")
try:
r = urllib.request.urlopen(rq, timeout=45)
return json.loads(r.read().decode()), None
except urllib.error.HTTPError as e:
return None, "http_%s %s" % (e.code, e.read().decode(errors="replace")[:120])
except Exception as e:
return None, str(e)[:120]
def main():
only = sys.argv[1] if len(sys.argv) > 1 else None
cache = load_cache()
if not cache:
log("cache empty (%s) - run hf_raw_claim.py first" % CFG.data_file("hf_hf_tokens.json"))
return
ok = fail = 0
for email, ent in list(cache.items()):
if only and email != only:
continue
rt = (ent or {}).get("refreshToken")
if not rt:
log(email, "no refreshToken cached - skip")
fail += 1
continue
new, err = refresh(rt)
if new and new.get("accessToken"):
merged = dict(ent)
merged.update(new)
merged["refreshed_ts"] = int(time.time())
cache[email] = merged
ok += 1
log(email, "REFRESH OK")
else:
fail += 1
log(email, "REFRESH FAIL:", err)
time.sleep(1)
save_cache(cache)
log("done ok=%d fail=%d" % (ok, fail))
if only or ok == 0:
sys.exit(0 if ok else 2)
if __name__ == "__main__":
main()
+3
View File
@@ -0,0 +1,3 @@
# hf-mlh-toolkit — stdlib only (urllib/imaplib/quopri/json). No pip deps required.
# Optional: a local real-page Turnstile solver on 127.0.0.1:8877 (reauth step only)
# and/or a 2captcha key (TWO_CAPTCHA_KEY) as fallback.