#!/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">(.*?)', 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()