one-command starter for beginners, free socks proxy pool from iishko, iishko gateway shim + channel sql
This commit is contained in:
+101
@@ -0,0 +1,101 @@
|
||||
# Быстрый старт для новичка
|
||||
|
||||
Три шага. Никакой настройки конфигов.
|
||||
|
||||
## 1. Поставить зависимости
|
||||
|
||||
```bash
|
||||
pip install playwright
|
||||
```
|
||||
|
||||
Chrome должен быть установлен (обычный Google Chrome, не Chromium).
|
||||
|
||||
## 2. Запустить мастер
|
||||
|
||||
```bash
|
||||
python start.py
|
||||
```
|
||||
|
||||
Он спросит три вещи:
|
||||
|
||||
```
|
||||
Почта: один адрес email:pass или путь к файлу со списком
|
||||
Сколько аккаунтов сделать [1]
|
||||
Использовать бесплатные прокси из пула iishko? (да/нет) [да]
|
||||
Создавать сайт на каждом аккаунте? (да/нет) [да]
|
||||
```
|
||||
|
||||
Дальше всё само: проверит прокси, поднимет Chrome, зарегистрирует, прочитает письмо,
|
||||
подтвердит аккаунт, создаст сайт, задеплоит страницу и покажет таблицу.
|
||||
|
||||
## 3. Результат
|
||||
|
||||
```
|
||||
email site token
|
||||
------------------------------------------------------------------------------------------
|
||||
douyutv@aliyun.com eni-lo9fo9ba.netlify.app nfu_ABxkoE...
|
||||
```
|
||||
|
||||
Файл `netlify_bank.jsonl` — по строке на аккаунт:
|
||||
|
||||
```json
|
||||
{"email":"...","password":"...","token":"nfu_...","user_id":"...","account_id":"...",
|
||||
"site_id":"...","site_domain":"eni-....netlify.app","deploy_id":"..."}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Где взять почту
|
||||
|
||||
Нужен ящик с доступом по IMAP. Рабочие варианты (проверены с живыми кредами):
|
||||
|
||||
| домен | сервер |
|
||||
|---|---|
|
||||
| t-online.de | secureimap.t-online.de |
|
||||
| aliyun.com | imap.aliyun.com |
|
||||
| singnet.com.sg | imap.singnet.com.sg |
|
||||
| rambler.ru | imap.rambler.ru |
|
||||
| gmx.net | imap.gmx.net |
|
||||
| icn.od.ua | imap.icn.od.ua |
|
||||
| rediffmail.com | POP3 pop.rediffmail.com |
|
||||
|
||||
Формат файла со списком — по строке `адрес:пароль`. Мастер сам определит сервер по домену.
|
||||
`gmail с +алиасом` Netlify отбивает как «Email address is invalid» — берите обычный адрес.
|
||||
|
||||
## Прокси
|
||||
|
||||
По умолчанию мастер тянет **бесплатные SOCKS5** из пула iishko (база проксиграббера на проде),
|
||||
проверяет каждый именно на `app.netlify.com` и подставляет по одному на аккаунт.
|
||||
|
||||
Если прокси не нужны:
|
||||
|
||||
```bash
|
||||
python start.py --proxies off
|
||||
```
|
||||
|
||||
Обычные HTTP-прокси из публичных списков часто подменяют TLS (в Chrome это
|
||||
`ERR_CERT_AUTHORITY_INVALID`) — мастер их отбрасывает и берёт только те, что реально
|
||||
открывают Netlify.
|
||||
|
||||
## Частые проблемы
|
||||
|
||||
| что видно | что делать |
|
||||
|---|---|
|
||||
| `нет playwright` | `pip install playwright` |
|
||||
| `Chrome не найден` | поставить Google Chrome |
|
||||
| `Chrome не поднялся` | закрыть все окна Chrome, запустить снова |
|
||||
| `no verify mail / imap err` | проверить пароль ящика, он должен работать по IMAP |
|
||||
| `Email address is invalid` | ящик с плюс-алиасом, взять обычный |
|
||||
| `Account suspended` | ручная модерация Netlify, аккаунт не спасти, брать другой ящик |
|
||||
| сайт отдаёт 401 | не снят SSO-замок, мастер снимает его сам |
|
||||
|
||||
## Что дальше
|
||||
|
||||
```bash
|
||||
python dashboard.py --port 8791 # панель: статусы, волны, деплой
|
||||
```
|
||||
|
||||
Открыть `http://127.0.0.1:8791/`.
|
||||
|
||||
Полный технический разбор (эндпоинты, капча, AI Gateway на 281 модель) — в
|
||||
[GUIDE.md](docs/GUIDE.md) и [REVERSE.md](docs/REVERSE.md).
|
||||
@@ -0,0 +1,72 @@
|
||||
# Подключение Netlify AI Gateway в iishko
|
||||
|
||||
Шлюз Netlify подключён к продовому new-api как канал `nfgw-pool` (тип 1, priority 350,
|
||||
группы default/premium/t1-t4, 15 моделей, 90 abilities).
|
||||
|
||||
## Схема
|
||||
|
||||
```
|
||||
new-api :48005 -> http://127.0.0.1:8833 (nfgw-shim, systemd unit nfgw-shim.service)
|
||||
-> https://<site>/.netlify/ai/v1/... (edge-прокси /ai/*)
|
||||
-> Netlify AI Gateway (281 модель, биллинг кредитами аккаунта)
|
||||
```
|
||||
|
||||
Шим тянет JWT из `/envdump` (защищён `x-proxy-secret`), кэширует его на 240 секунд и
|
||||
сам перевыпускает при 401. SSE проксируется чанками.
|
||||
|
||||
## Файлы
|
||||
|
||||
| путь | что |
|
||||
|---|---|
|
||||
| `/opt/nfgw-shim/nfgw_shim.py` | шим (stdlib, ThreadingHTTPServer) |
|
||||
| `/opt/nfgw-shim/sites.json` | список сайтов + секрет |
|
||||
| `/opt/nfgw-shim/shim.log`, `out.log` | логи |
|
||||
| `/etc/systemd/system/nfgw-shim.service` | юнит |
|
||||
| `shim/add_channel.sql` | создание канала в PG |
|
||||
| `shim/lower_priority.sql` | приоритет 350 (fallback) |
|
||||
|
||||
## Управление
|
||||
|
||||
```bash
|
||||
systemctl status nfgw-shim
|
||||
curl -s http://127.0.0.1:8833/healthz # {"ok":true,"sites":1,"models":15}
|
||||
curl -s http://127.0.0.1:8833/v1/models | head -c 200
|
||||
```
|
||||
|
||||
## Ограничение, из-за которого канал держим на priority 350
|
||||
|
||||
Бесплатный аккаунт Netlify имеет лимит AI-кредитов. После ~25-30 запросов на
|
||||
`claude-opus-5-5` шлюз начинает отвечать:
|
||||
|
||||
```
|
||||
503 {"error":"usage_exceeded","message":"Usage exceeded"}
|
||||
403 (пустое тело) на прямом /(.netlify/ai)
|
||||
```
|
||||
|
||||
`credits.used` в `/api/v1/accounts` при этом может показывать 0 (отчёт с задержкой), так что
|
||||
ориентир — именно ответ шлюза. Поэтому:
|
||||
|
||||
1. канал стоит как **fallback** (priority 350), чтобы не жечь квоту впустую;
|
||||
2. для реальной ёмкости нужен **пул аккаунтов**: 1 аккаунт = 1 сайт = свои кредиты;
|
||||
3. шим умеет перебирать `sites.json` — добавляйте туда сайты с их `secret`, и при
|
||||
ошибке он перейдёт к следующему.
|
||||
|
||||
## Важно про egress
|
||||
|
||||
Прямой вызов `https://<site>/.netlify/ai` **с прод-сервера** отдаёт 403 — Netlify режет
|
||||
датацентровые IP. Работает только через **свой** edge-прокси `/ai/*` на том же сайте
|
||||
(он исполняется внутри Netlify). Поэтому в шиме upstream — `/ai`, а не `/.netlify/ai`.
|
||||
|
||||
## Проверка после правок
|
||||
|
||||
```bash
|
||||
# внутри прода
|
||||
curl -s -m 10 http://127.0.0.1:8833/healthz
|
||||
curl -s -m 60 -X POST http://127.0.0.1:8833/v1/chat/completions \
|
||||
-H 'Content-Type: application/json' \
|
||||
-d '{"model":"claude-opus-5-5","messages":[{"role":"user","content":"Reply OK"}]}'
|
||||
# снаружи, через new-api
|
||||
curl -s -X POST http://2.27.98.196:48005/v1/chat/completions \
|
||||
-H "Authorization: Bearer <token>" -H 'Content-Type: application/json' \
|
||||
-d '{"model":"claude-opus-5-5","messages":[{"role":"user","content":"Reply OK"}]}'
|
||||
```
|
||||
+67
-13
@@ -14,7 +14,7 @@ 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 proxy_helpers import ensure_chrome, rotate_zte, egress_ip, ZTE_PROXY, kill_all_chrome
|
||||
from mailbox import MailboxPool, Mailbox
|
||||
import captcha as capmod
|
||||
|
||||
@@ -253,18 +253,14 @@ def browser_alive(port: int) -> bool:
|
||||
|
||||
|
||||
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)
|
||||
"""Kill ALL chrome trees (zombies pile up otherwise) and start a fresh one."""
|
||||
kill_all_chrome()
|
||||
time.sleep(3)
|
||||
ok = ensure_chrome(port, profile, proxy)
|
||||
if not ok:
|
||||
time.sleep(3)
|
||||
ok = ensure_chrome(port, profile, proxy)
|
||||
return ok
|
||||
|
||||
def main():
|
||||
global MAILS, BANK
|
||||
@@ -276,6 +272,7 @@ def main():
|
||||
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('--proxies', default='', help="'auto' = free pool from iishko, or path to a file with one proxy per line")
|
||||
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',
|
||||
@@ -300,6 +297,21 @@ def main():
|
||||
if not pool:
|
||||
print('[!] no fresh emails in pool'); return
|
||||
|
||||
ppool = None
|
||||
if args.proxies:
|
||||
try:
|
||||
if args.proxies == 'auto':
|
||||
from proxy_source import ProxyPool
|
||||
ppool = ProxyPool(limit=60, check=10)
|
||||
else:
|
||||
from proxy_source import ProxyPool as _PP
|
||||
lines = [l.strip() for l in open(args.proxies, encoding='utf-8') if l.strip()]
|
||||
ppool = _PP.__new__(_PP)
|
||||
ppool.verbose, ppool.items, ppool.used, ppool.source = True, lines, 0, 'file'
|
||||
print(f'[i] proxy pool: {len(ppool)} proxies ({ppool.source})')
|
||||
except Exception as e:
|
||||
print('[!] proxy pool failed:', str(e)[:120])
|
||||
|
||||
from playwright.sync_api import sync_playwright
|
||||
port = args.port
|
||||
if not ensure_chrome(port, args.profile or None, args.proxy or None):
|
||||
@@ -315,7 +327,10 @@ def main():
|
||||
page = pg; break
|
||||
if page is None:
|
||||
page = ctx.new_page()
|
||||
try:
|
||||
page.goto('https://app.netlify.com/signup/email', timeout=45000, wait_until='domcontentloaded')
|
||||
except Exception as e0:
|
||||
print('[i] initial page open skipped:', str(e0)[:70])
|
||||
page.set_default_timeout(45000)
|
||||
|
||||
for i in range(args.count):
|
||||
@@ -332,6 +347,19 @@ def main():
|
||||
break
|
||||
ctx = ctx2 or ctx
|
||||
page = ctx.new_page()
|
||||
if ppool is not None:
|
||||
px = ppool.take()
|
||||
if px:
|
||||
print(f' [proxy] {px}')
|
||||
restart_browser(args.port, args.profile or None, px)
|
||||
try:
|
||||
page.close()
|
||||
except Exception:
|
||||
pass
|
||||
_b = p.chromium.connect_over_cdp(f'http://127.0.0.1:{args.port}')
|
||||
ctx = _b.contexts[0] if _b.contexts else _b.new_context()
|
||||
page = ctx.new_page()
|
||||
page.set_default_timeout(45000)
|
||||
if args.rotate and i:
|
||||
newip = rotate_zte()
|
||||
print(f' [rotate] new egress: {newip or "fail"}')
|
||||
@@ -339,9 +367,35 @@ def main():
|
||||
email_addr, mail_pass = mb.addr, mb.password
|
||||
password = gen_pass()
|
||||
print(f'\n[{i+1}/{args.count}] {email_addr}')
|
||||
goto_ok = False
|
||||
for attempt in range(3):
|
||||
try:
|
||||
page.goto('https://app.netlify.com/signup/email', timeout=45000, wait_until='domcontentloaded')
|
||||
goto_ok = True
|
||||
break
|
||||
except Exception as ge:
|
||||
msg = str(ge)
|
||||
print(f' [goto] attempt {attempt+1} failed: {msg[:70]}')
|
||||
if ppool is not None and ('TUNNEL' in msg or 'PROXY' in msg or 'ERR_' in msg):
|
||||
px = ppool.take()
|
||||
if px:
|
||||
print(f' [proxy] switch -> {px}')
|
||||
restart_browser(args.port, args.profile or None, px)
|
||||
try:
|
||||
page.close()
|
||||
except Exception:
|
||||
pass
|
||||
_b = p.chromium.connect_over_cdp(f'http://127.0.0.1:{args.port}')
|
||||
ctx = _b.contexts[0] if _b.contexts else _b.new_context()
|
||||
page = ctx.new_page()
|
||||
page.set_default_timeout(45000)
|
||||
continue
|
||||
break
|
||||
if not goto_ok:
|
||||
print(' [x] could not open signup page')
|
||||
continue
|
||||
time.sleep(3)
|
||||
try:
|
||||
r = do_signup(page, email_addr, password)
|
||||
print(' signup:', r)
|
||||
if not r['ok']:
|
||||
|
||||
@@ -10,6 +10,16 @@ ROTATOR = r'C:\Users\User\tmp\zte_rotate3.py'
|
||||
ZTE_PROXY = 'http://127.0.0.1:8899'
|
||||
|
||||
|
||||
def kill_all_chrome():
|
||||
"""Kill every chrome process tree (MSYS needs MSYS_NO_PATHCONV for taskkill)."""
|
||||
env = dict(os.environ, MSYS_NO_PATHCONV='1')
|
||||
try:
|
||||
subprocess.run('taskkill /F /IM chrome.exe /T', shell=True,
|
||||
capture_output=True, timeout=60, env=env)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def cdp_alive(port: int) -> bool:
|
||||
try:
|
||||
with urllib.request.urlopen(f'http://127.0.0.1:{port}/json/version', timeout=3) as r:
|
||||
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
"""Free proxy source backed by the iishko proxygrabb pool.
|
||||
|
||||
The pool lives on the iishko prod box (SQLite, refreshed by the grabber).
|
||||
This module pulls live proxies over SSH, verifies them from the local machine,
|
||||
caches the result and hands out working ones round-robin.
|
||||
|
||||
Fallbacks, in order:
|
||||
1. fresh pull from iishko (if SSH reachable)
|
||||
2. local cache file (proxies_cache.json)
|
||||
3. built-in seed list (last known good)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
CACHE = os.path.join(HERE, 'proxies_cache.json')
|
||||
|
||||
IISHKO_HOST = 'root@2.27.98.196'
|
||||
IISHKO_KEY = r'C:\Users\User\.ssh\id_ed25519'
|
||||
DB = '/opt/proxygrab/proxies.db'
|
||||
SQL = ("select proxy from pool where alive=1 and https_ok=1 "
|
||||
"order by (case when protocol='socks5' then 0 else 1 end), score desc limit {n};")
|
||||
|
||||
SEED = [
|
||||
'http://185.195.254.72:5432',
|
||||
'http://128.199.202.122:8080',
|
||||
'socks5://69.55.49.177:38182',
|
||||
'socks5://82.180.146.251:10800',
|
||||
'http://161.35.70.249:80',
|
||||
]
|
||||
|
||||
|
||||
def _ssh(cmd: str, timeout: int = 45) -> str:
|
||||
args = ['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'ConnectTimeout=15',
|
||||
'-o', 'BatchMode=yes']
|
||||
if os.path.exists(IISHKO_KEY):
|
||||
args += ['-i', IISHKO_KEY]
|
||||
args += [IISHKO_HOST, cmd]
|
||||
try:
|
||||
r = subprocess.run(args, capture_output=True, text=True, timeout=timeout,
|
||||
errors='replace')
|
||||
if r.returncode != 0:
|
||||
return ''
|
||||
return r.stdout
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def fetch_from_iishko(limit: int = 60):
|
||||
"""Pull live https-capable proxies from the pool on iishko."""
|
||||
out = _ssh(f'sqlite3 {DB} "{SQL.format(n=limit)}"')
|
||||
items = [l.strip() for l in out.splitlines() if l.strip().startswith(('http', 'socks'))]
|
||||
return items
|
||||
|
||||
|
||||
TARGET = 'https://app.netlify.com/signup/email'
|
||||
|
||||
|
||||
def verify(proxy: str, timeout: int = 10, target: str = TARGET) -> str:
|
||||
"""Return the exit IP if the proxy reaches the real target over HTTPS.
|
||||
|
||||
Uses curl so SOCKS5 works too. Plain HTTP proxies that MITM TLS fail here
|
||||
(they surface in Chrome as ERR_CERT_AUTHORITY_INVALID) and get dropped.
|
||||
"""
|
||||
target = target.replace('TARGET', '') # tolerate an accidental literal
|
||||
try:
|
||||
r = subprocess.run(
|
||||
['curl', '-s', '-o', os.devnull, '-m', str(timeout), '-w', '%{http_code}',
|
||||
'-x', proxy, target],
|
||||
capture_output=True, text=True, timeout=timeout + 5)
|
||||
if r.stdout.strip() not in ('200', '301', '302'):
|
||||
return ''
|
||||
except Exception:
|
||||
return ''
|
||||
try:
|
||||
r2 = subprocess.run(
|
||||
['curl', '-s', '-m', str(timeout), '-x', proxy, 'https://api.ipify.org'],
|
||||
capture_output=True, text=True, timeout=timeout + 5)
|
||||
ip = r2.stdout.strip()
|
||||
return ip if (ip.count('.') == 3 or ':' in ip) else ''
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def load_cache():
|
||||
if os.path.exists(CACHE):
|
||||
try:
|
||||
return json.load(open(CACHE, encoding='utf-8'))
|
||||
except Exception:
|
||||
pass
|
||||
return {'updated': 0, 'items': []}
|
||||
|
||||
|
||||
def save_cache(items, checked):
|
||||
data = {'updated': time.time(), 'items': checked}
|
||||
try:
|
||||
json.dump(data, open(CACHE, 'w', encoding='utf-8'), indent=1)
|
||||
except Exception:
|
||||
pass
|
||||
return data
|
||||
|
||||
|
||||
class ProxyPool:
|
||||
"""Hands out working proxies one by one, refreshing when exhausted."""
|
||||
|
||||
def __init__(self, limit: int = 60, check: int = 12, verbose: bool = True):
|
||||
self.verbose = verbose
|
||||
self.check = check
|
||||
self.limit = limit
|
||||
self.items = []
|
||||
self.used = 0
|
||||
self.source = ''
|
||||
self.refresh()
|
||||
|
||||
def log(self, msg):
|
||||
if self.verbose:
|
||||
print(msg, flush=True)
|
||||
|
||||
def refresh(self):
|
||||
cache = load_cache()
|
||||
# reuse a warm cache (< 10 min) instead of re-checking everything
|
||||
if cache.get('items') and (time.time() - cache.get('updated', 0)) < 600:
|
||||
alive = [c for c in cache['items'] if (time.time() - c.get('ts', 0)) < 1800]
|
||||
if len(alive) >= max(2, self.check // 3):
|
||||
self.items = [c['proxy'] for c in alive]
|
||||
self.used = 0
|
||||
self.source = 'cache'
|
||||
self.log(f'[proxy] source=cache, {len(self.items)} alive proxies')
|
||||
return
|
||||
fresh = fetch_from_iishko(self.limit)
|
||||
candidates = fresh or [c['proxy'] for c in cache.get('items', [])] or SEED
|
||||
self.source = 'iishko' if fresh else ('cache' if cache.get('items') else 'seed')
|
||||
socks = [c for c in candidates if c.startswith('socks')]
|
||||
plain = [c for c in candidates if not c.startswith('socks')]
|
||||
batch = (socks + plain)[:max(self.check, 12)]
|
||||
self.log(f'[proxy] source={self.source}, checking {len(batch)} in parallel')
|
||||
checked = []
|
||||
with ThreadPoolExecutor(max_workers=10) as ex:
|
||||
for p, ip in zip(batch, ex.map(verify, batch)):
|
||||
if ip:
|
||||
checked.append({'proxy': p, 'exit_ip': ip, 'ts': time.time()})
|
||||
self.log(f'[proxy] ok {p} -> {ip}')
|
||||
if len(checked) >= self.check:
|
||||
break
|
||||
if not checked:
|
||||
self.log('[proxy] nothing verified, falling back to seed')
|
||||
for p in SEED:
|
||||
ip = verify(p)
|
||||
if ip:
|
||||
checked.append({'proxy': p, 'exit_ip': ip, 'ts': time.time()})
|
||||
self.log(f'[proxy] ok {p} -> {ip}')
|
||||
if checked:
|
||||
save_cache(candidates, checked)
|
||||
self.items = [c['proxy'] for c in checked]
|
||||
self.used = 0
|
||||
|
||||
def take(self) -> str:
|
||||
if not self.items or self.used >= len(self.items):
|
||||
self.refresh()
|
||||
if not self.items:
|
||||
return ''
|
||||
p = self.items[self.used % len(self.items)]
|
||||
self.used += 1
|
||||
return p
|
||||
|
||||
def __len__(self):
|
||||
return len(self.items)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
pool = ProxyPool(limit=40, check=6)
|
||||
print('verified:', len(pool), 'source:', pool.source)
|
||||
for _ in range(min(3, len(pool))):
|
||||
print(' take:', pool.take())
|
||||
@@ -0,0 +1,22 @@
|
||||
-- Netlify AI Gateway channel (shim on 127.0.0.1:8833)
|
||||
DELETE FROM abilities WHERE channel_id IN (SELECT id FROM channels WHERE name = 'nfgw-pool');
|
||||
DELETE FROM channels WHERE name = 'nfgw-pool';
|
||||
|
||||
INSERT INTO channels (type, key, status, name, base_url, models, "group", priority, weight, auto_ban, tag,
|
||||
setting, other_info, created_time, test_time)
|
||||
VALUES (1, 'nfgw-local-shim', 1, 'nfgw-pool', 'http://127.0.0.1:8833',
|
||||
'claude-opus-5-5,claude-sonnet-5-5,claude-haiku-5-5,claude-fable-5-2,gpt-6.1-sol,gpt-6-astra,gpt-6-luna,gpt-5.5,gpt-5.4-mini,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',
|
||||
'default,premium,t1,t2,t3,t4', 700, 0, 0, 'nfgw',
|
||||
'{"force_format":false,"thinking_to_content":false,"proxy":"","pass_through_body_enabled":false,"system_prompt":""}',
|
||||
'{}', 1794423600, 0);
|
||||
|
||||
INSERT INTO abilities ("group", model, channel_id, enabled, priority, weight, tag)
|
||||
SELECT g.grp, trim(m.model), c.id, true, c.priority, 0, c.tag
|
||||
FROM channels c
|
||||
CROSS JOIN LATERAL unnest(string_to_array(c."group", ',')) g(grp)
|
||||
CROSS JOIN LATERAL unnest(string_to_array(c.models, ',')) m(model)
|
||||
WHERE c.name = 'nfgw-pool' AND trim(m.model) <> ''
|
||||
ON CONFLICT ("group", model, channel_id) DO UPDATE SET enabled = true;
|
||||
|
||||
SELECT id, name, base_url, priority, status, length(models) AS models_len FROM channels WHERE name = 'nfgw-pool';
|
||||
SELECT count(*) AS abilities FROM abilities WHERE channel_id = (SELECT id FROM channels WHERE name='nfgw-pool');
|
||||
@@ -0,0 +1,3 @@
|
||||
UPDATE channels SET priority = 350 WHERE name = 'nfgw-pool';
|
||||
UPDATE abilities SET priority = 350 WHERE channel_id = (SELECT id FROM channels WHERE name='nfgw-pool');
|
||||
SELECT id, name, priority, status FROM channels WHERE name='nfgw-pool';
|
||||
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env python3
|
||||
"""nfgw-shim — OpenAI/Anthropic-compatible shim over Netlify AI Gateway sites.
|
||||
|
||||
Upstream: https://<netlify-site>/.netlify/ai (the gateway proxy edge function).
|
||||
The gateway JWT lives in the edge function env and rotates; this shim pulls a
|
||||
fresh one from /envdump (protected by x-proxy-secret) and caches it briefly.
|
||||
|
||||
Config: /opt/nfgw-shim/sites.json [{"url": "...", "secret": "..."}]
|
||||
Port: NFGW_PORT (default 8833)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
BASE = '/opt/nfgw-shim'
|
||||
SITES = os.path.join(BASE, 'sites.json')
|
||||
KEY_CACHE = {} # url -> {'key': str, 'ts': float}
|
||||
LOCK = threading.Lock()
|
||||
KEY_TTL = 240 # seconds; JWT lives minutes
|
||||
|
||||
MODELS = [
|
||||
'claude-opus-5-5', 'claude-sonnet-5-5', 'claude-haiku-5-5', 'claude-fable-5-2',
|
||||
'gpt-6.1-sol', 'gpt-6-astra', 'gpt-6-luna', 'gpt-5.5', 'gpt-5.4-mini',
|
||||
'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 load_sites():
|
||||
try:
|
||||
with open(SITES, encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def log(msg):
|
||||
line = time.strftime('[%H:%M:%S] ') + str(msg)
|
||||
print(line, flush=True)
|
||||
try:
|
||||
with open(os.path.join(BASE, 'shim.log'), 'a', encoding='utf-8') as f:
|
||||
f.write(line + '\n')
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def fetch_key(site):
|
||||
"""Return a fresh gateway JWT for one site, using the secret-protected envdump."""
|
||||
url = site['url'].rstrip('/')
|
||||
secret = site.get('secret', '')
|
||||
req = urllib.request.Request(url + '/envdump',
|
||||
headers={'x-proxy-secret': secret, 'accept': 'application/json'})
|
||||
with urllib.request.urlopen(req, timeout=25) as r:
|
||||
data = json.loads(r.read().decode())
|
||||
picked = data.get('picked') or {}
|
||||
return picked.get('NETLIFY_AI_GATEWAY_KEY') or picked.get('OPENAI_API_KEY') or ''
|
||||
|
||||
|
||||
def get_key(site, force=False):
|
||||
url = site['url'].rstrip('/')
|
||||
with LOCK:
|
||||
c = KEY_CACHE.get(url)
|
||||
if c and not force and (time.time() - c['ts']) < KEY_TTL:
|
||||
return c['key']
|
||||
key = fetch_key(site)
|
||||
if key:
|
||||
with LOCK:
|
||||
KEY_CACHE[url] = {'key': key, 'ts': time.time()}
|
||||
return key
|
||||
|
||||
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
protocol_version = 'HTTP/1.1'
|
||||
|
||||
def log_message(self, fmt, *args):
|
||||
pass
|
||||
|
||||
def _send(self, code, body: bytes, ctype='application/json', extra=None):
|
||||
self.send_response(code)
|
||||
self.send_header('Content-Type', ctype)
|
||||
self.send_header('Content-Length', str(len(body)))
|
||||
for k, v in (extra or {}).items():
|
||||
self.send_header(k, v)
|
||||
self.end_headers()
|
||||
try:
|
||||
self.wfile.write(body)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def _json(self, obj, code=200):
|
||||
self._send(code, json.dumps(obj).encode(), 'application/json')
|
||||
|
||||
def do_GET(self):
|
||||
if self.path.startswith('/healthz'):
|
||||
sites = load_sites()
|
||||
return self._json({'ok': True, 'sites': len(sites), 'models': len(MODELS),
|
||||
'cached_keys': len(KEY_CACHE)})
|
||||
if self.path.startswith('/v1/models'):
|
||||
now = int(time.time())
|
||||
return self._json({'object': 'list', 'data': [
|
||||
{'id': m, 'object': 'model', 'created': now, 'owned_by': 'netlify-ai-gateway'}
|
||||
for m in MODELS]})
|
||||
return self._json({'error': {'message': 'not found'}}, 404)
|
||||
|
||||
def do_POST(self):
|
||||
path = self.path
|
||||
length = int(self.headers.get('Content-Length') or 0)
|
||||
body = self.rfile.read(length) if length else b''
|
||||
sites = load_sites()
|
||||
if not sites:
|
||||
return self._json({'error': {'message': 'no sites configured'}}, 500)
|
||||
|
||||
last_err = 'no site tried'
|
||||
for site in sites:
|
||||
for attempt in (0, 1):
|
||||
key = get_key(site, force=(attempt == 1))
|
||||
if not key:
|
||||
last_err = 'no gateway key'
|
||||
continue
|
||||
target = site['url'].rstrip('/') + '/ai' + path # our edge proxy: /.netlify/ai is 403 from DC IPs
|
||||
req = urllib.request.Request(target, data=body if self.command == 'POST' else None,
|
||||
method=self.command)
|
||||
req.add_header('Content-Type', self.headers.get('Content-Type') or 'application/json')
|
||||
req.add_header('Authorization', 'Bearer ' + key)
|
||||
req.add_header('x-api-key', key)
|
||||
av = self.headers.get('anthropic-version')
|
||||
if av:
|
||||
req.add_header('anthropic-version', av)
|
||||
accept = self.headers.get('accept') or ''
|
||||
stream = b'"stream"' in body and b'true' in body
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=180)
|
||||
code = resp.status
|
||||
ctype = resp.headers.get('Content-Type') or 'application/json'
|
||||
if stream or 'event-stream' in ctype:
|
||||
self.send_response(code)
|
||||
self.send_header('Content-Type', ctype or 'text/event-stream')
|
||||
self.send_header('Cache-Control', 'no-cache')
|
||||
self.send_header('Transfer-Encoding', 'chunked')
|
||||
self.end_headers()
|
||||
try:
|
||||
while True:
|
||||
chunk = resp.read(2048)
|
||||
if not chunk:
|
||||
break
|
||||
self.wfile.write(b'%X\r\n' % len(chunk) + chunk + b'\r\n')
|
||||
self.wfile.flush()
|
||||
self.wfile.write(b'0\r\n\r\n')
|
||||
except Exception:
|
||||
pass
|
||||
return
|
||||
data = resp.read()
|
||||
return self._send(code, data, ctype)
|
||||
except urllib.error.HTTPError as e:
|
||||
err_body = e.read()
|
||||
if e.code in (401, 403) and attempt == 0:
|
||||
last_err = f'{e.code} (retry with fresh key)'
|
||||
continue
|
||||
if e.code >= 500:
|
||||
last_err = f'{e.code}'
|
||||
break
|
||||
return self._send(e.code, err_body, e.headers.get('Content-Type') or 'application/json')
|
||||
except Exception as e:
|
||||
last_err = f'{type(e).__name__}: {str(e)[:60]}'
|
||||
continue
|
||||
return self._json({'error': {'message': f'upstream failed: {last_err}'}}, 502)
|
||||
|
||||
|
||||
def main():
|
||||
port = int(os.environ.get('NFGW_PORT', '8833'))
|
||||
sites = load_sites()
|
||||
log(f'start on :{port}, sites={len(sites)}, models={len(MODELS)}')
|
||||
srv = ThreadingHTTPServer(('127.0.0.1', port), Handler)
|
||||
srv.daemon_threads = True
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Netlify Farm — интерактивный запуск для новичка.
|
||||
|
||||
Что делает:
|
||||
1. спрашивает почту (один адрес или файл со списком),
|
||||
2. спрашивает сколько аккаунтов,
|
||||
3. сам берёт бесплатные прокси из пула iishko и проверяет их,
|
||||
4. поднимает Chrome, регает аккаунты, создаёт сайт и деплой,
|
||||
5. складывает результат в netlify_bank.jsonl и показывает таблицу.
|
||||
|
||||
Запуск: python start.py
|
||||
Неинтерактивно: python start.py --mail-file mails.txt --count 3 --proxies auto --yes
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
PY = sys.executable
|
||||
BANK = os.path.join(HERE, 'netlify_bank.jsonl')
|
||||
CHROME_CANDIDATES = [
|
||||
r'C:\Program Files\Google\Chrome\Application\chrome.exe',
|
||||
r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe',
|
||||
os.path.expandvars(r'%LOCALAPPDATA%\Google\Chrome\Application\chrome.exe'),
|
||||
]
|
||||
|
||||
|
||||
def say(msg=''):
|
||||
print(msg, flush=True)
|
||||
|
||||
|
||||
def find_chrome():
|
||||
for c in CHROME_CANDIDATES:
|
||||
if c and os.path.exists(c):
|
||||
return c
|
||||
return ''
|
||||
|
||||
|
||||
def check_deps():
|
||||
ok = True
|
||||
try:
|
||||
import playwright # noqa: F401
|
||||
except Exception:
|
||||
say('[!] нет playwright. Поставь: pip install playwright')
|
||||
ok = False
|
||||
try:
|
||||
import httpx # noqa: F401
|
||||
except Exception:
|
||||
say('[i] httpx нет — понадобится только для дашборда, не критично')
|
||||
if not find_chrome():
|
||||
say('[!] Chrome не найден. Поставь Google Chrome.')
|
||||
ok = False
|
||||
return ok
|
||||
|
||||
|
||||
def ask(text, default=''):
|
||||
try:
|
||||
v = input(f'{text}' + (f' [{default}]' if default else '') + ': ').strip()
|
||||
except (EOFError, KeyboardInterrupt):
|
||||
say('\nотмена')
|
||||
sys.exit(1)
|
||||
return v or default
|
||||
|
||||
|
||||
def normalize_mail_line(line):
|
||||
line = line.strip()
|
||||
if not line or line.startswith('#'):
|
||||
return ''
|
||||
if ':' not in line:
|
||||
return ''
|
||||
return line
|
||||
|
||||
|
||||
def build_mail_file(single_or_path, workdir):
|
||||
"""Return path to a pool file. Accepts email:pass or a path to a file."""
|
||||
src = single_or_path.strip()
|
||||
if os.path.exists(src):
|
||||
return os.path.abspath(src)
|
||||
line = normalize_mail_line(src)
|
||||
if not line:
|
||||
return ''
|
||||
out = os.path.join(workdir, 'mails_input.txt')
|
||||
with open(out, 'w', encoding='utf-8') as f:
|
||||
f.write(line + '\n')
|
||||
return out
|
||||
|
||||
|
||||
def kill_chrome():
|
||||
try:
|
||||
subprocess.run('taskkill /F /IM chrome.exe /T', shell=True,
|
||||
capture_output=True, timeout=30,
|
||||
env={**os.environ, 'MSYS_NO_PATHCONV': '1'})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def launch_chrome(port, profile, proxy=''):
|
||||
chrome = find_chrome()
|
||||
if not chrome:
|
||||
return False
|
||||
args = [chrome, f'--remote-debugging-port={port}', f'--user-data-dir={profile}',
|
||||
'--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))
|
||||
import urllib.request
|
||||
for _ in range(20):
|
||||
time.sleep(1.5)
|
||||
try:
|
||||
urllib.request.urlopen(f'http://127.0.0.1:{port}/json/version', timeout=2).close()
|
||||
return True
|
||||
except Exception:
|
||||
continue
|
||||
return False
|
||||
|
||||
|
||||
def show_bank(limit=20):
|
||||
if not os.path.exists(BANK):
|
||||
say('банк пуст')
|
||||
return
|
||||
rows = []
|
||||
with open(BANK, encoding='utf-8', errors='ignore') as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if line:
|
||||
try:
|
||||
rows.append(json.loads(line))
|
||||
except Exception:
|
||||
pass
|
||||
say('')
|
||||
say(f'{"email":<38} {"site":<34} token')
|
||||
say('-' * 90)
|
||||
for r in rows[-limit:]:
|
||||
say(f'{r.get("email",""):<38} {r.get("site_domain") or "-":<34} {str(r.get("token"))[:10]}...')
|
||||
say('')
|
||||
say(f'всего аккаунтов в банке: {len(rows)} -> {BANK}')
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(add_help=True)
|
||||
ap.add_argument('--mail', help='email:password или путь к файлу пула')
|
||||
ap.add_argument('--count', type=int, default=0)
|
||||
ap.add_argument('--proxies', default='', help="auto | файл | off")
|
||||
ap.add_argument('--site', dest='site', action='store_true', default=None)
|
||||
ap.add_argument('--no-site', dest='site', action='store_false')
|
||||
ap.add_argument('--port', type=int, default=9233)
|
||||
ap.add_argument('--yes', action='store_true', help='без вопросов')
|
||||
a = ap.parse_args()
|
||||
|
||||
say('=' * 60)
|
||||
say(' NETLIFY FARM — авторегистрация аккаунтов')
|
||||
say('=' * 60)
|
||||
say('')
|
||||
|
||||
if not check_deps():
|
||||
say('')
|
||||
say('Установи зависимости и запусти снова:')
|
||||
say(' pip install playwright')
|
||||
sys.exit(1)
|
||||
|
||||
mail_src = a.mail or ('' if a.yes else ask('Почта: один адрес email:pass или путь к файлу со списком'))
|
||||
if not mail_src:
|
||||
say('[!] без почты никак: нужен рабочий ящик с IMAP')
|
||||
sys.exit(1)
|
||||
mail_file = build_mail_file(mail_src, HERE)
|
||||
if not mail_file:
|
||||
say('[!] не понял почту. Формат: адрес:пароль либо путь к файлу')
|
||||
sys.exit(1)
|
||||
|
||||
count = a.count
|
||||
if not count:
|
||||
raw = '1' if a.yes else ask('Сколько аккаунтов сделать', '1')
|
||||
try:
|
||||
count = int(raw)
|
||||
except ValueError:
|
||||
count = 1
|
||||
|
||||
proxies = a.proxies
|
||||
if not proxies:
|
||||
if a.yes:
|
||||
proxies = 'auto'
|
||||
else:
|
||||
ans = ask('Использовать бесплатные прокси из пула iishko? (да/нет)', 'да').lower()
|
||||
proxies = 'auto' if ans in ('да', 'д', 'y', 'yes', '1', '') else 'off'
|
||||
if proxies.lower() in ('off', 'нет', 'no', 'n'):
|
||||
proxies = ''
|
||||
|
||||
site = a.site
|
||||
if site is None:
|
||||
site = True if a.yes else ask('Создавать сайт на каждом аккаунте? (да/нет)', 'да').lower() in ('да', 'д', 'y', 'yes', '1', '')
|
||||
|
||||
say('')
|
||||
say('--- план ---')
|
||||
say(f' почты: {mail_file}')
|
||||
say(f' аккаунтов: {count}')
|
||||
say(f' прокси: {proxies or "без прокси (домашний IP)"}')
|
||||
say(f' сайт: {"да" if site else "нет"}')
|
||||
say('')
|
||||
|
||||
# Chrome / профиль
|
||||
profile = os.path.join(HERE, '_chrome_profile')
|
||||
if proxies:
|
||||
say('[*] беру прокси из пула iishko...')
|
||||
try:
|
||||
sys.path.insert(0, HERE)
|
||||
from proxy_source import ProxyPool
|
||||
pool = ProxyPool(limit=60, check=8)
|
||||
first = pool.take()
|
||||
say(f'[i] рабочих прокси: {len(pool)}')
|
||||
except Exception as e:
|
||||
say(f'[!] пул прокси недоступен ({str(e)[:60]}), иду напрямую')
|
||||
proxies, first = '', ''
|
||||
else:
|
||||
first = ''
|
||||
|
||||
say('[*] поднимаю Chrome...')
|
||||
kill_chrome()
|
||||
time.sleep(2)
|
||||
if not launch_chrome(a.port, profile):
|
||||
say('[!] Chrome не поднялся. Закрой все окна Chrome и запусти снова.')
|
||||
sys.exit(1)
|
||||
say('[i] Chrome готов')
|
||||
|
||||
cmd = [PY, os.path.join(HERE, 'netlify_farm.py'),
|
||||
'--count', str(count), '--mails', mail_file,
|
||||
'--bank', BANK, '--port', str(a.port),
|
||||
'--profile', profile, '--captcha', 'auto']
|
||||
if site:
|
||||
cmd.append('--site')
|
||||
if proxies:
|
||||
cmd += ['--proxies', proxies]
|
||||
|
||||
say('')
|
||||
say('[*] поехали. Это займёт ~1-2 минуты на аккаунт')
|
||||
say('')
|
||||
env = dict(os.environ)
|
||||
env.pop('PYTHONPATH', None)
|
||||
env['PYTHONIOENCODING'] = 'utf-8'
|
||||
try:
|
||||
subprocess.run(cmd, cwd=HERE, env=env)
|
||||
except KeyboardInterrupt:
|
||||
say('\n[!] остановлено пользователем')
|
||||
|
||||
show_bank()
|
||||
say('')
|
||||
say('Готово. Следующий раз просто: python start.py')
|
||||
say('Панель со статусами: python dashboard.py --port 8791 -> http://127.0.0.1:8791/')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user