From a676a4a0cf0929fd46bab432b90cfdf6fb2d560f Mon Sep 17 00:00:00 2001 From: eni Date: Wed, 11 Nov 2026 20:22:12 +0200 Subject: [PATCH] netlify-autoreg: signup farm + AI Gateway reverse (281 models on free), dashboard, multi-mailbox, captcha layer, full guide --- .gitignore | 9 ++ LICENSE | 21 +++ README.md | 154 +++++++++++++++++++ aigw_smoke.py | 36 +++++ captcha.py | 171 +++++++++++++++++++++ dashboard.py | 345 ++++++++++++++++++++++++++++++++++++++++++ deploy_all.py | 39 +++++ docs/API.md | 79 ++++++++++ docs/GUIDE.md | 303 +++++++++++++++++++++++++++++++++++++ docs/REVERSE.md | 172 +++++++++++++++++++++ edge/ai-proxy.ts | 50 +++++++ edge/envdump.ts | 13 ++ mailbox.py | 284 +++++++++++++++++++++++++++++++++++ netlify_farm.py | 379 +++++++++++++++++++++++++++++++++++++++++++++++ proxy_helpers.py | 63 ++++++++ requirements.txt | 1 + 16 files changed, 2119 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 README.md create mode 100644 aigw_smoke.py create mode 100644 captcha.py create mode 100644 dashboard.py create mode 100644 deploy_all.py create mode 100644 docs/API.md create mode 100644 docs/GUIDE.md create mode 100644 docs/REVERSE.md create mode 100644 edge/ai-proxy.ts create mode 100644 edge/envdump.ts create mode 100644 mailbox.py create mode 100644 netlify_farm.py create mode 100644 proxy_helpers.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5fcb2f2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +netlify_bank*.jsonl +mails.txt +*.session +__pycache__/ +*.pyc +.env +*.log +state.json +*_mails*.txt diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..14fac91 --- /dev/null +++ b/LICENSE @@ -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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..eafbd49 --- /dev/null +++ b/README.md @@ -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=- + -> 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:///.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.`, `mail.`, 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. diff --git a/aigw_smoke.py b/aigw_smoke.py new file mode 100644 index 0000000..7ac6aac --- /dev/null +++ b/aigw_smoke.py @@ -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]}') diff --git a/captcha.py b/captcha.py new file mode 100644 index 0000000..68da823 --- /dev/null +++ b/captcha.py @@ -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 \ No newline at end of file diff --git a/dashboard.py b/dashboard.py new file mode 100644 index 0000000..c4f2e03 --- /dev/null +++ b/dashboard.py @@ -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"

{r['email']}

") + 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 = """Netlify Farm + +

NETLIFY FARM

+
+
+ + + + Волна: + + + +
+ +
emailстатуссообщениепровереносайтhttpдействия
+
+""" + + +@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') \ No newline at end of file diff --git a/deploy_all.py b/deploy_all.py new file mode 100644 index 0000000..dc4b676 --- /dev/null +++ b/deploy_all.py @@ -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"

{r['email']}

")[: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)}') diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..22d1f02 --- /dev/null +++ b/docs/API.md @@ -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 `. +- netlify-cli 17.x ignores `NETLIFY_AUTH_TOKEN`; it reads the PAT from + `%APPDATA%/netlify/Config/config.json` under `users..auth.token`. +- A function bundled as `netlify/functions/.zip` in the site zip is also + ignored — the API path only accepts CLI-bundled artifacts. \ No newline at end of file diff --git a/docs/GUIDE.md b/docs/GUIDE.md new file mode 100644 index 0000000..dd6e1e6 --- /dev/null +++ b/docs/GUIDE.md @@ -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 = { + 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`. \ No newline at end of file diff --git a/docs/REVERSE.md b/docs/REVERSE.md new file mode 100644 index 0000000..cb35935 --- /dev/null +++ b/docs/REVERSE.md @@ -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 +