netlify-autoreg: signup farm + AI Gateway reverse (281 models on free), dashboard, multi-mailbox, captcha layer, full guide

This commit is contained in:
eni
2026-11-11 20:22:12 +02:00
commit a676a4a0cf
16 changed files with 2119 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
netlify_bank*.jsonl
mails.txt
*.session
__pycache__/
*.pyc
.env
*.log
state.json
*_mails*.txt
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+154
View File
@@ -0,0 +1,154 @@
# netlify-autoreg
Automated account registration + full API reverse for **app.netlify.com**.
No 2captcha. The captcha is solved by the real browser session that owns the page,
because Netlify's reCAPTCHA Enterprise token is bound to browser origin, action and
score: solver tokens from third-party services are silently dropped with
`Please complete the security check and try again`.
## What's inside
| file | purpose |
|---|---|
| `netlify_farm.py` | registration wave: captcha -> signup -> IMAP verify -> token -> site -> deploy |
| `proxy_helpers.py` | Chrome bootstrap (with `--proxy-server`), ZTE mobile rotation, egress probe |
| `mailbox.py` | multi-provider mailbox pool: IMAP presets, host autodetect, POP3 (rediffmail), SEARCH fallback |
| `captcha.py` | captcha layer: page detection, in-page enterprise execute, external solvers (2captcha/rucaptcha/capmonster) |
| `dashboard.py` | web control panel: account table, check/wave/deploy jobs, live log |
| `deploy_all.py` | re-deploy every site in the bank and verify HTTP 200 |
| `docs/REVERSE.md` | every endpoint, request body and response we observed |
| `docs/API.md` | API surface, PAT, AI Gateway status |
## Pipeline
```
Chrome (CDP, real profile, optional --proxy-server)
-> GET /signup/email
-> grecaptcha.enterprise.execute(SITEKEY, {action: "SIGNUP"}) ~2400 chars
-> POST api.netlify.com/auth/signup?provider=email... -> {code_id}
-> IMAP (t-online) "[Netlify] Let's verify your email" -> #verify_token=<code_id>-<code>
-> POST api.netlify.com/auth/verify {code_id, code} -> access_token nfu_...
-> POST api/v1/sites {name} -> site_id
-> PATCH api/v1/sites/{id} {"sso_login": false} (new accounts are SSO-locked -> 401)
-> POST api/v1/sites/{id}/deploys (zip) -> state=ready, HTTP 200
```
## Quick start
```bash
# direct (home IP)
python netlify_farm.py --count 5 --site \
--mails "C:/path/to/mails.txt" --bank "C:/path/to/netlify_bank.jsonl"
# through a proxy, rotating the mobile uplink before every account
python netlify_farm.py --count 5 --site \
--proxy http://127.0.0.1:8899 --port 9244 --rotate \
--profile "C:/tmp/nl_prof_zte" \
--mails "C:/path/to/mails.txt" --bank "C:/path/to/netlify_bank.jsonl"
# dashboard
python dashboard.py --port 8791 # http://127.0.0.1:8791/
```
`--proxy` starts Chrome with `--proxy-server` and sends the HTTP calls through the
same proxy, so signup, verify and the site API share one egress.
`--rotate` calls the ZTE rotator (PPP reconnect) before each account.
Bank record:
```json
{"email":"...@t-online.de","password":"...","token":"nfu_...","user_id":"...",
"account_id":"...","site_id":"...","site_domain":"...","ts":"2026-11-11T18:37:00"}
```
## Requirements
- Windows + real Chrome (Netlify fingerprints the browser; Camoufox/headless get
`Please complete the security check`)
- `playwright` (CDP client only, we connect to a running Chrome)
- IMAP-readable mailbox pool. **gmail `+alias` is rejected** (`Email address is
invalid`); t-online works.
- Python 3.11
## Dashboard
`dashboard.py` serves one page on `127.0.0.1:8791`:
- account table: email, status (`alive` / `suspended` / `rate_limited`), last check,
site domain and its HTTP code
- **Проверить все / 5** — login probe per account, writes `state.json`
- **Деплой всем** — `PATCH sso_login=false` + zip deploy + 200 check per site
- **Волна N** — spawns the farm, streams its stdout into the panel over SSE
- per-row: refresh token, redeploy
## Limitations (read before scaling)
1. **Captcha cannot be outsourced.** 2captcha Enterprise tokens with the correct
sitekey and `action: SIGNUP` are rejected: origin and score do not match. Every
account costs one real page execution in a real Chrome.
2. **`nfu_` tokens are short-lived** (tens of minutes) and rotate. The password is
the durable credential: `login()` re-issues a token without a captcha.
3. **Login is IP rate-limited.** After roughly 20 `POST /auth/login` calls from one
IP the endpoint answers `429`; the dashboard backs off 60 s per hit. Rotation or
a proxy pool is required for bulk status checks.
4. **Mobile rotation does not always change the IP.** The ZTE uplink reconnects in
~15-20 s but the carrier can hand back the same address (observed: identical IP
after a full PPP cycle). Treat `--rotate` as best-effort.
5. **Manual moderation is real.** `{"message":"Account suspended","spam":"manual"}`
is a human decision. It hit every account created during the messy phase (gmail
addresses with no mailbox, repeated failures on one IP) and none created by the
steady flow. No retry undoes it.
6. **AI Gateway works, but only from Edge Functions.** Lambda functions see 37 env
vars and no AI keys. A Deno edge function gets `NETLIFY_AI_GATEWAY_KEY` (JWT, 497
chars) plus `OPENAI_/ANTHROPIC_/GEMINI_/OPENROUTER_/META_/TYPESAFE_` key+base pair,
all pointing at `https://<your-site>/.netlify/ai`. The JWT expires in minutes;
any call to your own edge function issues a fresh one. See `edge/envdump.ts`
and `aigw_smoke.py`.
7. **Mailbox pool is the real bottleneck**, not the API: one working mailbox per
account, readable over IMAP.
## Mailboxes — many providers
`mailbox.py` keeps a union of any number of pool files and resolves the IMAP host by
domain with fallbacks (`imap.<domain>`, `mail.<domain>`, preset table). Providers tested
alive with real credentials: `t-online.de`, `aliyun.com`, `singnet.com.sg`, `rambler.ru`,
`gmx.net`, `icn.od.ua`, plus gmail/outlook/rambler/mail.ru/yandex presets. `rediffmail.com`
goes through POP3 (no IMAP). Servers that reject `SEARCH FROM` (aliyun, rambler) are
handled by an `ALL` + Python header filter fallback.
```bash
python netlify_farm.py --count 2 --site --mails "pool_a.txt,pool_b.txt,pool_c.txt" --captcha auto
```
Verified 11.11.26: one run created accounts on `aliyun.com` and `singnet.com.sg`,
both verified over IMAP, both sites serving 200.
## Captcha
`captcha.py` does three things:
1. **detect(page)** — reports recaptcha v2 / enterprise / hcaptcha / turnstile, extracted
sitekeys and the `sa`/action parameter from the iframes.
2. **execute_in_page(page)** — runs `grecaptcha.enterprise.execute(sitekey, {action})`
inside the page that will submit the form. This is the only path Netlify accepts.
3. **solve(provider, key, kind, url, sitekey, action)** — external solvers: 2captcha,
rucaptcha, capmonster; task types `recaptcha_v2`, `recaptcha_v2_enterprise`,
`recaptcha_v3`, `hcaptcha`, `turnstile`.
Modes: `--captcha auto` (in-page only, default), `--captcha off`, or an explicit provider
(`--captcha 2captcha --captcha-key ...`) to fall back when the in-page token fails.
Note: solver tokens for Netlify's invisible Enterprise are still rejected server-side
(origin/score bound) — the external path exists for other targets and for experimenting,
not as a Netlify shortcut.
## Docs
- [`docs/REVERSE.md`](docs/REVERSE.md) — endpoints, bodies, responses
- [`docs/API.md`](docs/API.md) — API surface, PAT, AI Gateway status
## Notes
No credentials, tokens or account data are stored in this repository. The bank
file and `mails.txt` are local and git-ignored.
+36
View File
@@ -0,0 +1,36 @@
import json, time, urllib.request, urllib.error
from concurrent.futures import ThreadPoolExecutor
SITE = 'https://enitest-1794413459.netlify.app'
K = json.load(urllib.request.urlopen(SITE + '/envdump', timeout=30))['picked']['NETLIFY_AI_GATEWAY_KEY']
B = SITE + '/.netlify/ai'
models = [
'gpt-6.1-sol','gpt-6-astra','gpt-6-luna','gpt-5.5','gpt-5.4-mini',
'claude-opus-5-5','claude-sonnet-5-5','claude-haiku-5-5','claude-fable-5-2',
'gemini-4-argon','gemini-3.8-flash',
'x-ai/grok-4.7','moonshotai/kimi-k3','deepseek/deepseek-v4.1-flash-1017','z-ai/glm-5.3',
]
def probe(m):
body = json.dumps({'model': m, 'messages':[{'role':'user','content':'Reply with the single word OK'}]}).encode()
req = urllib.request.Request(B + '/v1/chat/completions', data=body, method='POST',
headers={'Authorization':'Bearer '+K,'Content-Type':'application/json'})
t0=time.time()
try:
with urllib.request.urlopen(req, timeout=120) as r:
d=json.loads(r.read().decode())
dt=time.time()-t0
txt=(d['choices'][0]['message'].get('content') or '').strip()[:20]
u=d.get('usage') or {}
return (m,'200',round(dt,1),txt,f"{u.get('prompt_tokens')}/{u.get('completion_tokens')}")
except urllib.error.HTTPError as e:
dt=time.time()-t0
err=e.read().decode('utf-8','replace')[:90]
return (m,str(e.code),round(dt,1),err,'')
except Exception as e:
return (m,'ERR',round(time.time()-t0,1),str(e)[:60],'')
with ThreadPoolExecutor(max_workers=8) as ex:
for r in ex.map(probe, models):
print(f'{r[0]:<34} {r[1]:<4} {r[2]:>6}s {r[3]:<60} {r[4]}')
+171
View File
@@ -0,0 +1,171 @@
"""Captcha layer: detection + solver providers + in-page execution.
Netlify uses invisible reCAPTCHA Enterprise (sitekey 6Lfj2-Et..., action SIGNUP).
Third-party solver tokens are rejected by the signup endpoint (origin/score bound),
so the reliable path is executing grecaptcha inside the page. This module still
supports external solvers for the cases where they DO work (visible v2, hCaptcha,
Turnstile on other targets) and for fallback experimentation.
Providers: 2captcha, capmonster, rucaptcha (all via their HTTP APIs).
"""
import json
import time
import urllib.request
import urllib.error
NETLIFY_SITEKEY = '6Lfj2-EtAAAAAABMy0F1oAGRPQOCTZhnt1KQ7Xat'
NETLIFY_ACTION = 'SIGNUP'
PROVIDERS = {
'2captcha': {'create': 'https://api.2captcha.com/createTask',
'result': 'https://api.2captcha.com/getTaskResult',
'balance': 'https://api.2captcha.com/getBalance'},
'rucaptcha': {'create': 'https://rucaptcha.com/in.php',
'result': 'https://rucaptcha.com/res.php',
'balance': 'https://rucaptcha.com/res.php'},
'capmonster': {'create': 'https://api.capmonster.cloud/createTask',
'result': 'https://api.capmonster.cloud/getTaskResult',
'balance': 'https://api.capmonster.cloud/getBalance'},
}
TASK_TYPES = {
'recaptcha_v2': 'RecaptchaV2TaskProxyless',
'recaptcha_v2_enterprise': 'RecaptchaV2EnterpriseTaskProxyless',
'recaptcha_v3': 'RecaptchaV3TaskProxyless',
'hcaptcha': 'HCaptchaTaskProxyless',
'turnstile': 'TurnstileTaskProxyless',
}
def _post(url, payload, timeout=40):
data = json.dumps(payload).encode()
req = urllib.request.Request(url, data=data, method='POST',
headers={'Content-Type': 'application/json'})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode())
def balance(provider: str, key: str):
p = PROVIDERS.get(provider)
if not p:
return None
try:
d = _post(p['balance'], {'clientKey': key})
return d.get('balance')
except Exception:
return None
def solve(provider: str, key: str, kind: str, site_url: str, sitekey: str,
action: str = '', timeout: int = 180, poll: int = 5):
"""Solve a captcha via an external provider. Returns token or None."""
p = PROVIDERS.get(provider)
if not p:
raise ValueError(f'unknown captcha provider: {provider}')
ttype = TASK_TYPES.get(kind)
if not ttype:
raise ValueError(f'unknown captcha kind: {kind}')
task = {'type': ttype, 'websiteURL': site_url, 'websiteKey': sitekey}
if kind == 'recaptcha_v3':
task['pageAction'] = action or 'verify'
task['minScore'] = 0.7
if kind == 'recaptcha_v2_enterprise' and action:
task['enterprisePayload'] = {'action': action}
try:
created = _post(p['create'], {'clientKey': key, 'task': task})
except Exception as e:
return {'error': f'create {type(e).__name__}: {e}'}
if created.get('errorId'):
return {'error': created.get('errorCode') or created.get('errorDescription')}
tid = created.get('taskId')
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(poll)
try:
res = _post(p['result'], {'clientKey': key, 'taskId': tid})
except Exception:
continue
status = (res.get('status') or '').lower()
if status == 'ready':
sol = res.get('solution') or {}
tok = (sol.get('gRecaptchaResponse') or sol.get('token')
or sol.get('text') or sol.get('cf_clearance'))
return {'token': tok, 'raw': sol}
if res.get('errorId'):
return {'error': res.get('errorCode') or res.get('errorDescription')}
return {'error': 'timeout'}
def detect(page):
"""Inspect a Playwright page and report which captcha is present."""
return page.evaluate("""() => {
const out = {types: [], sitekeys: [], actions: []};
const ifr = [...document.querySelectorAll('iframe')].map(f => f.src || '');
for (const src of ifr) {
if (src.includes('/recaptcha/enterprise/')) {
out.types.push('recaptcha_enterprise');
const k = new URL(src).searchParams.get('k');
if (k && !out.sitekeys.includes(k)) out.sitekeys.push(k);
const sa = new URL(src).searchParams.get('sa');
if (sa) out.actions.push(sa);
} else if (src.includes('/recaptcha/')) {
out.types.push('recaptcha_v2');
const k = new URL(src).searchParams.get('k');
if (k && !out.sitekeys.includes(k)) out.sitekeys.push(k);
} else if (src.includes('hcaptcha.com')) {
out.types.push('hcaptcha');
} else if (src.includes('challenges.cloudflare.com')) {
out.types.push('turnstile');
}
}
if (window.grecaptcha && window.grecaptcha.enterprise) out.types.push('has_enterprise_js');
if (window.turnstile) out.types.push('has_turnstile_js');
if (window.hcaptcha) out.types.push('has_hcaptcha_js');
out.types = [...new Set(out.types)];
return out;
}""")
def execute_in_page(page, sitekey: str = NETLIFY_SITEKEY, action: str = NETLIFY_ACTION,
timeout: int = 60):
"""Run grecaptcha.enterprise.execute() inside the page (the only working path
for Netlify). Returns token string or 'ERR:...'."""
page.evaluate("""(ms) => new Promise(res => {
const start = Date.now();
const tick = () => {
if (window.grecaptcha && window.grecaptcha.enterprise) return res(true);
if (Date.now() - start > ms) return res(false);
setTimeout(tick, 200);
};
tick();
})""", timeout * 1000)
return page.evaluate("""async (a) => {
return await new Promise((resolve) => {
if (!window.grecaptcha || !window.grecaptcha.enterprise) return resolve('ERR:no_enterprise');
window.grecaptcha.enterprise.ready(async () => {
try {
const t = await window.grecaptcha.enterprise.execute(a.sitekey, {action: a.action});
resolve(t || 'ERR:empty_token');
} catch (e) { resolve('ERR:' + e.message); }
});
});
}""", {'sitekey': sitekey, 'action': action})
def click_visible_challenge(page):
"""If an invisible captcha escalated to a visible anchor/bframe, try clicking
the checkbox inside the anchor iframe."""
try:
for f in page.frames:
if 'recaptcha/enterprise/anchor' in (f.url or ''):
box = f.query_selector('#recaptcha-anchor')
if box:
box.click()
time.sleep(3)
return True
except Exception:
pass
return False
+345
View File
@@ -0,0 +1,345 @@
#!/usr/bin/env python3
"""
Netlify Farm Dashboard — web control panel for the netlify-autoreg pipeline.
Features
* account table: email, status (alive / suspended / rate-limited / unknown), site, site HTTP code
* actions: check all accounts (login probe), run a registration wave, deploy to all sites, refresh tokens
* live log stream (SSE) of every background job
* per-account row actions: check, deploy, open site
Run:
python dashboard.py --port 8791
UI: http://127.0.0.1:8791/
State is kept next to the bank file in state.json.
"""
import argparse, json, os, re, subprocess, sys, threading, time, queue
from pathlib import Path
from typing import Dict, Any, List
import httpx
import urllib.request, urllib.error
from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse, StreamingResponse, JSONResponse
HERE = Path(__file__).parent.resolve()
BANK = Path(os.environ.get('NETLIFY_BANK', HERE / 'netlify_bank.jsonl'))
STATE = Path(os.environ.get('NETLIFY_STATE', HERE / 'state.json'))
FARM = HERE / 'netlify_farm.py'
PY = os.environ.get('NETLIFY_PY', r'C:\Users\User\AppData\Local\Programs\Python\Python311\python.exe')
sys.path.insert(0, str(HERE))
from netlify_farm import login, api_call, deploy_static # noqa: E402
app = FastAPI(title='Netlify Farm Dashboard')
LOG: "queue.Queue[str]" = queue.Queue()
RUNNING: Dict[str, bool] = {'wave': False, 'check': False, 'deploy': False}
def log(msg: str):
line = f"[{time.strftime('%H:%M:%S')}] {msg}"
LOG.put(line)
try:
print(line, flush=True)
except Exception:
try:
print(line.encode('ascii', 'replace').decode(), flush=True)
except Exception:
pass
def load_bank() -> List[Dict[str, Any]]:
if not BANK.exists():
return []
return [json.loads(l) for l in BANK.read_text(encoding='utf-8').splitlines() if l.strip()]
def load_state() -> Dict[str, Any]:
if STATE.exists():
try:
return json.loads(STATE.read_text(encoding='utf-8'))
except Exception:
pass
return {}
def save_state(st: Dict[str, Any]):
STATE.write_text(json.dumps(st, ensure_ascii=False, indent=1), encoding='utf-8')
def site_http(domain: str) -> int:
if not domain:
return 0
try:
with urllib.request.urlopen('https://' + domain, timeout=12) as r:
return r.status
except urllib.error.HTTPError as e:
return e.code
except Exception:
return 0
def check_account(rec: Dict[str, Any], st: Dict[str, Any]) -> Dict[str, Any]:
"""Login-probe one account. Updates state in place."""
email = rec['email']
prev = st.get(email) or {}
try:
tok, msg = login(email, rec['password'])
except Exception as e:
tok, msg = None, f'exc {e}'
now = time.strftime('%Y-%m-%d %H:%M:%S')
if tok:
prev.update({'status': 'alive', 'msg': 'ok', 'token': tok, 'checked': now})
elif 'suspended' in str(msg).lower():
prev.update({'status': 'suspended', 'msg': msg, 'checked': now})
elif '429' in str(msg):
prev.update({'status': 'rate_limited', 'msg': msg, 'checked': now})
else:
prev.update({'status': 'error', 'msg': msg, 'checked': now})
st[email] = prev
return prev
def job_check(limit: int = 0, pause: float = 2.5):
if RUNNING['check']:
log('check: уже идёт')
return
RUNNING['check'] = True
try:
recs = load_bank()
if limit:
recs = recs[:limit]
st = load_state()
log(f'check: {len(recs)} аккаунтов')
alive = susp = rl = 0
for i, r in enumerate(recs, 1):
res = check_account(r, st)
s = res['status']
alive += s == 'alive'; susp += s == 'suspended'; rl += s == 'rate_limited'
log(f" [{i}/{len(recs)}] {r['email']}: {s} {res.get('msg','')}")
save_state(st)
if s == 'rate_limited':
log(' login rate-limited by IP, пауза 60с')
time.sleep(60)
else:
time.sleep(pause)
log(f'check готово: alive={alive} suspended={susp} rate_limited={rl}')
finally:
RUNNING['check'] = False
def job_wave(count: int):
if RUNNING['wave']:
log('wave: уже идёт')
return
RUNNING['wave'] = True
try:
log(f'wave: {count} аккаунтов')
env = dict(os.environ)
env.pop('PYTHONPATH', None)
p = subprocess.Popen([PY, str(FARM), '--count', str(count), '--site'],
cwd=str(HERE), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
text=True, encoding='utf-8', errors='replace', env=env, bufsize=1)
for line in p.stdout:
log(' farm| ' + line.rstrip())
p.wait()
log(f'wave готово, exit={p.returncode}')
finally:
RUNNING['wave'] = False
def job_deploy():
if RUNNING['deploy']:
log('deploy: уже идёт')
return
RUNNING['deploy'] = True
try:
recs = load_bank()
st = load_state()
log(f'deploy: {len(recs)} сайтов')
ok = 0
for r in recs:
sid, dom = r.get('site_id'), r.get('site_domain') or ''
tok = (st.get(r['email']) or {}).get('token') or r.get('token')
if not (sid and tok):
log(f" {r['email']}: пропуск (нет site/token)")
continue
try:
api_call(tok, f'/api/v1/sites/{sid}', 'PATCH',
{'sso_login': False, 'account_sso_login': False})
except Exception:
pass
good, dep, state = deploy_static(tok, sid,
f"<html><body><h1>{r['email']}</h1></body></html>")
code = 0
for _ in range(5):
time.sleep(4)
code = site_http(dom)
if code == 200:
break
ok += code == 200
st.setdefault(r['email'], {})['site_http'] = code
log(f" {r['email']}: deploy={'ok' if good else 'fail'} http={code}")
save_state(st)
log(f'deploy готово: {ok}/{len(recs)} отдают 200')
finally:
RUNNING['deploy'] = False
def job_token(email: str):
st = load_state()
recs = {r['email']: r for r in load_bank()}
r = recs.get(email)
if not r:
log(f'token: {email} не найден')
return
res = check_account(r, st)
save_state(st)
log(f"token: {email} -> {res['status']} {res.get('msg','')}")
def run_bg(fn, *a):
threading.Thread(target=fn, args=a, daemon=True).start()
# ---------------- API ----------------
@app.get('/api/state')
def api_state():
recs = load_bank()
st = load_state()
rows = []
for r in recs:
s = st.get(r['email']) or {}
rows.append({
'email': r['email'],
'status': s.get('status', 'unknown'),
'msg': s.get('msg', ''),
'checked': s.get('checked', ''),
'site': r.get('site_domain') or '',
'site_http': s.get('site_http', None),
'has_site': bool(r.get('site_id')),
'ts': r.get('ts', ''),
})
counts = {}
for row in rows:
counts[row['status']] = counts.get(row['status'], 0) + 1
return JSONResponse({'rows': rows, 'total': len(rows), 'counts': counts, 'running': RUNNING})
@app.post('/api/check')
def api_check(n: int = 0):
run_bg(job_check, n)
return {'ok': True}
@app.post('/api/wave')
def api_wave(n: int = 3):
run_bg(job_wave, n)
return {'ok': True}
@app.post('/api/deploy')
def api_deploy():
run_bg(job_deploy)
return {'ok': True}
@app.post('/api/token')
async def api_token(req: Request):
d = await req.json()
run_bg(job_token, d.get('email', ''))
return {'ok': True}
@app.get('/api/log')
async def api_log():
async def gen():
while True:
try:
line = LOG.get(timeout=1.0)
except queue.Empty:
yield ': ping\n\n'
continue
yield 'data: ' + json.dumps({'line': line}, ensure_ascii=False) + '\n\n'
return StreamingResponse(gen(), media_type='text/event-stream',
headers={'Cache-Control': 'no-cache', 'X-Accel-Buffering': 'no'})
HTML = """<!doctype html><html><head><meta charset="utf-8"><title>Netlify Farm</title>
<style>
*{box-sizing:border-box}
body{background:#0b0f14;color:#c9d1d9;font:13px/1.5 ui-monospace,Consolas,monospace;margin:0;padding:16px}
h2{margin:0 0 12px;font-size:16px;color:#e6edf3}
.bar{display:flex;gap:8px;flex-wrap:wrap;margin-bottom:12px;align-items:center}
button{background:#1f6feb;color:#fff;border:0;border-radius:6px;padding:7px 12px;cursor:pointer;font:inherit}
button.gray{background:#21262d;border:1px solid #30363d}
button:disabled{opacity:.5;cursor:default}
input{background:#161b22;color:#c9d1d9;border:1px solid #30363d;border-radius:6px;padding:6px 8px;width:70px;font:inherit}
.stats{display:flex;gap:14px;margin-bottom:10px;font-size:12px}
.stats b{color:#7ee787}
table{width:100%;border-collapse:collapse;font-size:12px}
th,td{text-align:left;padding:6px 8px;border-bottom:1px solid #21262d}
th{color:#8b949e;font-weight:400;position:sticky;top:0;background:#0b0f14}
.alive{color:#7ee787}.suspended{color:#ff7b72}.rate_limited{color:#e3b341}.unknown{color:#8b949e}.error{color:#ffa657}
a{color:#58a6ff;text-decoration:none}
#log{background:#010409;border:1px solid #21262d;border-radius:8px;padding:10px;height:230px;overflow:auto;white-space:pre-wrap;font-size:11.5px;margin-top:14px}
.act{background:transparent;border:1px solid #30363d;color:#8b949e;padding:2px 7px;border-radius:5px;font-size:11px;cursor:pointer}
</style></head><body>
<h2>NETLIFY FARM</h2>
<div class="stats" id="stats"></div>
<div class="bar">
<button onclick="act('/api/check',{n:0})">Проверить все</button>
<button class="gray" onclick="act('/api/check',{n:5})">Проверить 5</button>
<button onclick="act('/api/deploy')">Деплой всем</button>
<span style="margin-left:14px">Волна:</span>
<input id="waveN" value="3">
<button onclick="act('/api/wave',{n:+document.getElementById('waveN').value})">Регистрировать</button>
<button class="gray" onclick="location.reload()">Обновить</button>
</div>
<table><thead><tr><th>email</th><th>статус</th><th>сообщение</th><th>проверено</th><th>сайт</th><th>http</th><th>действия</th></tr></thead>
<tbody id="rows"></tbody></table>
<div id="log"></div>
<script>
async function act(url,body){
await fetch(url,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body||{})});
setTimeout(refresh,700);
}
async function refresh(){
const d=await (await fetch('/api/state')).json();
const c=d.counts||{};
document.getElementById('stats').innerHTML =
'всего <b>'+d.total+'</b> · живых <b>'+(c.alive||0)+'</b> · suspended <b>'+(c.suspended||0)+
'</b> · rate-limited <b>'+(c.rate_limited||0)+'</b> · неизвестно <b>'+(c.unknown||0)+'</b>';
document.getElementById('rows').innerHTML = d.rows.map(r=>`<tr>
<td>${r.email}</td>
<td class="${r.status}">${r.status}</td>
<td>${(r.msg||'').slice(0,40)}</td>
<td>${(r.checked||'').slice(11)}</td>
<td>${r.site? '<a href="https://'+r.site+'" target="_blank">'+r.site+'</a>':'-'}</td>
<td>${r.site_http??'-'}</td>
<td>
<button class="act" onclick="act('/api/token',{email:'${r.email}'})">токен</button>
<button class="act" onclick="act('/api/deploy')">деплой</button>
</td></tr>`).join('');
}
const es=new EventSource('/api/log');
es.onmessage=e=>{const el=document.getElementById('log');
try{const d=JSON.parse(e.data); el.textContent += d.line+'\\n'; el.scrollTop=el.scrollHeight;}catch(_){} };
refresh(); setInterval(refresh, 15000);
</script></body></html>"""
@app.get('/', response_class=HTMLResponse)
def index():
return HTML
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument('--port', type=int, default=8791)
a = ap.parse_args()
import uvicorn
print(f'dashboard on http://127.0.0.1:{a.port}/ bank={BANK} exists={BANK.exists()}')
uvicorn.run(app, host='127.0.0.1', port=a.port, log_level='warning')
+39
View File
@@ -0,0 +1,39 @@
#!/usr/bin/env python3
"""Deploy a minimal page to every site in netlify_bank.jsonl and verify HTTP 200."""
import json, os, sys, time, urllib.request
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from netlify_farm import api_call, deploy_static
BANK = os.environ.get('NETLIFY_BANK', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'netlify_bank.jsonl'))
recs = [json.loads(l) for l in open(BANK, encoding='utf-8') if l.strip()]
ok = 0
for r in recs:
sid, tok = r.get('site_id'), r.get('token')
if not sid or not tok:
continue
try:
api_call(tok, f'/api/v1/sites/{sid}', 'PATCH',
{'sso_login': False, 'account_sso_login': False})
except Exception:
pass
good, dep = deploy_static(tok, sid, f"<html><body><h1>{r['email']}</h1></body></html>")[:2]
time.sleep(1)
code = 0
dom = r.get('site_domain')
for _ in range(6):
if not dom:
break
try:
with urllib.request.urlopen('https://' + dom, timeout=12) as resp:
code = resp.status
except urllib.error.HTTPError as e:
code = e.code
except Exception:
code = 0
if code == 200:
break
time.sleep(5)
print(f"{r['email']:<40} deploy={'ok' if good else 'FAIL'} http={code}")
if code == 200:
ok += 1
print(f'\nlive: {ok}/{len(recs)}')
+79
View File
@@ -0,0 +1,79 @@
# Netlify API surface
Everything below was exercised with a fresh account token (`nfu_…`) obtained from
the signup flow. The token behaves like an ordinary bearer for the whole v1 API.
## Auth tokens
| kind | prefix | how to get | use |
|---|---|---|---|
| session access token | `nfu_` | `POST /auth/verify` result | everything in `/api/v1` |
| personal access token | `nfp_` | UI only: `/user/applications#personal-access-tokens` → *New access token* → *Generate token* | `netlify-cli`, long-lived scripts |
There is **no API endpoint** to create a PAT. `POST /api/v1/access_tokens`
returns the OAuth discovery root, not a token factory. Automate the UI with a
browser if you need `nfp_` (needed only for CLI deploys of functions).
## Endpoints (verified)
```
GET /api/v1/user → current profile
GET /api/v1/accounts → account object + capabilities
GET /api/v1/accounts/{id} → full capability matrix
GET /api/v1/sites → your sites
POST /api/v1/sites {name} → create site
GET /api/v1/sites/{id} → site detail (sso flags, build settings)
PATCH /api/v1/sites/{id} → update (sso_login, build_settings, …)
POST /api/v1/sites/{id}/deploys → zip deploy (Content-Type: application/zip)
GET /api/v1/sites/{id}/deploys/{did} → deploy state + summary messages
GET /api/v1/dns_zones → DNS zones (0 on fresh accounts)
GET /api/v1/accounts/{id}/env → env vars (empty until you add some)
GET /api/v1/ai-gateway/providers/detailed → model catalog + pricing
GET /api/v1/ai-gateway/providers → model ids per provider
```
404 on `/api/v1/forms`, `/api/v1/deploys`, `/api/v1/hooks`, `/api/v1/builds` —
those are site-scoped only.
## Free plan capabilities (snapshot)
```
sites: 500 domains: 10 collaborators: 1
credits: 300 concurrent_builds: 1 identity: true
firewall: true traffic_rules: 2 analytics: true
dev_servers: 1 agent_runners: 1 netlify_server: true
custom_provider_credentials: true ai_gateway_disabled: false
```
## AI Gateway
Catalog: **281 models** across six providers, exposed with per-model pricing.
| provider | env vars | models |
|---|---|---|
| anthropic | `ANTHROPIC_API_KEY`, `ANTHROPIC_BASE_URL` | 18 (claude-opus-5-5, sonnet-5-5, fable-5-x, haiku-5-5) |
| openai | `OPENAI_API_KEY`, `OPENAI_BASE_URL` | 48 (gpt-6.1-sol/terra, gpt-6-astra/luna, gpt-5.4-*, images) |
| gemini | `GEMINI_API_KEY`, `GOOGLE_GEMINI_BASE_URL` | 18 (gemini-4-argon/carbon, 3.8-flash) |
| openrouter | `OPENROUTER_API_KEY`, `OPENROUTER_BASE_URL` | 188 (grok-4.7, kimi-k3, deepseek-v4.1, qwen3.8, glm-5.3) |
| meta | `META_API_KEY`, `META_BASE_URL` | 5 (muse-*) |
| typesafe | `TYPESAFE_API_KEY`, `TYPESAFE_BASE_URL` | 4 |
Credentials are injected **only into function runtime env**, and only when the
project has AI Gateway enabled. On a fresh free account a deployed function
enumerates 37 environment variables and **none** of them are AI keys;
`/projects/{slug}/configuration/general/ai-gateway` does not exist for the free
plan. `ai_gateway_disabled: false` in the capability matrix means "not blocked by
policy", not "provisioned".
Billing: token usage is converted into the account credit pool (300 credits on
free).
## Function deployment constraints
- Manual (zip) deploys never compile functions — the deploy summary reports
`No functions deployed`.
- Functions require `netlify-cli deploy --prod --no-build` after `netlify link --id <site>`.
- netlify-cli 17.x ignores `NETLIFY_AUTH_TOKEN`; it reads the PAT from
`%APPDATA%/netlify/Config/config.json` under `users.<uid>.auth.token`.
- A function bundled as `netlify/functions/<name>.zip` in the site zip is also
ignored — the API path only accepts CLI-bundled artifacts.
+303
View File
@@ -0,0 +1,303 @@
# Полный гайд: свой OpenAI/Anthropic-совместимый шлюз на бесплатном Netlify
Коротко: любой free-проект Netlify получает доступ к их AI Gateway. Каталог — 281 модель
(Claude Opus 5.5, GPT-6.1 Sol, Gemini 4 Argon, Grok 4.7, Kimi K3, DeepSeek V4.1, GLM 5.3).
Ключ и база живут в переменных окружения **edge-функции** (Deno), а не обычной функции.
Проксируешь шлюз своей edge-функцией — получаешь личный эндпоинт `/ai/v1/...`, который
работает как обычный OpenAI/Anthropic API.
Проверено 11.11.2026: 15/15 моделей отвечают 200, стриминг и tool use работают.
---
## 1. Что нужно
| нужно | зачем | где взять |
|---|---|---|
| аккаунт Netlify (free) | 300 кредитов на шлюз | авторег (`netlify_farm.py`) или руками |
| сайт в аккаунте | шлюз привязан к домену сайта | `POST /api/v1/sites` |
| одна edge-функция | она видит ключ и проксирует | код ниже, деплой CLI или drag-n-drop |
| Node + netlify-cli (для CLI-деплоя) | удобно | или залить через UI |
Время: 5 минут на аккаунт, если аккаунт уже есть.
---
## 2. Шаг 1 — аккаунт
Авторег (быстро, пачкой):
```bash
python netlify_farm.py --count 1 --site \
--mails "C:/path/to/mails.txt" \
--bank "C:/path/to/netlify_bank.jsonl"
```
Руками: `app.netlify.com/signup/email`, email + пароль. Капча невидимая, обычно проходит сама.
Внимание: gmail с `+алиасом` форма отбивает как «Email address is invalid» — нужен обычный ящик.
Из ответа сохрани `token` (`nfu_...`) и `site_id`.
---
## 3. Шаг 2 — сайт
```bash
curl -X POST https://api.netlify.com/api/v1/sites \
-H "Authorization: Bearer $NF_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"name":"my-ai-gw"}'
```
Сразу сними SSO-замок, иначе публичный URL отдаёт 401:
```bash
curl -X PATCH https://api.netlify.com/api/v1/sites/$SITE_ID \
-H "Authorization: Bearer $NF_TOKEN" \
-H 'Content-Type: application/json' \
-d '{"sso_login":false,"account_sso_login":false}'
```
---
## 4. Шаг 3 — edge-функция прокси
Создай в проекте файл `netlify/edge-functions/ai-proxy.ts`:
```ts
export default async (req: Request, _ctx: any) => {
// ключ читаем НА КАЖДЫЙ запрос: JWT живёт минуты и ротируется
const KEY = Deno.env.get('NETLIFY_AI_GATEWAY_KEY') || '';
const SECRET = Deno.env.get('PROXY_SECRET') || '';
if (SECRET && req.headers.get('x-proxy-secret') !== SECRET) {
return new Response('{"error":"unauthorized"}', {status: 401, headers: {'content-type':'application/json'}});
}
const url = new URL(req.url);
const upstream = `${url.origin}/.netlify/ai${url.pathname.replace(/^\/ai/, '')}${url.search}`;
const headers: Record<string,string> = {
authorization: `Bearer ${KEY}`,
'x-api-key': KEY,
'content-type': req.headers.get('content-type') || 'application/json',
accept: req.headers.get('accept') || 'application/json',
};
const av = req.headers.get('anthropic-version');
if (av) headers['anthropic-version'] = av;
const init: RequestInit = { method: req.method, headers };
if (req.method !== 'GET' && req.method !== 'HEAD') {
init.body = req.body;
// @ts-ignore требуется Deno для стриминга тела запроса
init.duplex = 'half';
}
const r = await fetch(upstream, init);
return new Response(r.body, {
status: r.status,
headers: {
'content-type': r.headers.get('content-type') || 'application/json',
'cache-control': 'no-store',
'x-gateway-status': String(r.status),
},
});
};
export const config = { path: "/ai/*" };
```
Три правила, без которых не работает:
1. `Deno.env.get(...)` **внутри** обработчика, не в константе модуля. Ключ ротируется, а константа
кешируется на деплое и через несколько минут даёт 401.
2. `init.duplex = 'half'` при передаче `req.body`, иначе Deno бросает `TypeError: duplex`.
3. `export const config = { path: "/ai/*" }` — без этого маршрут не зарегистрируется.
Деплой через CLI:
```bash
netlify link --id $SITE_ID # привязать каталог к сайту
netlify deploy --prod --no-build --dir="$PWD"
```
`--no-build` обязателен, иначе Netlify попытается собрать проект (часто падает на hugo/jekyll).
Деплой через UI: создай на сайте файл тем же путём и задеплой проект как обычно.
---
## 5. Шаг 4 — проверка
```bash
S="https://<твой-сайт>.netlify.app/ai"
# OpenAI-совместимый вызов
curl -s -X POST "$S/v1/chat/completions" -H 'Content-Type: application/json' -d '{
"model":"gpt-6.1-sol",
"messages":[{"role":"user","content":"Reply with OK"}]
}'
# Anthropic-совместимый вызов
curl -s -X POST "$S/v1/messages" \
-H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' \
-d '{"model":"claude-opus-5-5","max_tokens":50,"messages":[{"role":"user","content":"Reply OK"}]}'
# стриминг
curl -sN -X POST "$S/v1/chat/completions" -H 'Content-Type: application/json' -d '{
"model":"gpt-6.1-sol","messages":[{"role":"user","content":"Count 1 to 5"}],"stream":true
}'
# tool use (Anthropic shape)
curl -s -X POST "$S/v1/messages" -H 'Content-Type: application/json' -H 'anthropic-version: 2023-06-01' -d '{
"model":"claude-opus-5-5","max_tokens":200,
"messages":[{"role":"user","content":"Weather in Berlin? Use tool."}],
"tools":[{"name":"get_weather","description":"weather",
"input_schema":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}]
}'
# ответ: stop_reason=tool_use, content[0].input={"city":"Berlin"}
```
Ожидаемый результат: 200 и текст. Если 401 — см. FAQ.
---
## 6. Использование из кода
### Python (openai SDK)
```python
from openai import OpenAI
client = OpenAI(base_url="https://<сайт>.netlify.app/ai/v1", api_key="unused")
r = client.chat.completions.create(
model="claude-opus-5-5", # да, Claude через OpenAI-схему тоже идёт
messages=[{"role": "user", "content": "say OK"}],
)
print(r.choices[0].message.content)
```
### Python (anthropic SDK)
```python
from anthropic import Anthropic
client = Anthropic(base_url="https://<сайт>.netlify.app/ai", api_key="unused")
r = client.messages.create(
model="claude-opus-5-5", max_tokens=200,
messages=[{"role": "user", "content": "say OK"}],
)
print(r.content[0].text)
```
### OpenAI-совместимые клиенты (Cursor, Cline, LiteLLM, any)
```
Base URL: https://<сайт>.netlify.app/ai/v1
API key: любой непустой (если PROXY_SECRET не задан), иначе тот же секрет в заголовке
Model: gpt-6.1-sol / claude-opus-5-5 / gemini-4-argon / ...
```
---
## 7. Модели
Проверенные (все 200, замер латентности на коротком промпте):
| модель | id | латентность |
|---|---|---|
| GPT-6.1 Sol | `gpt-6.1-sol` | 2.3s |
| GPT-6 Astra | `gpt-6-astra` | 2.3s |
| GPT-6 Luna | `gpt-6-luna` | 3.0s |
| GPT-5.5 | `gpt-5.5` | 1.7s |
| GPT-5.4 mini | `gpt-5.4-mini` | 1.3s |
| Claude Opus 5.5 | `claude-opus-5-5` | 2.3s |
| Claude Sonnet 5.5 | `claude-sonnet-5-5` | 1.9s |
| Claude Haiku 5.5 | `claude-haiku-5-5` | 1.3s |
| Claude Fable 5.2 | `claude-fable-5-2` | 2.8s |
| Gemini 4 Argon | `gemini-4-argon` | 7.7s |
| Gemini 3.8 Flash | `gemini-3.8-flash` | 2.3s |
| Grok 4.7 | `x-ai/grok-4.7` | 5.6s |
| Kimi K3 | `moonshotai/kimi-k3` | 1.3s |
| DeepSeek V4.1 Flash | `deepseek/deepseek-v4.1-flash-1017` | 1.2s |
| GLM 5.3 | `z-ai/glm-5.3` | 1.3s |
Полный каталог без авторизации:
```bash
curl -s https://api.netlify.com/api/v1/ai-gateway/providers/detailed | jq '.providers | to_entries[] | {p:.key, n:(.value.models|length)}'
```
Модели OpenRouter-нотации (`x-ai/`, `moonshotai/`, `deepseek/`, `z-ai/`) идут через OpenRouter-плечо,
они доступны только при Zero Data Retention у провайдера.
Цены берутся из того же ответа: `claude-opus-5-5` $4/$20 за 1M, `gpt-6.1-sol` $2/$10,
`gemini-4-argon` $2/$10, `claude-haiku-5-5` $1/$5.
---
## 8. Лимиты и экономика
- **300 кредитов** на аккаунт. Расход считается по токенам, курс виден в кабинете Netlify.
- контекст **200k** токенов на запрос.
- один аккаунт = один шлюз. Больше аккаунтов = больше суммарного лимита, но каждый требует
своего сайта и своей edge-функции.
- кэш промпта: Anthropic — стандартные 5 минут, OpenAI — `prompt_cache_key` на аккаунт.
- таймаут edge-функции ~30-50 с: длинные стримы рвать на части, а не ждать одним куском.
---
## 9. Минусы (проверено)
| минус | деталь | обход |
|---|---|---|
| кредитов мало | 300 на аккаунт, хватает на день работы | несколько аккаунтов/сайтов |
| ключ короткий | JWT 497 симв., живёт минуты | читать `Deno.env` в каждом запросе (уже в коде) |
| база прибита к домену | снаружи нужен именно твой сайт | свой домен/алиас на тот же сайт |
| Lambda не видит ключи | в обычных функциях 37 env без AI | только Edge Functions (Deno) |
| `max_tokens` в chat | 400 `unsupported_parameter` | не передавать, либо `max_completion_tokens` |
| tools в chat/completions | у gpt-6.1-sol 400 (конфликт с reasoning) | `POST /v1/responses` или Anthropic `/v1/messages` |
| ручная модерация | `Account suspended`, `spam: manual` | чистые ящики, ровный темп |
| логин 429 | после ~20 проб с IP | пауза, ротация egress |
| Chrome умирает | падает на 4-м аккаунте | перезапуск браузера каждые 3 аккаунта |
---
## 10. FAQ
**401 от `/ai/...`**
1. Ключ прочитан на уровне модуля → перенести `Deno.env.get` внутрь обработчика.
2. Edge-функция не задеплоилась: проверь `netlify deploy --prod --no-build` вывод, должно быть
«Edge function ... deployed».
3. `PROXY_SECRET` задан, а заголовок `x-proxy-secret` не передан.
**404 на `/ai/v1/chat/completions`**
Нет `export const config = { path: "/ai/*" }` или путь отличается.
**`unsupported_parameter: max_tokens`**
Убрать параметр. Для ограничения длины — `max_completion_tokens`.
**`Function tools with reasoning_effort are not supported`**
Использовать `/v1/responses` для OpenAI-моделей или `/v1/messages` для Anthropic.
**Пустой ответ, `finish_reason=length`**
У reasoning-моделей бюджет уходит в thinking. Поднять лимит до 512+ или не ограничивать.
**Сайт отдаёт 401 с «Login Redirect»**
Не снят SSO-замок: `PATCH /api/v1/sites/{id} {"sso_login":false,"account_sso_login":false}`.
---
## 11. Мультиаккаунт
Один шлюз = один сайт. Схема на N аккаунтов:
```
account_1 -> site_1 -> edge fn -> https://site1.netlify.app/ai
account_2 -> site_2 -> edge fn -> https://site2.netlify.app/ai
...
```
Клиент (LiteLLM, свой роутер) держит список base_url и переключает при 429/исчерпании кредитов.
Авторег и деплой обоих шагов — в `netlify_farm.py` и `deploy_all.py` этого репозитория.
Дашборд по аккаунтам: `python dashboard.py --port 8791`.
+172
View File
@@ -0,0 +1,172 @@
# Netlify signup — reverse engineering notes
Captured 2026-11-11 from a live Chrome session on `app.netlify.com`.
## 1. Front-end page
- `https://app.netlify.com/signup` — provider chooser (Google / GitHub / email / SSO)
- `https://app.netlify.com/signup/email` — the real form (email + password)
The page loads webpack chunks (`actions.*.js`, `app.*.js`, `lib.*.js`,
`helpers.*.js`). The captcha wrapper lives in `helpers`, the API client in `lib`
(`apiBase`, `captcha_source`, `authLink`, `async authenticate()`).
## 2. reCAPTCHA Enterprise
```html
<iframe src="https://www.google.com/recaptcha/enterprise/anchor
?k=6Lfj2-EtAAAAAABMy0F1oAGRPQOCTZhnt1KQ7Xat
&co=aHR0cHM6Ly9hcHAubmV0bGlmeS5jb206NDQz
&size=invisible&sa=SIGNUP">
```
- sitekey: `6Lfj2-EtAAAAAABMy0F1oAGRPQOCTZhnt1KQ7Xat`
- action: **`SIGNUP`** (visible as `sa=SIGNUP` on the anchor iframe)
- size: `invisible`, render args include `anchor-ms=20000&execute-ms=30000`
Token acquisition inside the page:
```js
await new Promise(res => grecaptcha.enterprise.ready(async () => {
res(await grecaptcha.enterprise.execute(SITEKEY, {action: 'SIGNUP'}));
}));
// → 2400-2500 char token
```
### Solver tokens are rejected
| attempt | token | result |
|---|---|---|
| no captcha | `""` | `Please complete the security check` |
| fake | `test_token` | same |
| 2captcha, `RecaptchaV2EnterpriseTaskProxyless`, action SIGNUP | 2425 chars | same |
| in-page `enterprise.execute` | 2510 chars | **`success`** |
## 3. Signup endpoint
```
POST 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
```
Headers: `Content-Type: application/json`, `Origin: https://app.netlify.com`,
`Referer: https://app.netlify.com/signup/email`.
Body:
```json
{
"email": "…",
"password": "…",
"invite_code": null,
"no_autosignup": false,
"redirect": "https://app.netlify.com",
"entry_point": "direct",
"captcha_response": "<token>",
"captcha_source": "google",
"browser_fingerprint": "<32 hex>",
"device_fingerprint": "<32 hex>"
}
```
`browser_fingerprint` / `device_fingerprint` are optional — the real form sends
them, but the request succeeds without them. They come from a fingerprint
module loaded lazily (`l.u$.getFingerprints()` in `lib.js`).
Success:
```json
{"state":"success","verify":true,"code_id":"6af4928ee9f2819062b957cb"}
```
Failure variants seen:
```json
{"state":"error","message":"Please complete the security check and try again."}
{"state":"error","message":"Email address is invalid"}
```
The second one fires for gmail `+alias` addresses — Netlify validates the mailbox
format and rejects plus-addressing.
## 4. Email verification
Subject: `[Netlify] Let's verify your email` from `team@netlify.com`.
The link is:
```
https://app.netlify.com/signup?redirect=…#verify_token=<code_id>-<8 digits>&new_user=true
```
Both halves matter: `code_id` is the 24-hex string returned by signup, the second
part is the secret.
## 5. Verify endpoint
```
POST https://api.netlify.com/auth/verify
Content-Type: application/json
{"code_id":"6af4928ee9f2819062b957cb","code":"79923092"}
```
Success returns the full user object including `access_token` (`nfu_…`),
`account_id`, `id`, `login_providers: ["password"]`, `has_pending_email_verification: false`.
In the bundle this is `verifyUserByToken()`: it splits the token on `-` into
`code_id` + `code` and POSTs `/auth/verify` with `noPrefix: true`.
There is also `PUT /users/{id}/confirm_email {secret}` (`verifyUser`) used by the
in-app flow.
## 6. Sites
### New accounts are SSO-locked
`POST /api/v1/sites` succeeds, deployment succeeds, and the public URL returns
**401 Unauthorized** with a `Login Redirect` body. The site object has:
```json
{"sso_login": true, "sso_login_context": "all",
"account_sso_login": true, "account_sso_login_context": "all"}
```
Fix:
```
PATCH /api/v1/sites/{site_id}
{"sso_login": false, "account_sso_login": false}
```
After that the same URL returns 200.
### Deploy
```
POST /api/v1/sites/{site_id}/deploys
Authorization: Bearer nfu_…
Content-Type: application/zip
<body: raw zip bytes>
```
Response: `{"id":"…","state":"uploaded", …}`; the deploy transitions
`uploaded → ready` within ~10-15s (`published_deploy` points at it).
### Build settings
A site created via API may inherit `build_settings.cmd = "hugo"` from the
project template, which breaks CLI deploys. Reset with
`PATCH /api/v1/sites/{id} {"build_settings":{"cmd":"","dir":"","publish":""}}`
or always pass `--no-build`.
## 7. Account creation counters
Nothing rate-limited us at 15 accounts from a single residential IP. Every
account: signup → verify → site → deploy → 200. The wall is the mailbox pool, not
the API.
+50
View File
@@ -0,0 +1,50 @@
// Netlify Edge Function: pass-through proxy to the project's AI Gateway.
// Deploy at netlify/edge-functions/ai-proxy.ts, then call:
// POST https://<your-site>/ai/v1/chat/completions
// POST https://<your-site>/ai/v1/messages (Anthropic shape)
// Keeps the short-lived gateway JWT server-side, so clients never see it.
// Optional shared secret: set PROXY_SECRET env var in the Netlify UI and send x-proxy-secret.
export default async (req: Request, _ctx: any) => {
// read per-request: the gateway JWT rotates and must not be cached at module scope
const GATEWAY_KEY = Deno.env.get('NETLIFY_AI_GATEWAY_KEY') || '';
const PROXY_SECRET = Deno.env.get('PROXY_SECRET') || '';
if (PROXY_SECRET && req.headers.get('x-proxy-secret') !== PROXY_SECRET) {
return new Response(JSON.stringify({ error: { message: 'unauthorized' } }), {
status: 401, headers: { 'content-type': 'application/json' },
});
}
const url = new URL(req.url);
const path = url.pathname.replace(/^\/ai/, ''); // /v1/chat/completions
const upstream = `${url.origin}/.netlify/ai${path}${url.search}`;
const headers: Record<string, string> = {
authorization: `Bearer ${GATEWAY_KEY}`,
'x-api-key': GATEWAY_KEY,
'content-type': req.headers.get('content-type') || 'application/json',
accept: req.headers.get('accept') || 'application/json',
};
const anth = req.headers.get('anthropic-version');
if (anth) headers['anthropic-version'] = anth;
const init: RequestInit = { method: req.method, headers };
if (req.method !== 'GET' && req.method !== 'HEAD') {
init.body = req.body;
// @ts-ignore duplex is required for streamed request bodies in Deno
init.duplex = 'half';
}
const r = await fetch(upstream, init);
return new Response(r.body, {
status: r.status,
headers: {
'content-type': r.headers.get('content-type') || 'application/json',
'cache-control': 'no-store',
'x-gateway-status': String(r.status),
},
});
};
export const config = { path: "/ai/*" };
+13
View File
@@ -0,0 +1,13 @@
export default async (req: Request, ctx: any) => {
const keys = Object.keys(Deno.env.toObject()).sort();
const picked: Record<string, string> = {};
for (const k of keys) {
if (/API_KEY|BASE_URL|GATEWAY|OPENAI|ANTHROPIC|GEMINI|OPENROUTER|META|TYPESAFE/i.test(k)) {
picked[k] = Deno.env.get(k) || '';
}
}
return new Response(JSON.stringify({ count: keys.length, keys, picked }, null, 1), {
headers: { 'content-type': 'application/json' },
});
};
export const config = { path: "/envdump" };
+284
View File
@@ -0,0 +1,284 @@
"""Mailbox pool with multi-provider IMAP support.
Handles many pool files, detects the IMAP host by domain, falls back across
candidate hosts, supports POP3 providers (rediffmail) and STARTTLS.
Pool line format: email:password
"""
import email as email_lib
import imaplib
import os
import poplib
import random
import re
import socket
import ssl
import time
# domain -> IMAP host (993, SSL)
IMAP_PRESETS = {
't-online.de': 'secureimap.t-online.de',
'gmail.com': 'imap.gmail.com',
'googlemail.com': 'imap.gmail.com',
'outlook.com': 'outlook.office365.com',
'hotmail.com': 'outlook.office365.com',
'live.com': 'outlook.office365.com',
'yahoo.com': 'imap.mail.yahoo.com',
'rambler.ru': 'imap.rambler.ru',
'lenta.ru': 'imap.rambler.ru',
'ro.ru': 'imap.rambler.ru',
'mail.ru': 'imap.mail.ru',
'inbox.ru': 'imap.mail.ru',
'bk.ru': 'imap.mail.ru',
'list.ru': 'imap.mail.ru',
'yandex.ru': 'imap.yandex.ru',
'ya.ru': 'imap.yandex.ru',
'i.ua': 'imap.i.ua',
'ukr.net': 'imap.ukr.net',
'aliyun.com': 'imap.aliyun.com',
'gmx.de': 'imap.gmx.net',
'gmx.net': 'imap.gmx.net',
'web.de': 'imap.web.de',
'singnet.com.sg': 'imap.singnet.com.sg',
'icn.od.ua': 'imap.icn.od.ua',
'protonmail.com': '127.0.0.1', # bridge only
'zoho.com': 'imap.zoho.com',
'aol.com': 'imap.aol.com',
'mail.com': 'imap.mail.com',
'email.com': 'imap.mail.com',
'posteo.de': 'posteo.de',
'gmx.at': 'imap.gmx.net',
'seznam.cz': 'imap.seznam.cz',
'interia.pl': 'imap.interia.pl',
'o2.pl': 'imap.o2.pl',
'wp.pl': 'imap.wp.pl',
'onet.pl': 'imap.onet.pl',
'naver.com': 'imap.naver.com',
'daum.net': 'imap.daum.net',
}
# domain -> POP3 host (995, SSL) for providers without IMAP
POP3_PRESETS = {
'rediffmail.com': 'pop.rediffmail.com',
}
def domain_of(addr: str) -> str:
return addr.rsplit('@', 1)[-1].lower()
def imap_candidates(addr: str):
d = domain_of(addr)
hosts = []
if d in IMAP_PRESETS:
hosts.append(IMAP_PRESETS[d])
hosts += [f'imap.{d}', f'mail.{d}', f'imap.mail.{d}', d]
seen, out = set(), []
for h in hosts:
if h and h not in seen:
seen.add(h)
out.append(h)
return out
class Mailbox:
"""One mailbox: knows how to fetch messages from it."""
def __init__(self, addr: str, password: str, timeout: int = 20):
self.addr = addr
self.password = password
self.timeout = timeout
self.last_error = ''
# ---------- IMAP ----------
def _imap_connect(self):
d = domain_of(self.addr)
last = ''
for host in imap_candidates(self.addr):
try:
socket.create_connection((host, 993), timeout=6).close()
except Exception as e:
last = f'{host}: {type(e).__name__}'
continue
try:
m = imaplib.IMAP4_SSL(host, timeout=self.timeout)
m.login(self.addr, self.password)
return m, host
except Exception as e:
last = f'{host}: {type(e).__name__}: {str(e)[:50]}'
continue
self.last_error = last or 'no imap host reachable'
return None, None
def _imap_search_from(self, m, sender: str, since_uid: int = 0, limit: int = 8):
"""Some servers (aliyun, rambler) reject SEARCH FROM; fall back to ALL + python filter."""
m.select('INBOX')
ids = []
try:
typ, data = m.search(None, f'(FROM "{sender}")')
if typ == 'OK' and data and data[0]:
ids = data[0].split()
except Exception:
ids = []
if not ids:
try:
typ, data = m.search(None, 'ALL')
if typ == 'OK' and data and data[0]:
ids = data[0].split()[-60:]
ids = [i for i in ids if self._from_matches(m, i, sender)]
except Exception:
ids = []
if since_uid:
ids = [i for i in ids if int(i) > since_uid]
return ids[-limit:]
def _from_matches(self, m, uid: bytes, sender: str) -> bool:
try:
typ, md = m.fetch(uid, '(BODY.PEEK[HEADER.FIELDS (FROM)])')
if not md or not md[0]:
return False
raw = md[0][1]
if isinstance(raw, tuple):
raw = raw[0]
return sender.lower() in raw.decode('utf-8', 'ignore').lower()
except Exception:
return False
def _read_msg(self, m, uid: bytes) -> str:
typ, md = m.fetch(uid, '(RFC822)')
if not md or not md[0]:
return ''
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
return body
def wait_for_link(self, sender: str, pattern: str, timeout: int = 180,
since_uid: int = 0, poll: int = 10):
"""Poll mailbox for a message from `sender` and return first regex match."""
rx = re.compile(pattern)
deadline = time.time() + timeout
while time.time() < deadline:
m, host = self._imap_connect()
if m:
try:
for uid in reversed(self._imap_search_from(m, sender, since_uid)):
body = self._read_msg(m, uid)
hit = rx.search(body)
if hit:
m.logout()
return hit
except Exception as e:
self.last_error = f'{type(e).__name__}: {str(e)[:60]}'
finally:
try:
m.logout()
except Exception:
pass
elif domain_of(self.addr) in POP3_PRESETS:
hit = self._pop3_lookup(sender, rx)
if hit:
return hit
time.sleep(poll)
return None
# ---------- POP3 ----------
def _pop3_lookup(self, sender: str, rx):
host = POP3_PRESETS[domain_of(self.addr)]
try:
ctx = ssl.create_default_context()
try:
ctx.set_ciphers('DEFAULT@SECLEVEL=1')
except Exception:
pass
p = poplib.POP3_SSL(host, 995, timeout=self.timeout, context=ctx)
p.user(self.addr)
p.pass_(self.password)
count = len(p.list()[1])
for i in range(count, max(0, count - 15), -1):
raw = b'\r\n'.join(p.retr(i)[1])
body = raw.decode('utf-8', 'ignore')
if sender.lower() not in body.lower():
continue
hit = rx.search(body)
if hit:
p.quit()
return hit
p.quit()
except Exception as e:
self.last_error = f'pop3 {type(e).__name__}: {str(e)[:50]}'
return None
def alive(self) -> bool:
m, host = self._imap_connect()
if m:
try:
m.select('INBOX')
m.logout()
return True
except Exception:
pass
d = domain_of(self.addr)
if d in POP3_PRESETS:
try:
p = poplib.POP3_SSL(POP3_PRESETS[d], 995, timeout=self.timeout)
p.user(self.addr)
p.pass_(self.password)
p.quit()
return True
except Exception as e:
self.last_error = f'pop3 {type(e).__name__}'
return False
class MailboxPool:
"""Union of several pool files, deduped, with skip-list support."""
def __init__(self, files, skip=None):
self.files = [f for f in files if f and os.path.exists(f)]
self.skip = {s.lower() for s in (skip or [])}
self.items = []
self._load()
def _load(self):
seen = set(self.skip)
for path in self.files:
try:
with open(path, encoding='utf-8', errors='ignore') as f:
for line in f:
line = line.strip()
if not line or line.startswith('#') or ':' not in line:
continue
addr, pwd = line.split(':', 1)
addr, pwd = addr.strip(), pwd.strip()
if '@' not in addr or not pwd:
continue
low = addr.lower()
if low in seen:
continue
seen.add(low)
self.items.append(Mailbox(addr, pwd))
except Exception:
continue
random.shuffle(self.items)
def take(self, n: int):
return self.items[:n]
def domains(self):
from collections import Counter
return Counter(domain_of(m.addr) for m in self.items).most_common(20)
def __len__(self):
return len(self.items)
+379
View File
@@ -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()
+63
View File
@@ -0,0 +1,63 @@
"""Chrome/egress helpers for the Netlify farm (proxy mode + ZTE rotation)."""
import os
import subprocess
import sys
import time
import urllib.request
CHROME_EXE = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
ROTATOR = r'C:\Users\User\tmp\zte_rotate3.py'
ZTE_PROXY = 'http://127.0.0.1:8899'
def cdp_alive(port: int) -> bool:
try:
with urllib.request.urlopen(f'http://127.0.0.1:{port}/json/version', timeout=3) as r:
return r.status == 200
except Exception:
return False
def ensure_chrome(port: int = 9233, profile: str = None, proxy: str = None) -> bool:
"""Start a real Chrome with CDP (optionally behind a proxy) if not already up."""
if cdp_alive(port):
return True
prof = profile or os.path.join(
os.environ.get('LOCALAPPDATA', r'C:\Windows\Temp'), 'hermes', 'cache', 'scratch',
f'nl_prof_{port}')
args = [CHROME_EXE, f'--remote-debugging-port={port}', f'--user-data-dir={prof}',
'--no-first-run', '--no-default-browser-check',
'--disable-blink-features=AutomationControlled']
if proxy:
args.append(f'--proxy-server={proxy}')
args.append('about:blank')
subprocess.Popen(args, env=dict(os.environ))
for _ in range(20):
time.sleep(1.5)
if cdp_alive(port):
return True
return False
def rotate_zte(timeout: int = 120) -> str:
"""Reconnect ZTE PPP; returns new public IP seen through the proxy, or ''."""
try:
subprocess.run([sys.executable, ROTATOR], timeout=timeout,
capture_output=True, text=True, errors='replace')
except Exception:
pass
time.sleep(6)
return egress_ip(ZTE_PROXY)
def egress_ip(proxy: str = None) -> str:
try:
if proxy:
op = urllib.request.build_opener(
urllib.request.ProxyHandler({'http': proxy, 'https': proxy}))
else:
op = urllib.request.build_opener()
with op.open('https://api.ipify.org', timeout=15) as r:
return r.read().decode().strip()
except Exception:
return ''
+1
View File
@@ -0,0 +1 @@
playwright>=1.40