"""Core helpers for the GitHub Education (Student Developer Pack) application flow. Everything here was derived from a live account: the form is a React modal that POSTs to /settings/education/developer_pack_applications. Required gates are in the hidden fields of that form (see GATES.md). """ import json import os import time from playwright.sync_api import sync_playwright import pyotp CHROME_CANDIDATES = [ r"C:\Program Files\Google\Chrome\Application\chrome.exe", r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe", os.path.expandvars(r"%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe"), ] BENEFITS = "https://github.com/settings/education/benefits" def chrome_path(): for p in CHROME_CANDIDATES: if os.path.exists(p): return p raise RuntimeError("Chrome not found; install Chrome or pass executable_path") def load_accounts(path): """Accepts .jsonl or .json with login/password/totp records.""" if path.endswith(".jsonl"): rows = [json.loads(l) for l in open(path, encoding="utf-8") if l.strip()] else: rows = json.load(open(path, encoding="utf-8")) return {r["login"]: r for r in rows if r.get("login")} def launch(profile_dir, geo=None, headless=False, extra_args=None): args = ["--disable-blink-features=AutomationControlled"] args += extra_args or [] kw = dict(user_data_dir=profile_dir, executable_path=chrome_path(), headless=headless, args=args, viewport={"width": 1300, "height": 950}, locale="en-US") if geo: kw["geolocation"] = {"latitude": geo[0], "longitude": geo[1]} kw["permissions"] = ["geolocation"] p = sync_playwright().start() ctx = p.chromium.launch_persistent_context(**kw) pg = ctx.pages[0] if ctx.pages else ctx.new_page() return p, ctx, pg def login(pg, acc, timeout=60000): """Logs in if the session is gone. Returns True when authenticated.""" pg.goto(BENEFITS, wait_until="domcontentloaded", timeout=timeout) time.sleep(2) if "/login" not in pg.url and not pg.query_selector("#login_field"): return True pg.goto("https://github.com/login", wait_until="domcontentloaded", timeout=timeout) time.sleep(1.5) pg.fill("#login_field", acc["login"]) pg.fill("#password", acc["password"]) pg.click("input[type=submit][name=commit]") pg.wait_for_load_state("domcontentloaded", timeout=timeout) time.sleep(2.5) if "two-factor" in pg.url or pg.query_selector("#app_totp"): secret = (acc.get("totp") or "").strip() if not secret: raise RuntimeError("2FA required but no totp secret for " + acc["login"]) pg.fill("#app_totp" if pg.query_selector("#app_totp") else "input[name=app_otp]", pyotp.TOTP(secret).now()) pg.keyboard.press("Enter") pg.wait_for_load_state("domcontentloaded", timeout=timeout) time.sleep(2.5) pg.goto(BENEFITS, wait_until="domcontentloaded", timeout=timeout) time.sleep(2) return "/login" not in pg.url def open_application(pg): """Opens the 'Education Benefits Application' modal. Raises AccountFlagged when the button is an : GitHub hides the application for flagged accounts and that anchor is the signature. """ marker = pg.evaluate("""() => { const els = [...document.querySelectorAll('a,button')] .filter(e => /start an application/i.test(e.innerText || '')); if (!els.length) return {found: false}; const e = els[0]; return {found: true, tag: e.tagName, href: e.getAttribute('href'), text: (e.innerText || '').trim()}; }""") if not marker.get("found"): raise RuntimeError("no 'Start an application' control (unexpected page state)") if marker["tag"] == "A" and marker.get("href") == "/pricing": raise AccountFlagged("button is - account is flagged for education") pg.evaluate("""() => { const e = [...document.querySelectorAll('button')] .find(x => /start an application/i.test(x.innerText || '')); e && e.click(); }""") time.sleep(5) if not pg.query_selector("dialog"): raise RuntimeError("application modal did not open") class AccountFlagged(RuntimeError): pass def set_role(pg, role="student"): pg.check(f"input[name='dev_pack_form[application_type]'][value={role}]") def share_location(pg): pg.evaluate("""() => { const b = [...document.querySelectorAll('button,a')] .find(e => /share location/i.test(e.innerText || '')); b && b.click(); }""") time.sleep(3) def select_school(pg, query, timeout=4.0): """School autocomplete only reacts to real keystrokes, not to value=... .""" pg.evaluate("""() => { const i = [...document.querySelectorAll("input[name='dev_pack_form[school_name]']")][0]; i.scrollIntoView(); i.focus(); i.value = ''; }""") pg.keyboard.press("Control+A") pg.keyboard.press("Backspace") pg.keyboard.type(query, delay=60) time.sleep(timeout) picked = pg.evaluate("""() => { const o = document.querySelector('[role=option]'); if (!o) return null; const t = o.innerText; o.click(); return t; }""") time.sleep(2) return picked def dump_flags(pg): """Hidden fields of the application form = the real gates.""" return pg.evaluate("""() => { const out = {}; document.querySelectorAll('dialog input[type=hidden], dialog select').forEach(e => { if (!e.name) return; out[e.name] = e.tagName === 'SELECT' ? [...e.options].map(o => o.value) : e.value; }); return out; }""") def parse_email_domains(raw): try: rows = json.loads(raw or "[]") except Exception: return [] return [{"domain": r[0], "required": bool(r[1]) if len(r) > 1 else None, "class": r[2] if len(r) > 2 else None, "status": r[3] if len(r) > 3 else None} for r in rows if r] def submit(pg): """Submits the form and returns the server verdict shown in the modal.""" pg.evaluate("""() => { const f = document.querySelector('dialog form'); f && f.requestSubmit(); }""") time.sleep(10) return pg.evaluate("""() => { const d = [...document.querySelectorAll('dialog')].filter(x => x.open); const err = [...document.querySelectorAll('.flash-error,.FormControl-inlineValidation,[role=alert]')] .map(e => e.innerText.trim()).filter(Boolean).slice(0, 4); return {dialogs: d.map(x => x.innerText.slice(0, 600)), errors: err}; }""")