netlify-autoreg: signup farm + AI Gateway reverse (281 models on free), dashboard, multi-mailbox, captcha layer, full guide
This commit is contained in:
+379
@@ -0,0 +1,379 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Netlify autoreg farm.
|
||||
Flow (reverse-engineered):
|
||||
1. Chrome CDP -> app.netlify.com/signup/email
|
||||
2. grecaptcha.enterprise.execute(sitekey, {action:'SIGNUP'}) inside page
|
||||
3. POST https://api.netlify.com/auth/signup?provider=email... -> {code_id}
|
||||
4. IMAP (t-online) -> email with #verify_token=<code_id>-<code>
|
||||
5. POST https://api.netlify.com/auth/verify {code_id, code} -> access_token (nfu_...)
|
||||
6. POST https://api.netlify.com/api/v1/sites (create) -> site_id
|
||||
Usage:
|
||||
python netlify_farm.py --count 3 --port 9233
|
||||
Output: netlify_bank.jsonl (email, password, token, user_id, site_id, ts)
|
||||
"""
|
||||
import argparse, json, os, random, re, string, time, imaplib, email as email_lib, sys
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from proxy_helpers import ensure_chrome, rotate_zte, egress_ip, ZTE_PROXY
|
||||
from mailbox import MailboxPool, Mailbox
|
||||
import captcha as capmod
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
BANK = os.environ.get('NETLIFY_BANK', os.path.join(HERE, 'netlify_bank.jsonl'))
|
||||
# mailbox pool: lines of email:password, readable over IMAP
|
||||
MAILS = os.environ.get('NETLIFY_MAILS', os.path.join(HERE, 'mails.txt'))
|
||||
SITEKEY = '6Lfj2-EtAAAAAABMy0F1oAGRPQOCTZhnt1KQ7Xat'
|
||||
SIGNUP_URL = ('https://api.netlify.com/auth/signup?provider=email&site_id=app.netlify.com'
|
||||
'&tracking_session_id=&login=true&entry_point=direct'
|
||||
'&redirect=https%3A%2F%2Fapp.netlify.com%2F')
|
||||
|
||||
def gen_pass(n=14):
|
||||
alphabet = string.ascii_letters + string.digits + '!@#$%'
|
||||
return ''.join(random.choice(alphabet) for _ in range(n))
|
||||
|
||||
def used_emails():
|
||||
seen = set()
|
||||
if os.path.exists(BANK):
|
||||
for line in open(BANK, encoding='utf-8', errors='ignore'):
|
||||
try:
|
||||
seen.add(json.loads(line)['email'].lower())
|
||||
except Exception:
|
||||
pass
|
||||
return seen
|
||||
|
||||
def load_mails(skip):
|
||||
"""t-online pool: email:password lines."""
|
||||
out = []
|
||||
for line in open(MAILS, encoding='utf-8', errors='ignore'):
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#') or ':' not in line:
|
||||
continue
|
||||
e, p = line.split(':', 1)
|
||||
if '@' not in e:
|
||||
continue
|
||||
if e.lower() in skip:
|
||||
continue
|
||||
out.append((e.strip(), p.strip()))
|
||||
random.shuffle(out)
|
||||
return out
|
||||
|
||||
def solve_captcha(page):
|
||||
return page.evaluate("""async (sk) => {
|
||||
return await new Promise((resolve) => {
|
||||
if (!window.grecaptcha?.enterprise) return resolve('ERR:no_enterprise');
|
||||
window.grecaptcha.enterprise.ready(async () => {
|
||||
try {
|
||||
const t = await window.grecaptcha.enterprise.execute(sk, {action: 'SIGNUP'});
|
||||
resolve(t);
|
||||
} catch (e) { resolve('ERR:' + e.message); }
|
||||
});
|
||||
});
|
||||
}""", SITEKEY)
|
||||
|
||||
CAPTCHA_MODE = 'auto'
|
||||
CAPTCHA_KEY = ''
|
||||
CAPTCHA_KIND = 'recaptcha_v2_enterprise'
|
||||
|
||||
|
||||
def do_signup(page, email, password):
|
||||
"""Get a captcha token: in-page enterprise execute first, external solver as fallback."""
|
||||
tok = capmod.execute_in_page(page) if CAPTCHA_MODE != 'off' else ''
|
||||
if (not tok or tok.startswith('ERR')) and CAPTCHA_MODE not in ('auto', 'off') and CAPTCHA_KEY:
|
||||
info = capmod.detect(page)
|
||||
sitekey = (info.get('sitekeys') or [capmod.NETLIFY_SITEKEY])[0]
|
||||
print(f' [captcha] in-page failed ({str(tok)[:40]}), trying {CAPTCHA_MODE}')
|
||||
res = capmod.solve(CAPTCHA_MODE, CAPTCHA_KEY, CAPTCHA_KIND,
|
||||
'https://app.netlify.com/signup/email', sitekey,
|
||||
action=capmod.NETLIFY_ACTION)
|
||||
tok = res.get('token') or ''
|
||||
if res.get('error'):
|
||||
print(' [captcha] solver error:', res['error'])
|
||||
if not tok or str(tok).startswith('ERR'):
|
||||
return {'ok': False, 'stage': 'captcha', 'raw': tok}
|
||||
res = page.evaluate("""async (a) => {
|
||||
try {
|
||||
const r = await fetch(a.url, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/json', 'Origin': 'https://app.netlify.com',
|
||||
'Referer': 'https://app.netlify.com/signup/email'},
|
||||
body: JSON.stringify({
|
||||
email: a.email, password: a.password, invite_code: null,
|
||||
no_autosignup: false, redirect: 'https://app.netlify.com',
|
||||
entry_point: 'direct', captcha_response: a.tok, captcha_source: 'google'
|
||||
})
|
||||
});
|
||||
return {status: r.status, body: await r.json()};
|
||||
} catch (e) { return {error: String(e)}; }
|
||||
}""", {'url': SIGNUP_URL, 'email': email, 'password': password, 'tok': tok})
|
||||
b = res.get('body') or {}
|
||||
if b.get('state') == 'success' and b.get('code_id'):
|
||||
return {'ok': True, 'code_id': b['code_id']}
|
||||
return {'ok': False, 'stage': 'signup', 'raw': json.dumps(res)[:300]}
|
||||
|
||||
def read_verify_token(email_addr, mail_pass, code_id, timeout=180):
|
||||
"""Poll IMAP for netlify verify mail; return (code_id, code)."""
|
||||
deadline = time.time() + timeout
|
||||
pattern = re.compile(r'verify_token=([0-9a-f]{24})-(\d+)')
|
||||
last_err = None
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
m = imaplib.IMAP4_SSL('secureimap.t-online.de')
|
||||
m.login(email_addr, mail_pass)
|
||||
m.select('INBOX')
|
||||
typ, data = m.search(None, '(FROM "netlify")')
|
||||
ids = (data[0].split() if data and data[0] else [])
|
||||
for i in reversed(ids[-6:]):
|
||||
typ, md = m.fetch(i, '(RFC822)')
|
||||
if md and md[0]:
|
||||
msg = email_lib.message_from_bytes(md[0][1])
|
||||
body = ''
|
||||
if msg.is_multipart():
|
||||
for part in msg.walk():
|
||||
if part.get_content_type() in ('text/plain', 'text/html'):
|
||||
try:
|
||||
body += part.get_payload(decode=True).decode('utf-8', 'ignore')
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
body = msg.get_payload(decode=True).decode('utf-8', 'ignore')
|
||||
except Exception:
|
||||
pass
|
||||
for cid, code in pattern.findall(body):
|
||||
if cid == code_id:
|
||||
m.logout()
|
||||
return cid, code
|
||||
m.logout()
|
||||
except Exception as e:
|
||||
last_err = str(e)[:120]
|
||||
time.sleep(10)
|
||||
return None, last_err
|
||||
|
||||
def verify_account(code_id, code):
|
||||
import urllib.request
|
||||
req = urllib.request.Request(
|
||||
'https://api.netlify.com/auth/verify',
|
||||
data=json.dumps({'code_id': code_id, 'code': code}).encode(),
|
||||
headers={'Content-Type': 'application/json', 'Origin': 'https://app.netlify.com',
|
||||
'Referer': 'https://app.netlify.com/signup',
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/157.0.0.0 Safari/537.36'},
|
||||
method='POST')
|
||||
with urllib.request.urlopen(req, timeout=40) as r:
|
||||
d = json.loads(r.read().decode())
|
||||
if d.get('state') == 'success':
|
||||
u = d['data']['user']
|
||||
return {'ok': True, 'token': u.get('access_token'), 'user_id': u.get('id'),
|
||||
'account_id': u.get('account_id')}
|
||||
return {'ok': False, 'raw': json.dumps(d)[:300]}
|
||||
|
||||
LOGIN_URL = ('https://api.netlify.com/auth/login?provider=email&site_id=app.netlify.com'
|
||||
'&tracking_session_id=&login=true&redirect=https%3A%2F%2Fapp.netlify.com%2F')
|
||||
|
||||
def login(email_addr, password):
|
||||
"""Return a fresh access token for an existing account, or ('suspended'|'bad', msg).
|
||||
|
||||
Session tokens (nfu_) expire/rotate within tens of minutes; the password does not.
|
||||
No captcha is required for login — only signup is captcha-gated.
|
||||
"""
|
||||
import urllib.request, urllib.error
|
||||
body = json.dumps({'email': email_addr, 'password': password, 'no_autosignup': False,
|
||||
'redirect': 'https://app.netlify.com', 'entry_point': 'direct',
|
||||
'captcha_response': '', 'captcha_source': ''}).encode()
|
||||
req = urllib.request.Request(LOGIN_URL, data=body, method='POST', headers={
|
||||
'Content-Type': 'application/json', 'Origin': 'https://app.netlify.com',
|
||||
'Referer': 'https://app.netlify.com/login',
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/157.0.0.0 Safari/537.36'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=40) as r:
|
||||
d = json.loads(r.read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f'http {e.code}'
|
||||
if d.get('state') == 'success':
|
||||
u = (d.get('data') or {}).get('user') or {}
|
||||
return u.get('access_token'), 'ok'
|
||||
return None, d.get('message') or 'error'
|
||||
|
||||
def api_call(token, path, method='GET', payload=None):
|
||||
import urllib.request
|
||||
data = json.dumps(payload).encode() if payload is not None else None
|
||||
req = urllib.request.Request('https://api.netlify.com' + path, data=data, method=method,
|
||||
headers={'Authorization': 'Bearer ' + token,
|
||||
'Content-Type': 'application/json'})
|
||||
with urllib.request.urlopen(req, timeout=60) as r:
|
||||
return r.status, json.loads(r.read().decode() or '{}')
|
||||
|
||||
def create_site(token, name):
|
||||
try:
|
||||
st, d = api_call(token, '/api/v1/sites', 'POST', {'name': name})
|
||||
if st not in (200, 201):
|
||||
return None, json.dumps(d)[:120]
|
||||
sid = d.get('id')
|
||||
# new accounts get SSO lock on every site -> 401 for visitors
|
||||
try:
|
||||
api_call(token, f'/api/v1/sites/{sid}', 'PATCH',
|
||||
{'sso_login': False, 'account_sso_login': False})
|
||||
except Exception:
|
||||
pass
|
||||
return sid, d.get('default_domain')
|
||||
except Exception as e:
|
||||
return None, str(e)[:120]
|
||||
|
||||
|
||||
def deploy_static(token, site_id, html='<html><body>ok</body></html>'):
|
||||
"""Zip-deploy a minimal index.html; returns (ok, info)."""
|
||||
import io, zipfile, urllib.request
|
||||
buf = io.BytesIO()
|
||||
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as z:
|
||||
z.writestr('index.html', html)
|
||||
body = buf.getvalue()
|
||||
req = urllib.request.Request(
|
||||
f'https://api.netlify.com/api/v1/sites/{site_id}/deploys',
|
||||
data=body, method='POST',
|
||||
headers={'Authorization': 'Bearer ' + token, 'Content-Type': 'application/zip'})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=120) as r:
|
||||
d = json.loads(r.read().decode())
|
||||
return True, d.get('id'), d.get('state')
|
||||
except Exception as e:
|
||||
return False, str(e)[:120], None
|
||||
|
||||
def append_bank(rec):
|
||||
with open(BANK, 'a', encoding='utf-8') as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + '\n')
|
||||
|
||||
def browser_alive(port: int) -> bool:
|
||||
try:
|
||||
import urllib.request
|
||||
urllib.request.urlopen(f'http://127.0.0.1:{port}/json/version', timeout=3).close()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def restart_browser(port: int, profile: str = None, proxy: str = None):
|
||||
"""Kill chrome bound to this profile/port and start a fresh one."""
|
||||
import psutil
|
||||
for pr in psutil.process_iter(['pid', 'name', 'cmdline']):
|
||||
try:
|
||||
cl = ' '.join(pr.info.get('cmdline') or [])
|
||||
if pr.info['name'] and 'chrome' in pr.info['name'].lower() and (
|
||||
f'--remote-debugging-port={port}' in cl or (profile and profile in cl)):
|
||||
pr.kill()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(4)
|
||||
return ensure_chrome(port, profile, proxy)
|
||||
|
||||
def main():
|
||||
global MAILS, BANK
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument('--count', type=int, default=3)
|
||||
ap.add_argument('--port', type=int, default=9233)
|
||||
ap.add_argument('--site', action='store_true', help='create a site per account')
|
||||
ap.add_argument('--proxy', default='', help='http proxy for Chrome+HTTP, e.g. http://127.0.0.1:8899')
|
||||
ap.add_argument('--rotate', action='store_true', help='rotate ZTE mobile IP before each account')
|
||||
ap.add_argument('--profile', default='', help='Chrome user-data-dir')
|
||||
ap.add_argument('--mails', default='', help='mailbox pool file(s), comma separated: email:password lines')
|
||||
ap.add_argument('--captcha', default='auto', help='auto|off|2captcha|capmonster|rucaptcha')
|
||||
ap.add_argument('--captcha-key', dest='captcha_key', default='', help='solver API key')
|
||||
ap.add_argument('--captcha-kind', dest='captcha_kind', default='recaptcha_v2_enterprise',
|
||||
help='recaptcha_v2|recaptcha_v2_enterprise|recaptcha_v3|hcaptcha|turnstile')
|
||||
ap.add_argument('--bank', default='', help='output bank jsonl')
|
||||
args = ap.parse_args()
|
||||
if args.mails:
|
||||
MAILS = args.mails
|
||||
if args.bank:
|
||||
BANK = args.bank
|
||||
|
||||
global CAPTCHA_MODE, CAPTCHA_KEY, CAPTCHA_KIND
|
||||
CAPTCHA_MODE = args.captcha
|
||||
CAPTCHA_KEY = args.captcha_key or os.environ.get('CAPTCHA_KEY', '')
|
||||
CAPTCHA_KIND = args.captcha_kind
|
||||
skip = used_emails()
|
||||
mail_files = [m.strip() for m in (args.mails or MAILS).split(',') if m.strip()]
|
||||
mbp = MailboxPool(mail_files, skip)
|
||||
pool = mbp.items
|
||||
print('[i] captcha mode:', CAPTCHA_MODE, '| mail domains:', mbp.domains()[:5])
|
||||
print(f'[i] pool available: {len(pool)}, already used: {len(skip)}')
|
||||
if not pool:
|
||||
print('[!] no fresh emails in pool'); return
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
port = args.port
|
||||
if not ensure_chrome(port, args.profile or None, args.proxy or None):
|
||||
print('[!] chrome did not start on', port); return
|
||||
print('[i] egress:', egress_ip(args.proxy or None) or 'unknown')
|
||||
ok = 0
|
||||
with sync_playwright() as p:
|
||||
b = p.chromium.connect_over_cdp(f'http://127.0.0.1:{args.port}')
|
||||
ctx = b.contexts[0]
|
||||
page = None
|
||||
for pg in ctx.pages:
|
||||
if 'netlify.com' in pg.url:
|
||||
page = pg; break
|
||||
if page is None:
|
||||
page = ctx.new_page()
|
||||
page.goto('https://app.netlify.com/signup/email', timeout=45000, wait_until='domcontentloaded')
|
||||
page.set_default_timeout(45000)
|
||||
|
||||
for i in range(args.count):
|
||||
if i and (not browser_alive(args.port) or page.is_closed()):
|
||||
print(' [browser] dead -> restarting')
|
||||
restart_browser(args.port, args.profile or None, args.proxy or None)
|
||||
try:
|
||||
page.close()
|
||||
except Exception:
|
||||
pass
|
||||
ctx2 = None
|
||||
for c in p.chromium.connect_over_cdp(f'http://127.0.0.1:{args.port}').contexts:
|
||||
ctx2 = c
|
||||
break
|
||||
ctx = ctx2 or ctx
|
||||
page = ctx.new_page()
|
||||
if args.rotate and i:
|
||||
newip = rotate_zte()
|
||||
print(f' [rotate] new egress: {newip or "fail"}')
|
||||
mb = pool[i]
|
||||
email_addr, mail_pass = mb.addr, mb.password
|
||||
password = gen_pass()
|
||||
print(f'\n[{i+1}/{args.count}] {email_addr}')
|
||||
try:
|
||||
page.goto('https://app.netlify.com/signup/email', timeout=45000, wait_until='domcontentloaded')
|
||||
time.sleep(3)
|
||||
r = do_signup(page, email_addr, password)
|
||||
print(' signup:', r)
|
||||
if not r['ok']:
|
||||
continue
|
||||
hit = mb.wait_for_link('netlify', r'verify_token=([0-9a-f]{24})-(\d+)', timeout=180)
|
||||
if not hit:
|
||||
print(' [!] no verify mail / imap err:', mb.last_error[:80])
|
||||
continue
|
||||
cid, code = hit.group(1), hit.group(2)
|
||||
print(f' verify token: {cid} {code} (imap: {email_addr.split("@")[-1]})')
|
||||
v = verify_account(cid, code)
|
||||
print(' verify:', {k: (str(val)[:20] if k == 'token' else val) for k, val in v.items()})
|
||||
if not v['ok']:
|
||||
continue
|
||||
rec = {'email': email_addr, 'password': password, 'token': v['token'],
|
||||
'user_id': v['user_id'], 'account_id': v['account_id'],
|
||||
'ts': time.strftime('%Y-%m-%dT%H:%M:%S')}
|
||||
if args.site:
|
||||
sid, dom = create_site(v['token'], 'eni-' + ''.join(random.choices(string.ascii_lowercase + string.digits, k=8)))
|
||||
rec['site_id'], rec['site_domain'] = sid, dom
|
||||
if sid:
|
||||
ok_dep, dep_id, dep_state = deploy_static(
|
||||
v['token'], sid,
|
||||
f'<html><body><h1>{email_addr}</h1></body></html>')
|
||||
rec['deploy_id'] = dep_id if ok_dep else None
|
||||
append_bank(rec)
|
||||
ok += 1
|
||||
print(f' [+] SAVED (#{ok})')
|
||||
except Exception as e:
|
||||
print(' [x] error:', str(e)[:200])
|
||||
continue
|
||||
print(f'\n[done] created {ok}/{args.count}; bank: {BANK}')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user