From 363d95baacf469d5867486bc7a22dbf62813f9bf Mon Sep 17 00:00:00 2001 From: reform Date: Fri, 23 Oct 2026 20:03:58 +0300 Subject: [PATCH] recovered snapshot from suspended aaronjaworski710 (history unavailable) --- .gitignore | 10 +++ README.md | 68 +++++++++++++++++ creds.example.json | 6 ++ dashboard.py | 181 +++++++++++++++++++++++++++++++++++++++++++++ event_reg.py | 87 ++++++++++++++++++++++ mass_reg.py | 132 +++++++++++++++++++++++++++++++++ partner_claim.py | 87 ++++++++++++++++++++++ promo_watch.py | 84 +++++++++++++++++++++ requirements.txt | 1 + 9 files changed, 656 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 creds.example.json create mode 100644 dashboard.py create mode 100644 event_reg.py create mode 100644 mass_reg.py create mode 100644 partner_claim.py create mode 100644 promo_watch.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..f6abea8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,10 @@ +creds.json +*.jsonl +cookies_*.txt +promo_state.json +promo_found.json +promo_email_*.html +redeem_page*.html +event_reg_result.html +__pycache__/ +*.pyc diff --git a/README.md b/README.md new file mode 100644 index 0000000..ee02191 --- /dev/null +++ b/README.md @@ -0,0 +1,68 @@ +# 🦀 MLH Promo Farm — Cursor Pro и партнёрская халява + +👻 Канал: [t.me/AlStack](https://t.me/AlStack) + +Тулкит для MLH Global Hack Week (9–15 октября): массовая регистрация аккаунтов MLH, чекин на ивент GHW: Hacktoberfest и вотчер почты на промо-коды (Cursor Pro и другие партнёрские офферы). + +## Запуск (3 шага) + +1. Скачать репо (Code → Download ZIP) и распаковать +2. `python dashboard.py` → откроется http://localhost:8000 +3. Вставить креды в дашборде: Gmail + app password, ключ 2captcha → Сохранить → запускать задачи кнопками + +Python 3.10+, **ноль pip-зависимостей** (только stdlib). Все данные хранятся локально: `creds.json` никуда не отправляется, кроме Gmail/2captcha/MLH напрямую. + +## Как работает промо + +- На [странице челленджей GHW](https://mlh.com/events/global-hack-week-open-source-90/challenges) есть челлендж «Sign up for a Cursor Pro Account» +- Промо-код приходит **письмом от команды MLH** после чекина на ивент (активируется в Billings & Invoices Cursor) +- ⚠️ Рассылка ручная: код приходит не сразу после чекина. По нашим наблюдениям MLH может ждать сабмишн челленджа (скрин дашборда Cursor с Pro) +- Дедлайн ивента: 15.10, 17:00 UTC + +## Состав + +| Файл | Назначение | +|------|-----------| +| `dashboard.py` | Веб-UI: креды, запуск задач, живой лог, скачивание результатов | +| `mass_reg.py` | Масс-рег MLH-аккаунтов на Gmail-алиасы `+mlhXXXXX` (Turnstile через 2captcha, логин через magic-link из IMAP) | +| `event_reg.py` | Регистрация аккаунта на ивент GHW + чекин (Rails-форма на events.mlh.com) | +| `promo_watch.py` | Скан почтового ящика: алертит на новые промо-письма (Cursor / партнёры). Для cron | +| `partner_claim.py` | Проход по ссылке «Claim your promo code» из письма: проверка `claimRequirements` и POST redeem | + +## CLI (без дашборда) + +```bash +cp creds.example.json creds.json # заполнить imap_user, imap_pass, twocaptcha_key + +python mass_reg.py 5 # зарегать 5 аккаунтов → mlh_farm_accounts.jsonl +python event_reg.py +python promo_watch.py # один скан почты (cron-friendly) +python partner_claim.py +``` + +Cron для вотчера: + +``` +*/20 * * * * cd /path/to/toolkit && python promo_watch.py >> watch.log 2>&1 +``` + +Состояние (id просмотренных писем) — в `promo_state.json`; найденные письма дамбятся в `promo_email_.html`, хиты — в `promo_found.json`. + +## Технически + +- MLH на **Inertia.js**: прямые POST требуют `X-Inertia`, `X-Inertia-Version` (свежий со страницы), `X-CSRF-Token`; устаревшая версия = `409` +- Signup-форма реально POSTит на `/signin`, не `/signup` +- Turnstile sitekey `0x4AAAAAAARi-8xgLgfKOXIb` (публичный, из JS-бандла); токен одноразовый +- Письмо «Verify Your Identity» содержит OTP **и magic link** (`transactional.mlh.io`) — magic link в том же opener'е надёжнее; голый OTP-POST молча отбивается (302/409) +- Gmail IMAP: искать `ALL`, а не `UNSEEN` (предыдущие fetch'и помечают письма прочитанными); тег алиаса матчить в lowercase в заголовке `To` +- Партнёрский redeem (Inertia): `POST {redeemUrl}` с JSON `{"token": <из props страницы>}`, кнопка `data-testid="claim-promo-code-button"` +- `verified_phone`: SMS через Twilio, бесплатные виртуальные номера часто не получают (A2P-фильтрация). Платные SMS-сервисы работают +- Проверено: 6 из 6 аккаунтов прошли путь рег → онбординг → чекин «checked in successfully» за один прогон + +## Дисклеймер + +Только для образовательных целей. Автоматизация регистрации может нарушать ToS MLH — используйте на свой риск. + +--- + +👻 [**иишко**](https://t.me/AlStack) — халява, тулкиты, AI-абузы diff --git a/creds.example.json b/creds.example.json new file mode 100644 index 0000000..38b8197 --- /dev/null +++ b/creds.example.json @@ -0,0 +1,6 @@ +{ + "imap_user": "yourmailbox@gmail.com", + "imap_pass": "gmail-app-password", + "twocaptcha_key": "your-2captcha-api-key", + "mlh_sitekey": "0x4AAAAAAARi-8xgLgfKOXIb" +} diff --git a/dashboard.py b/dashboard.py new file mode 100644 index 0000000..9be163c --- /dev/null +++ b/dashboard.py @@ -0,0 +1,181 @@ +# -*- coding: utf-8 -*- +"""MLH Promo Farm — dashboard (stdlib only, Python 3.10+). +Запуск: python dashboard.py → http://localhost:8000 +Все данные локально: creds.json, tasks/*.log +👻 https://t.me/AlStack +""" +import json, os, sys, subprocess, threading, glob, urllib.parse +from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler + +BASE = os.path.dirname(os.path.abspath(__file__)) +os.chdir(BASE) +CREDS = "creds.json" +os.makedirs("tasks", exist_ok=True) +SCRIPTS = {"reg": "mass_reg.py", "event": "event_reg.py", "watch": "promo_watch.py", "claim": "partner_claim.py"} +SITEKEY = "0x4AAAAAAARi-8xgLgfKOXIb" +_tasks, _lock = {}, threading.Lock() +_next = [1] + +PAGE = """MLH Promo Farm + +

