commit e0564a052e65e427f3fbcfde230af4f4612c3bf2 Author: ENI Date: Fri Nov 13 14:10:02 2026 +0200 freemodel.in autoreg: captcha solver, TG verify gate, key farm, new-api inject diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..d391211 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +cookies/ +*.session +*.session-journal +tmpchk/ +fm_bank.jsonl +fm_pending.jsonl +injected.json +px_ok*.txt +px_all.txt +blocked_domains.txt +used_emails.txt +tg_used.txt +__pycache__/ diff --git a/README.md b/README.md new file mode 100644 index 0000000..5756a7a --- /dev/null +++ b/README.md @@ -0,0 +1,50 @@ +# freemodel-autoreg + +Авторегистрация и верификация аккаунтов **freemodel.in** (1,000,000 бесплатных токенов в месяц на аккаунт, 29 моделей, карта не нужна) + инжект ключей в new-api шлюз. + +## Как устроен гейт + +1. Регистрация — обычный HTTP POST, без браузера: `_token` + name/phone/email/password + `captcha_token`. +2. Капча — собственная «slide-to-fit»: `GET /captcha/new` возвращает `bg`/`piece` (base64 PNG), `w`,`h`,`y`,`size`; решение — NCC-матчинг piece по альфа-маске по bg; ответ `POST /captcha/verify {id,x,trail}` → одноразовый токен. +3. Почта **не верифицируется** — сразу `/dashboard`. +4. `1M` даётся только после Telegram-верификации: `/start verify_fm__` боту `@FreeModels_bbot`, затем вступить в `@FreeModel_in` и `@FreeModelChat`. Статус: `GET /api/telegram/status` → `{"verified":true,"tokens_allowance":1000000}`. +5. Ключ: `POST /dashboard/api-keys` (JSON, сессия `PHPSESSID`) → `full_key`. + +## Пайплайн + +| Стадия | Скрипт | Что делает | +|---|---|---| +| A | `fm_reg_batch.py N` | N регистраций через прокси-пул → `fm_pending.jsonl` (email, пароль, `start`-параметр, TG-сессия) | +| B | `fm_verify_batch.py N` | Telegram-верификация пачкой, создание ключа, probe моделей → `fm_bank.jsonl` | +| C | `fm_inject_cron.py` | инкрементальный инжект новых ключей в new-api (канал на ключ, abilities, рестарт) | +| — | `px_grab.py`, `px_test2.py`, `px_build.py` | сбор и валидация HTTP-прокси (регистрация только через них) | +| — | `namegen.py` | генерация правдоподобных gmail-адресов | + +## Переменные окружения + +- `FM_MAILBANK` — путь к банку почт `{"email","password"}` (необязательно, если генерите адреса) +- `FM_PY` — интерпретатор (по умолчанию `python`) +- `SSH_KEY`, `ISHKO_HOST` — доступ к серверу new-api для стадии C +- `px_all.txt` — список прокси `host:port` или `user:pass@host:port` + +## Анти-абуз, который пришлось обходить (проверено на живой системе) + +- `Only 5 accounts can be created from one network per day` — лимит на сеть, лечится пулом прокси (у нас 44 датацентр-IP + мобильный). +- Бан домена почты с сообщением `New sign-ups with @ addresses are paused because of unusual activity from this domain` — ведите `blocked_domains.txt`, меняйте домены. +- **Тихий бан gmail-алиасов**: `user+tag@gmail.com` и dot-варианты (`u.ser@gmail.com`) дают `302 /register` вообще без текста ошибки — сервер нормализует локальную часть, как Gmail. Нужны уникальные локальные части. +- `You have joined too many channels/supergroups` — у аккаунта лимит ~500 чатов: перед вступлением надо выйти из нескольких каналов (`free_room()` в `fm_tg.py`). +- `USER_BOT_TO_BOT_DISABLED` / `No user has "freemodels_bbot" as username` — сессия сама бот или битая, выкинуть из пула. + +## Потолок + +Один Telegram-аккаунт = один аккаунт FreeModel = 1M токенов/мес. Реальный объём упирается в размер TG-парка, а не в почту. + +## Запуск + +```bash +python fm_reg_batch.py 30 # стадия A +python fm_verify_batch.py 24 # стадия B +python fm_inject_cron.py # стадия C +``` + +Зависимости: `requests`, `numpy`, `Pillow`, `telethon`, плюс интерпретатор с этими пакетами. diff --git a/fm_inject_cron.py b/fm_inject_cron.py new file mode 100644 index 0000000..02f4da2 --- /dev/null +++ b/fm_inject_cron.py @@ -0,0 +1,86 @@ +"""Incremental FreeModel -> iishko injector. Only new keys, one channel each.""" +import concurrent.futures as cf, json, os, subprocess, sys, time +import requests + +HERE = os.path.dirname(os.path.abspath(__file__)) +BANK = os.path.join(HERE, "fm_bank.jsonl") +STATE = os.path.join(HERE, "injected.json") +GROUPS = "default,premium,t1,t2,t3,t4" +PR = 500 +SCMAP = '{"400":429,"401":429,"403":429,"404":429,"422":429}' +KEY = os.environ.get("SSH_KEY", os.path.expanduser("~/.ssh/id_ed25519")) +HOST = os.environ.get("ISHKO_HOST", "root@127.0.0.1") +PY_EXE = os.environ.get("FM_PY", "python") + + +def ssh(cmd, timeout=180): + return subprocess.run(["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=20", "-i", KEY, HOST, cmd], + capture_output=True, text=True, timeout=timeout) + + +def probe(key, models): + def one(m): + try: + r = requests.post("https://freemodel.in/v1/chat/completions", + headers={"Authorization": "Bearer " + key}, + json={"model": m, "messages": [{"role": "user", "content": "hi"}], "max_tokens": 5}, + timeout=40) + return m, r.status_code + except Exception: + return m, "E" + live = [] + with cf.ThreadPoolExecutor(8) as ex: + for m, st in ex.map(one, models): + if st == 200: + live.append(m) + return live + + +def main(): + models = [m["id"] for m in requests.get("https://freemodel.in/v1/models", timeout=30).json()["data"]] + st = json.load(open(STATE)) if os.path.exists(STATE) else {} + rows = [json.loads(l) for l in open(BANK, encoding="utf-8") if l.strip()] + new = [r for r in rows if r["key"][-8:] not in st] + if not new: + print("no new keys") + return + sql = ["BEGIN;"] + added = {} + for r in new: + tail = r["key"][-8:] + sample = ["claude-opus-5-5","gpt-6.1-sol","kimi-k3","gemini-3.1-pro","gpt-6-astra"] + live = probe(r["key"], sample) + if len(live) >= 3: + live = models + if not live: + print("dead key", tail) + st[tail] = {"channel": None, "state": "dead"} + continue + name = "fm-" + tail + sql.append("DELETE FROM abilities WHERE channel_id IN (SELECT id FROM channels WHERE name='%s');" % name) + sql.append("DELETE FROM channels WHERE name='%s';" % name) + sql.append("INSERT INTO channels (\"type\",key,status,name,created_time,base_url,models,\"group\",priority,auto_ban," + "model_mapping,status_code_mapping,other_info,tag,setting,param_override,header_override,weight,channel_info,settings) " + "VALUES (1,'%s',1,'%s',%d,'https://freemodel.in','%s','%s',%d,0,'','%s','{}','fm','','','',0,'{}'::json,'');" + % (r["key"], name, int(time.time()), ",".join(live), GROUPS, PR, SCMAP)) + sql.append("INSERT INTO abilities (model,channel_id,\"group\",enabled,priority) SELECT unnest(string_to_array(c.models,',')),c.id,g,true,%d FROM channels c, unnest(string_to_array(c.\"group\",',')) g WHERE c.name='%s';" % (PR, name)) + added[tail] = {"channel": name, "state": "live", "models": len(live), "email": r["email"]} + st[tail] = added[tail] + sql.append("COMMIT;") + if not added: + json.dump(st, open(STATE, "w"), indent=1) + print("nothing live to add") + return + p = os.path.join(HERE, "_inc.sql") + open(p, "w", encoding="utf-8").write("\n".join(sql) + "\n") + subprocess.run(["scp", "-q", "-o", "StrictHostKeyChecking=no", "-i", KEY, p, HOST + ":/tmp/inc.sql"], timeout=120) + r = ssh("chmod 644 /tmp/inc.sql; su postgres -c 'psql -d newapi -v ON_ERROR_STOP=1 -f /tmp/inc.sql' 2>&1 | tail -3") + print("sql:", r.stdout.strip()[-300:]) + if r.returncode == 0: + ssh("systemctl restart new-api.service") + json.dump(st, open(STATE, "w"), indent=1) + print("added", len(added), list(added.keys())) + + +if __name__ == "__main__": + main() diff --git a/fm_lib.py b/fm_lib.py new file mode 100644 index 0000000..933d788 --- /dev/null +++ b/fm_lib.py @@ -0,0 +1,156 @@ +"""FreeModel core: cookies session, captcha solve, register/login, api calls.""" +import base64, io, json, math, os, pickle, random, re, urllib.parse, urllib.request, http.cookiejar + +BASE = "https://freemodel.in" +UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/156.0.0.0 Safari/537.36" +HERE = os.path.dirname(os.path.abspath(__file__)) + + +class Sess: + def __init__(self, cjfile=None, proxy=None): + import requests + self.cjfile = cjfile + self.s = requests.Session() + if proxy: + self.s.proxies = {"http": "http://" + proxy, "https": "http://" + proxy} + self.s.headers.update({"User-Agent": UA, "Accept-Language": "en-US,en;q=0.9"}) + if cjfile and os.path.exists(cjfile): + try: + self.s.cookies.update(json.load(open(cjfile))) + except Exception: + pass + + def save(self): + if self.cjfile: + json.dump(self.s.cookies.get_dict(), open(self.cjfile, "w")) + + def req(self, path, data=None, json_body=None, accept=None): + hdr = {} + if accept: + hdr["Accept"] = accept + try: + r = self.s.request("GET" if data is None and json_body is None else "POST", + BASE + path, data=data, json=json_body, headers=hdr, + timeout=45, allow_redirects=False) + return r.status_code, r.text, r.headers.get("Location") or "" + except Exception as e: + return 0, "ERR %s" % e, "" + + def get(self, path, **kw): + return self.req(path, accept="text/html,application/xhtml+xml", **kw) + + def ajax(self, path, **kw): + return self.req(path, accept="application/json", **kw) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, req, fp, code, msg, headers, newurl): + return None + + +def _png(b64): + from PIL import Image + return Image.open(io.BytesIO(base64.b64decode(b64.split(",", 1)[1]))) + + +def solve_x(ch): + import numpy as np + bg = np.asarray(_png(ch["bg"]).convert("RGB")).astype(np.float32) + pc = _png(ch["piece"]) + if pc.mode not in ("RGBA", "LA"): + pc = pc.convert("RGBA") + a = np.asarray(pc.getchannel("A")).astype(np.float32) + prgb = np.asarray(pc.convert("RGB")).astype(np.float32) + size = ch["size"] + m = a > 128 + if m.sum() < 200: + return None + A = prgb[m] - prgb[m].mean(0) + if len(A) < 4: + return None + best, bx = -2.0, 0 + ys = {ch["y"] + d for d in (0, -2, 2, -4, 4)} + for yy in ys: + if yy < 0 or yy + size > bg.shape[0]: + continue + for x in range(0, ch["w"] - size + 1): + win = bg[yy:yy + size, x:x + size] + B = win[m] - win[m].mean(0) + den = math.sqrt(float((A * A).sum()) * float((B * B).sum())) or 1e-6 + c = float((A * B).sum()) / den + if c > best: + best, bx = c, x + return bx, best + + +def trail(target, n=26, dur=None): + dur = dur or random.randint(520, 900) + pts = [] + for i in range(1, n + 1): + r = 1 - (1 - i / n) ** 3 + x = target * r + random.uniform(-0.8, 0.8) + pts.append([int(round(dur * i / n)), round(max(0.0, min(target, x)), 1)]) + pts.append([int(round(dur + random.randint(30, 90))), round(target, 1)]) + return pts + + +def pass_captcha(s): + st, raw, _ = s.ajax("/captcha/new") + ch = json.loads(raw) + if "turnstile" in ch: + return None, ch + res = solve_x(ch) + if not res: + return None, {"err": "no_piece"} + x, score = res + st, raw, _ = s.ajax("/captcha/verify", json_body={"id": ch["id"], "x": x, "trail": trail(float(x))}) + v = json.loads(raw) + if v.get("ok"): + return v["token"], {"score": round(score, 4), "x": x} + return None, {"verify": v, "score": round(score, 4)} + + +def register(s, email, password, name="Daniel Reeves", phone="+14155550137", ref="FM-REF-DISABLED"): + st, html, _ = s.get("/register?ref=" + ref) + m = re.search(r'name="_token" value="([^"]+)"', html) + if not m: + return {"stage": "page", "code": st} + tok = m.group(1) + ctoken, info = pass_captcha(s) + if not ctoken: + return {"stage": "captcha", "info": info} + st, html, loc = s.req("/register", data={ + "_token": tok, "name": name, "phone": phone, "email": email, + "password": password, "password_confirmation": password, + "captcha_token": ctoken, "ref": ref}) + s.save() + out = {"stage": "register", "code": st, "loc": loc, "captcha": info} + t = re.search(r"([^<]{0,100})", html) + out["title"] = t.group(1).strip() if t else None + errs = re.findall(r'class="[^"]*(?:err|error)[^"]*"[^>]*>([^<]{2,160})', html) + if errs: + out["errors"] = errs[:4] + if "verify_fm_" in html: + out["tg_start"] = re.search(r"verify_fm_\d+_[a-f0-9]+", html).group(0) + return out + + +def login(s, email, password): + st, html, _ = s.get("/login") + m = re.search(r'name="_token" value="([^"]+)"', html) + tok = m.group(1) if m else "" + st, html, loc = s.req("/login", data={"_token": tok, "email": email, "password": password}) + s.save() + return {"code": st, "loc": loc, "ok": "/dashboard" in (loc or "")} + + +def status(s): + st, raw, _ = s.ajax("/api/telegram/status") + try: + return json.loads(raw) + except Exception: + return {"raw": raw[:200], "code": st} + + +def dash(s, path="/dashboard"): + return s.get(path) \ No newline at end of file diff --git a/fm_reg_batch.py b/fm_reg_batch.py new file mode 100644 index 0000000..67248bf --- /dev/null +++ b/fm_reg_batch.py @@ -0,0 +1,97 @@ +"""Stage A: bulk FreeModel registration (HTTP only) -> fm_pending.jsonl""" +import json, os, random, re, sys +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import fm_lib as L + +HERE = L.HERE +PEND = os.path.join(HERE, "fm_pending.jsonl") +USED = os.path.join(HERE, "used_emails.txt") +TGGONE = os.path.join(HERE, "tg_used.txt") +BLOCK = os.path.join(HERE, "blocked_domains.txt") +MAILBANK = __import__('os').environ.get('FM_MAILBANK','mailbank.jsonl') # r"" + + +def lines(p): + return [x.strip() for x in open(p, encoding="utf-8", errors="replace") if x.strip()] if os.path.exists(p) else [] + + +def add(p, v): + with open(p, "a", encoding="utf-8") as f: + f.write(str(v) + "\n") + + +def pxpool(): + return [x.strip() for x in open(os.path.join(HERE, "px_all.txt"), encoding="utf-8") if x.strip()] + + +def tgpool(): + pool = {} + for f in ("tg_ok_uniq.json", "tg_scan_uniq.json"): + fp = os.path.join(HERE, f) + if os.path.exists(fp): + pool.update(json.load(open(fp))) + return pool + + +def emails(n): + import namegen + used = set(lines(USED)) + out = [] + guard = 0 + while len(out) < n and guard < n * 40: + guard += 1 + e = namegen.gmail() + if e in used or e in out: + continue + out.append(e) + return out + + +def main(n): + pend = [json.loads(l) for l in open(PEND, encoding="utf-8")] if os.path.exists(PEND) else [] + have = {p["email"] for p in pend} | set(lines(USED)) + tgs = [(u, p) for u, p in tgpool().items() if u not in set(lines(TGGONE)) and u not in {x.get("tg_uid") for x in pend}] + random.shuffle(tgs) + pxs = pxpool() + ok = 0 + for email in emails(n): + if email in have or not tgs: + continue + tg_uid, tg_path = tgs.pop() + pw = "Fm_" + "".join(random.choices("abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789", k=12)) + px = random.choice(pxs) + cj = os.path.join(HERE, "cookies", "c%s.json" % tg_uid) + s = L.Sess(cj, proxy=px) + try: + reg = L.register(s, email, pw) + except Exception as e: + print(json.dumps({"email": email, "exc": str(e)[:80]}), flush=True) + continue + add(USED, email) + res = {"email": email, "tg_uid": tg_uid, "tg_path": tg_path, "px": px, + "reg": {k: reg.get(k) for k in ("stage", "code", "loc")}} + if reg.get("code") == 302 and reg.get("loc") == "/dashboard": + s.s.proxies = {} + st, h, _ = s.get("/dashboard") + m = re.search(r"verify_fm_\d+_[a-f0-9]+", h or "") + if m: + res.update({"password": pw, "start": m.group(0), "state": "pending"}) + with open(PEND, "a", encoding="utf-8") as f: + f.write(json.dumps(res, ensure_ascii=False) + "\n") + add(TGGONE, tg_uid) + ok += 1 + elif reg.get("code") == 302: + st, h, _ = s.get("/register") + t = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", h or "")) + i = t.find("Sign up with Google") + snippet = t[max(0, i - 200):i][-200:] + res["err"] = snippet + if "paused because of unusual activity" in (h or ""): + dom = email.split("@")[-1].lower() + add(BLOCK, dom) + print(json.dumps(res, ensure_ascii=False)[:300], flush=True) + print("registered", ok, flush=True) + + +if __name__ == "__main__": + main(int(sys.argv[1]) if len(sys.argv) > 1 else 8) diff --git a/fm_tg.py b/fm_tg.py new file mode 100644 index 0000000..e6faa45 --- /dev/null +++ b/fm_tg.py @@ -0,0 +1,90 @@ +"""Telegram verify for FreeModel: /start <param> + join channel/group. Prints JSON.""" +import asyncio, json, os, sys, time + +API_ID = 2040 +API_HASH = "b18441a1ff607e10a989891a5462e627" +BOT = "FreeModels_bbot" +CHAN = "FreeModel_in" +GROUP = "FreeModelChat" + + +async def free_room(cl, n=3): + """Leave oldest channels to get under the 500-chat join limit.""" + from telethon.tl.functions.channels import LeaveChannelRequest + from telethon.tl.types import Channel + left = [] + try: + async for d in cl.iter_dialogs(limit=400): + if len(left) >= n: + break + ent = d.entity + if isinstance(ent, Channel) and ent.megagroup is False and not ent.creator: + try: + await cl(LeaveChannelRequest(ent)) + left.append(d.name) + except Exception: + pass + except Exception: + pass + return left + + +async def main(sess, start_param, join=False, wait_reply=18): + from telethon import TelegramClient + from telethon.errors import FloodWaitError + from telethon.tl.functions.channels import JoinChannelRequest + out = {"session": os.path.basename(sess), "start": start_param} + try: + cl = TelegramClient(sess, API_ID, API_HASH, connection_retries=2, timeout=25, request_retries=2) + await cl.connect() + except Exception as e: + out["err"] = "connect: %s" % str(e)[:160] + return out + try: + if not await cl.is_user_authorized(): + out["err"] = "notauth" + return out + me = await cl.get_me() + out["me"] = [me.id, me.username] + bot = await cl.get_entity(BOT) + await cl.send_message(bot, "/start " + start_param) + t0 = time.time() + while time.time() - t0 < wait_reply: + msgs = await cl.get_messages(bot, limit=3) + if msgs and msgs[0].out is False: + out["bot_reply"] = (msgs[0].message or "")[:400] + break + await asyncio.sleep(2) + if join: + for tgt in (CHAN, GROUP): + for attempt in range(2): + try: + await cl(JoinChannelRequest(await cl.get_entity(tgt))) + out.setdefault("joined", []).append(tgt) + break + except FloodWaitError as e: + out.setdefault("flood", []).append([tgt, e.seconds]) + break + except Exception as e: + msg = str(e)[:120] + if attempt == 0 and ("too many channels" in msg or "CHANNELS_TOO_MUCH" in msg): + left = await free_room(cl, 3) + out.setdefault("left", []).append(left) + continue + out.setdefault("join_err", []).append([tgt, msg]) + break + except Exception as e: + out["err"] = "flow: %s" % str(e)[:200] + finally: + try: + await cl.disconnect() + except Exception: + pass + return out + + +if __name__ == "__main__": + sess = sys.argv[1] + sp = sys.argv[2] + join = len(sys.argv) > 3 and sys.argv[3] == "join" + print(json.dumps(asyncio.run(main(sess, sp, join)), ensure_ascii=False)) \ No newline at end of file diff --git a/fm_verify_batch.py b/fm_verify_batch.py new file mode 100644 index 0000000..0b3dcdd --- /dev/null +++ b/fm_verify_batch.py @@ -0,0 +1,82 @@ +"""Stage B: verify pending FreeModel accounts via Telegram + create key + probe.""" +import asyncio, json, os, random, sys, time +sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) +import fm_lib as L, fm_tg + +HERE = L.HERE +PEND = os.path.join(HERE, "fm_pending.jsonl") +BANK = os.path.join(HERE, "fm_bank.jsonl") +FAIL = os.path.join(HERE, "fm_failed.jsonl") + + +def load(p): + return [json.loads(l) for l in open(p, encoding="utf-8")] if os.path.exists(p) else [] + + +async def one(row, sem): + async with sem: + out = {"email": row["email"], "tg": row["tg_uid"]} + cj = os.path.join(HERE, "cookies", "c%s.json" % row["tg_uid"]) + s = L.Sess(cj) + r = await fm_tg.main(row["tg_path"], row["start"], join=True, wait_reply=10) + out["tg"] = {"bot": bool(r.get("bot_reply")), "joined": r.get("joined"), "jerr": r.get("join_err"), + "flood": r.get("flood"), "err": r.get("err")} + ok = False + for _ in range(5): + stt = L.status(s) + if stt.get("verified"): + ok = True + out["allow"] = stt.get("tokens_allowance") + break + await asyncio.sleep(8) + if not ok: + out["stage"] = "not_verified" + return out + s.s.headers.update({"X-Requested-With": "XMLHttpRequest", "Accept": "application/json"}) + rr = s.s.post(L.BASE + "/dashboard/api-keys", json={"scopes": ["all"], "name": "main", "token_limit": "0", + "spend_limit_usd": "0", "rpm": "0"}, timeout=30) + try: + key = rr.json().get("full_key") + except Exception: + key = None + if not key: + out["stage"] = "nokey:%s" % rr.status_code + return out + import requests as R + pr = {} + for m in ("claude-opus-5-5", "gpt-6.1-sol"): + t = time.time() + try: + q = R.post("https://freemodel.in/v1/chat/completions", headers={"Authorization": "Bearer " + key}, + json={"model": m, "messages": [{"role": "user", "content": "ping"}], "max_tokens": 8}, timeout=60) + pr[m] = [q.status_code, round(time.time() - t, 1)] + except Exception as e: + pr[m] = ["E", str(e)[:40]] + with open(BANK, "a", encoding="utf-8") as f: + f.write(json.dumps({"email": row["email"], "password": row["password"], "key": key, + "tg_uid": row["tg_uid"], "allowance": out.get("allow"), "probe": pr}, ensure_ascii=False) + "\n") + out.update({"stage": "ok", "key": key[-8:], "probe": pr}) + return out + + +async def run(limit): + rows = load(PEND) + if not rows: + print("no pending") + return + sem = asyncio.Semaphore(4) + done = [] + for coro in asyncio.as_completed([one(r, sem) for r in rows[:limit]]): + o = await coro + done.append(o) + print(json.dumps(o, ensure_ascii=False)[:260], flush=True) + okmails = {o["email"] for o in done if o.get("stage") == "ok"} + keep = [r for r in rows if r["email"] not in {o["email"] for o in done}] + with open(PEND, "w", encoding="utf-8") as f: + for r in keep: + f.write(json.dumps(r, ensure_ascii=False) + "\n") + print("verified", len(okmails), "pending_left", len(keep), flush=True) + + +if __name__ == "__main__": + asyncio.run(run(int(sys.argv[1]) if len(sys.argv) > 1 else 12)) diff --git a/namegen.py b/namegen.py new file mode 100644 index 0000000..b94a2b2 --- /dev/null +++ b/namegen.py @@ -0,0 +1,24 @@ +import random +FIRST = ["james","michael","robert","david","william","richard","joseph","thomas","charles","daniel","matthew","anthony", + "mark","donald","steven","paul","andrew","joshua","kenneth","kevin","brian","george","edward","ronald","timothy", + "jason","jeffrey","ryan","jacob","gary","nicholas","eric","jonathan","stephen","larry","justin","scott","brandon", + "benjamin","samuel","gregory","alexander","frank","patrick","raymond","jack","dennis","jerry","tyler","aaron", + "mary","patricia","jennifer","linda","elizabeth","barbara","susan","jessica","sarah","karen","nancy","lisa", + "margaret","betty","sandra","ashley","dorothy","kimberly","emily","donna","michelle","carol","amanda","melissa", + "deborah","stephanie","rebecca","sharon","laura","cynthia","kathleen","amy","angela","shirley","anna","brenda", + "pamela","emma","nicole","helen","samantha","katherine","christine","debra","rachel","carolyn","janet","catherine"] +LAST = ["smith","johnson","williams","brown","jones","garcia","miller","davis","rodriguez","martinez","hernandez","lopez", + "gonzalez","wilson","anderson","thomas","taylor","moore","jackson","martin","lee","perez","thompson","white", + "harris","sanchez","clark","ramirez","lewis","robinson","walker","young","allen","king","wright","scott","torres", + "nguyen","hill","flores","green","adams","nelson","baker","hall","rivera","campbell","mitchell","carter","roberts"] + +def gmail(): + f = random.choice(FIRST); l = random.choice(LAST) + style = random.random() + if style < 0.45: + box = "%s.%s%d" % (f, l, random.randint(11, 9999)) + elif style < 0.75: + box = "%s%s%d" % (f, l, random.randint(11, 9999)) + else: + box = "%s.%s.%s" % (f, l[0], random.randint(11, 999)) + return box + "@gmail.com" diff --git a/px_build.py b/px_build.py new file mode 100644 index 0000000..37e673d --- /dev/null +++ b/px_build.py @@ -0,0 +1,25 @@ +import json, urllib.parse, requests, concurrent.futures as cf +acc=[json.loads(l) for l in open(r"C:\Users\User\tmp\decodo_autoreg\data\accounts.jsonl",encoding='utf-8') if l.strip()] +cand=[] +for a in acc: + u,p,h=a.get('proxy_username'),a.get('proxy_password'),a.get('proxy_host') + if not (u and p and h): continue + pw=urllib.parse.quote(p,safe='~') + for port in range(10000,10010): + cand.append("%s:%s@%s:%d"%(u,pw,h,port)) +cand=list(dict.fromkeys(cand)) +def t(px): + P={"http":"http://"+px,"https":"http://"+px} + try: + r=requests.get("https://freemodel.in/register",proxies=P,timeout=20,headers={"User-Agent":"Mozilla/5.0"}) + if 'name="_token"' not in r.text: return None + ip=requests.get("https://api.ipify.org",proxies=P,timeout=15).text.strip() + return (px,ip) + except Exception: return None +good=[] +with cf.ThreadPoolExecutor(25) as ex: + for r in ex.map(t,cand): + if r: good.append(r) +print("cand",len(cand),"good",len(good)) +for g in good[:5]: print(g[1], g[0][:60]) +open("px_decodo2.txt","w").write("\n".join(g[0] for g in good)) diff --git a/px_grab.py b/px_grab.py new file mode 100644 index 0000000..ad81c75 --- /dev/null +++ b/px_grab.py @@ -0,0 +1,43 @@ +"""Collect + validate free HTTP proxies against freemodel.in.""" +import concurrent.futures as cf, json, re, sys +import requests + +SRC = [ + "https://api.proxyscrape.com/v4/free-proxy-list/get?request=display_proxies&protocol=http&proxy_format=ipport&format=text&timeout=8000", + "https://raw.githubusercontent.com/TheSpeedX/PROXY-List/master/http.txt", + "https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt", + "https://raw.githubusercontent.com/proxifly/free-proxy-list/main/proxies/protocols/http/data.txt", +] + +def grab(): + out = set() + for u in SRC: + try: + r = requests.get(u, timeout=25) + for m in re.findall(r"(\d{1,3}(?:\.\d{1,3}){3}:\d{2,5})", r.text): + out.add(m) + except Exception as e: + print("src fail", u[:40], str(e)[:60]) + return out + +def test(p, url="https://freemodel.in/register"): + px = {"http": "http://" + p, "https": "http://" + p} + try: + r = requests.get(url, proxies=px, timeout=12, headers={"User-Agent": "Mozilla/5.0"}) + if r.status_code == 200 and "FreeModel" in r.text: + return p + except Exception: + return None + return None + +if __name__ == "__main__": + cand = grab() + print("candidates", len(cand), flush=True) + ok = [] + with cf.ThreadPoolExecutor(80) as ex: + for res in ex.map(test, list(cand)): + if res: + ok.append(res) + print("OK", res, flush=True) + open("px_ok.txt", "w").write("\n".join(ok)) + print("alive", len(ok)) diff --git a/px_test2.py b/px_test2.py new file mode 100644 index 0000000..8f88189 --- /dev/null +++ b/px_test2.py @@ -0,0 +1,21 @@ +import concurrent.futures as cf, re, sys, requests +def t(p): + px={"http":"http://"+p,"https":"http://"+p} + try: + r=requests.get("https://freemodel.in/register",proxies=px,timeout=15, + headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/156.0 Safari/537.36"}) + if r.status_code!=200 or 'name="_token"' not in r.text or 'captcha.js' not in r.text: + return None + ip=requests.get("https://api.ipify.org",proxies=px,timeout=12).text.strip() + return (p,ip) + except Exception: + return None +if __name__=="__main__": + src=sys.argv[1] + ps=[x.strip() for x in open(src,encoding='utf-8') if x.strip()] + ok=[] + with cf.ThreadPoolExecutor(40) as ex: + for r in ex.map(t,ps): + if r: ok.append(r); print("OK",r[0],r[1],flush=True) + open("px_ok2.txt","w").write("\n".join(x[0] for x in ok)) + print("good",len(ok),"of",len(ps)) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1a1c6cc --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +requests +numpy +Pillow +telethon