diff --git a/README.md b/README.md index a72ea83..dea55d7 100644 --- a/README.md +++ b/README.md @@ -2,91 +2,98 @@ Mass auto-registration toolkit for **[treg.to](https://treg.to/)** — the "OpenRouter for agent tools" (3955 endpoints, 111 providers, one API key). -Each fresh account gets a **$1.00 signup grant** (~1600–2000 tool calls: X/Twitter posts at $0.0005, TikTok profiles at $0.001, web search free). Zero captcha — pure email OTP flow. +Each fresh account gets a **$1.00 signup grant** (~1600–2000 tool calls: X/Twitter posts at $0.0005, TikTok profiles at $0.001, web search free). + +**v3: the primary door is GitHub OAuth** (`gh_oauth_reg.py`). The old email+OTP door (`treg_farm.py`) still creates accounts but **no longer pays the grant** — see below. > Part of the free-tools series. More finds: [t.me/AlStack](https://t.me/AlStack) -## How it works (full protocol, reverse-engineered) +## Why GitHub OAuth (the email door is dead for grants) + +From the reversed backend: the email flow sets `promo_eligible = (turnstile_outcome == "PASS")`. Headless-obtained Turnstile tokens pass Cloudflare siteverify but are not classified `PASS` server-side, so email signups are created with `promo_eligible=False` → **$0**. + +The GitHub OAuth door provisions the user via `find_or_create_user(...)` with `promo_eligible` defaulting to **True** — no captcha in the loop at all → **$1 grant fires on org creation**. + +Observed hit rates: **69/69** on a pool with virgin inboxes, ~50–70% on mixed pools (see anti-fraud notes). + +## Protocol (GitHub OAuth door) ``` -POST /auth/email/start {"email": "you+treg1@gmail.com"} -> {"sent": true} - OTP: 6-digit code arrives in the email SUBJECT (sender treg.to) -POST /auth/email/verify {"email", "code"} -> {"token"} + Set-Cookie session -POST /orgs {"name": "myorg123"} [X-Treg-Token] -> org created, grant $1 (async ~2s) -GET /auth/cli-token [X-Treg-Org: myorg123, SESSION COOKIE] -> {"token": } <-- usable API key -GET /orgs/{id}/balance [X-Treg-Token: org_key] -> {"balance_micro": 1000000} +GET {base}/auth/github -> 302 github.com/login/oauth/authorize?client_id&state&redirect_uri + + Set-Cookie treg_oauth_state +GH password + TOTP login (pure HTTP, no browser) +GET -> code (direct 302 / meta-refresh page / consent POST authorize=1) +GET {base}/auth/github/callback?code&state [Cookie: treg_oauth_state] -> treg_session cookie +POST {base}/orgs {"name": "studioXXXX"} [session cookie] -> org_id + slug <-- $1 claim fires here +GET {base}/auth/cli-token [X-Treg-Org: slug, session cookie] -> {"token": } +GET {base}/orgs/{id}/balance [X-Treg-Token + X-Treg-Key-Protocol: 1] -> {"balance_micro": 1000000} ``` -All requests carry `X-Treg-Key-Protocol: 1`. +Auth notes: +- Balance/team endpoints require `X-Treg-Token: ` + `X-Treg-Key-Protocol: 1`. Plain `Authorization: Bearer` gets **401** on team resources. +- Tokens minted before the Oct-2026 scopes deploy are BOOTSTRAP-scoped → **403 "finish team setup first"** on every team endpoint (balance included). Fresh logins mint proper team tokens. -### Pitfalls this toolkit solves +## Anti-fraud notes (why some accounts get $0) -| Pitfall | Fix | -|---|---| -| `GET /auth/cli-token` returns **403** "a bootstrap token cannot mint a Default key" | Send the verify **session cookie only**, NO `X-Treg-Token` header on that request | -| Org names containing `treg` are rejected | Neutral random names (`keynest983`, `gothlab331`, ...) | -| Gmail IMAP `search` returns **stale** results | `m.noop()` before every search | -| Re-issued `start` invalidates the previous code | Filter mails by `Date >= since_ts - 30` | -| Render backend saturates (503 `treg_saturated: true`) | Exponential backoff retry on every call | -| IP budget: 30 OTP starts / 15 min | Pacing 10–22 s between accounts, auto-cool 900 s on 429 | -| Grant is per-**user**, once (DB-locked) | One Gmail `+alias` = one user = one $1 | +- `SignupPromoClaim` is **unique per normalized inbox**: `+tag` is stripped for every domain, dots are stripped for gmail. One grant per mailbox, forever. +- Retrying a $0 account with a second org does **not** pay again — the claim is already consumed. +- Gmail `+alias` / dot-alias farms are therefore dead for this promo. Only genuinely fresh inboxes pay (separate real mailboxes, e.g. independent GH accounts with unique emails). +- Flagged/suspended GitHub accounts bounce off `authorize` (redirect to `/dashboard` without a `code`) — the script reports it and moves on. ## Setup ```bash -# Python 3.10+, only dependency: requests -pip install requests +# Python 3.10+ +pip install pyotp requests -# 1. create config -cp config.example.json config.json -# 2. edit config.json: put your Gmail address + IMAP app password -# (Gmail: Security -> 2-Step Verification -> App passwords) +cp config.example.json config.json # optional; env overrides work too + +# GH pool: JSON array of accounts +# [{"login": "...", "password": "...", "totp": "", "email": "..."}] ``` -No secrets in the repo — `config.json` is gitignored. Env vars `TREG_IMAP_USER` / `TREG_IMAP_PASS` work too. +No secrets in the repo — `config.json`, pools, banks and state files are gitignored. ## Usage ```bash -# register accounts 1..30 (aliases you+treg1 ... you+treg30) -python treg_farm.py 1 30 +# register N accounts from the pool (resumable via gh_reg_state.json) +python gh_oauth_reg.py 25 -# re-login accounts that have an org but no pinned key (recovers 403-stuck accounts) -python treg_farm.py recover - -# live-check the bank: balances + pinned keys -python verify_bank.py +# env overrides +GH_POOL=/path/to/pool.json GH_STATE=my_state.json python gh_oauth_reg.py 50 ``` Output: -- `treg_accounts.jsonl` — the bank: `{email, token, org_token, org, org_id, balance_micro, ts}` -- `treg_farm_state.json` — resumable wave state (`registered` / `no_grant` / `failed`) +- `treg_gh_bank.jsonl` — the bank: `{ts, email, gh_login, org, org_id, token, balance_usd, via}` +- `gh_reg_state.json` — resumable pool index -Auto-stop: 4 consecutive accounts without grant. The wave is resumable — rerun with a new start index any time. +Pacing is built in (8–15 s/account, `pace` in config.json). ## Using the keys ```bash -# raw HTTP +# tool calls take Bearer: curl https://treg.to/call/treg.web.search \ -H "Authorization: Bearer ***" \ -H "Content-Type: application/json" \ -d '{"q": "hello world"}' +# team/balance endpoints take X-Treg-Token: +curl "https://treg.to/orgs//balance?limit=3" \ + -H "X-Treg-Token: ***" -H "X-Treg-Key-Protocol: 1" + # official CLI pip install "tools-registry[proxy]" treg login --token *** treg call treg.x.user.posts --data '{"username": "elonmusk", "limit": 3}' -treg balance ``` -Prices (live-verified): X user posts **$0.0005**, X search $0.00075, TikTok profile **$0.001**, web search **free** (19 providers), email verify free. Platform margin 0% — you pay provider cost. BYOK keys are unmetered. +Prices (live-verified): X user posts **$0.0005**, X search $0.00075, TikTok profile **$0.001**, web search **free** (19 providers), image gen ~$0.04, video gen ~$0.21. Platform margin 0% — you pay provider cost. BYOK keys are unmetered. -## Rate limits (from source) +## Legacy: email+OTP door (treg_farm.py / verify_bank.py) -- 30 OTP starts / 15 min / IP, 5 / email -- 1 signup grant per user (not per IP) — alias farming is the intended scale path -- Backend on Render: expect occasional 503 saturation windows +Kept for reference. Flow: `POST /auth/email/start` → 6-digit OTP in the mail SUBJECT → `/auth/email/verify` → org → cli-token. Still registers fine, but grants are **$0** since the Turnstile-PASS gate (Oct 2026). Pitfalls it solves (IMAP `noop()` staleness, session-cookie-only cli-token mint, org-name filter, IP budget 30 starts/15 min, per-user grant lock) are documented in its file header. ## Disclaimer diff --git a/gh_oauth_reg.py b/gh_oauth_reg.py new file mode 100644 index 0000000..68b6947 --- /dev/null +++ b/gh_oauth_reg.py @@ -0,0 +1,236 @@ +# -*- coding: utf-8 -*- +"""gh_oauth_reg — treg.to registration via the GitHub OAuth door. + +The email+OTP door no longer pays the signup grant (Turnstile outcome must be +"PASS" server-side; headless tokens are not classified PASS, so email signups +are created with promo_eligible=False). The GitHub OAuth door provisions the +user with promo_eligible defaulting to True -> $1 signup grant per fresh inbox. + +Flow per account: + 1. GET {base}/auth/github -> 302 to github.com/login/oauth/authorize + (client_id, state) + treg_oauth_state cookie + 2. GH password+TOTP login, follow the FULL authorize URL (redirect_uri matters) + -> code (direct redirect / meta-refresh / consent POST) + 3. GET {base}/auth/github/callback?code&state with the state cookie -> treg_session + 4. POST {base}/orgs {"name": ...} -> org_id + slug + 5. GET {base}/auth/cli-token (X-Treg-Org header) -> team token + 6. GET {base}/orgs/{id}/balance (X-Treg-Token + X-Treg-Key-Protocol: 1) + +Usage: python gh_oauth_reg.py +Config: config.json (see config.example.json) or env TREG_* / GH_POOL. +Pool: JSON array of {"login","password","totp","email"} GitHub accounts. + +Anti-fraud notes (why some accounts get $0): + - SignupPromoClaim is unique per normalized inbox: "+tag" stripped for every + domain, dots stripped for gmail. One grant per mailbox, forever. Retrying + with a second org does NOT pay again (claim already consumed). + - So: gmail alias/dot farms are dead for this promo; only genuinely fresh + inboxes pay. Observed hit rate on a fresh pool: 69/69; on a pool with + previously-touched inboxes: ~50-70%. +""" +import sys +import os +import re +import json +import time +import random +import string +import urllib.request +import urllib.error +import urllib.parse +import http.cookiejar + +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +from gh_session import GHSession # noqa: E402 + +HERE = os.path.dirname(os.path.abspath(__file__)) + + +def _cfg(): + cfg = {} + p = os.path.join(HERE, 'config.json') + if os.path.exists(p): + cfg = json.load(open(p, encoding='utf-8')) + return cfg + + +CFG = _cfg() +B = os.environ.get('TREG_BASE', CFG.get('base', 'https://treg.to')) +POOL = os.environ.get('GH_POOL', CFG.get('gh_pool', 'gh_accounts.json')) +if not os.path.isabs(POOL): + POOL = os.path.join(HERE, POOL) +STATE_F = os.path.join(HERE, os.environ.get('GH_STATE', CFG.get('state', 'gh_reg_state.json'))) +BANK_F = os.path.join(HERE, CFG.get('bank', 'treg_gh_bank.jsonl')) +PACE = CFG.get('pace', [8, 15]) + +UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + '(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36') + + +def load_state(): + try: + return json.load(open(STATE_F)) + except Exception: + return {'idx': 0} + + +def save_state(st): + with open(STATE_F, 'w') as f: + json.dump(st, f) + + +def opener_noredir(): + class NoRedir(urllib.request.HTTPRedirectHandler): + def redirect_request(self, rq, fp, code, msg, headers, newurl): + return None + jar = http.cookiejar.CookieJar() + op = urllib.request.build_opener(NoRedir, urllib.request.HTTPCookieProcessor(jar)) + op.addheaders = [('User-Agent', UA)] + return op, jar + + +def req(op, url, data=None, method=None, timeout=40, ctype=None, extra=None): + r = urllib.request.Request(url, data=data, method=method) + r.add_header('User-Agent', UA) + r.add_header('Accept', '*/*') + if ctype: + r.add_header('Content-Type', ctype) + if extra: + for k, v in extra.items(): + r.add_header(k, v) + try: + with op.open(r, timeout=timeout) as resp: + return resp.status, resp.read()[:400000] + except urllib.error.HTTPError as e: + return e.code, e.read()[:4000] + except Exception as e: + return -1, ('%s: %s' % (type(e).__name__, str(e)[:120])).encode() + + +def rndname(pfx='studio'): + return pfx + ''.join(random.choices(string.ascii_lowercase + string.digits, k=7)) + + +def run(gh_acc): + op, jar = opener_noredir() + # step 1: OAuth start -> authorize URL + state + try: + with op.open(B + '/auth/github', timeout=30) as resp: + return None, 'unexpected %s on /auth/github' % resp.status + except urllib.error.HTTPError as e: + if e.code not in (301, 302, 303, 307): + return None, 'start http=%s' % e.code + loc = e.headers.get('Location', '') + m = re.search(r'client_id=([^&]+)', loc) + ms = re.search(r'state=([^&]+)', loc) + if not m or not ms: + return None, 'no client_id/state in redirect: %s' % loc[:120] + state = ms.group(1) + state_cookie = '' + for c in jar: + if c.name == 'treg_oauth_state': + state_cookie = c.value + + # step 2: GitHub login + authorize (FULL url — redirect_uri is required) + sess = GHSession() + ok, err = sess.login(gh_acc['login'], gh_acc['password'], gh_acc.get('totp', '')) + if not ok: + return None, 'gh login failed: %s' % str(err)[:120] + code, err = sess.oauth_code(loc) + if not code: + return None, 'gh authorize failed: %s' % str(err)[:200] + + # step 3: callback with the state cookie -> treg session + cb = B + '/auth/github/callback?code=%s&state=%s' % ( + urllib.parse.quote(code), urllib.parse.quote(state)) + st, body = req(op, cb, timeout=40, extra={'Cookie': 'treg_oauth_state=' + state_cookie}) + if st not in (200, 302, 303, 307): + return None, 'callback http=%s %s' % (st, body[:200]) + sess_cookie = '' + for c in jar: + if 'session' in c.name or 'treg' in c.name: + sess_cookie += '%s=%s; ' % (c.name, c.value) + if not sess_cookie.strip(): + return None, 'no session cookie after callback; body=%s' % body[:200].decode('utf-8', 'ignore') + + # step 4: create org (claim fires here) + name = rndname() + st, body = req(op, B + '/orgs', data=json.dumps({'name': name}).encode(), + method='POST', timeout=30, ctype='application/json', + extra={'Cookie': sess_cookie}) + org_id = slug = None + try: + pj = json.loads(body) + org_id = pj.get('org_id') or (pj.get('org') or {}).get('id') + slug = pj.get('org') if isinstance(pj.get('org'), str) else pj.get('slug') + if isinstance(pj.get('org'), dict): + org_id = org_id or pj['org'].get('id') + slug = slug or pj['org'].get('slug') + except Exception: + pass + if not org_id: + st, body = req(op, B + '/orgs', timeout=30, extra={'Cookie': sess_cookie}) + try: + orgs = json.loads(body) + if isinstance(orgs, dict): + orgs = orgs.get('orgs') or orgs.get('data') or [] + if orgs: + org_id = orgs[0].get('org_id') or orgs[0].get('id') + slug = orgs[0].get('org') or orgs[0].get('slug') + except Exception: + pass + + # step 5: team token + st, body = req(op, B + '/auth/cli-token', timeout=30, + extra={'Cookie': sess_cookie, 'X-Treg-Org': str(slug or org_id or '')}) + try: + tok = json.loads(body).get('token', '') + except Exception: + tok = '' + if not tok: + return {'email': gh_acc.get('email'), 'gh_login': gh_acc['login'], + 'org': slug, 'org_id': org_id, 'cookie': sess_cookie.strip()}, \ + 'no cli token: %s' % body[:150] + + # step 6: balance (X-Treg-Token auth; Bearer is rejected with 401) + bal = -1.0 + if org_id: + st2, b2 = req(op, '%s/orgs/%s/balance?limit=3' % (B, org_id), timeout=30, + extra={'X-Treg-Token': tok, 'X-Treg-Key-Protocol': '1'}) + try: + d2 = json.loads(b2) + bal = d2.get('balance_micro', d2.get('balance', -1)) / 1e6 + except Exception: + pass + rec = {'ts': time.time(), 'email': gh_acc.get('email'), 'gh_login': gh_acc['login'], + 'org': slug, 'org_id': org_id, 'token': tok, 'balance_usd': bal, + 'via': 'github-oauth'} + with open(BANK_F, 'a', encoding='utf-8') as f: + f.write(json.dumps(rec, ensure_ascii=False) + '\n') + return rec, 'bal=$%.2f' % bal + + +def main(): + n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 + pool = json.load(open(POOL, encoding='utf-8')) + st = load_state() + done = 0 + for i in range(n): + idx = st['idx'] + if idx >= len(pool): + print('pool exhausted') + break + acc = pool[idx] + st['idx'] = idx + 1 + save_state(st) + print('=== acc %d/%d gh=%s' % (i + 1, n, acc['login']), flush=True) + rec, msg = run(acc) + print('RESULT: %s' % msg, flush=True) + if rec and rec.get('balance_usd', 0) > 0: + done += 1 + time.sleep(random.uniform(*PACE)) + print('GRANT>0: %d/%d' % (done, n)) + + +if __name__ == '__main__': + main() diff --git a/gh_session.py b/gh_session.py new file mode 100644 index 0000000..7217d78 --- /dev/null +++ b/gh_session.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- +"""gh_session — GitHub HTTP session (password + TOTP login) and OAuth authorize. + +Pure stdlib + pyotp. No browser. Optional proxy via HTTPS_PROXY env var. +Vendored & sanitized for public release (original: private regfarm tooling). +""" +import re +import time +import html as htmlmod +import urllib.request +import urllib.error +import urllib.parse +import http.cookiejar +import os + +try: + import pyotp +except ImportError: + pyotp = None + +UA = ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ' + '(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36') +GH = 'https://github.com' + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def form_fields(fragment): + """Extract hidden/input fields from an HTML form fragment.""" + out = {} + for m in re.finditer(r']*>', fragment): + tag = m.group(0) + nm = re.search(r'name="([^"]+)"', tag) + vl = re.search(r'value="([^"]*)"', tag) + if nm: + out[nm.group(1)] = htmlmod.unescape(vl.group(1)) if vl else '' + return out + + +def find_form(html, action_hint): + for m in re.finditer(r']*>.*?', html, re.S): + f = m.group(0) + if action_hint in f: + return f + return None + + +class GHSession: + def __init__(self, proxy=None): + self.jar = http.cookiejar.CookieJar() + proxy = proxy or os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy') + handlers = [] + if proxy: + handlers.append(urllib.request.ProxyHandler({'https': proxy, 'http': proxy})) + handlers += [NoRedirect, urllib.request.HTTPCookieProcessor(self.jar)] + self.op = urllib.request.build_opener(*handlers) + self.op.addheaders = [('User-Agent', UA), + ('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'), + ('Accept-Language', 'en-US,en;q=0.9'), + ('Origin', GH), ('Referer', GH + '/')] + self.detail = [] + + def _req(self, url, data=None, timeout=30): + r = urllib.request.Request(url, data=data) + try: + with self.op.open(r, timeout=timeout) as resp: + return resp.status, dict(resp.headers), resp.read().decode('utf-8', 'ignore') + except urllib.error.HTTPError as e: + return e.code, dict(e.headers or {}), e.read().decode('utf-8', 'ignore') + except Exception as e: + return -1, {}, '%s: %s' % (type(e).__name__, str(e)[:120]) + + def get(self, url): + return self._req(url) + + def post_form(self, url, fields): + return self._req(url, urllib.parse.urlencode(fields).encode()) + + # ---- login ---- + def login(self, login, password, totp): + st, h, body = self.get(GH + '/login') + if st != 200: + return False, 'login page http=%s %s' % (st, body[:120]) + form = find_form(body, '/session') + if not form: + return False, 'no /session form on login page' + fields = form_fields(form) + fields['login'] = login + fields['password'] = password + st, h, body = self.post_form(GH + '/session', fields) + self.detail.append('session http=%s loc=%s' % (st, h.get('Location', '')[:80])) + loc = h.get('Location', '') + if 'verified-device' in loc or 'device-verification' in loc or 'verify' in loc: + return False, 'device-verification required: %s' % loc + if st in (301, 302) and ('two-factor' in loc or '2fa' in loc): + return self._totp(totp, loc) + if st in (301, 302) and loc.rstrip('/').endswith('github.com'): + return self._check_login(login) + if 'two-factor' in body or 'Two-factor' in body: + return self._totp(totp, '/sessions/two-factor') + return False, 'login unexpected http=%s loc=%s body=%s' % (st, loc[:100], body[:200]) + + def _totp(self, totp, loc): + if pyotp is None: + return False, 'pyotp not installed (pip install pyotp)' + page = loc if loc.startswith('http') else GH + loc + st, h, body = self.get(page) + for _ in range(3): + if st in (301, 302) and h.get('Location'): + nloc = h['Location'] + page = nloc if nloc.startswith('http') else GH + nloc + st, h, body = self.get(page) + else: + break + for _attempt in range(3): + form = find_form(body, 'two-factor') + if not form: + return False, 'no 2fa form http=%s %s' % (st, body[:150]) + am = re.search(r'action="([^"]+)"', form) + post_url = (am.group(1) if am else page) + if not post_url.startswith('http'): + post_url = GH + post_url + fields = form_fields(form) + fields['app_otp'] = pyotp.TOTP(totp).now() + st2, h2, body2 = self.post_form(post_url, fields) + self.detail.append('2fa http=%s loc=%s' % (st2, h2.get('Location', '')[:80])) + loc2 = h2.get('Location', '') + if st2 in (301, 302): + if 'two-factor' in loc2: + time.sleep(2) # code expired near TOTP window edge — retry fresh + st, h, body = self.get(page) + continue + return self._check_login(loc2 or None) + if 'Incorrect' in body2 or 'incorrect' in body2 or st2 == 422: + time.sleep(2) + st, h, body = self.get(page) + continue + return self._check_login(None) + return False, 'totp: 3 failed attempts' + + def _check_login(self, redirect=None): + if redirect: + self.get(redirect if redirect.startswith('http') else GH + redirect) + for c in self.jar: + if c.name == 'logged_in' and c.value in ('yes', 'true'): + return True, 'logged in (cookie)' + st, h, body = self.get(GH + '/settings/profile') + if st == 200 and ('authenticity' in body or 'Settings' in body): + return True, 'logged in (settings)' + st, h, body = self.get(GH + '/') + if 'logged-in' in body or 'Sign out' in body or 'sign_out' in body: + return True, 'logged in (home)' + return False, 'not logged in: settings http=%s' % st + + # ---- OAuth authorize ---- + def oauth_code(self, full_url): + """Follow a full /login/oauth/authorize URL (client_id, state, redirect_uri, + scope all included). Returns (code, error). Handles: direct redirect with + code, meta-refresh page with code (already-authorized app), consent form.""" + st, h, body = self.get(full_url) + self.detail.append('authorize http=%s loc=%s' % (st, h.get('Location', '')[:80])) + loc = h.get('Location', '') + if st in (301, 302): + code = self._code_from(loc) + if code: + return code, None + if 'verified-device' in loc or 'device-verification' in loc: + return None, 'device-verification: %s' % loc + return None, 'authorize redirect without code: %s' % loc[:150] + if st != 200: + return None, 'authorize http=%s %s' % (st, body[:200]) + m = re.search(r'url=[^"?&]+\?code=([a-f0-9]+)', body) + if m: + return m.group(1), None + m = re.search(r'[?&]code=([a-f0-9]{16,})', body) + if m: + return m.group(1), None + tok = re.search(r'name="authenticity_token"[^>]*value="([^"]+)"', body) + if not tok: + tok = re.search(r'value="([^"]+)"[^>]*name="authenticity_token"', body) + if not tok: + return None, 'consent page without authenticity_token (len=%d)' % len(body) + fields = {'authorize': '1', 'authenticity_token': tok.group(1)} + st2, h2, body2 = self.post_form(full_url, fields) + self.detail.append('consent http=%s loc=%s' % (st2, h2.get('Location', '')[:80])) + loc2 = h2.get('Location', '') + if st2 in (301, 302): + code = self._code_from(loc2) + if code: + return code, None + return None, 'consent redirect without code: %s' % loc2[:150] + m = re.search(r'url=[^"?&]+\?code=([a-f0-9]+)', body2) + if m: + return m.group(1), None + m = re.search(r'[?&]code=([a-f0-9]{16,})', body2) + if m: + return m.group(1), None + return None, 'consent http=%s len=%d: %s' % (st2, len(body2), body2[:200]) + + @staticmethod + def _code_from(loc): + if not loc: + return None + q = urllib.parse.urlparse(loc).query + return urllib.parse.parse_qs(q).get('code', [None])[0]