🦀 MLH Promo Farm — Cursor Pro и партнёрская халява

+
+

1. Креды (Gmail + 2captcha)

+
+ + + + +
Gmail app password: Google Account → Security → 2-Step Verification → App passwords. Аккаунты регятся на алиасы yourmail+mlhXXXXX@gmail.com.
+

2. Задачи

+
Масс-регmass_reg.py → mlh_farm_accounts.jsonl
+
Рег на ивентevent_reg.py
+
Скан почтыpromo_watch.py (одноразово; для cron — CLI)
+
Клейм промоpartner_claim.py
+

3. Лог

+
—
+

4. Файлы

+
+
👻 иишко — больше халявы и тулкитов · только для образовательных целей
+""" + +def run_task(tid, script, args): + logf = os.path.join("tasks", str(tid) + ".log") + with open(logf, "w", encoding="utf-8") as lf: + p = subprocess.Popen([sys.executable, script] + args, stdout=lf, stderr=subprocess.STDOUT) + with _lock: + _tasks[tid]["pid"] = p.pid + rc = p.wait() + with _lock: + _tasks[tid]["running"] = False + _tasks[tid]["rc"] = rc + +class H(BaseHTTPRequestHandler): + def log_message(self, *a): pass + def _send(self, code, body, ctype="application/json; charset=utf-8"): + b = body.encode("utf-8") if isinstance(body, str) else body + self.send_response(code) + self.send_header("Content-Type", ctype) + self.send_header("Content-Length", str(len(b))) + self.end_headers() + self.wfile.write(b) + def _body(self): + n = int(self.headers.get("Content-Length", 0)) + return json.loads(self.rfile.read(n) or b"{}") + def do_GET(self): + u = urllib.parse.urlparse(self.path) + if u.path == "/": + return self._send(200, PAGE, "text/html; charset=utf-8") + if u.path == "/api/state": + with _lock: + tasks = [{"id": t["id"], "cmd": t["cmd"], "running": t["running"], "rc": t.get("rc")} for t in _tasks.values()] + tasks.sort(key=lambda x: -x["id"]) + files = sorted(glob.glob("*.jsonl") + glob.glob("promo_*.json") + glob.glob("promo_email_*.html")) + creds_ok, imap_user = os.path.exists(CREDS), "" + if creds_ok: + try: + imap_user = json.load(open(CREDS, encoding="utf-8")).get("imap_user", "") + except Exception: + creds_ok = False + return self._send(200, json.dumps({"creds_ok": creds_ok, "imap_user": imap_user, "tasks": tasks, "files": files})) + if u.path == "/api/log": + tid = int(urllib.parse.parse_qs(u.query).get("id", [0])[0]) + with _lock: + t = _tasks.get(tid) + if not t: + return self._send(404, '{"error":"no task"}') + try: + log = open(os.path.join("tasks", str(tid) + ".log"), encoding="utf-8", errors="replace").read()[-20000:] + except OSError: + log = "" + return self._send(200, json.dumps({"log": log, "running": t["running"], "rc": t.get("rc")})) + if u.path.startswith("/dl/"): + name = os.path.basename(urllib.parse.unquote(u.path[4:])) + fp = os.path.join(BASE, name) + if os.path.isfile(fp) and name != CREDS: + return self._send(200, open(fp, "rb").read(), "application/octet-stream") + return self._send(404, "not found", "text/plain") + return self._send(404, '{"error":"404"}') + def do_POST(self): + u = urllib.parse.urlparse(self.path) + if u.path == "/api/creds": + d = self._body() + cfg = {"imap_user": d.get("imap_user", ""), "imap_pass": d.get("imap_pass", ""), + "twocaptcha_key": d.get("twocaptcha_key", ""), "mlh_sitekey": SITEKEY} + if not cfg["imap_user"] or not cfg["imap_pass"]: + return self._send(400, '{"error":"imap_user/imap_pass required"}') + json.dump(cfg, open(CREDS, "w", encoding="utf-8"), ensure_ascii=False, indent=1) + return self._send(200, '{"ok":true}') + if u.path == "/api/run": + d = self._body() + kind = d.get("kind") + args = [str(a) for a in d.get("args", []) if str(a).strip()] + if kind not in SCRIPTS: + return self._send(400, '{"error":"bad kind"}') + if not os.path.exists(CREDS): + return self._send(400, '{"error":"save creds first"}') + if kind == "reg" and not args: + args = ["5"] + if kind in ("event", "claim") and len(args) < 2: + return self._send(400, '{"error":"need 2 args"}') + with _lock: + tid = _next[0] + _next[0] += 1 + _tasks[tid] = {"id": tid, "cmd": SCRIPTS[kind] + " " + " ".join(args), "running": True, "rc": None} + threading.Thread(target=run_task, args=(tid, SCRIPTS[kind], args), daemon=True).start() + return self._send(200, json.dumps({"id": tid})) + return self._send(404, '{"error":"404"}') + +if __name__ == "__main__": + srv = None + PORT = 8000 + for port in range(8000, 8020): + try: + srv = ThreadingHTTPServer(("127.0.0.1", port), H) + PORT = port + break + except OSError: + continue + if srv is None: + print("no free port 8000-8019", flush=True) + sys.exit(1) + print("MLH Promo Farm dashboard: http://localhost:" + str(PORT), flush=True) + srv.serve_forever() diff --git a/event_reg.py b/event_reg.py new file mode 100644 index 0000000..1f5f4a8 --- /dev/null +++ b/event_reg.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +"""Register an MLH account for the GHW event (Rails form on events.mlh.com). +Prereq: account signed in (cookies file), MLH profile/internal-auth completed. +Usage: python event_reg.py [event-path] +Default event: /events/14553-global-hack-week-hacktoberfest +Retries on Heroku 503.""" +import json, http.client, re, ssl, urllib.parse, time, sys + +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36" +CKF = sys.argv[1] if len(sys.argv) > 1 else "cookies.txt" +GHU = sys.argv[2] if len(sys.argv) > 2 else "your-github-username" +EVENT = sys.argv[3] if len(sys.argv) > 3 else "/events/14553-global-hack-week-hacktoberfest" + +class Cli: + def __init__(self, ck, host): + self.ck = ck; self.host = host + self.ctx = ssl.create_default_context() + self.conn = http.client.HTTPSConnection(host, 443, context=self.ctx, timeout=60) + def _merge(self, r): + jar = {} + for p in self.ck.split("; "): + if "=" in p: + n, v = p.split("=", 1); jar[n] = v + for k, v in r.getheaders(): + if k.lower() == "set-cookie": + kv = v.split(";")[0] + if "=" in kv: + n, vv = kv.split("=", 1); jar[n] = vv + self.ck = "; ".join(f"{n}={v}" for n, v in jar.items()) + def req(self, method, path, body=None, extra=None): + hdrs = {"User-Agent": UA, "Accept": "text/html, application/xhtml+xml", "Cookie": self.ck} + if extra: hdrs.update(extra) + self.conn.request(method, path, body=body, headers=hdrs) + r = self.conn.getresponse() + data = r.read().decode(errors="replace") + self._merge(r) + return r.status, dict(r.headers), data + +for attempt in range(3): + C = Cli(open(CKF).read().strip(), "events.mlh.com") + st, h, d = C.req("GET", EVENT + "?intent=register") + i = d.find('id="new_participation"') + if i < 0: + print("NO FORM — account probably needs internal-auth first (profile steps). Status:", st, + "url-len:", len(d)); break + j = d.find("", i) + frag = d[i:j] + tok = re.search(r'name="authenticity_token" value="([^"]+)"', frag).group(1) + # question field names differ per event — auto-discover from the form fragment + Q = "participation[event_questions_form]" + form = {"authenticity_token": tok, "participation[status]": "completed", "commit": "Submit"} + for name in re.findall(r'name="(participation\[event_questions_form\]\[[^\"]+\])"', frag): + key = name.split("[")[-1].rstrip("]") + if "github" in key: form[name] = GHU + elif "country" in key: form[name] = "UA" + elif "region" in key: form[name] = "Europe (EU)" + elif "signup_source" in key: form[name] = "Email" + elif "opt" in key or "understand" in key: form[name] = "true" + else: form[name] = "1" # checkboxes/accepts + body = urllib.parse.urlencode(form) + st2, h2, d2 = C.req("POST", EVENT + "/registration", body, + {"Content-Type": "application/x-www-form-urlencoded", + "Referer": "https://events.mlh.com" + EVENT + "?intent=register", + "Origin": "https://events.mlh.com"}) + print(f"ATT{attempt} POST:", st2, "loc:", str(h2.get("Location", ""))[:160], flush=True) + if st2 != 503: + loc = h2.get("Location"); n = 0; cur = d2 + while loc and n < 5: + n += 1 + host = "events.mlh.com" if "events.mlh.com" in loc else "www.mlh.com" + if host != C.host: C = Cli(C.ck, host) + path = loc.replace("https://" + host, "") + st3, h3, cur = C.req("GET", path) + print(f"FLW{n}:", st3, path[:110], "len", len(cur), flush=True) + loc = h3.get("Location") + open("event_reg_result.html", "w", encoding="utf-8").write(cur) + txt = re.sub(r"<[^>]*>", "|", cur) + parts = [p.strip() for p in txt.split("|") if p.strip() and 4 < len(p.strip()) < 90] + seen = set() + for p in parts[:60]: + if any(k in p.lower() for k in ("regist", "check", "confirm", "complete", "thanks", + "cursor", "promo", "error", "you're", "success")) and p not in seen: + seen.add(p); print("T:", p, flush=True) + break + time.sleep(15) +open(CKF, "w").write(C.ck) +print("COOKIES:", len(C.ck), "host:", C.host, flush=True) diff --git a/mass_reg.py b/mass_reg.py new file mode 100644 index 0000000..3d9a393 --- /dev/null +++ b/mass_reg.py @@ -0,0 +1,132 @@ +# -*- coding: utf-8 -*- +"""MLH mass registration: signup + Turnstile (2captcha) + magic-link sign-in + onboarding name. +Usage: python mass_reg.py [N] +Output: mlh_farm_accounts.jsonl (email, name, cookies, signed) +Stdlib only, Python 3.11+.""" +import json, time, random, string, urllib.request, urllib.parse, urllib.error +import http.cookiejar, re, imaplib, email, sys + +N = int(sys.argv[1]) if len(sys.argv) > 1 else 5 +OUT = "mlh_farm_accounts.jsonl" +CFG = json.load(open("creds.json")) +IMAP_USER = CFG["imap_user"]; IMAP_PASS = CFG["imap_pass"] +KK = CFG["twocaptcha_key"]; SITEKEY = CFG.get("mlh_sitekey", "0x4AAAAAAARi-8xgLgfKOXIb") +ALIAS_BASE = IMAP_USER.split("@")[0] + +FIRST = ["Alex","Max","Dan","Nick","Sam","Leo","Ivan","Mark","Paul","Victor","Oleg","Roman","Egor","Timur","Kirill"] +LAST = ["Orlov","Kovalov","Smirnov","Petrov","Ivanov","Novak","Shevchenko","Morozov","Volkov","Lebedev","Sokolov","Popov","Ermakov","Zaitsev","Golubev"] +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 api(url, data): + req = urllib.request.Request(url, data=urllib.parse.urlencode(data).encode()) + return json.loads(urllib.request.urlopen(req, timeout=30).read()) + +def solve(action="authentication"): + 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: 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: return rr["request"] + if rr.get("request") != "CAPCHA_NOT_READY": return None + return None + +def wait_magic(tag, timeout=300): + """Poll Gmail for the 'Verify Your Identity' email addressed to the alias; return magic link.""" + 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") + typ, data = M.search(None, "ALL") + for i in reversed(data[0].split()[-25:]): + typ, hd = M.fetch(i, "(BODY.PEEK[HEADER.FIELDS (TO SUBJECT)])") + hs = hd[0][1].decode(errors="replace").lower() + if tag not in hs or "verify your identity" not in hs: continue + typ, full = M.fetch(i, "(BODY.PEEK[])") + msg = email.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]+)\s*\)', b2) + M.logout() + if lab: return lab[0] + except Exception as e: + log("imap err:", str(e)[:80]) + time.sleep(6) + return None + +def register_one(): + tag = "mlh" + "".join(random.choices(string.ascii_lowercase, k=2)) + str(random.randint(10000, 99999)) + addr = f"{ALIAS_BASE}+{tag}@gmail.com" + fn, ln = random.choice(FIRST), random.choice(LAST) + log("=== REG", addr) + cj = http.cookiejar.CookieJar() + opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) + opener.addheaders = [("User-Agent", UA)] + g = opener.open("https://www.mlh.com/signup", 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) + tok = solve() + if not tok: return {"email": addr, "err": "no_token"} + body = json.dumps({"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 {"Content-Type": "application/json", "Accept": "text/html,application/xhtml+xml", + "X-Inertia": "true", "X-Inertia-Version": ver, "X-CSRF-Token": csrf, + "Referer": "https://www.mlh.com/signup", "Origin": "https://www.mlh.com"}.items(): + req.add_header(k, v) + try: + resp = opener.open(req, timeout=45); resp.read() + log("step1:", resp.status, resp.url[:80]) + except urllib.error.HTTPError as e: + return {"email": addr, "err": "step1_%s" % e.code} + link = wait_magic(tag) + if not link: return {"email": addr, "err": "no_magic"} + r = opener.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 {"email": addr, "err": "not_signed", "cookies": "; ".join(f"{c.name}={c.value}" for c in cj)} + # onboarding: set name + try: + r2 = opener.open("https://www.mlh.com/account/onboarding", timeout=40) + d2 = r2.read().decode(errors="replace") + m = re.search(r']*type="application/json"[^>]*>(.*?)', d2, re.S) + pg = json.loads(m.group(1)) if m else {} + c2 = re.search(r'name="csrf-token" content="([^"]+)"', d2) + ob = json.dumps({"user": {"first_name": fn, "last_name": ln}}).encode() + rq = urllib.request.Request("https://www.mlh.com/account/onboarding", data=ob, method="POST") + for k, v in {"Content-Type": "application/json", "X-Inertia": "true", + "X-Inertia-Version": pg.get("version", ""), "X-CSRF-Token": c2.group(1) if c2 else "", + "X-Requested-With": "XMLHttpRequest", "Origin": "https://www.mlh.com", + "Referer": "https://www.mlh.com/account/onboarding", + "Accept": "application/json, text/html"}.items(): + rq.add_header(k, v) + try: + rr = opener.open(rq, timeout=40); log("onboard:", rr.status) + except urllib.error.HTTPError as e: + log("onboard err:", e.code) + except Exception as e: + log("onboard exc:", str(e)[:100]) + ck = "; ".join(f"{c.name}={c.value}" for c in cj) + open(f"cookies_{tag}.txt", "w").write(ck) + rec = {"email": addr, "name": fn + " " + ln, "cookies_file": f"cookies_{tag}.txt", + "ts": int(time.time()), "signed": True, "event_reg": False} + with open(OUT, "a", encoding="utf-8") as f: + f.write(json.dumps(rec) + "\n") + log("SAVED", addr) + return rec + +ok = 0 +for i in range(N): + try: + r = register_one() + if r.get("signed"): ok += 1 + else: log("FAIL:", json.dumps(r)[:200]) + except Exception as e: + log("EXC:", str(e)[:200]) + time.sleep(random.randint(20, 45)) +log("DONE ok=%d/%d" % (ok, N)) diff --git a/partner_claim.py b/partner_claim.py new file mode 100644 index 0000000..2875397 --- /dev/null +++ b/partner_claim.py @@ -0,0 +1,87 @@ +# -*- coding: utf-8 -*- +"""Follow a partner 'Claim your promo code' link, check claim requirements and redeem. +Usage: python partner_claim.py +Claim URL = the tracked link from the MLH partner-offers email. +Output: promo_claimed.json (promoCode), redeem_page.html dumps.""" +import json, re, sys, time, html as H, urllib.request, urllib.parse, urllib.error, http.cookiejar + +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36" +CKF, CLAIM = sys.argv[1], sys.argv[2] + +cj = http.cookiejar.CookieJar() +for p in open(CKF).read().strip().split("; "): + if "=" in p: + n, v = p.split("=", 1) + c = http.cookiejar.Cookie(0, n, v, None, False, ".mlh.com", True, False, + "/", True, False, None, False, None, None, {}) + cj.set_cookie(c) +opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj)) +opener.addheaders = [("User-Agent", UA)] + +def inertia_props(html): + m = re.search(r']*type="application/json"[^>]*>(.*?)', html, re.S) + if m: + try: return json.loads(m.group(1)) + except Exception: pass + md = re.search(r'data-page="([^"]+)"', html) + if md: + try: return json.loads(H.unescape(md.group(1))) + except Exception: pass + return {} + +r = opener.open(CLAIM, timeout=60) +d = r.read().decode(errors="replace") +print("final url:", r.geturl()[:200], "status:", r.status) +open("redeem_page.html", "w", encoding="utf-8").write(d) +pg = inertia_props(d) +props = pg.get("props", {}) +print("component:", pg.get("component")) +unmet = props.get("unmetClaimRequirements") or [] +reqs = props.get("claimRequirements") or [] +pc = props.get("promoCode") +rtok = props.get("token"); rurl = props.get("redeemUrl") +print("claimRequirements:", reqs) +print("unmet:", unmet) +print("already has promoCode:", bool(pc)) + +if pc: + json.dump({"promoCode": pc}, open("promo_claimed.json", "w")) + print("SAVED promo_claimed.json") + sys.exit(0) + +if unmet: + hints = {"verified_phone": "verify a phone number in account settings (Twilio SMS; free virtual pools often blocked)", + "github_oauth": "connect GitHub: GET /social_profiles/connect/github and complete OAuth", + "github_account_age": "GitHub account too young — connect an older one", + "checked_in": "register/check in to the GHW event"} + for u in unmet: + print("UNMET:", u, "->", hints.get(u, "?")) + sys.exit(1) + +if rtok and rurl: + full = "https://www.mlh.com" + rurl if rurl.startswith("/") else rurl + body = json.dumps({"token": rtok}).encode() + rq = urllib.request.Request(full, data=body, method="POST") + for k, v in {"Content-Type": "application/json", "X-Inertia": "true", + "X-Inertia-Version": pg.get("version", ""), "X-Requested-With": "XMLHttpRequest", + "Origin": "https://www.mlh.com", "Referer": r.geturl(), + "Accept": "application/json, text/html"}.items(): + rq.add_header(k, v) + try: + rr = opener.open(rq, timeout=60); rd = rr.read().decode(errors="replace") + print("claim POST:", rr.status) + except urllib.error.HTTPError as e: + rd = e.read().decode(errors="replace"); print("claim POST err:", e.code, rd[:200]) + time.sleep(2) + r2 = opener.open(r.geturl(), timeout=60) + d2 = r2.read().decode(errors="replace") + open("redeem_page2.html", "w", encoding="utf-8").write(d2) + p2 = inertia_props(d2).get("props", {}) + pc2 = p2.get("promoCode") + print("promoCode after claim:", bool(pc2)) + if pc2: + json.dump({"promoCode": pc2, "sponsor": (p2.get("sponsor") or {}).get("name", "")}, + open("promo_claimed.json", "w")) + print("SAVED promo_claimed.json") +else: + print("no token/redeemUrl in props — dump:", json.dumps(props)[:400]) diff --git a/promo_watch.py b/promo_watch.py new file mode 100644 index 0000000..9332f19 --- /dev/null +++ b/promo_watch.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +"""MLH promo mailbox watchdog: prints ONLY when a NEW relevant promo email is found. +Cron-friendly (every 20 min). State: promo_state.json; dumps: promo_email_.html, promo_found.json. +Stdlib only.""" +import imaplib, email, re, json, os, time +from email.header import decode_header + +CFG = json.load(open("creds.json")) +STATE = "promo_state.json" + +def hdecode(s): + if not s: return "" + try: + return "".join(p.decode(c or "utf-8", errors="replace") if isinstance(p, bytes) else str(p) + for p, c in decode_header(s)) + except Exception: + return str(s) + +def main(): + st = {"seen": []} + if os.path.exists(STATE): + try: st = json.load(open(STATE)) + except Exception: pass + seen = set(st.get("seen", [])) + M = imaplib.IMAP4_SSL("imap.gmail.com", timeout=60) + M.login(CFG["imap_user"], CFG["imap_pass"]) + M.select("INBOX") + typ, data = M.search(None, "ALL") + ids = data[0].split() + new_hits = [] + for i in reversed(ids[-40:]): + iid = i.decode() if isinstance(i, bytes) else str(i) + if iid in seen: continue + typ, hd = M.fetch(i, "(BODY.PEEK[HEADER.FIELDS (DATE FROM SUBJECT TO)])") + hs = hd[0][1] + hs = hs.decode(errors="replace") if isinstance(hs, bytes) else str(hs) + seen.add(iid) + blob = hs.lower() + hit = ("cursor" in blob) or ("promo" in blob) or ("x.ai" in blob) or ("redeem" in blob) + frm = any(k in blob for k in ("mlh", "cursor", "x.ai", "spacexai", "grok")) + if hit or frm: + typ2, md = M.fetch(i, "(BODY.PEEK[])") + raw = md[0][1] + msg = email.message_from_bytes(raw) + frmh = hdecode(msg.get("From", "")).lower() + subj = hdecode(msg.get("Subject", "")) + body = "" + for part in msg.walk(): + if part.get_content_type() in ("text/plain", "text/html"): + try: + pl = part.get_payload(decode=True) + body += pl.decode(errors="replace") if isinstance(pl, bytes) else str(pl) + except Exception: pass + low = (frmh + subj + body).lower() + relevant = (("cursor" in low and any(k in low for k in ("promo", "code", "pro ", "redeem"))) + or ("redeem" in low and "cursor" in low)) + if relevant and "verify your identity" not in subj.lower(): + txt = re.sub(r"<[^>]*>", " ", body); txt = re.sub(r"\s+", " ", txt) + codes = re.findall(r"\b[A-Z0-9]{4,8}-[A-Z0-9]{4,8}(?:-[A-Z0-9]{4,8})?\b", txt) + codes += re.findall(r"(?i)promo[^A-Za-z0-9]{0,15}([A-Za-z0-9_-]{6,32})", txt) + links = [l for l in set(re.findall(r"https?://[^\s\"<>'\\]+", body)) + if any(k in l.lower() for k in ("cursor", "promo", "redeem", "claim"))] + open("promo_email_%s.html" % iid, "w", encoding="utf-8").write(body[:500000]) + new_hits.append({"id": iid, "from": frmh[:80], "subject": subj[:120], + "codes": codes[:5], "links": links[:5], "snippet": txt[:600]}) + M.logout() + st["seen"] = list(seen)[-500:] + st["last_run"] = time.strftime("%Y-%m-%d %H:%M:%S") + json.dump(st, open(STATE, "w")) + if new_hits: + json.dump(new_hits, open("promo_found.json", "w"), ensure_ascii=False, indent=1) + out = ["PROMO EMAIL FOUND (%d):" % len(new_hits)] + for h2 in new_hits: + out.append("From: %s | Subj: %s" % (h2["from"], h2["subject"])) + if h2["codes"]: out.append("CODES: %s" % h2["codes"]) + if h2["links"]: out.append("LINKS: %s" % h2["links"][:2]) + out.append("SNIPPET: %s" % h2["snippet"][:400]) + print("\n".join(out).encode("ascii", "replace").decode()) + +if __name__ == "__main__": + try: + main() + except Exception as e: + print("WATCH ERR: %s" % str(e)[:150]) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..6213f35 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +# mlh-promo-farm — stdlib only (urllib/imaplib/http.server). No pip deps required.