recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
@@ -0,0 +1,162 @@
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
# Codeberg (Gitea) reg: HOME + mail.tm + API token via Basic Auth
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import string
|
||||
import sys
|
||||
import time
|
||||
import urllib.request
|
||||
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from camoufox.sync_api import Camoufox
|
||||
from gh_mail import MailTM
|
||||
|
||||
SIGNUP_URL = "https://codeberg.org/user/sign_up"
|
||||
API = "https://codeberg.org/api/v1"
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
|
||||
|
||||
def log(m):
|
||||
print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
|
||||
|
||||
|
||||
mail = MailTM()
|
||||
mb = mail.create()
|
||||
if not mb:
|
||||
log("FATAL: mailbox")
|
||||
sys.exit(2)
|
||||
addr, token = mb["address"], mb["token"]
|
||||
log(f"mailbox: {addr}")
|
||||
|
||||
username = "rev" + "".join(random.choices(string.ascii_lowercase, k=4)) + "".join(random.choices(string.digits, k=3))
|
||||
password = "Cb#" + "".join(random.choices(string.ascii_letters + string.digits, k=14)) + "!9"
|
||||
log(f"account: {username}")
|
||||
|
||||
result = {"status": "unknown", "username": username, "password": password, "email": addr}
|
||||
|
||||
with Camoufox(headless=True, humanize=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(SIGNUP_URL, timeout=90000, wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
|
||||
# Gitea signup form: user_name, email, password, retype
|
||||
fields = page.evaluate("(() => Array.from(document.querySelectorAll('input')).map(i => i.name + '|' + i.type + '|' + (i.id||'')).slice(0,12))()")
|
||||
log(f"form fields: {fields}")
|
||||
|
||||
def fill(sel, val):
|
||||
try:
|
||||
page.fill(sel, val, timeout=8000)
|
||||
time.sleep(0.6)
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
ok1 = fill("input[name=user_name]", username)
|
||||
ok2 = fill("input[name=email]", addr)
|
||||
ok3 = fill("input[name=password]", password)
|
||||
ok4 = fill("input[name=retype]", password)
|
||||
log(f"filled: name={ok1} email={ok2} pass={ok3} retype={ok4}")
|
||||
|
||||
try:
|
||||
page.click("button[type=submit], #submit", timeout=8000)
|
||||
except Exception:
|
||||
page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('button.green') || document.querySelector('button'); if (b) b.click(); })()")
|
||||
time.sleep(8)
|
||||
|
||||
st = page.evaluate("(() => ({url: location.href, body: document.body.innerText.slice(0,600)}))()")
|
||||
log(f"after submit: {st['url'][:90]}")
|
||||
log("BODY: " + st["body"][:400].replace("\n", " | "))
|
||||
|
||||
# verification code flow?
|
||||
needs_code = bool(re.search(r"verification code|confirm|activate", st["body"], re.I)) or "activate" in st["url"]
|
||||
code_el = page.evaluate("(() => !!document.querySelector('input[name*=code i], input[id*=code i], input[inputmode=numeric]'))()")
|
||||
if needs_code or code_el:
|
||||
log("email-code flow detected")
|
||||
code = mail.wait_code(token, sender_hint="codeberg", timeout_sec=300)
|
||||
log(f"code: {code}")
|
||||
if code:
|
||||
page.evaluate("""(code) => {
|
||||
const cands = ['input[name*=code i]','input[id*=code i]','input[autocomplete=one-time-code]','input[inputmode=numeric]'];
|
||||
let el = null;
|
||||
for (const c of cands) { el = document.querySelector(c); if (el) break; }
|
||||
if (!el) return;
|
||||
el.focus(); el.value = code;
|
||||
el.dispatchEvent(new Event('input', {bubbles:true}));
|
||||
}""", code)
|
||||
time.sleep(1.2)
|
||||
page.evaluate("(() => { const b = document.querySelector('button[type=submit]'); if (b) b.click(); })()")
|
||||
time.sleep(8)
|
||||
st = page.evaluate("(() => ({url: location.href, body: document.body.innerText.slice(0,500)}))()")
|
||||
log(f"after code: {st['url'][:90]}")
|
||||
log("BODY: " + st["body"][:350].replace("\n", " | "))
|
||||
|
||||
result["final_url"] = st["url"][:200]
|
||||
result["body"] = st["body"][:300]
|
||||
page.screenshot(path=OUT + r"\cb_state.png")
|
||||
|
||||
# --- API token via Basic Auth (works only if account activated) ---
|
||||
import base64
|
||||
|
||||
def api(method, path, data=None, auth=True):
|
||||
h = {"Content-Type": "application/json"}
|
||||
if auth:
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
h["Authorization"] = "Basic " + cred
|
||||
req = urllib.request.Request(
|
||||
API + path,
|
||||
data=json.dumps(data).encode() if data else None,
|
||||
headers=h,
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
return r.status, json.load(r)
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
return e.code, json.load(e)
|
||||
except Exception:
|
||||
return e.code, {}
|
||||
except Exception as e:
|
||||
return 0, {"err": str(e)[:80]}
|
||||
|
||||
stc, me = api("GET", "/user")
|
||||
log(f"API /user: {stc} -> {str(me)[:120]}")
|
||||
if stc == 200:
|
||||
stt, tok = api("POST", f"/users/{username}/tokens", {"name": "push", "scopes": ["write:repository", "read:user"]})
|
||||
log(f"API token: {stt} -> {str(tok)[:120]}")
|
||||
result["status"] = "OK"
|
||||
result["pat"] = tok.get("sha1")
|
||||
print(json.dumps(result))
|
||||
else:
|
||||
result["status"] = "pending_activation"
|
||||
print(json.dumps(result))
|
||||
@@ -0,0 +1,170 @@
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
# Codeberg reg v2: image-captcha solved by operator (poll answer file)
|
||||
import json
|
||||
import random
|
||||
import string
|
||||
import sys
|
||||
import time
|
||||
import base64
|
||||
import os
|
||||
import re
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from camoufox.sync_api import Camoufox
|
||||
from gh_mail import MailTM
|
||||
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
CAP = OUT + r"\cb_captcha.png"
|
||||
ANS = OUT + r"\cb_answer.txt"
|
||||
SIGNUP_URL = "https://codeberg.org/user/sign_up"
|
||||
API = "https://codeberg.org/api/v1"
|
||||
|
||||
|
||||
def log(m):
|
||||
print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
|
||||
|
||||
|
||||
for f in (ANS,):
|
||||
if os.path.exists(f):
|
||||
os.remove(f)
|
||||
|
||||
mail = MailTM()
|
||||
mb = mail.create()
|
||||
addr, token = mb["address"], mb["token"]
|
||||
log(f"mailbox: {addr}")
|
||||
|
||||
username = "dev" + "".join(random.choices(string.ascii_lowercase, k=5)) + "".join(random.choices(string.digits, k=3))
|
||||
password = "Cb#" + "".join(random.choices(string.ascii_letters + string.digits, k=14)) + "!9"
|
||||
log(f"account: {username}")
|
||||
|
||||
result = {"username": username, "password": password, "email": addr}
|
||||
|
||||
with Camoufox(headless=True, humanize=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(SIGNUP_URL, timeout=90000, wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
|
||||
page.fill("input[name=user_name]", username)
|
||||
page.fill("input[name=email]", addr)
|
||||
page.fill("input[name=password]", password)
|
||||
page.fill("input[name=retype]", password)
|
||||
time.sleep(1)
|
||||
|
||||
# screenshot the captcha image
|
||||
try:
|
||||
img = page.locator("img.captcha, img#captcha-img, img[src*=captcha]").first
|
||||
img.wait_for(state="visible", timeout=10000)
|
||||
img.screenshot(path=CAP)
|
||||
log("captcha screenshot saved -> cb_captcha.png")
|
||||
except Exception:
|
||||
page.screenshot(path=CAP)
|
||||
log("captcha element not found; full page saved")
|
||||
|
||||
# wait for operator answer
|
||||
log("waiting operator answer (cb_answer.txt)...")
|
||||
answer = None
|
||||
for _ in range(90):
|
||||
if os.path.exists(ANS):
|
||||
answer = open(ANS).read().strip()
|
||||
if answer:
|
||||
break
|
||||
time.sleep(4)
|
||||
log(f"captcha answer: {answer!r}")
|
||||
if not answer:
|
||||
log("FATAL: no operator answer")
|
||||
sys.exit(3)
|
||||
|
||||
page.fill("input[name=img-captcha-response]", answer)
|
||||
time.sleep(0.8)
|
||||
try:
|
||||
page.click("button[type=submit]", timeout=8000)
|
||||
except Exception:
|
||||
page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('button'); if (b) b.click(); })()")
|
||||
time.sleep(8)
|
||||
|
||||
st = page.evaluate("() => ({url: location.href, body: document.body.innerText.slice(0,500)})()")
|
||||
log(f"after submit: {st['url'][:90]}")
|
||||
log("BODY: " + st["body"][:350].replace("\n", " | "))
|
||||
page.screenshot(path=OUT + r"\cb_state2.png")
|
||||
result["after_submit"] = st["body"][:200]
|
||||
|
||||
# email code?
|
||||
code_el = page.evaluate("() => !!document.querySelector('input[name*=code i], input[id*=code i]')")
|
||||
if code_el or "verification" in st["body"].lower():
|
||||
log("email-code flow")
|
||||
code = mail.wait_code(token, sender_hint="codeberg", timeout_sec=300)
|
||||
log(f"code: {code}")
|
||||
if code:
|
||||
page.evaluate("""(code) => {
|
||||
const cands = ['input[name*=code i]','input[id*=code i]','input[autocomplete=one-time-code]'];
|
||||
let el = null;
|
||||
for (const c of cands) { el = document.querySelector(c); if (el) break; }
|
||||
if (!el) return;
|
||||
el.focus(); el.value = code;
|
||||
el.dispatchEvent(new Event('input', {bubbles:true}));
|
||||
}""", code)
|
||||
time.sleep(1)
|
||||
page.evaluate("(() => { const b = document.querySelector('button[type=submit]'); if (b) b.click(); })()")
|
||||
time.sleep(8)
|
||||
st = page.evaluate("() => ({url: location.href, body: document.body.innerText.slice(0,400)})()")
|
||||
log("AFTER CODE: " + st["body"][:300].replace("\n", " | "))
|
||||
result["after_code"] = st["body"][:200]
|
||||
|
||||
# API token via Basic Auth
|
||||
def api(method, path, data=None):
|
||||
cred = base64.b64encode(f"{username}:{password}".encode()).decode()
|
||||
req = urllib.request.Request(
|
||||
API + path,
|
||||
data=json.dumps(data).encode() if data else None,
|
||||
headers={"Content-Type": "application/json", "Authorization": "Basic " + cred},
|
||||
method=method,
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as r:
|
||||
return r.status, json.load(r)
|
||||
except urllib.error.HTTPError as e:
|
||||
try:
|
||||
return e.code, json.load(e)
|
||||
except Exception:
|
||||
return e.code, {}
|
||||
|
||||
stc, me = api("GET", "/user")
|
||||
log(f"API /user: {stc} -> {str(me)[:140]}")
|
||||
result["api_user"] = stc
|
||||
if stc == 200:
|
||||
stt, tok = api("POST", f"/users/{username}/tokens", {"name": "push1", "scopes": ["write:repository", "read:user"]})
|
||||
log(f"token: {stt} -> {str(tok)[:100]}")
|
||||
if stt == 201:
|
||||
result["pat"] = tok.get("sha1")
|
||||
print(json.dumps(result))
|
||||
@@ -0,0 +1,140 @@
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
# FAST registration worker: tight loop, rotate IP every 3 accounts, no long pauses
|
||||
import subprocess, time, sqlite3, sys
|
||||
|
||||
PY = _PY
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
DB = OUT + r"\accounts.db"
|
||||
LOG = open(OUT + r"\fast_reg.log", "a", encoding="utf-8")
|
||||
|
||||
TARGET = int(sys.argv[1]) if len(sys.argv) > 1 else 1000
|
||||
PER_IP = 3
|
||||
|
||||
|
||||
def log(m):
|
||||
print(m, flush=True)
|
||||
LOG.write(m + "\n")
|
||||
LOG.flush()
|
||||
|
||||
|
||||
def ok_count():
|
||||
db = sqlite3.connect(DB)
|
||||
n = db.execute("SELECT COUNT(*) FROM accounts WHERE status='OK_VERIFIED'").fetchone()[0]
|
||||
db.close()
|
||||
return n
|
||||
|
||||
|
||||
def run(cmd, timeout):
|
||||
try:
|
||||
r = subprocess.run([PY, "-u"] + cmd, cwd=OUT, capture_output=True, text=True, timeout=timeout)
|
||||
return r.returncode, (r.stdout or "") + (r.stderr or "")
|
||||
except subprocess.TimeoutExpired:
|
||||
return 99, "timeout"
|
||||
|
||||
|
||||
idx = 400
|
||||
made_on_ip = PER_IP # rotate immediately on start
|
||||
consecutive_ft = 0
|
||||
|
||||
|
||||
def relay_alive():
|
||||
import socket as sk
|
||||
try:
|
||||
s = sk.create_connection(("127.0.0.1", 8899), timeout=3)
|
||||
s.close()
|
||||
return True
|
||||
except OSError:
|
||||
return False
|
||||
|
||||
|
||||
def heal_relay():
|
||||
import subprocess as sp
|
||||
try:
|
||||
sp.Popen([PY, "zte_relay.py"], cwd=str(_d("tmp")),
|
||||
creationflags=0x00000008) # DETACHED_PROCESS, no wait
|
||||
log("relay healed (restarted)")
|
||||
except Exception as e:
|
||||
log(f"relay heal failed: {e}")
|
||||
|
||||
|
||||
while True:
|
||||
if not relay_alive():
|
||||
log("relay dead (proactive probe) — healing")
|
||||
heal_relay()
|
||||
time.sleep(5)
|
||||
ok = ok_count()
|
||||
if ok >= TARGET:
|
||||
log(f"TARGET {TARGET} reached (ok={ok})")
|
||||
break
|
||||
# rotate every PER_IP accounts
|
||||
if made_on_ip >= PER_IP:
|
||||
# wait for warm worker to finish its browser session (modem disconnect kills it)
|
||||
import os, glob
|
||||
for _ in range(60):
|
||||
flags = glob.glob(OUT + r"\warm_busy_*.flag")
|
||||
if not flags:
|
||||
break
|
||||
# stale flag cleanup (crashed warm worker)
|
||||
for f in flags:
|
||||
try:
|
||||
if time.time() - os.path.getmtime(f) > 1200:
|
||||
os.remove(f)
|
||||
log("removed stale warm flag")
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(3)
|
||||
|
||||
try:
|
||||
subprocess.run([PY, "-u", "zte_ui_rotate2.py"], cwd=OUT, capture_output=True, timeout=300)
|
||||
log("rotated IP")
|
||||
except Exception:
|
||||
log("rotate failed — continuing on current IP")
|
||||
made_on_ip = 0
|
||||
idx += 1
|
||||
t0 = time.time()
|
||||
rc, out = run(["gh_autoreg.py", str(idx).zfill(3), "ZTE", "gmail"], 700)
|
||||
dt = time.time() - t0
|
||||
if "OK_VERIFIED" in out:
|
||||
made_on_ip += 1
|
||||
consecutive_ft = 0
|
||||
log(f"reg #{idx}: OK ({dt:.0f}s) ok_total={ok + 1}")
|
||||
time.sleep(20)
|
||||
else:
|
||||
reason = "timeout" if rc == 99 else ("FORM_TIMEOUT" if "FORM_TIMEOUT" in out else "fail")
|
||||
log(f"reg #{idx}: {reason} ({dt:.0f}s)")
|
||||
if reason == "FORM_TIMEOUT":
|
||||
consecutive_ft += 1
|
||||
if consecutive_ft >= 3:
|
||||
heal_relay()
|
||||
consecutive_ft = 0
|
||||
time.sleep(8)
|
||||
made_on_ip += 2 # fails burn the IP budget 2x faster -> rotate sooner
|
||||
@@ -0,0 +1,655 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""GitHub account autoregister 2026 (v3).
|
||||
2026 form = single page: #email, #password, #login + country + one submit.
|
||||
Flow: mailbox -> /signup (wait DataDome; drag slider if shown) -> reject cookies ->
|
||||
fill all fields -> submit (form button[type=submit] only) -> mail code -> verify -> save.
|
||||
Usage: python gh_autoreg.py IDX [proxy_label|HOME] [mailtm|gmail]
|
||||
"""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import time, json, re, random, string, sys, os
|
||||
from camoufox.sync_api import Camoufox
|
||||
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from gh_mail import MailTM, GmailIMAP
|
||||
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
ACCOUNTS = OUT + r"\github_accounts.jsonl"
|
||||
LOG = OUT + r"\gh_autoreg.log"
|
||||
|
||||
IDX = (sys.argv[1] if len(sys.argv) > 1 else str(random.randint(1, 999))).zfill(3)
|
||||
PROXY_LABEL = sys.argv[2] if len(sys.argv) > 2 else "HOME"
|
||||
MAIL_MODE = sys.argv[3] if len(sys.argv) > 3 else "mailtm"
|
||||
|
||||
P_USER = "bpproxy-user"
|
||||
P_PASS = "BPPROXY_PASS"
|
||||
P_HOST = "bpproxy-host:1000"
|
||||
DEBUG_SHOTS = os.path.isdir(str(_w("tmp/bpproxy_run/shots")))
|
||||
CAPTCHA_WAIT = 160
|
||||
|
||||
gmail = GmailIMAP()
|
||||
|
||||
# ---- TG push: instant creds delivery ----
|
||||
TG_BOT = {"bot_token": "TG_BOT_TOKEN"}
|
||||
TG_BACKUP = {"chat_id": "TG_CHAT_ID", "thread": "350384",
|
||||
"token_alt": "7189316701"}
|
||||
TG_CHATID_FILE = OUT + r"\gh_bot_chatid.txt"
|
||||
|
||||
|
||||
def tg_request(token, method, params, timeout=25):
|
||||
try:
|
||||
req = __import__("urllib").request.Request(
|
||||
"https://api.telegram.org/bot%s/%s" % (token, method),
|
||||
data=__import__("urllib").parse.urlencode(params).encode())
|
||||
with __import__("urllib").request.urlopen(req, timeout=timeout) as r:
|
||||
return json.loads(r.read().decode())
|
||||
except Exception:
|
||||
return {"ok": False}
|
||||
|
||||
|
||||
def tg_chat_id():
|
||||
try:
|
||||
with open(TG_CHATID_FILE) as f:
|
||||
v = f.read().strip()
|
||||
if v:
|
||||
return v
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
upd = tg_request(TG_BOT["bot_token"], "getUpdates",
|
||||
{"limit": 5, "timeout": 1})
|
||||
for u in upd.get("result", []):
|
||||
ch = u.get("message", {}).get("chat", {}).get("id")
|
||||
if ch:
|
||||
open(TG_CHATID_FILE, "w").write(str(ch))
|
||||
return str(ch)
|
||||
except Exception:
|
||||
pass
|
||||
return None
|
||||
|
||||
|
||||
def tg_push_creds(email, username, password):
|
||||
msg = ("GitHub OK!\nemail: %s\nusername: %s\npassword: %s" %
|
||||
(email, username, password))
|
||||
cid = tg_chat_id()
|
||||
if cid:
|
||||
r = tg_request(TG_BOT["bot_token"], "sendMessage",
|
||||
{"chat_id": cid, "text": msg})
|
||||
if r.get("ok"):
|
||||
log("TG pushed to Hermetik chat " + cid)
|
||||
return True
|
||||
try:
|
||||
tok = re.search(r"[0-9]{10}:[A-Za-z0-9_-]{30,}",
|
||||
open((_pos.environ.get("HERMES_CONFIG","")),
|
||||
encoding="utf-8").read()).group(1)
|
||||
except Exception:
|
||||
tok = None
|
||||
if tok:
|
||||
r = tg_request(tok, "sendMessage",
|
||||
{"chat_id": TG_BACKUP["chat_id"],
|
||||
"message_thread_id": TG_BACKUP["thread"],
|
||||
"text": msg})
|
||||
if r.get("ok"):
|
||||
log("TG pushed to backup chat")
|
||||
else:
|
||||
log("TG push failed: no token")
|
||||
# last-resort fallback: Telethon R3fIex -> reformboss DM
|
||||
try:
|
||||
import subprocess
|
||||
rc = subprocess.run(
|
||||
[_PY, OUT + "\tg_push_r3f.py", msg],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
if rc.returncode == 0:
|
||||
log("TG pushed via R3fIex DM")
|
||||
else:
|
||||
log("R3fIex push rc=%d %s" % (rc.returncode, rc.stdout[-120:]))
|
||||
except Exception as e:
|
||||
log("R3fIex push EXC: " + str(e)[:120])
|
||||
|
||||
def log(m):
|
||||
line = f"[{time.strftime('%H:%M:%S')}] [{IDX}] {m}"
|
||||
print(line, flush=True)
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
|
||||
def save(rec):
|
||||
rec = {"idx": IDX, "ts": time.strftime("%Y-%m-%d %H:%M:%S"), **rec}
|
||||
with open(ACCOUNTS, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||
log("SAVED: " + json.dumps(rec, ensure_ascii=False)[:240])
|
||||
try:
|
||||
import gh_db
|
||||
db_rec = {k: v for k, v in rec.items() if k in gh_db.VALID_COLS}
|
||||
if "ts" in rec and "created_ts" not in db_rec:
|
||||
db_rec["created_ts"] = rec["ts"]
|
||||
if "body" in rec or set(rec) - set(gh_db.VALID_COLS):
|
||||
extra = {k: v for k, v in rec.items() if k not in gh_db.VALID_COLS}
|
||||
if extra:
|
||||
db_rec["notes"] = json.dumps(extra, ensure_ascii=False)[:2000]
|
||||
gh_db.upsert_account(db_rec)
|
||||
log("DB saved")
|
||||
except Exception as e:
|
||||
log("DB save EXC: " + str(e)[:150])
|
||||
if rec.get("status") == "OK_VERIFIED":
|
||||
try:
|
||||
tg_push_creds(rec.get("email", ""), rec.get("username", ""),
|
||||
rec.get("password", ""))
|
||||
except Exception as e:
|
||||
log("tg_push EXC: " + str(e)[:150])
|
||||
|
||||
def proxy_cfg():
|
||||
if PROXY_LABEL == "SOCKSH":
|
||||
return {"server": "socks5://127.0.0.1:2090"}
|
||||
if PROXY_LABEL == "ZTE":
|
||||
return {"server": "http://127.0.0.1:8899"}
|
||||
if PROXY_LABEL == "HK1024":
|
||||
# 1024proxy HK mobile sticky: rotate over verified-clean sids
|
||||
import random as _r
|
||||
try:
|
||||
pool = [88291] + [int(x) for x in open(str(_w("tmp/bpproxy_run/clean_sids.txt"))).read().split() if x.strip()]
|
||||
except Exception:
|
||||
pool = [88291]
|
||||
sid = _r.choice(pool)
|
||||
return {"server": "http://hk.1024proxy.io:3000",
|
||||
"username": f"PROXY_USER-region-HK-sid-{sid}-t-30",
|
||||
"password": "PROXY_PASS"}
|
||||
if PROXY_LABEL == "ZTE":
|
||||
return {"server": "http://127.0.0.1:8899"}
|
||||
return {"server": f"http://{P_HOST}", "username": P_USER,
|
||||
"password": f"{P_PASS}_session-{PROXY_LABEL}_lifetime-30"}
|
||||
|
||||
def gen_pass():
|
||||
return "Gh#" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "@9x"
|
||||
|
||||
def gen_username():
|
||||
adj = ["neon", "crimson", "violet", "silver", "arctic", "lunar", "cobalt", "amber", "steel", "ember"]
|
||||
noun = ["dev", "lab", "forge", "stack", "grid", "byte", "flux", "chip", "logic", "node"]
|
||||
return (random.choice(adj) + random.choice(noun) + "".join(random.choices(string.digits, k=3)))[:28].lower()
|
||||
|
||||
def ev(page, js):
|
||||
try:
|
||||
return page.evaluate(js)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def try_drag_slider(page):
|
||||
for fr in page.frames:
|
||||
try:
|
||||
u = fr.url or ""
|
||||
except Exception:
|
||||
continue
|
||||
if "captcha" not in u:
|
||||
continue
|
||||
try:
|
||||
info = fr.evaluate("""(() => {
|
||||
const out = [];
|
||||
document.querySelectorAll('button,input,div[id],div[class]').forEach(e => {
|
||||
if (out.length > 40) return;
|
||||
const r = e.getBoundingClientRect();
|
||||
const blob = ((e.id||'')+' '+((e.className||'')).toString()).toLowerCase();
|
||||
if (r.width>8 && r.height>8 && /slider|drag|handle|captcha|button/i.test(blob))
|
||||
out.push({tag:e.tagName, id:e.id||'', cls:(e.className||'').toString().slice(0,50),
|
||||
x:Math.round(r.x), y:Math.round(r.y), w:Math.round(r.width), h:Math.round(r.height)});
|
||||
});
|
||||
return out;
|
||||
})()""")
|
||||
except Exception:
|
||||
continue
|
||||
target = None
|
||||
for e in info:
|
||||
blob = (e["id"] + " " + e["cls"]).lower()
|
||||
if ("slider" in blob or "drag" in blob or "handle" in blob) and e["w"] < 100:
|
||||
target = e
|
||||
break
|
||||
if not target:
|
||||
continue
|
||||
try:
|
||||
fb = page.evaluate("""(() => {
|
||||
const f = Array.from(document.querySelectorAll('iframe')).find(f => f.src.includes('captcha'));
|
||||
if (!f) return null; const r = f.getBoundingClientRect();
|
||||
return {x:r.x, y:r.y, w:r.width, h:r.height};
|
||||
})()""")
|
||||
if not fb:
|
||||
return False
|
||||
iw = fr.evaluate("document.documentElement.clientWidth") or fb["w"] or 1
|
||||
scale = fb["w"] / max(iw, 1)
|
||||
ax = fb["x"] + (target["x"] + target["w"] / 2) * scale
|
||||
ay = fb["y"] + (target["y"] + target["h"] / 2) * scale
|
||||
endx = fb["x"] + fb["w"] - 30
|
||||
except Exception:
|
||||
continue
|
||||
rng = random.Random()
|
||||
log(f"SLIDER drag {round(ax)}->{round(endx)}")
|
||||
page.mouse.move(ax, ay)
|
||||
time.sleep(0.35 + rng.random() * 0.3)
|
||||
page.mouse.down()
|
||||
time.sleep(0.3)
|
||||
steps = rng.randint(26, 36)
|
||||
for i in range(steps):
|
||||
f_ = (i + 1) / steps
|
||||
page.mouse.move(ax + (endx - ax) * f_, ay + rng.uniform(-3, 3))
|
||||
time.sleep(rng.uniform(0.012, 0.036))
|
||||
page.mouse.move(endx, ay + rng.uniform(-2, 2))
|
||||
time.sleep(0.2)
|
||||
page.mouse.up()
|
||||
log("SLIDER dragged")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ---- DataDome trust-cookie carry-over (ported from regkit) ----
|
||||
_TRUST_FILE = OUT + r"\.datadome-trust.json"
|
||||
_TRUST_NAMES = {"datadome", "datadome_proxied", "device_id", "_device_id"}
|
||||
_cur_exit_ip = None
|
||||
|
||||
|
||||
def _exit_ip():
|
||||
global _cur_exit_ip
|
||||
if _cur_exit_ip:
|
||||
return _cur_exit_ip
|
||||
import requests
|
||||
try:
|
||||
server = (proxy_cfg() or {}).get("server", "http://127.0.0.1:8899")
|
||||
px = {"http": server, "https": server}
|
||||
_cur_exit_ip = requests.get("https://api.ipify.org", proxies=px, timeout=10).text.strip()
|
||||
except Exception:
|
||||
_cur_exit_ip = ""
|
||||
return _cur_exit_ip
|
||||
|
||||
|
||||
def dd_save_trust(context):
|
||||
import json as _j
|
||||
try:
|
||||
keep = [c for c in context.cookies()
|
||||
if c.get("name") in _TRUST_NAMES and c.get("domain", "").endswith("github.com")]
|
||||
if not keep:
|
||||
return
|
||||
open(_TRUST_FILE, "w").write(_j.dumps({"cookies": keep, "exit_ip": _exit_ip()}))
|
||||
log(f"dd trust saved ({len(keep)} cookies, ip={_cur_exit_ip})")
|
||||
except Exception as e:
|
||||
log(f"trust save err {str(e)[:60]}")
|
||||
|
||||
|
||||
def dd_restore_trust(context):
|
||||
import json as _j, os
|
||||
try:
|
||||
if not os.path.exists(_TRUST_FILE):
|
||||
return
|
||||
data = _j.loads(open(_TRUST_FILE).read())
|
||||
bound_ip = data.get("exit_ip") or ""
|
||||
cur = _exit_ip()
|
||||
if bound_ip and cur and bound_ip != cur:
|
||||
log(f"trust skip (bound {bound_ip} != cur {cur})")
|
||||
return
|
||||
if not cur:
|
||||
return
|
||||
clean = []
|
||||
for c in data.get("cookies") or []:
|
||||
cc = {k: c[k] for k in ("name", "value", "domain", "path",
|
||||
"expires", "httpOnly", "secure", "sameSite") if k in c}
|
||||
cc.setdefault("domain", ".github.com")
|
||||
cc.setdefault("path", "/")
|
||||
cc.setdefault("secure", True)
|
||||
cc.setdefault("httpOnly", False)
|
||||
clean.append(cc)
|
||||
context.add_cookies(clean)
|
||||
log(f"dd trust restored ({len(clean)})")
|
||||
except Exception as e:
|
||||
log(f"trust restore err {str(e)[:60]}")
|
||||
|
||||
|
||||
def is_hard_block(page):
|
||||
t = (body_text(page) or "").lower()
|
||||
return "access is temporarily restricted" in t or "too many requests" in t
|
||||
|
||||
|
||||
def open_signup(page):
|
||||
deadline = time.time() + CAPTCHA_WAIT
|
||||
last_drag = 0
|
||||
first_pass = True
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
if first_pass:
|
||||
# referral entry (regkit): arrive like a search-result visitor
|
||||
try:
|
||||
page.goto("https://github.com/?utm_source=google", timeout=60000,
|
||||
wait_until="domcontentloaded")
|
||||
ev(page, """(() => { const a = Array.from(document.querySelectorAll('a'))
|
||||
.find(x => (x.innerText||'').trim() === 'Sign up'); if (a) { a.click(); return true; } return false; })()""")
|
||||
time.sleep(3)
|
||||
except Exception:
|
||||
page.goto("https://github.com/signup", timeout=60000, wait_until="domcontentloaded")
|
||||
first_pass = False
|
||||
else:
|
||||
page.goto("https://github.com/signup", timeout=60000, wait_until="domcontentloaded")
|
||||
except Exception as e:
|
||||
log(f"nav err {str(e)[:60]}")
|
||||
time.sleep(5)
|
||||
continue
|
||||
t0 = time.time()
|
||||
last_reload = time.time()
|
||||
while time.time() < deadline:
|
||||
if is_hard_block(page):
|
||||
log("HARD BLOCK detected — aborting early")
|
||||
return False
|
||||
st = ev(page, "(() => ({email: !!(document.querySelector('input#email') && document.querySelector('input#email').offsetParent), captcha: !!document.querySelector('iframe[src*=captcha]')}))()")
|
||||
if st["email"]:
|
||||
log(f"FORM VISIBLE after ~{int(time.time()-t0)}s")
|
||||
return True
|
||||
if st["captcha"] and time.time() - last_drag > 8:
|
||||
if try_drag_slider(page):
|
||||
last_drag = time.time()
|
||||
time.sleep(6)
|
||||
if time.time() - last_reload > 25:
|
||||
log("stale challenge, reloading")
|
||||
try:
|
||||
page.goto("https://github.com/signup", timeout=60000, wait_until="domcontentloaded")
|
||||
except Exception:
|
||||
pass
|
||||
last_reload = time.time()
|
||||
time.sleep(4)
|
||||
return False
|
||||
|
||||
def dismiss_cookies(page):
|
||||
ev(page, """(() => {
|
||||
let b = document.querySelector('button[data-testid=cookie-banner-accept], #ghcc button, .cookie-banner button, button[data-accept-cookie], button[data-consent-accept]');
|
||||
if (!b) b = Array.from(document.querySelectorAll('button')).find(x => /^(Accept|Reject|Accept all|Allow all|Agree)( all| cookies)?$/i.test((x.innerText||'').trim()));
|
||||
if (b) { b.click(); }
|
||||
setTimeout(() => { const c = document.querySelector('ghcc-consent'); if (c) c.remove(); }, 500);
|
||||
return b ? 'dismissed' : 'none';
|
||||
})()""")
|
||||
|
||||
def setf(page, sel, val):
|
||||
s = json.dumps(sel)
|
||||
v = json.dumps(val)
|
||||
return ev(page, f"""(() => {{
|
||||
const el = document.querySelector({s});
|
||||
if (!el) return 'NO_EL';
|
||||
el.focus(); el.value = {v};
|
||||
el.dispatchEvent(new Event('input', {{bubbles:true}}));
|
||||
el.dispatchEvent(new Event('change', {{bubbles:true}}));
|
||||
el.dispatchEvent(new Event('blur', {{bubbles:true}}));
|
||||
return el.value === {v} ? 'OK' : 'MISMATCH:' + el.value;
|
||||
}})()""")
|
||||
|
||||
|
||||
def human_sleep(base=1.0, spread=0.6):
|
||||
"""Human-ish pause: base +- spread, occasionally a longer 'distraction'."""
|
||||
t = random.uniform(base - spread, base + spread)
|
||||
if random.random() < 0.08: # rare distraction pause
|
||||
t += random.uniform(2.0, 5.0)
|
||||
time.sleep(max(0.2, t))
|
||||
|
||||
|
||||
def human_type(page, sel, text, click_first=True, allow_typo=False):
|
||||
"""Type like a person: click into field, variable per-char delays.
|
||||
allow_typo=True adds rare typo+backspace-fix (use only for usernames/bios,
|
||||
NEVER for email/password — a half-fixed typo corrupts creds)."""
|
||||
loc = page.locator(sel)
|
||||
if click_first:
|
||||
box = loc.bounding_box()
|
||||
if box:
|
||||
page.mouse.move(box["x"] + box["width"] * random.uniform(0.3, 0.7),
|
||||
box["y"] + box["height"] * random.uniform(0.3, 0.7),
|
||||
steps=random.randint(8, 18))
|
||||
human_sleep(0.4, 0.3)
|
||||
loc.click()
|
||||
human_sleep(0.3, 0.2)
|
||||
# rare typo: swap two adjacent chars, then fix with backspaces
|
||||
typo_idx = None
|
||||
if allow_typo and len(text) > 4 and random.random() < 0.18:
|
||||
typo_idx = random.randint(1, len(text) - 2)
|
||||
broken = text[:typo_idx] + text[typo_idx + 1] + text[typo_idx] + text[typo_idx + 2:]
|
||||
else:
|
||||
broken = text
|
||||
typed = ""
|
||||
for ch_i, ch in enumerate(broken):
|
||||
page.keyboard.type(ch, delay=0)
|
||||
typed += ch
|
||||
# per-char variable delay
|
||||
d = random.uniform(0.05, 0.16)
|
||||
if ch in "@.#-_!": # shifted keys take longer
|
||||
d += random.uniform(0.05, 0.12)
|
||||
if random.random() < 0.04: # micro-think
|
||||
d += random.uniform(0.3, 0.9)
|
||||
time.sleep(d)
|
||||
if typo_idx is not None:
|
||||
time.sleep(random.uniform(0.3, 0.8)) # notice the typo
|
||||
page.keyboard.press("Backspace")
|
||||
time.sleep(random.uniform(0.08, 0.2))
|
||||
page.keyboard.press("Backspace")
|
||||
time.sleep(random.uniform(0.15, 0.4))
|
||||
for ch in (text[typo_idx], text[typo_idx + 1]):
|
||||
page.keyboard.type(ch, delay=0)
|
||||
time.sleep(random.uniform(0.06, 0.15))
|
||||
return typed
|
||||
|
||||
|
||||
def human_scroll(page, direction="down", n=None):
|
||||
"""Scroll like a reader: several wheel steps with pauses, sometimes up a bit."""
|
||||
n = n or random.randint(2, 5)
|
||||
dy = random.randint(180, 420) * (1 if direction == "down" else -1)
|
||||
for _ in range(n):
|
||||
page.mouse.wheel(0, dy + random.randint(-60, 60))
|
||||
time.sleep(random.uniform(0.2, 0.7))
|
||||
if random.random() < 0.25: # scroll back up to check something
|
||||
page.mouse.wheel(0, -random.randint(100, 300))
|
||||
time.sleep(random.uniform(0.3, 0.8))
|
||||
|
||||
|
||||
def human_move_mouse(page, target_box=None):
|
||||
"""Idle-ish mouse drift to a random spot or near a target box."""
|
||||
if target_box:
|
||||
x = target_box["x"] + random.uniform(0.1, 0.9) * target_box["width"]
|
||||
y = target_box["y"] + random.uniform(0.1, 0.9) * target_box["height"]
|
||||
else:
|
||||
x = random.uniform(120, 900)
|
||||
y = random.uniform(120, 700)
|
||||
page.mouse.move(x, y, steps=random.randint(10, 25))
|
||||
time.sleep(random.uniform(0.1, 0.4))
|
||||
|
||||
def submit_form(page):
|
||||
"""Click the primary Create account button; SSO buttons excluded."""
|
||||
return ev(page, """(() => {
|
||||
const bs = Array.from(document.querySelectorAll('button'));
|
||||
let b = bs.find(x => {
|
||||
const t = (x.innerText||'').trim();
|
||||
return !x.disabled && x.offsetParent && /^Create account/i.test(t) && !/google|apple|continue with/i.test(t);
|
||||
});
|
||||
if (b) { b.click(); return 'create_account'; }
|
||||
const f = document.querySelector('form[action*=signup]');
|
||||
if (f) {
|
||||
const s = f.querySelector('button[type=submit]');
|
||||
if (s && !/google|apple|continue with/i.test((s.innerText||''))) { s.click(); return 'signup_form_submit'; }
|
||||
}
|
||||
return 'NONE';
|
||||
})()""")
|
||||
|
||||
def body_text(page):
|
||||
try:
|
||||
return ev(page, "document.body.innerText.slice(0,500)").replace("\n", " | ")
|
||||
except Exception:
|
||||
return "?"
|
||||
|
||||
def main():
|
||||
email = None
|
||||
mailtm_box = None
|
||||
if MAIL_MODE == "mailtm":
|
||||
try:
|
||||
mailtm_box = MailTM().create()
|
||||
email = mailtm_box["address"]
|
||||
log(f"mailbox: {email}")
|
||||
except Exception as e:
|
||||
log(f"mailtm failed ({str(e)[:100]}) -> gmail fallback")
|
||||
mailtm_box = None
|
||||
if not email:
|
||||
email = gmail.make_address()
|
||||
log(f"mailbox(gmail): {email}")
|
||||
username = gen_username()
|
||||
password = gen_pass()
|
||||
cfg = None if PROXY_LABEL == "HOME" else proxy_cfg()
|
||||
attempt_label = PROXY_LABEL
|
||||
for browser_try in range(3):
|
||||
if browser_try > 0 and PROXY_LABEL not in ("HOME", "SOCKSH", "HK1024", "ZTE"):
|
||||
attempt_label = (("ghrt" + IDX + "x" * browser_try))[:15]
|
||||
cfg = {"server": f"http://{P_HOST}", "username": P_USER,
|
||||
"password": f"{P_PASS}_session-{attempt_label}_lifetime-30"}
|
||||
log(f"browser retry #{browser_try} new sticky label={attempt_label}")
|
||||
elif browser_try > 0:
|
||||
cfg = None if PROXY_LABEL == "HOME" else proxy_cfg()
|
||||
log(f"browser retry #{browser_try} fresh {PROXY_LABEL} session")
|
||||
try:
|
||||
with Camoufox(proxy=cfg, headless=True, humanize=True, geoip=True) as browser:
|
||||
page = browser.new_page()
|
||||
dd_restore_trust(page.context)
|
||||
if not open_signup(page):
|
||||
save({"status": "FORM_TIMEOUT", "email": email, "username": username, "password": password})
|
||||
return 2
|
||||
time.sleep(random.uniform(2.5, 4.5)) # look at the page first
|
||||
dismiss_cookies(page)
|
||||
human_move_mouse(page) # idle drift
|
||||
human_sleep(1.5, 0.8)
|
||||
|
||||
# type like a human: email -> pause -> password -> pause -> username
|
||||
human_type(page, "#email", email)
|
||||
human_sleep(1.4, 0.7)
|
||||
human_move_mouse(page)
|
||||
human_type(page, "#password", password)
|
||||
human_sleep(1.1, 0.5)
|
||||
human_type(page, "#login", username, allow_typo=True)
|
||||
# 'review' the form: small scroll + re-read
|
||||
human_sleep(1.8, 0.9)
|
||||
human_move_mouse(page)
|
||||
human_sleep(0.9, 0.5)
|
||||
if DEBUG_SHOTS:
|
||||
page.screenshot(path=OUT + f"\\gh_a{IDX}_1filled.png")
|
||||
|
||||
sub = submit_form(page)
|
||||
log("submit: " + sub)
|
||||
time.sleep(12)
|
||||
st = ev(page, "(() => ({url: location.href, body: document.body.innerText.slice(0,500)}))()") or {}
|
||||
st.setdefault("body", "")
|
||||
st.setdefault("url", "")
|
||||
st["body"] = (st["body"] or "").replace("\n", " | ")
|
||||
log("after submit: url=" + st["url"][:120])
|
||||
log("BODY: " + st["body"][:400])
|
||||
if DEBUG_SHOTS:
|
||||
page.screenshot(path=OUT + f"\\gh_a{IDX}_4submit.png")
|
||||
|
||||
if "accounts.google.com" in st["url"] or "apple" in st["url"]:
|
||||
save({"status": "SSO_REDIRECT", "email": email, "username": username, "password": password, "url": st["url"]})
|
||||
return 7
|
||||
if "captcha" in st["url"].lower() or "arkose" in st["body"].lower() or "challenge" in st["url"].lower():
|
||||
save({"status": "CHALLENGE_ON_SUBMIT", "email": email, "username": username, "password": password, "url": st["url"]})
|
||||
return 5
|
||||
|
||||
code_screen = False
|
||||
for _ in range(12):
|
||||
time.sleep(4)
|
||||
s2 = ev(page, "(() => ({url: location.href, inputsN: document.querySelectorAll('input').length}))()") or {}
|
||||
log(f"wait code: url={str(s2.get('url',''))[:90]} inputs={s2.get('inputsN')}")
|
||||
if "account_verifications" in str(s2.get("url", "")).lower():
|
||||
code_screen = True
|
||||
break
|
||||
if not code_screen:
|
||||
save({"status": "NO_CODE_SCREEN", "email": email, "username": username, "password": password,
|
||||
"url": (page.url or "")[:160]})
|
||||
return 4
|
||||
code = None
|
||||
if mailtm_box:
|
||||
code, _ = MailTM().wait_code(mailtm_box["token"], timeout_sec=260)
|
||||
if not code:
|
||||
code = gmail.wait_code(email, timeout_sec=260)
|
||||
if not code:
|
||||
save({"status": "NO_MAIL", "email": email, "username": username, "password": password})
|
||||
return 6
|
||||
log(f"code={code}")
|
||||
|
||||
c = json.dumps(code)
|
||||
filled = ev(page, f"""(() => {{
|
||||
const ins = Array.from(document.querySelectorAll('input[inputmode=numeric], input[autocomplete=one-time-code], input[name*=code i], input[id*=code i]'));
|
||||
if (!ins.length) return 'NO_INPUT';
|
||||
if (ins.length === 1) {{
|
||||
const i = ins[0]; i.focus(); i.value = {c};
|
||||
i.dispatchEvent(new Event('input',{{bubbles:true}}));
|
||||
i.dispatchEvent(new Event('change',{{bubbles:true}}));
|
||||
return 'SINGLE';
|
||||
}}
|
||||
ins.forEach((i, n) => {{ i.focus(); i.value = String({c})[n] || ''; i.dispatchEvent(new Event('input',{{bubbles:true}})); }});
|
||||
return 'SPLIT:' + ins.length;
|
||||
}})()""")
|
||||
log("code fill: " + str(filled))
|
||||
time.sleep(2)
|
||||
log("verify click: " + str(ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => !x.disabled && x.offsetParent && /^Continue$/i.test((x.innerText||'').trim()));
|
||||
if (b) { b.click(); return 'continue'; }
|
||||
return 'NONE';
|
||||
})()""")))
|
||||
time.sleep(12)
|
||||
|
||||
final = ev(page, "(() => ({url: location.href, body: document.body.innerText.slice(0,400)}))()") or {}
|
||||
final["body"] = (final.get("body") or "").replace("\n", " | ")
|
||||
log("FINAL url=" + str(final.get("url", ""))[:130])
|
||||
log("FINAL BODY: " + str(final.get("body", ""))[:350])
|
||||
if DEBUG_SHOTS:
|
||||
page.screenshot(path=OUT + f"\\gh_a{IDX}_6final.png")
|
||||
for _ in range(6):
|
||||
t = (body_text(page) or "").lower()
|
||||
if "welcome" in t or "where teams" in t or "plan" in t or "cancel" in t or "skip" in t:
|
||||
ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button, a')).find(x =>
|
||||
/^(Skip|Cancel|Continue|Next|Maybe later|Do this later)$/i.test((x.innerText||'').trim()) && !x.disabled);
|
||||
if (b) { b.click(); return true; } return false;
|
||||
})()""")
|
||||
time.sleep(4)
|
||||
else:
|
||||
break
|
||||
dd_save_trust(page.context)
|
||||
cookies = page.context.cookies()
|
||||
verdict = "OK_VERIFIED"
|
||||
save({"status": verdict, "email": email, "username": username, "password": password,
|
||||
"mail_password": (mailtm_box or {}).get("password", ""),
|
||||
"mail_token": (mailtm_box or {}).get("token", ""),
|
||||
"final_url": (page.url or "")[:160], "cookie_count": len(cookies),
|
||||
"final_body": final.get("body", "")[:180]})
|
||||
return 0
|
||||
except Exception as e:
|
||||
log(f"EXC(try {browser_try}) " + type(e).__name__ + ": " + str(e)[:220])
|
||||
if browser_try == 2:
|
||||
save({"status": "EXC", "email": email, "username": username, "password": password,
|
||||
"err": f"{type(e).__name__}: {str(e)[:160]}"})
|
||||
return 1
|
||||
time.sleep(20)
|
||||
save({"status": "BROWSER_DEAD", "email": email, "username": username, "password": password})
|
||||
return 1
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,244 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""SQLite store for GitHub/GitLab accounts.
|
||||
Central DB: accounts.db (SQLite, WAL mode).
|
||||
All autoreg / postreg / verify flows write here.
|
||||
JSONL files stay as append-only raw feed, DB is the source of truth.
|
||||
"""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import json, os, sqlite3, time, threading
|
||||
|
||||
DB_PATH = str(_w("tmp/bpproxy_run/accounts.db"))
|
||||
_LOCK = threading.Lock()
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
provider TEXT NOT NULL DEFAULT 'github',
|
||||
idx TEXT,
|
||||
email TEXT,
|
||||
username TEXT,
|
||||
password TEXT,
|
||||
status TEXT DEFAULT 'NEW',
|
||||
mail_password TEXT,
|
||||
mail_token TEXT,
|
||||
final_url TEXT,
|
||||
err TEXT,
|
||||
-- postreg fields
|
||||
new_username TEXT,
|
||||
avatar TEXT, -- local avatar file
|
||||
avatar_url TEXT, -- github user avatar url
|
||||
bio TEXT,
|
||||
repo_name TEXT,
|
||||
repo_type TEXT, -- 'fork' | 'own' | None
|
||||
totp_secret TEXT,
|
||||
totp_ok INTEGER DEFAULT 0,
|
||||
backup_codes TEXT, -- JSON array
|
||||
twofa_enabled INTEGER DEFAULT 0,
|
||||
cookies_json TEXT,
|
||||
notes TEXT,
|
||||
created_ts TEXT,
|
||||
updated_ts TEXT
|
||||
);
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS ux_provider_username ON accounts(provider, username);
|
||||
CREATE INDEX IF NOT EXISTS ix_provider_status ON accounts(provider, status);
|
||||
"""
|
||||
|
||||
VALID_COLS = {"provider", "idx", "email", "username", "password", "status",
|
||||
"mail_password", "mail_token", "final_url", "err",
|
||||
"new_username", "avatar", "avatar_url", "bio", "repo_name",
|
||||
"repo_type", "totp_secret", "totp_ok", "backup_codes",
|
||||
"twofa_enabled", "cookies_json", "notes", "created_ts", "updated_ts"}
|
||||
|
||||
|
||||
def connect():
|
||||
os.makedirs(os.path.dirname(DB_PATH), exist_ok=True)
|
||||
con = sqlite3.connect(DB_PATH, timeout=30)
|
||||
con.row_factory = sqlite3.Row
|
||||
con.execute("PRAGMA journal_mode=WAL;")
|
||||
con.execute("PRAGMA busy_timeout=15000;")
|
||||
return con
|
||||
|
||||
|
||||
def init():
|
||||
with _LOCK:
|
||||
con = connect()
|
||||
con.executescript(SCHEMA)
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def upsert_account(rec, con=None):
|
||||
"""rec: dict matching accounts columns (subset ok).
|
||||
Match key: (provider, username) if username present else (provider, email).
|
||||
Returns account id.
|
||||
"""
|
||||
own = con is None
|
||||
if own:
|
||||
con = connect()
|
||||
try:
|
||||
rec = dict(rec)
|
||||
rec.setdefault("provider", "github")
|
||||
rec.setdefault("updated_ts", time.strftime("%Y-%m-%d %H:%M:%S"))
|
||||
for k, v in list(rec.items()):
|
||||
if isinstance(v, (list, dict)):
|
||||
rec[k] = json.dumps(v, ensure_ascii=False)
|
||||
username = rec.get("username") or ""
|
||||
email = rec.get("email") or ""
|
||||
row = None
|
||||
if username:
|
||||
row = con.execute(
|
||||
"SELECT id FROM accounts WHERE provider=? AND username=?",
|
||||
(rec["provider"], username)).fetchone()
|
||||
if row is None and email:
|
||||
row = con.execute(
|
||||
"SELECT id FROM accounts WHERE provider=? AND email=?",
|
||||
(rec["provider"], email)).fetchone()
|
||||
cols = [c for c in rec.keys() if c not in ("id", "created_ts")]
|
||||
if row:
|
||||
aid = row["id"]
|
||||
sets = ", ".join(f"{c}=?" for c in cols)
|
||||
vals = [rec[c] for c in cols] + [aid]
|
||||
if cols:
|
||||
con.execute(f"UPDATE accounts SET {sets} WHERE id=?", vals)
|
||||
else:
|
||||
cur_cols = ["provider", "created_ts"] + cols
|
||||
cur_vals = [rec["provider"], rec["updated_ts"]] + [rec[c] for c in cols]
|
||||
ph = ", ".join("?" for _ in cur_vals)
|
||||
cur = con.execute(
|
||||
f"INSERT INTO accounts ({', '.join(cur_cols)}) VALUES ({ph})", cur_vals)
|
||||
aid = cur.lastrowid
|
||||
con.commit()
|
||||
return aid
|
||||
finally:
|
||||
if own:
|
||||
con.close()
|
||||
|
||||
|
||||
def import_jsonl(path, provider):
|
||||
"""Import legacy jsonl feed into DB. Skips records already present
|
||||
(same username+status) to keep idempotent."""
|
||||
if not os.path.exists(path):
|
||||
return 0
|
||||
imported = 0
|
||||
con = connect()
|
||||
try:
|
||||
con.executescript(SCHEMA)
|
||||
with open(path, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
u = r.get("username") or ""
|
||||
if not u and not r.get("email"):
|
||||
continue
|
||||
# map legacy fields to schema columns, dump the rest into notes
|
||||
r.setdefault("provider", provider)
|
||||
if "ts" in r and not r.get("created_ts"):
|
||||
r["created_ts"] = r.pop("ts")
|
||||
else:
|
||||
r.pop("ts", None)
|
||||
extra = {k: v for k, v in r.items()
|
||||
if k not in VALID_COLS}
|
||||
for k in extra:
|
||||
r.pop(k)
|
||||
if extra:
|
||||
r["notes"] = json.dumps(extra, ensure_ascii=False)[:2000]
|
||||
# keep latest record per username: import in order, upsert overwrites
|
||||
upsert_account(r, con=con)
|
||||
imported += 1
|
||||
con.commit()
|
||||
finally:
|
||||
con.close()
|
||||
return imported
|
||||
|
||||
|
||||
def import_all():
|
||||
n1 = import_jsonl(str(_w("tmp/bpproxy_run/github_accounts.jsonl")), "github")
|
||||
n2 = import_jsonl(str(_w("tmp/bpproxy_run/gitlab_accounts.jsonl")), "gitlab")
|
||||
return n1, n2
|
||||
|
||||
|
||||
def set_status(provider, username, status, con=None):
|
||||
return upsert_account({"provider": provider, "username": username,
|
||||
"status": status}, con=con)
|
||||
|
||||
|
||||
def stats(provider=None):
|
||||
con = connect()
|
||||
try:
|
||||
q = "SELECT status, COUNT(*) n FROM accounts"
|
||||
args = []
|
||||
if provider:
|
||||
q += " WHERE provider=?"
|
||||
args.append(provider)
|
||||
q += " GROUP BY status ORDER BY n DESC"
|
||||
return [(r["status"], r["n"]) for r in con.execute(q, args)]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def fetch(provider="github", status="OK_VERIFIED", limit=0, need_postreg=False):
|
||||
con = connect()
|
||||
try:
|
||||
q = "SELECT * FROM accounts WHERE provider=? AND status=?"
|
||||
args = [provider, status]
|
||||
if need_postreg:
|
||||
q += " AND twofa_enabled=0"
|
||||
q += " ORDER BY id"
|
||||
if limit:
|
||||
q += " LIMIT ?"
|
||||
args.append(limit)
|
||||
return [dict(r) for r in con.execute(q, args)]
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def get_by_username(username, provider="github"):
|
||||
con = connect()
|
||||
try:
|
||||
r = con.execute("SELECT * FROM accounts WHERE provider=? AND username=?",
|
||||
(provider, username)).fetchone()
|
||||
return dict(r) if r else None
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
init()
|
||||
n1, n2 = import_all()
|
||||
print(f"imported github={n1} gitlab={n2} -> {DB_PATH}")
|
||||
for prov in ("github", "gitlab"):
|
||||
print(prov, stats(prov))
|
||||
@@ -0,0 +1,139 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Mailboxes for the GitHub autoreg pipeline.
|
||||
Primary: mail.tm REST API (disposable inbox, uberip.com etc).
|
||||
Fallback: Gmail IMAP with +alias addressing (FARM_ALIAS@gmail.com).
|
||||
All code ASCII. Prints are UTF-8 safe via caller's PYTHONIOENCODING.
|
||||
"""
|
||||
import time, re, random, string, json
|
||||
import requests
|
||||
|
||||
TM_BASE = "https://api.mail.tm"
|
||||
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
|
||||
|
||||
|
||||
class MailTM:
|
||||
def __init__(self):
|
||||
d = requests.get(f"{TM_BASE}/domains", headers={"User-Agent": UA}, timeout=20).json()
|
||||
self.domains = [x["domain"] for x in d["hydra:member"]]
|
||||
if not self.domains:
|
||||
raise RuntimeError("mail.tm no domains")
|
||||
|
||||
def create(self, local=None, password=None):
|
||||
local = local or "gh" + "".join(random.choices(string.ascii_lowercase + string.digits, k=12))
|
||||
password = password or "Gh#" + "".join(random.choices(string.ascii_letters + string.digits, k=13)) + "!7z"
|
||||
domain = self.domains[0]
|
||||
address = f"{local}@{domain}"
|
||||
r = requests.post(f"{TM_BASE}/accounts",
|
||||
headers={"User-Agent": UA, "Content-Type": "application/json"},
|
||||
json={"address": address, "password": password}, timeout=20)
|
||||
if r.status_code not in (201, 200):
|
||||
raise RuntimeError(f"mail.tm create {r.status_code}: {r.text[:160]}")
|
||||
tok = self._token(address, password)
|
||||
return {"address": address, "password": password, "token": tok}
|
||||
|
||||
def _token(self, address, password):
|
||||
r = requests.post(f"{TM_BASE}/token",
|
||||
headers={"User-Agent": UA, "Content-Type": "application/json"},
|
||||
json={"address": address, "password": password}, timeout=20)
|
||||
r.raise_for_status()
|
||||
return r.json()["token"]
|
||||
|
||||
def wait_code(self, token, sender_hint="github", timeout_sec=300, pattern=r"\b(\d{6,8})\b", seen_ids=None):
|
||||
"""Poll inbox for a code in the newest message matching sender_hint.
|
||||
Returns (code, message_id) or (None, None) on timeout."""
|
||||
seen_ids = seen_ids or set()
|
||||
hdr = {"User-Agent": UA, "Authorization": f"Bearer {token}"}
|
||||
deadline = time.time() + timeout_sec
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
r = requests.get(f"{TM_BASE}/messages", headers=hdr, timeout=20)
|
||||
if r.status_code == 200:
|
||||
for m in r.json()["hydra:member"]:
|
||||
mid = m["id"]
|
||||
if mid in seen_ids:
|
||||
continue
|
||||
seen_ids.add(mid)
|
||||
sender = (m.get("from") or {}).get("address", "")
|
||||
subject = m.get("subject", "")
|
||||
if not (sender_hint.lower() in sender.lower() or sender_hint.lower() in subject.lower()):
|
||||
continue
|
||||
d = requests.get(f"{TM_BASE}/messages/{mid}", headers=hdr, timeout=20).json()
|
||||
text = " ".join([d.get("text", "") or "", d.get("html", "") or ""])
|
||||
mm = re.search(pattern, text, re.I)
|
||||
if mm:
|
||||
return mm.group(1), mid
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(5)
|
||||
return None, None
|
||||
|
||||
|
||||
class GmailIMAP:
|
||||
"""Gmail +alias mailbox via IMAP. All aliases land in one inbox."""
|
||||
|
||||
def __init__(self, user="FARM_GMAIL@gmail.com", app_pass="GMAIL_APP_PASS", alias_prefix="ghsig"):
|
||||
import imaplib
|
||||
self.user = user
|
||||
self.pass_ = app_pass
|
||||
self.prefix = alias_prefix
|
||||
|
||||
def make_address(self, idx=None):
|
||||
idx = idx or random.randint(10000, 99999)
|
||||
u, d = self.user.split("@")
|
||||
return f"{u}+{self.prefix}{idx}@{d}"
|
||||
|
||||
def wait_code(self, address, timeout_sec=300):
|
||||
import imaplib
|
||||
import email as email_lib
|
||||
deadline = time.time() + timeout_sec
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
|
||||
m.login(self.user, self.pass_)
|
||||
m.select("INBOX")
|
||||
st, data = m.search(None, f'TO "{address}"')
|
||||
ids = []
|
||||
if st == "OK" and data[0]:
|
||||
ids = data[0].split()[-5:]
|
||||
else:
|
||||
st, data = m.search(None, 'FROM "noreply@github.com"')
|
||||
if st == "OK" and data[0]:
|
||||
ids = data[0].split()[-5:]
|
||||
found = None
|
||||
for mid in reversed(ids):
|
||||
st, md = m.fetch(mid, "(RFC822)")
|
||||
if st != "OK":
|
||||
continue
|
||||
msg = email_lib.message_from_bytes(md[0][1])
|
||||
body = ""
|
||||
if msg.is_multipart():
|
||||
for part in msg.walk():
|
||||
if part.get_content_type() in ("text/plain", "text/html"):
|
||||
try:
|
||||
body += part.get_payload(decode=True).decode("utf-8", "ignore")
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
body = msg.get_payload(decode=True).decode("utf-8", "ignore")
|
||||
except Exception:
|
||||
body = ""
|
||||
mm = re.search(r"(\b\d{8}\b|\b\d{6}\b)", body)
|
||||
if mm and ("github" in str(msg.get("From", "")).lower() or address in str(msg.get("To", "")) or address in str(msg.get("Delivered-To", ""))):
|
||||
found = mm.group(1)
|
||||
break
|
||||
m.logout()
|
||||
if found:
|
||||
return found
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(6)
|
||||
return None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
tm = MailTM()
|
||||
box = tm.create()
|
||||
print(json.dumps({"address": box["address"], "token_len": len(box["token"])}, ensure_ascii=False))
|
||||
g = GmailIMAP()
|
||||
print("gmail alias sample:", g.make_address())
|
||||
@@ -0,0 +1,217 @@
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
# PAT harvester for warmed accounts: login w/ TOTP -> device-code via gmail -> PAT -> DB
|
||||
import time, sys, re, json, sqlite3
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from camoufox.sync_api import Camoufox
|
||||
import pyotp
|
||||
import imaplib
|
||||
import email as el
|
||||
|
||||
DB = str(_w("tmp/bpproxy_run/accounts.db"))
|
||||
from gh_mail import GmailIMAP # real creds live in gh_mail - never copy them here
|
||||
_GMAIL = GmailIMAP()
|
||||
# The workstation IP drives the fleet control plane; a fraud flag on it costs
|
||||
# the whole fleet. Every login goes through the VPS SOCKS tunnel instead.
|
||||
proxy = {"server": "socks5://127.0.0.1:2090"}
|
||||
|
||||
|
||||
def fetch_device_code(addr, timeout=240, since=None):
|
||||
since = since or 0
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
try:
|
||||
m = imaplib.IMAP4_SSL("imap.gmail.com", 993)
|
||||
m.login(_GMAIL.user, _GMAIL.pass_)
|
||||
m.select("INBOX")
|
||||
st, data = m.search(None, '(FROM "noreply@github.com")')
|
||||
ids = data[0].split()[-4:]
|
||||
for mid in reversed(ids):
|
||||
st, md = m.fetch(mid, "(BODY.PEEK[HEADER.FIELDS (SUBJECT TO DATE)])")
|
||||
msg = el.message_from_bytes(md[0][1])
|
||||
if addr.lower() not in str(msg.get("To", "")).lower():
|
||||
continue
|
||||
import email.utils as eutils
|
||||
try:
|
||||
dt = eutils.parsedate_to_datetime(str(msg.get("Date", "")))
|
||||
if since and dt.timestamp() < since - 60:
|
||||
continue # stale code from earlier session
|
||||
except Exception:
|
||||
pass
|
||||
st2, md2 = m.fetch(mid, "(BODY.PEEK[])")
|
||||
body = md2[0][1].decode("utf-8", "ignore")
|
||||
mm = re.search(r'\b(\d{6,8})\b', str(msg.get("Subject", "")) + body[:800])
|
||||
if mm:
|
||||
m.logout()
|
||||
return mm.group(1)
|
||||
m.logout()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(8)
|
||||
return None
|
||||
|
||||
|
||||
def pat_for(username, password, totp_secret, email):
|
||||
login_start = time.time()
|
||||
with Camoufox(headless=True, humanize=True, proxy=proxy) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto("https://github.com/login", wait_until="domcontentloaded", timeout=60000)
|
||||
time.sleep(3)
|
||||
page.fill("#login_field", username, timeout=15000)
|
||||
page.fill("#password", password, timeout=15000)
|
||||
page.click("input[name='commit'], button[type=submit]", timeout=10000)
|
||||
time.sleep(8)
|
||||
url = page.url
|
||||
# device verification?
|
||||
if "verified-device" in url:
|
||||
code = fetch_device_code(email, since=login_start)
|
||||
print(f"[p] {username} device code: {code}")
|
||||
if not code:
|
||||
return None
|
||||
try:
|
||||
loc = page.locator("input#otp, input[name='otp'], input[inputmode='numeric']").first
|
||||
loc.wait_for(state="visible", timeout=15000)
|
||||
loc.click()
|
||||
loc.press_sequentially(str(code), delay=90)
|
||||
time.sleep(2)
|
||||
page.click("button:has-text('Verify')", timeout=10000)
|
||||
except Exception as e:
|
||||
print(f"[p] {username} verify click: {str(e)[:50]}")
|
||||
# wait for the page to advance (slow 3G)
|
||||
for _ in range(12):
|
||||
time.sleep(5)
|
||||
if "verified-device" not in page.url:
|
||||
break
|
||||
url = page.url
|
||||
if "verified-device" in url:
|
||||
try:
|
||||
b = " ".join(page.inner_text("body").split())[:200]
|
||||
print(f"[p] {username} device stuck, body: {b}")
|
||||
inputs = page.evaluate("() => Array.from(document.querySelectorAll('input')).map(i => i.type + '#' + (i.id || i.name || '?')).join(' | ')")
|
||||
print(f"[p] inputs: {inputs[:200]}")
|
||||
except Exception:
|
||||
pass
|
||||
# 2FA TOTP?
|
||||
if "two-factor" in url:
|
||||
if not totp_secret:
|
||||
print(f"[p] {username} two-factor without totp_secret - skip")
|
||||
return None
|
||||
totp = pyotp.TOTP(totp_secret).now()
|
||||
try:
|
||||
page.fill("input[name='otp'], input#app_totp", totp, timeout=10000)
|
||||
page.click("button:has-text('Verify'), input[name='commit']", timeout=25000)
|
||||
time.sleep(8)
|
||||
except Exception as e:
|
||||
print(f"[p] {username} totp click slow: {str(e)[:50]}")
|
||||
time.sleep(10)
|
||||
if "two-factor" in page.url:
|
||||
return None
|
||||
# navigation completed despite click timeout
|
||||
print(f"[p] {username} logged in: {page.url[:50]}")
|
||||
# PAT
|
||||
page.goto("https://github.com/settings/tokens/new", wait_until="domcontentloaded", timeout=60000)
|
||||
time.sleep(3)
|
||||
try:
|
||||
page.fill("input#oauth_access_description", f"ci-{username}-{int(time.time())%100000}", timeout=10000)
|
||||
page.evaluate("""() => { document.querySelectorAll('input[type="checkbox"]').forEach(cb => { if (!cb.checked) cb.click(); }); }""")
|
||||
time.sleep(1)
|
||||
for sel in ("label:has-text('No expiration')", "input[value='no_expiration']"):
|
||||
try:
|
||||
if page.locator(sel).count() > 0:
|
||||
page.locator(sel).first.click()
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
for bt in ("Generate token", "Generate"):
|
||||
try:
|
||||
b = page.locator(f"button:has-text('{bt}')").first
|
||||
if b.count() > 0:
|
||||
b.click(timeout=8000)
|
||||
time.sleep(4)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
pat = page.evaluate("() => { const m = document.body.innerText.match(/gh[pousr]_[a-zA-Z0-9]{36,}/); return m ? m[0] : null; }")
|
||||
if not pat:
|
||||
# diagnostics: why no token
|
||||
try:
|
||||
u = page.url
|
||||
b = " ".join(page.inner_text("body").split())[:150]
|
||||
print(f"[p] {username} no-token url={u[:60]} body={b[:120]}")
|
||||
except Exception:
|
||||
pass
|
||||
return pat
|
||||
except Exception as e:
|
||||
print(f"[p] {username} PAT err: {str(e)[:80]}")
|
||||
return None
|
||||
|
||||
|
||||
def main():
|
||||
limit = int(sys.argv[1]) if len(sys.argv) > 1 else 5
|
||||
only = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
db = sqlite3.connect(DB)
|
||||
# warmed accounts (2FA on, no PAT yet) — PAT stored in notes col? add col
|
||||
try:
|
||||
db.execute("ALTER TABLE accounts ADD COLUMN pat TEXT")
|
||||
db.commit()
|
||||
except Exception:
|
||||
pass
|
||||
q = """SELECT username, password, totp_secret, email FROM accounts
|
||||
WHERE twofa_enabled=1 AND (pat IS NULL OR pat='') AND COALESCE(pat_fail,0) < 3"""
|
||||
if only:
|
||||
q += " AND username=?"
|
||||
rows = db.execute(q, (only,)).fetchall()
|
||||
else:
|
||||
rows = db.execute(q + " ORDER BY (pat_fail IS NULL) DESC, username LIMIT ?", (limit,)).fetchall()
|
||||
print(f"[p] target accounts: {len(rows)}")
|
||||
ok = 0
|
||||
for username, password, totp_secret, email in rows:
|
||||
print(f"[p] === {username} ===")
|
||||
pat = pat_for(username, password, totp_secret, email)
|
||||
if pat:
|
||||
db.execute("UPDATE accounts SET pat=?, pat_fail=0 WHERE username=?", (pat, username))
|
||||
db.commit()
|
||||
print(f"[p] {username} PAT: {pat[:18]}...")
|
||||
ok += 1
|
||||
else:
|
||||
print(f"[p] {username} PAT: FAILED")
|
||||
try:
|
||||
db.execute("UPDATE accounts SET pat_fail=COALESCE(pat_fail,0)+1 WHERE username=?", (username,))
|
||||
db.commit()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(60)
|
||||
print(f"[p] DONE ok={ok}/{len(rows)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,113 @@
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
# 24/7 pipeline supervisor: register -> warmup -> PAT, loop until target
|
||||
import subprocess, time, json, sqlite3, sys, os
|
||||
|
||||
PY = _PY
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
DB = OUT + r"\accounts.db"
|
||||
LOG = open(OUT + r"\pipeline.log", "a", encoding="utf-8")
|
||||
|
||||
TARGET = int(sys.argv[1]) if len(sys.argv) > 1 else 1000
|
||||
|
||||
|
||||
def log(m):
|
||||
line = f"[{time.strftime('%H:%M:%S')}] PIPE: {m}"
|
||||
print(line, flush=True)
|
||||
LOG.write(line + "\n")
|
||||
LOG.flush()
|
||||
|
||||
|
||||
def counts():
|
||||
db = sqlite3.connect(DB)
|
||||
ok = db.execute("SELECT COUNT(*) FROM accounts WHERE status='OK_VERIFIED'").fetchone()[0]
|
||||
warmed = db.execute("SELECT COUNT(*) FROM accounts WHERE twofa_enabled=1").fetchone()[0]
|
||||
pats = db.execute("SELECT COUNT(*) FROM accounts WHERE pat IS NOT NULL AND pat != ''").fetchone()[0]
|
||||
db.close()
|
||||
return ok, warmed, pats
|
||||
|
||||
|
||||
def run(cmd, timeout):
|
||||
try:
|
||||
r = subprocess.run([PY, "-u"] + cmd, cwd=OUT, capture_output=True, text=True, timeout=timeout)
|
||||
out = (r.stdout or "") + (r.stderr or "")
|
||||
return r.returncode, out
|
||||
except subprocess.TimeoutExpired:
|
||||
return 99, "timeout"
|
||||
|
||||
|
||||
idx = 200 # supervisor's own registration index space
|
||||
cycle = 0
|
||||
while True:
|
||||
cycle += 1
|
||||
ok, warmed, pats = counts()
|
||||
log(f"cycle {cycle}: ok={ok} warmed={warmed} pat={pats} target={TARGET}")
|
||||
if ok >= TARGET:
|
||||
log("TARGET REACHED")
|
||||
break
|
||||
|
||||
# 1) registration if below target
|
||||
if ok < TARGET:
|
||||
idx += 1
|
||||
# ZTE: fresh mobile IP before each attempt (UI toggle rotation)
|
||||
try:
|
||||
subprocess.run([PY, "-u", "zte_ui_rotate2.py"], cwd=OUT,
|
||||
capture_output=True, timeout=300)
|
||||
except Exception:
|
||||
pass
|
||||
rc, out = run(["gh_autoreg.py", str(idx).zfill(3), "ZTE", "gmail"], 900)
|
||||
status = "ok" if "OK_VERIFIED" in out else ("timeout" if rc == 99 else "fail")
|
||||
log(f"reg #{idx}: {status}")
|
||||
time.sleep(30) # let modem/browser settle before warmup
|
||||
time.sleep(__import__("random").uniform(90, 200))
|
||||
|
||||
# 2) warmup: pick one warmed-less account (retry once)
|
||||
rc, out = run(["gh_postreg.py", "1"], 900)
|
||||
if ("skip" not in out and "finished: ok=0" in out) or rc in (99, None):
|
||||
time.sleep(45)
|
||||
rc, out = run(["gh_postreg.py", "1"], 900)
|
||||
if "finished: ok=1" in out or "ok=1/" in out:
|
||||
log("warmup: +1")
|
||||
elif "no accounts to process" in out:
|
||||
log("warmup: queue empty")
|
||||
else:
|
||||
log("warmup: skip/fail")
|
||||
time.sleep(20)
|
||||
|
||||
# 3) PAT for one warmed account without PAT
|
||||
rc, out = run(["gh_pat.py", "1"], 900)
|
||||
if "DONE ok=1" in out:
|
||||
log("pat: +1")
|
||||
elif "target accounts: 0" in out:
|
||||
log("pat: queue empty")
|
||||
else:
|
||||
log("pat: skip/fail")
|
||||
time.sleep(20)
|
||||
@@ -0,0 +1,777 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""GitHub post-registration profiler + 2FA hardening.
|
||||
|
||||
For each OK_VERIFIED account from accounts.db:
|
||||
1. login (email + password) through Camoufox
|
||||
2. generate + upload avatar (Pillow, identicon-style gradient)
|
||||
3. set bio + name (profile "oformlenie")
|
||||
4. change username (fresh, non-patterned)
|
||||
5. create own repo OR fork a real one (README with content)
|
||||
6. enable TOTP 2FA, download backup codes
|
||||
7. save everything back to accounts.db, push creds to TG
|
||||
|
||||
Usage:
|
||||
python gh_postreg.py [limit] [username_filter]
|
||||
python gh_postreg.py 1 # one oldest account
|
||||
python gh_postreg.py 0 cobaltdev128 # exactly this account
|
||||
"""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import time, json, re, sys, os, random, string, base64, io
|
||||
|
||||
sys.path.insert(0, str(_REPO))
|
||||
import gh_db
|
||||
from gh_db import upsert_account
|
||||
|
||||
from camoufox.sync_api import Camoufox
|
||||
import pyotp
|
||||
from PIL import Image, ImageDraw
|
||||
from gh_autoreg import human_sleep, human_type, human_scroll, human_move_mouse
|
||||
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
AVATARS = OUT + r"\avatars"
|
||||
LOG = OUT + r"\gh_postreg.log"
|
||||
|
||||
P_USER = "bpproxy-user"
|
||||
P_PASS = "BPPROXY_PASS"
|
||||
P_HOST = "bpproxy-host:1000"
|
||||
|
||||
FORK_TARGETS = [
|
||||
("awesome-chatgpt-prompts", "f/awesome-chatgpt-prompts"),
|
||||
("public-api", "public-api"),
|
||||
]
|
||||
REPO_TOPICS = ["automation", "tools", "python", "scripts", "web", "api", "dev", "utils"]
|
||||
|
||||
# bios pool (short, human, no AI-isms)
|
||||
BIOS = [
|
||||
"tinkering with python & web automation",
|
||||
"building small tools that do boring stuff",
|
||||
"dev tools, scripts, occasional scraping",
|
||||
"python / js. mostly experiments here",
|
||||
"code, coffee, side projects",
|
||||
"making repos so my scripts have a home",
|
||||
"software tinkering. random useful stuff",
|
||||
]
|
||||
NAMES_POOL = [
|
||||
("Alex", "Moreau"), ("Sam", "Ridley"), ("Kai", "Novak"), ("Robin", "Hale"),
|
||||
("Jesse", "Linden"), ("Morgan", "Reyes"), ("Ash", "Brennan"), ("Drew", "Karlsen"),
|
||||
("Casey", "Volker"), ("Noel", "Ferrer"),
|
||||
]
|
||||
|
||||
REPO_README = """# {repo}
|
||||
|
||||
{tagline}
|
||||
|
||||
## What's inside
|
||||
|
||||
- {item1}
|
||||
- {item2}
|
||||
- {item3}
|
||||
|
||||
## Notes
|
||||
|
||||
{note}
|
||||
|
||||
Made with too much coffee. License: MIT.
|
||||
"""
|
||||
|
||||
|
||||
def log(m):
|
||||
line = f"[{time.strftime('%H:%M:%S')}] {m}"
|
||||
print(line, flush=True)
|
||||
with open(LOG, "a", encoding="utf-8") as f:
|
||||
f.write(line + "\n")
|
||||
|
||||
|
||||
def proxy_cfg(label):
|
||||
if label == "HOME":
|
||||
return None
|
||||
if label == "ZTE":
|
||||
return {"server": "http://127.0.0.1:8899"}
|
||||
if label == "HK1024":
|
||||
import random as _r
|
||||
try:
|
||||
pool = [88291] + [int(x) for x in open(str(_w("tmp/bpproxy_run/clean_sids.txt"))).read().split() if x.strip()]
|
||||
except Exception:
|
||||
pool = [88291]
|
||||
sid = _r.choice(pool)
|
||||
return {"server": "http://hk.1024proxy.io:3000",
|
||||
"username": f"PROXY_USER-region-HK-sid-{sid}-t-30",
|
||||
"password": "PROXY_PASS"}
|
||||
return {"server": f"http://{P_HOST}", "username": P_USER,
|
||||
"password": f"{P_PASS}_session-{label}_lifetime-30"}
|
||||
|
||||
|
||||
def gen_new_username():
|
||||
"""less bot-looking than adj+noun+3digits: word+digits, sometimes underscore."""
|
||||
words = ["harbor", "quill", "fjord", "wren", "onyx", "cedar", "maple", "rune",
|
||||
"solace", "vector", "kestrel", "lumen", "cobble", "thistle", "brisk",
|
||||
"hollow", "gravel", "saffron", "tidal", "ember"]
|
||||
w = random.choice(words)
|
||||
style = random.randint(0, 3)
|
||||
if style == 0:
|
||||
return w + str(random.randint(2, 99))
|
||||
if style == 1:
|
||||
return w + "_" + random.choice(["dev", "ops", "hq", "labs", "x"]) + str(random.randint(1, 99))
|
||||
if style == 2:
|
||||
return random.choice(words) + random.choice(words) + str(random.randint(1, 999))
|
||||
return w + str(random.randint(1000, 99999))
|
||||
|
||||
|
||||
def make_avatar(seed):
|
||||
"""Deterministic gradient identicon 512x512, saved to avatars/<seed>.png"""
|
||||
os.makedirs(AVATARS, exist_ok=True)
|
||||
path = os.path.join(AVATARS, seed + ".png")
|
||||
if os.path.exists(path):
|
||||
return path
|
||||
rnd = random.Random(seed)
|
||||
h = rnd.randint(0, 359)
|
||||
base = (h, rnd.randint(55, 75), rnd.randint(45, 65))
|
||||
h2 = (h + rnd.randint(30, 120)) % 360
|
||||
img = Image.new("RGB", (512, 512))
|
||||
dr = ImageDraw.Draw(img, "RGBA")
|
||||
|
||||
def hx(hh, ss, vv):
|
||||
import colorsys
|
||||
r, g, b = colorsys.hsv_to_rgb(hh / 360, ss / 100, vv / 100)
|
||||
return (int(r * 255), int(g * 255), int(b * 255))
|
||||
|
||||
for y in range(512):
|
||||
t = y / 511
|
||||
# gradient blend h->h2
|
||||
hh = (h + (h2 - h) * t) % 360
|
||||
ss = base[1] + (30 - 60 * t)
|
||||
vv = base[2] + (25 - 10 * t)
|
||||
dr.line([(0, y), (512, y)], fill=hx(hh, max(15, min(90, ss)), max(35, min(80, vv))))
|
||||
# random geometric overlay blocks
|
||||
for _ in range(rnd.randint(6, 12)):
|
||||
x0, y0 = rnd.randint(-60, 460), rnd.randint(-60, 460)
|
||||
s = rnd.randint(40, 200)
|
||||
alpha = rnd.randint(30, 90)
|
||||
col = hx((h + rnd.randint(0, 90)) % 360, rnd.randint(40, 80), rnd.randint(50, 90)) + (alpha,)
|
||||
if rnd.random() < 0.5:
|
||||
dr.rounded_rectangle([x0, y0, x0 + s, y0 + s], radius=s // 6, fill=col)
|
||||
else:
|
||||
dr.ellipse([x0, y0, x0 + s, y0 + s], fill=col)
|
||||
img.save(path, "PNG")
|
||||
return path
|
||||
|
||||
|
||||
def ev(page, js):
|
||||
try:
|
||||
return page.evaluate(js)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def body_text(page):
|
||||
try:
|
||||
return (page.evaluate("document.body.innerText") or "")[:2000]
|
||||
except Exception:
|
||||
return ""
|
||||
|
||||
|
||||
def login(page, email, password, username):
|
||||
page.goto("https://github.com/login", timeout=90000,
|
||||
wait_until="domcontentloaded")
|
||||
human_sleep(3.0, 1.5) # read the page
|
||||
human_move_mouse(page)
|
||||
human_scroll(page, "down", n=random.randint(1, 2))
|
||||
human_scroll(page, "up", n=1)
|
||||
human_sleep(1.2, 0.6)
|
||||
# type email like a person (no instant fill)
|
||||
human_type(page, "#login_field", email)
|
||||
human_sleep(1.3, 0.7)
|
||||
human_type(page, "#password", password)
|
||||
human_sleep(1.5, 0.8)
|
||||
page.screenshot(path=OUT + "\\pr_login_filled.png")
|
||||
# human pause before submit
|
||||
human_move_mouse(page)
|
||||
human_sleep(0.9, 0.5)
|
||||
page.click("input[name=commit], button[type=submit]")
|
||||
human_sleep(10, 3)
|
||||
url = page.url
|
||||
log("login url: " + url[:120])
|
||||
body = body_text(page)
|
||||
if "two-factor" in url or "2fa" in url:
|
||||
return "2FA_ALREADY", None
|
||||
if "Incorrect username or password" in body:
|
||||
return "BAD_CREDS", None
|
||||
# device verification screen (email code) — BEFORE generic /session check,
|
||||
# because its url contains /sessions/verified-device
|
||||
if "verified-device" in url or ("verify" in body.lower() and "code" in body.lower()
|
||||
and "resend" in body.lower()):
|
||||
return "DEVICE_VERIFY", url
|
||||
if "/session" in url:
|
||||
return "LOGIN_FAIL", None
|
||||
return "OK", url
|
||||
|
||||
|
||||
def wait_device_code(page, account, timeout_sec=280):
|
||||
"""If GitHub wants email device verification code, fetch it from mail."""
|
||||
from gh_mail import MailTM, GmailIMAP
|
||||
email = account["email"]
|
||||
code = None
|
||||
if account.get("mail_token"):
|
||||
code, _ = MailTM().wait_code(account["mail_token"], timeout_sec=timeout_sec,
|
||||
pattern=r"\b(\d{6,8})\b")
|
||||
if not code and "+ghsig" in (email or ""):
|
||||
code = GmailIMAP().wait_code(email, timeout_sec=timeout_sec)
|
||||
if not code:
|
||||
return False
|
||||
log(f"device code={code}")
|
||||
# type code like a human (found in live flow: #app_totp / numeric inputs)
|
||||
human_sleep(1.5, 0.8) # "check the phone/email" pause
|
||||
sel = "input[name=otp], input[name=app_otp], input[autocomplete=one-time-code]"
|
||||
try:
|
||||
loc = page.locator(sel).first
|
||||
loc.wait_for(state="visible", timeout=8000)
|
||||
loc.click()
|
||||
loc.press_sequentially(str(code), delay=random.uniform(90, 160))
|
||||
except Exception as e:
|
||||
log("devver typewriter fallback: " + str(e)[:60])
|
||||
ev(page, f"""(() => {{
|
||||
const ins = Array.from(document.querySelectorAll('input[inputmode=numeric], input[autocomplete=one-time-code], input[name*=code i], input[id*=code i]'));
|
||||
if (!ins.length) return 'NO_INPUT';
|
||||
if (ins.length === 1) {{
|
||||
const i = ins[0]; i.focus(); i.value = {json.dumps(str(code))};
|
||||
i.dispatchEvent(new Event('input',{{bubbles:true}}));
|
||||
i.dispatchEvent(new Event('change',{{bubbles:true}}));
|
||||
return 'SINGLE';
|
||||
}}
|
||||
ins.forEach((i, n) => {{ i.focus(); i.value = String({json.dumps(str(code))})[n] || ''; i.dispatchEvent(new Event('input',{{bubbles:true}})); }});
|
||||
return 'SPLIT:' + ins.length;
|
||||
}})()""")
|
||||
human_sleep(2.0, 0.8)
|
||||
ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => !x.disabled && x.offsetParent && /verify/i.test((x.innerText||'').trim()));
|
||||
if (b) { b.click(); return true; }
|
||||
return false;
|
||||
})()""")
|
||||
time.sleep(10)
|
||||
return "/login" not in page.url
|
||||
|
||||
|
||||
def upload_avatar(page, path):
|
||||
page.goto("https://github.com/settings/profile", timeout=90000,
|
||||
wait_until="domcontentloaded")
|
||||
human_sleep(3.0, 1.2)
|
||||
try:
|
||||
inp = page.query_selector("#avatar_upload, input[type=file][accept*=image], input.js-profile-file-edit")
|
||||
if not inp:
|
||||
# 2026 UI: avatar edit under button
|
||||
human_move_mouse(page)
|
||||
human_sleep(0.8, 0.4)
|
||||
ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button, summary')).find(x => /avatar|photo|picture/i.test((x.innerText||'') + (x.getAttribute('aria-label')||'')));
|
||||
if (b) { b.click(); return true; } return false;
|
||||
})()""")
|
||||
human_sleep(2.0, 0.8)
|
||||
inp = page.query_selector("input[type=file]")
|
||||
if not inp:
|
||||
return "NO_FILE_INPUT"
|
||||
inp.set_input_files(path)
|
||||
human_sleep(3.0, 1.0) # photo 'processing'
|
||||
# crop/scale dialog may appear -> confirm
|
||||
ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => !x.disabled && /^(set new profile photo|save|apply|use photo|confirm)$/i.test((x.innerText||'').trim()));
|
||||
if (b) { b.click(); return 'SET'; } return 'NOBTN';
|
||||
})()""")
|
||||
human_sleep(4.0, 1.5)
|
||||
save_profile_settings(page)
|
||||
return "OK"
|
||||
except Exception as e:
|
||||
return "AVATAR_EXC:" + str(e)[:80]
|
||||
|
||||
|
||||
def save_profile_settings(page):
|
||||
ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => !x.disabled && /^update profile$/i.test((x.innerText||'').trim()));
|
||||
if (b) { b.click(); return true; }
|
||||
const b2 = document.querySelector("button[data-testid='update-profile-button'], .js-profile-editable-save button");
|
||||
if (b2) { b2.click(); return true; }
|
||||
return false;
|
||||
})()""")
|
||||
time.sleep(5)
|
||||
|
||||
|
||||
def set_profile(page, first, last, bio):
|
||||
try:
|
||||
if "settings/profile" not in page.url:
|
||||
page.goto("https://github.com/settings/profile", timeout=90000,
|
||||
wait_until="domcontentloaded")
|
||||
except Exception:
|
||||
pass # avatar step already navigated; double-nav race is harmless
|
||||
human_sleep(3.0, 1.2)
|
||||
human_scroll(page, "down", n=random.randint(1, 3)) # look around settings
|
||||
human_sleep(1.0, 0.5)
|
||||
# name — type like a person
|
||||
name_sel = "#user_display_name, #user_profile_name, input[name='user[profile_name]']"
|
||||
try:
|
||||
el = page.query_selector(name_sel.replace(", ", ", "))
|
||||
if el:
|
||||
human_type(page, name_sel.split(",")[0].strip(), f"{first} {last}")
|
||||
except Exception as e:
|
||||
log("name fill exc: " + str(e)[:60])
|
||||
human_sleep(1.2, 0.6)
|
||||
# bio
|
||||
bio_sel = "#user_profile_bio, textarea[name='user[profile_bio]']"
|
||||
try:
|
||||
human_type(page, bio_sel.split(",")[0].strip(), bio, click_first=True)
|
||||
except Exception as e:
|
||||
log("bio fill exc: " + str(e)[:60])
|
||||
human_sleep(1.5, 0.7)
|
||||
page.screenshot(path=OUT + "\\pr_profile_filled.png")
|
||||
save_profile_settings(page)
|
||||
human_sleep(2.5, 1.0)
|
||||
|
||||
|
||||
def change_username(page, new_username):
|
||||
page.goto("https://github.com/settings/admin", timeout=90000)
|
||||
time.sleep(4)
|
||||
body = body_text(page)
|
||||
if "change username" not in body.lower() and "Change your username" not in body:
|
||||
log("no change-username block visible; trying UI anyway")
|
||||
ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button, summary, a')).find(x => /change username/i.test((x.innerText||'').trim()));
|
||||
if (b) { b.click(); return true; } return false;
|
||||
})()""")
|
||||
time.sleep(2.5)
|
||||
# danger-zone modal with input
|
||||
filled = ev(page, """(() => {
|
||||
const inp = Array.from(document.querySelectorAll('input[aria-describedby], input[name*=login i], input[placeholder*=current i]'))
|
||||
.find(i => i.offsetParent);
|
||||
if (!inp) return 'NO_INP';
|
||||
inp.focus();
|
||||
return 'FOUND:' + (inp.name || inp.id || 'x');
|
||||
})()""")
|
||||
log("rename input: " + str(filled))
|
||||
# type new name into the dialog field
|
||||
try:
|
||||
el = page.query_selector("input[name*='login' i], dialog input, modal input")
|
||||
if el:
|
||||
el.fill(new_username)
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
r = ev(page, """(() => {
|
||||
const dlg = document.querySelector('dialog[open], .Overlay, [role=dialog]');
|
||||
const scope = dlg || document;
|
||||
const b = Array.from(scope.querySelectorAll('button')).find(x => /update username|change username|rename/i.test((x.innerText||'').trim()) && !x.disabled);
|
||||
if (b) { b.click(); return 'CLICKED'; }
|
||||
return 'NOBTN';
|
||||
})()""")
|
||||
log("rename click: " + str(r))
|
||||
time.sleep(8)
|
||||
# confirm page: "I understand, update my username"
|
||||
r2 = ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => /i understand, update/i.test((x.innerText||'').trim()) && !x.disabled);
|
||||
if (b) { b.click(); return 'CONFIRM'; }
|
||||
return 'NOCONFIRM';
|
||||
})()""")
|
||||
log("rename confirm: " + str(r2))
|
||||
time.sleep(10)
|
||||
url = page.url
|
||||
ok = "admin" in url or page.query_selector("input[name*=login i]") is None
|
||||
# verify on profile
|
||||
page.goto(f"https://github.com/{new_username}", timeout=90000)
|
||||
time.sleep(4)
|
||||
notfound = "404" in body_text(page)[:200] or "This is not the web page" in body_text(page)
|
||||
if notfound:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def create_repo(page, repo_name, account):
|
||||
"""2026 UI: #repository-name-input, Public toggle-button, Create repository submit."""
|
||||
page.goto("https://github.com/new", timeout=90000,
|
||||
wait_until="domcontentloaded")
|
||||
human_sleep(4.0, 1.5) # read the form
|
||||
human_scroll(page, "down", n=random.randint(1, 3))
|
||||
human_scroll(page, "up", n=1)
|
||||
human_sleep(1.2, 0.6)
|
||||
# name (new 2026 input) — typed char by char
|
||||
try:
|
||||
page.wait_for_selector("#repository-name-input", timeout=30000)
|
||||
loc = page.locator("#repository-name-input")
|
||||
loc.click()
|
||||
loc.press_sequentially(repo_name, delay=random.uniform(80, 150))
|
||||
human_sleep(2.0, 0.8)
|
||||
except Exception as e:
|
||||
log("repo name fill exc: " + str(e)[:80])
|
||||
return False
|
||||
# description
|
||||
try:
|
||||
loc = page.locator("input[name='Description']")
|
||||
loc.click()
|
||||
loc.press_sequentially(random.choice([
|
||||
"small tools collection", "automation scripts", "helper utilities",
|
||||
"misc dev experiments", "tiny python utilities"])[:80],
|
||||
delay=random.uniform(30, 90))
|
||||
human_sleep(1.2, 0.6)
|
||||
except Exception:
|
||||
pass
|
||||
# Public (button in 2026 UI)
|
||||
ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => /^public$/i.test((x.innerText||'').trim()) && x.offsetParent !== null);
|
||||
if (b) { b.click(); return 'public'; }
|
||||
const r = document.querySelector('input#repository_visibility_public, input[name=repository_visibility][value=public]');
|
||||
if (r) { r.click(); return 'radio'; }
|
||||
return 'none';
|
||||
})()""")
|
||||
human_sleep(1.3, 0.6)
|
||||
# "Add a README" (checkbox or button in new UI)
|
||||
ev(page, """(() => {
|
||||
const c = document.querySelector('#repository_auto_init, input[name=auto_init]');
|
||||
if (c) { c.click(); return 'old'; }
|
||||
const b = Array.from(document.querySelectorAll('button, label, summary')).find(x => /readme/i.test((x.innerText||'').trim()) && x.offsetParent !== null);
|
||||
if (b) { b.click(); return 'btn'; }
|
||||
return 'none';
|
||||
})()""")
|
||||
human_sleep(1.5, 0.7)
|
||||
page.screenshot(path=OUT + "\\pr_repo_form.png")
|
||||
# submit "Create repository"
|
||||
r = ev(page, """(() => {
|
||||
const b = Array.from(document.querySelectorAll('button[type=submit], button')).find(x => /create repository/i.test((x.innerText||'').trim()) && x.offsetParent !== null);
|
||||
if (b && !b.disabled) { b.click(); return 'CLICK'; }
|
||||
return 'DISABLED';
|
||||
})()""")
|
||||
log("repo create click: " + str(r))
|
||||
time.sleep(14)
|
||||
# verify creation: page may sit at /new while redirect completes — re-check url + repo page
|
||||
ok_url = repo_name in page.url and "/new" not in page.url
|
||||
if not ok_url:
|
||||
try:
|
||||
page.goto(f"https://github.com/{account['username']}/{repo_name}",
|
||||
timeout=60000, wait_until="domcontentloaded")
|
||||
time.sleep(3)
|
||||
ok_url = "Page not found" not in (body_text(page) or "")
|
||||
except Exception:
|
||||
ok_url = False
|
||||
if ok_url:
|
||||
# edit README with real content
|
||||
try:
|
||||
page.goto(f"https://github.com/{account['username']}/{repo_name}/edit/main/README.md",
|
||||
timeout=90000)
|
||||
time.sleep(3)
|
||||
tagline = random.choice([
|
||||
"assorted scripts and tools", "random dev utilities",
|
||||
"small tools, nothing fancy", "stuff that automates stuff"])
|
||||
content = REPO_README.format(
|
||||
repo=repo_name, tagline=tagline,
|
||||
item1=random.choice(["CLI helpers", "scrapers", "file utilities", "API wrappers"]),
|
||||
item2=random.choice(["backup scripts", "cron jobs", "one-off experiments", "glue code"]),
|
||||
item3=random.choice(["notes & docs", "tiny libs", "docker snippets", "config templates"]),
|
||||
note=random.choice([
|
||||
"Mostly for personal use, shared in case it helps.",
|
||||
"Written late at night, works on my machine.",
|
||||
"Refactor when time allows.",
|
||||
"See commits for the mess in progress."]))
|
||||
ed = page.query_selector("textarea, div.CodeMirror, [role=textbox]")
|
||||
if ed:
|
||||
try:
|
||||
ed.fill("")
|
||||
ed.fill(content)
|
||||
except Exception:
|
||||
ev(page, """(() => {
|
||||
const t = document.querySelector('textarea');
|
||||
if (t) { t.value = %s; t.dispatchEvent(new Event('input',{bubbles:true})); }
|
||||
})()""" % json.dumps(content))
|
||||
page.screenshot(path=OUT + "\\pr_readme_edit.png")
|
||||
ev(page, """(() => {
|
||||
const b = document.querySelector("button[type=submit], .Button--primary");
|
||||
if (b && !b.disabled) { b.click(); return 'COMMIT'; }
|
||||
return 'NO';
|
||||
})()""")
|
||||
time.sleep(8)
|
||||
except Exception as e:
|
||||
log("readme edit exc: " + str(e)[:80])
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def fork_repo(page):
|
||||
target = random.choice(["microsoft/WSL", "torvalds/linux", "psf/requests",
|
||||
"tiangolo/fastapi", "sindresorhus/awesome"])
|
||||
log(f"fork target: {target}")
|
||||
page.goto(f"https://github.com/{target}/fork", timeout=90000,
|
||||
wait_until="domcontentloaded")
|
||||
human_sleep(4.0, 1.5) # look at the fork page
|
||||
human_scroll(page, "down", n=random.randint(1, 2))
|
||||
r = ev(page, """(() => {
|
||||
const b = document.querySelector('.Button--primary, button[type=submit]');
|
||||
const b2 = Array.from(document.querySelectorAll('button')).find(x => /^create fork$/i.test((x.innerText||'').trim()));
|
||||
const bb = b2 || b;
|
||||
if (bb && !bb.disabled) { bb.click(); return 'CLICK'; }
|
||||
return 'FAIL:' + (bb ? bb.disabled : 'nobtn');
|
||||
})()""")
|
||||
log("fork click: " + str(r))
|
||||
human_sleep(15, 4)
|
||||
body = body_text(page)
|
||||
return "forked" in body.lower() or "already exists" in body.lower() or "your fork" in body.lower()
|
||||
|
||||
|
||||
def enable_2fa_totp(page, uname):
|
||||
"""Enable TOTP 2FA via wizard (verified live flow 2026-09).
|
||||
Returns (totp_secret, backup_codes_list) or (None, None)."""
|
||||
page.goto("https://github.com/settings/two_factor_authentication/setup/intro",
|
||||
timeout=90000, wait_until="domcontentloaded")
|
||||
human_sleep(5.0, 1.5) # read the wizard
|
||||
human_scroll(page, "down", n=random.randint(1, 2))
|
||||
body = body_text(page)
|
||||
if "two-factor authentication" in body and "setup" not in page.url:
|
||||
log("2fa: already enabled?")
|
||||
return "ALREADY", None
|
||||
# 1. open "setup key" dialog
|
||||
page.evaluate("""(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => /setup key/i.test((x.innerText||'').trim()));
|
||||
if (b) b.click();
|
||||
})()""")
|
||||
time.sleep(3)
|
||||
# 2. extract secret from dialog
|
||||
secret = page.evaluate("""(() => {
|
||||
const dlg = document.querySelector('dialog[open]');
|
||||
const m = (dlg || document).innerText.match(/\\b([A-Z2-7]{16,})\\b/);
|
||||
return m ? m[1] : null;
|
||||
})()""")
|
||||
log("2fa secret: " + str(secret))
|
||||
if not secret:
|
||||
page.screenshot(path=OUT + f"\\pr_2fa_nosecret_{uname}.png")
|
||||
return None, None
|
||||
# 3. close dialog (X button, fallback Escape)
|
||||
closed = page.evaluate("""(() => {
|
||||
const dlg = document.querySelector('dialog[open]');
|
||||
if (!dlg) return 'nodialog';
|
||||
const x = dlg.querySelector('button[aria-label="Close"], .Overlay-closeButton, button[data-close-dialog-id]');
|
||||
if (x) { x.click(); return 'x'; }
|
||||
return 'nox';
|
||||
})()""")
|
||||
log("2fa dialog close: " + str(closed))
|
||||
if closed == "nox":
|
||||
page.keyboard.press("Escape")
|
||||
time.sleep(2)
|
||||
# dialog may persist — force remove overlay via Escape if still open
|
||||
still = page.evaluate("(() => !!document.querySelector('dialog[open]'))()")
|
||||
if still:
|
||||
page.keyboard.press("Escape")
|
||||
time.sleep(1.5)
|
||||
page.evaluate("""(() => {
|
||||
const dlg = document.querySelector('dialog[open]');
|
||||
if (dlg) dlg.close ? dlg.close() : dlg.removeAttribute('open');
|
||||
})()""")
|
||||
time.sleep(1)
|
||||
# 4. type TOTP code: focus via evaluate + keyboard.type (survives overlay/viewport issues)
|
||||
# human touch: 'open authenticator app' pause + variable per-key delay
|
||||
human_sleep(1.8, 0.9)
|
||||
entered = False
|
||||
for attempt in range(2):
|
||||
code = pyotp.TOTP(secret).now()
|
||||
log(f"2fa code={code} (attempt {attempt + 1})")
|
||||
page.evaluate("""(() => {
|
||||
const i = document.querySelector("input[name=otp][data-target*='appOtpInput']");
|
||||
if (i) { i.scrollIntoView({block: 'center'}); i.focus(); }
|
||||
})()""")
|
||||
human_sleep(0.9, 0.4)
|
||||
# variable typing speed, occasional slow key
|
||||
for ch in str(code):
|
||||
page.keyboard.type(ch, delay=0)
|
||||
d = random.uniform(0.09, 0.22)
|
||||
if random.random() < 0.15:
|
||||
d += random.uniform(0.2, 0.5)
|
||||
time.sleep(d)
|
||||
time.sleep(2.5)
|
||||
# verify value landed
|
||||
val = page.evaluate("""(() => document.querySelector("input[name=otp][data-target*='appOtpInput']").value)""")
|
||||
if val == code:
|
||||
entered = True
|
||||
# 5. scroll to Continue + click
|
||||
page.evaluate("""(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => /^continue$/i.test((x.innerText||'').trim()));
|
||||
if (b) b.scrollIntoView({block: 'center'});
|
||||
})()""")
|
||||
time.sleep(1)
|
||||
r = page.evaluate("""(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => /^continue$/i.test((x.innerText||'').trim()));
|
||||
if (b && !b.disabled) { b.click(); return 'clicked'; }
|
||||
return 'state:' + (b ? b.disabled : 'nobtn');
|
||||
})()""")
|
||||
log("2fa continue: " + str(r))
|
||||
# nobtn == step already advanced (observed live) — treat as success
|
||||
if r in ("clicked", "state:nobtn", "state:false"):
|
||||
break
|
||||
# code window rotated — retry
|
||||
time.sleep(5)
|
||||
if not entered:
|
||||
page.screenshot(path=OUT + f"\\pr_2fa_nocontinue_{uname}.png")
|
||||
return secret, None
|
||||
time.sleep(15)
|
||||
# 6. recovery step: download codes file (this also unlocks "I have saved")
|
||||
body = page.evaluate("document.body.innerText")
|
||||
m = re.search(r"\b([0-9a-f]{6}(?:-[0-9a-f]{6,}){6,})\b", body)
|
||||
recovery_inline = m.group(1) if m else None
|
||||
codes = None
|
||||
dl_path = os.path.join(OUT, "recovery_codes_download.txt")
|
||||
try:
|
||||
with page.expect_download(timeout=25000) as dl:
|
||||
page.evaluate("""(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => /^download$/i.test((x.innerText||'').trim()) && x.offsetParent !== null);
|
||||
if (b) b.click();
|
||||
})()""")
|
||||
codes = dl.value
|
||||
path = dl.value.path()
|
||||
# parse: each line "xxxxx-yyyyy"
|
||||
txt = open(path, encoding="utf-8").read()
|
||||
codes = [c for c in re.findall(r"\b([a-z0-9]{5}-[a-z0-9]{5})\b", txt, re.I)]
|
||||
import shutil
|
||||
shutil.copy(path, dl_path)
|
||||
log(f"2fa codes downloaded: {len(codes)}")
|
||||
except Exception as e:
|
||||
log("2fa download exc: " + str(e)[:120])
|
||||
if recovery_inline:
|
||||
codes = [recovery_inline]
|
||||
time.sleep(3)
|
||||
# 7. finalize: "I have saved my recovery codes"
|
||||
fin = page.evaluate("""(() => {
|
||||
const b = Array.from(document.querySelectorAll('button')).find(x => /i have saved my recovery codes/i.test((x.innerText||'').trim()));
|
||||
if (b && !b.disabled) { b.click(); return 'clicked'; }
|
||||
return 'disabled:' + (b ? b.disabled : 'nobtn');
|
||||
})()""")
|
||||
log("2fa finalize: " + str(fin))
|
||||
time.sleep(12)
|
||||
return secret, codes
|
||||
|
||||
|
||||
def process_account(account, proxy_label="HOME"):
|
||||
uname = account["username"]
|
||||
email = account["email"]
|
||||
password = account["password"]
|
||||
log(f"=== POSTREG {uname} ({email}) ===")
|
||||
updates = {"provider": "github", "username": uname}
|
||||
avatar_path = make_avatar(uname)
|
||||
new_username = gen_new_username()
|
||||
first, last = random.choice(NAMES_POOL)
|
||||
bio = random.choice(BIOS)
|
||||
cfg = proxy_cfg(proxy_label)
|
||||
with Camoufox(proxy=cfg, headless=True, humanize=True) as browser:
|
||||
page = browser.new_page()
|
||||
st, url = login(page, email, password, uname)
|
||||
log("login: " + st)
|
||||
if st == "2FA_ALREADY":
|
||||
upsert_account({**updates, "status": "OK_VERIFIED", "twofa_enabled": 1})
|
||||
return "2FA_ALREADY"
|
||||
if st != "OK":
|
||||
if st == "DEVICE_VERIFY":
|
||||
if not wait_device_code(page, account):
|
||||
upsert_account({**updates, "status": "DEVICE_VERIFY_FAIL"})
|
||||
return "DEVICE_VERIFY_FAIL"
|
||||
log("device verified")
|
||||
else:
|
||||
upsert_account({**updates, "status": st})
|
||||
return st
|
||||
# ---- avatar ----
|
||||
av = upload_avatar(page, avatar_path)
|
||||
log("avatar: " + str(av))
|
||||
updates["avatar"] = avatar_path
|
||||
# ---- profile: name + bio ----
|
||||
set_profile(page, first, last, bio)
|
||||
updates["bio"] = bio
|
||||
# ---- repo ----
|
||||
repo_name = (uname + "-lab")[:60]
|
||||
repo_type = "own" if random.random() < 0.7 else "fork"
|
||||
if repo_type == "own":
|
||||
made = create_repo(page, repo_name, account)
|
||||
else:
|
||||
made = fork_repo(page)
|
||||
repo_name = None
|
||||
log(f"repo({repo_type}): {made}")
|
||||
if made:
|
||||
updates["repo_name"] = repo_name
|
||||
updates["repo_type"] = repo_type
|
||||
# ---- 2FA ----
|
||||
secret, codes = enable_2fa_totp(page, uname)
|
||||
if secret and secret != "ALREADY":
|
||||
updates["totp_secret"] = secret
|
||||
updates["totp_ok"] = 1
|
||||
updates["twofa_enabled"] = 1
|
||||
if codes:
|
||||
updates["backup_codes"] = codes
|
||||
elif secret == "ALREADY":
|
||||
updates["twofa_enabled"] = 1
|
||||
else:
|
||||
log("2FA FAILED for " + uname)
|
||||
# GitHub: rename disabled for fresh accounts ("contact us") — skip
|
||||
page.screenshot(path=OUT + "\\pr_final.png")
|
||||
updates["status"] = "POSTREG_DONE"
|
||||
upsert_account(updates)
|
||||
# TG push
|
||||
try:
|
||||
from gh_autoreg import tg_push_creds
|
||||
tg_push_creds(email, uname, password)
|
||||
except Exception as e:
|
||||
log("tg push exc: " + str(e)[:100])
|
||||
return "DONE"
|
||||
|
||||
|
||||
def main():
|
||||
limit = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
||||
uname_filter = sys.argv[2] if len(sys.argv) > 2 else None
|
||||
gh_db.init()
|
||||
if uname_filter:
|
||||
acc = gh_db.get_by_username(uname_filter)
|
||||
accounts = [acc] if acc else []
|
||||
else:
|
||||
accounts = gh_db.fetch("github", "OK_VERIFIED", limit=1000)
|
||||
# only un-warmed accounts; no fallback to already-warmed ones
|
||||
accounts = [a for a in accounts if not a.get("twofa_enabled")][:limit or 1]
|
||||
if not accounts:
|
||||
print("no accounts to process")
|
||||
return 0
|
||||
ok = 0
|
||||
for a in accounts[: (limit or len(accounts))]:
|
||||
res = None
|
||||
try:
|
||||
res = process_account(a, proxy_label="HOME") # direct: ZTE modem dead
|
||||
if res in ("DONE", "2FA_ALREADY"):
|
||||
ok += 1
|
||||
except Exception as e:
|
||||
log(f"process EXC {a['username']}: {type(e).__name__} {str(e)[:200]}")
|
||||
upsert_account({"provider": "github", "username": a["username"],
|
||||
"status": "OK_VERIFIED", "err": f"{type(e).__name__}: {str(e)[:160]}"})
|
||||
# fast cadence for unattended workers: short gap, skip trailing sleep
|
||||
gap = random.uniform(30, 60) if res in ("DONE", "2FA_ALREADY") else random.uniform(15, 30)
|
||||
log(f"waiting {int(gap)}s before next account")
|
||||
time.sleep(gap)
|
||||
log(f"postreg finished: ok={ok}/{len(accounts[:limit or 100])}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,131 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Batch runner for GitHub autoreg. Alternates between HOME IP and VPS SOCKS
|
||||
to spread ban risk, with human-ish pauses. Continues until target count of
|
||||
OK_VERIFIED accounts is reached. Progress journaled so restarts are safe.
|
||||
Usage: python gh_runner.py [target_total] [start_idx]
|
||||
"""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import subprocess, time, json, random, sys, os
|
||||
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
ACCOUNTS = OUT + r"\github_accounts.jsonl"
|
||||
STATE = OUT + r"\gh_runner_state.json"
|
||||
PY = _PY
|
||||
SCRIPT = OUT + r"\gh_autoreg.py"
|
||||
|
||||
TARGET = int(sys.argv[1]) if len(sys.argv) > 1 else 50
|
||||
START = int(sys.argv[2]) if len(sys.argv) > 2 else 10
|
||||
LIMIT = int(sys.argv[3]) if len(sys.argv) > 3 else 0 # max accounts this run, 0 = unlimited
|
||||
|
||||
def log(m):
|
||||
line = f"[{time.strftime('%H:%M:%S')}] RUNNER: {m}"
|
||||
print(line, flush=True)
|
||||
|
||||
def read_state():
|
||||
try:
|
||||
with open(STATE, encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return {"done": 0, "tries": 0, "next_idx": START, "errors": {}}
|
||||
|
||||
def write_state(st):
|
||||
with open(STATE, "w", encoding="utf-8") as f:
|
||||
json.dump(st, f, ensure_ascii=False, indent=1)
|
||||
|
||||
def count_ok():
|
||||
n = 0
|
||||
try:
|
||||
with open(ACCOUNTS, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
try:
|
||||
if json.loads(line).get("status") == "OK_VERIFIED":
|
||||
n += 1
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return n
|
||||
|
||||
def run_one(idx, source):
|
||||
env = os.environ.copy()
|
||||
env["PYTHONIOENCODING"] = "utf-8"
|
||||
proc = subprocess.run([PY, SCRIPT, str(idx).zfill(3), source, "gmail"],
|
||||
capture_output=True, text=True, env=env, timeout=600)
|
||||
return proc.returncode, proc.stdout[-600:]
|
||||
|
||||
def main():
|
||||
st = read_state()
|
||||
ok_total = count_ok()
|
||||
log(f"state: done_total_ok={ok_total} target={TARGET} next_idx={st['next_idx']}")
|
||||
if ok_total >= TARGET:
|
||||
log("target already reached, nothing to do")
|
||||
return
|
||||
sources = ["SOCKSH"]
|
||||
done_this_run = 0
|
||||
while ok_total < TARGET and (not LIMIT or done_this_run < LIMIT):
|
||||
idx = st["next_idx"]
|
||||
st["next_idx"] += 1
|
||||
st["tries"] += 1
|
||||
source = random.choice(sources)
|
||||
log(f"== account {idx} via {source} (have {ok_total}/{TARGET}) ==")
|
||||
rc = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
rc, tail = run_one(idx, source if attempt == 0 else random.choice(sources))
|
||||
log(f"rc={rc} tail={tail[-200:].strip()[:180]}")
|
||||
except subprocess.TimeoutExpired:
|
||||
rc = 90
|
||||
log("timeout 600s")
|
||||
except Exception as e:
|
||||
rc = 99
|
||||
log("launch err: " + str(e)[:100])
|
||||
if rc == 0:
|
||||
done_this_run += 1
|
||||
break
|
||||
if rc in (7, 5, 4, 6, 1, 3): # late-stage/logic - no retry value
|
||||
break
|
||||
# rc 2 = FORM_TIMEOUT, 90/99 -> retry with different source
|
||||
time.sleep(random.uniform(30, 90))
|
||||
ok_total = count_ok()
|
||||
if ok_total >= TARGET:
|
||||
log(f"DONE: {ok_total} OK_VERIFIED")
|
||||
break
|
||||
st["errors"][str(idx)] = rc
|
||||
write_state(st)
|
||||
pause = random.uniform(90, 240)
|
||||
log(f"pause {int(pause)}s before next")
|
||||
time.sleep(pause)
|
||||
write_state(st)
|
||||
log(f"final OK count = {ok_total}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,102 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Verify all collected OK_VERIFIED GitHub accounts via web login flow:
|
||||
GET /login (authenticity_token) -> POST /session -> expect 302 away from /login.
|
||||
Usage: python gh_verify_accounts.py [mode]
|
||||
mode: check (default) / out (print table)
|
||||
"""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import requests, re, json, sys, time
|
||||
|
||||
ACC = str(_w("tmp/bpproxy_run/github_accounts.jsonl"))
|
||||
|
||||
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/125.0.0.0 Safari/537.36"
|
||||
|
||||
|
||||
def get_accounts():
|
||||
rows = []
|
||||
try:
|
||||
with open(ACC, encoding="utf-8") as f:
|
||||
for line in f:
|
||||
try:
|
||||
rows.append(json.loads(line))
|
||||
except Exception:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
return rows
|
||||
|
||||
|
||||
def check_login(user, pwd):
|
||||
s = requests.Session()
|
||||
s.headers.update({"User-Agent": UA})
|
||||
try:
|
||||
r = s.get("https://github.com/login", timeout=30)
|
||||
tok = re.search(r'name="authenticity_token" value="([^"]+)"', r.text)
|
||||
if not tok:
|
||||
return "NO_TOKEN"
|
||||
payload = {"authenticity_token": tok.group(1), "login": user, "password": pwd, "commit": "Sign in"}
|
||||
r2 = s.post("https://github.com/session", data=payload, timeout=30, allow_redirects=False)
|
||||
loc = r2.headers.get("Location", "")
|
||||
if r2.status_code in (302, 303) and "/login" not in loc.split("?")[0]:
|
||||
return "OK"
|
||||
if "two_factor" in loc or "2fa" in loc:
|
||||
return "2FA"
|
||||
if r2.status_code == 200:
|
||||
# maybe wrong password message
|
||||
if "Incorrect username or password" in r2.text:
|
||||
return "BAD_CREDS"
|
||||
return "UNKNOWN"
|
||||
return f"HTTP{r2.status_code}"
|
||||
except Exception as e:
|
||||
return "ERR"
|
||||
|
||||
|
||||
def main():
|
||||
rows = get_accounts()
|
||||
verified = [r for r in rows if r.get("status") == "OK_VERIFIED"]
|
||||
print(f"total records={len(rows)} verified={len(verified)}", flush=True)
|
||||
results = []
|
||||
for i, r in enumerate(verified, 1):
|
||||
res = check_login(r["username"], r["password"])
|
||||
results.append((r["username"], r["email"], res))
|
||||
print(f"[{i}/{len(verified)}] {r['username']} -> {res}", flush=True)
|
||||
time.sleep(2)
|
||||
ok = sum(1 for _ in results if _[2] == "OK")
|
||||
full_path = ACC.replace(".jsonl", "_verify.jsonl")
|
||||
with open(full_path, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps({"ts": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"results": results, "ok": ok, "total": len(verified)}) + "\n")
|
||||
print(f"OK={ok}/{len(verified)} saved -> {full_path}", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,154 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""GitHub autoreg watchdog. Cron (no_agent): silent when healthy,
|
||||
prints ALERT lines when attention needed. Restarts dead components,
|
||||
sends alerts to Vlad's TG chat (token parsed from hermes config.yaml)."""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import json, os, re, subprocess, sys, time, urllib.parse, urllib.request
|
||||
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
ACC = os.path.join(OUT, "github_accounts.jsonl")
|
||||
LOG = os.path.join(OUT, "gh_autoreg.log")
|
||||
CFG = (_pos.environ.get("HERMES_CONFIG",""))
|
||||
TARGET = 100
|
||||
PY = _PY
|
||||
CHAT = "TG_CHAT_ID"
|
||||
THREAD = "350384"
|
||||
DETACH = 0x00000008
|
||||
|
||||
|
||||
def get_token():
|
||||
for pat in (r"7189316701:[A-Za-z0-9_-]{20,}", r"8873155556:[A-Za-z0-9_-]{20,}"):
|
||||
m = re.search(pat, open(CFG, encoding="utf-8").read())
|
||||
if m:
|
||||
return m.group(1)
|
||||
return None
|
||||
|
||||
|
||||
def tg(msg):
|
||||
t = get_token()
|
||||
if not t:
|
||||
return False
|
||||
try:
|
||||
data = urllib.parse.urlencode({
|
||||
"chat_id": CHAT, "message_thread_id": THREAD, "text": msg[:3500]}).encode()
|
||||
urllib.request.urlopen("https://api.telegram.org/bot%s/sendMessage" % t,
|
||||
data=data, timeout=25).read()
|
||||
return True
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def count_statuses():
|
||||
c, ok_uniq, bad = {}, set(), []
|
||||
for line in open(ACC, encoding="utf-8"):
|
||||
try:
|
||||
r = json.loads(line)
|
||||
except Exception:
|
||||
continue
|
||||
st = r.get("status", "?")
|
||||
c[st] = c.get(st, 0) + 1
|
||||
if st == "OK_VERIFIED":
|
||||
ok_uniq.add(r.get("username"))
|
||||
else:
|
||||
bad.append(r.get("ts", ""))
|
||||
return c, len(ok_uniq), len(bad[-12:])
|
||||
|
||||
|
||||
def proc_alive(name):
|
||||
try:
|
||||
out = subprocess.run(
|
||||
["wmic", "process", "where", "name='python.exe' or name='python3.exe'",
|
||||
"get", "CommandLine", "/format:list"],
|
||||
capture_output=True, text=True, timeout=30).stdout
|
||||
return name in out
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
|
||||
def fresh_log():
|
||||
try:
|
||||
return time.time() - os.path.getmtime(LOG) < 60 * 15
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
alerts = []
|
||||
c, ok, bads = count_statuses()
|
||||
needed = TARGET - ok
|
||||
runner = proc_alive("gh_runner.py")
|
||||
socks = proc_alive("vps_socks.py")
|
||||
|
||||
if not runner and needed > 0:
|
||||
subprocess.Popen([PY, os.path.join(OUT, "gh_runner.py"), str(TARGET)],
|
||||
cwd=OUT, creationflags=DETACH)
|
||||
alerts.append("RESTART runner (ok=%d/%d)" % (ok, TARGET))
|
||||
if not socks:
|
||||
subprocess.Popen([PY, os.path.join(OUT, "vps_socks.py"), "2090", "27022"],
|
||||
cwd=OUT, creationflags=DETACH)
|
||||
alerts.append("RESTART vps_socks")
|
||||
if runner and not fresh_log():
|
||||
alerts.append("STALE: log silent 15min, runner alive; ok=%d/%d" % (ok, TARGET))
|
||||
|
||||
if TARGET - ok <= 3 and ok >= 97:
|
||||
alerts.append("ALMOST: %d/%d" % (ok, TARGET))
|
||||
if ok >= TARGET:
|
||||
alerts.append("DONE: %d OK_VERIFIED reached" % ok)
|
||||
|
||||
hour_mark = os.path.join(OUT, ".wdg_hour")
|
||||
hb = False
|
||||
try:
|
||||
if time.time() - os.path.getmtime(hour_mark) > 3600:
|
||||
hb = True
|
||||
except Exception:
|
||||
hb = True
|
||||
if hb:
|
||||
try:
|
||||
open(hour_mark, "w").write(time.strftime("%H:%M"))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if hb and not alerts:
|
||||
alerts.append("watchdog beat: %d/%d | %s" % (ok, TARGET, c))
|
||||
if alerts:
|
||||
print("\n".join(alerts), flush=True)
|
||||
if not tg("GH-REG: " + "\n".join(alerts)):
|
||||
try:
|
||||
subprocess.run(
|
||||
[PY, OUT + r"\tg_push_r3f.py", "GH-REG: " + "\n".join(alerts)],
|
||||
capture_output=True, text=True, timeout=60)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,141 @@
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
# GitLab reg: HOME + gmail alias (IMAP code)
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import string
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from camoufox.sync_api import Camoufox
|
||||
from gh_mail import GmailIMAP
|
||||
|
||||
SIGNUP_URL = "https://gitlab.com/users/sign_up"
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
ACC = OUT + r"\gitlab_accounts.jsonl"
|
||||
|
||||
FIRST = ["Diego", "Mateo", "Sofia", "Valentina", "Lucas", "Camila", "Martin", "Elena", "Andres", "Isabel", "Javier", "Natalia", "Pablo", "Lucia", "Marco", "Ana"]
|
||||
LAST = ["Costa", "Silva", "Rodriguez", "Martinez", "Lopez", "Garcia", "Pereira", "Fernandez", "Rojas", "Moreno", "Vargas", "Castro", "Ramos", "Suarez", "Medina", "Ortiz"]
|
||||
|
||||
gmail = GmailIMAP()
|
||||
addr = gmail.make_address()
|
||||
print(f"[{time.strftime('%H:%M:%S')}] gmail alias: {addr}", flush=True)
|
||||
|
||||
first, last = random.choice(FIRST), random.choice(LAST)
|
||||
username = (first.lower() + last.lower() + random.choice(["", "dev", "42", "77"]) + "".join(random.choices(string.digits, k=2)))[:28]
|
||||
password = "Gl#" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!7"
|
||||
print(f"account: {username}", flush=True)
|
||||
|
||||
|
||||
def save(**kw):
|
||||
kw["ts"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
with open(ACC, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(kw, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
with Camoufox(headless=True, humanize=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(SIGNUP_URL, timeout=90000, wait_until="domcontentloaded")
|
||||
page.wait_for_selector("#new_user_email", timeout=25000)
|
||||
time.sleep(3)
|
||||
|
||||
for sel, val, d in [("#new_user_first_name", first, 0.5), ("#new_user_last_name", last, 0.4),
|
||||
("#new_user_username", username, 0.6), ("#new_user_email", addr, 0.6),
|
||||
("#new_user_password", password, 0.8)]:
|
||||
try:
|
||||
page.fill(sel, val, timeout=8000)
|
||||
time.sleep(d)
|
||||
except Exception as e:
|
||||
print(f"fill {sel}: ERR {str(e)[:60]}", flush=True)
|
||||
time.sleep(1)
|
||||
|
||||
try:
|
||||
page.click("button[type=submit], input[type=submit]", timeout=10000)
|
||||
except Exception:
|
||||
page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('.btn-confirm') || document.querySelector('button'); if (b) b.click(); })()")
|
||||
time.sleep(6)
|
||||
|
||||
for _ in range(12):
|
||||
try:
|
||||
body = page.evaluate("document.body.innerText.slice(0,300)") or ""
|
||||
except Exception:
|
||||
body = ""
|
||||
if re.search(r"Just a moment|checking your browser|verifies that you", body, re.I):
|
||||
time.sleep(4)
|
||||
continue
|
||||
break
|
||||
|
||||
st = page.evaluate("(() => ({url: location.href, arkose: !!document.querySelector('iframe[src*=arkoselabs]'), body: document.body.innerText.slice(0,400)}))()")
|
||||
print(f"after submit: {st['url'][:90]} arkose={st['arkose']}", flush=True)
|
||||
print("BODY: " + st["body"][:250].replace("\n", " | "), flush=True)
|
||||
|
||||
if "identity_verification" not in st["url"]:
|
||||
page.screenshot(path=OUT + r"\gl_g_state.png")
|
||||
save(status="unexpected", username=username, password=password, email=addr, url=st["url"], body=st["body"][:200])
|
||||
print(json.dumps({"status": "unexpected", "url": st["url"], "body": st["body"][:200]}))
|
||||
sys.exit(0)
|
||||
|
||||
print("flow: identity_verification", flush=True)
|
||||
has_input = page.evaluate("(() => !!document.querySelector('input[inputmode=numeric], input[name*=code i], input[id*=code i], input[type=tel]'))()")
|
||||
if not has_input:
|
||||
sb = page.evaluate("""(() => { const btns = Array.from(document.querySelectorAll('button, a')); const b = btns.find(x => /Send|Get|Code|Verif|Enviar/i.test((x.innerText||''))); if (b) { b.click(); return (b.innerText||'').trim(); } return null; })()""")
|
||||
print(f"clicked send: {sb}", flush=True)
|
||||
time.sleep(6)
|
||||
|
||||
code = gmail.wait_code(addr, timeout_sec=300)
|
||||
print(f"code: {code}", flush=True)
|
||||
if not code:
|
||||
save(status="no_code", username=username, password=password, email=addr)
|
||||
page.screenshot(path=OUT + r"\gl_g_nocode.png")
|
||||
sys.exit(4)
|
||||
|
||||
page.evaluate("""(code) => {
|
||||
const cands = ['input[name*=code i]','input[id*=code i]','input[name*=verification i]','input[id*=verification i]','input[autocomplete=one-time-code]','input[inputmode=numeric]','input[type=tel]'];
|
||||
let el = null;
|
||||
for (const c of cands) { el = document.querySelector(c); if (el) break; }
|
||||
if (!el) return;
|
||||
el.focus(); el.value = code;
|
||||
el.dispatchEvent(new Event('input', {bubbles:true}));
|
||||
el.dispatchEvent(new Event('change', {bubbles:true}));
|
||||
}""", code)
|
||||
time.sleep(1.2)
|
||||
page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('.btn-confirm'); if (b) b.click(); })()")
|
||||
time.sleep(9)
|
||||
|
||||
s2 = page.evaluate("(() => ({url: location.href, body: document.body.innerText.slice(0,900)}))()")
|
||||
print("STEP2 url=" + s2["url"][:90], flush=True)
|
||||
print("STEP2 BODY: " + s2["body"][:600].replace("\n", " | "), flush=True)
|
||||
page.screenshot(path=OUT + r"\gl_g_step2.png")
|
||||
save(status="iv_done", username=username, password=password, email=addr, step2_url=s2["url"], step2_body=s2["body"][:300])
|
||||
print(json.dumps({"username": username, "password": password, "email": addr,
|
||||
"step2_url": s2["url"], "step2_body": s2["body"][:300]}))
|
||||
@@ -0,0 +1,154 @@
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
# GitLab single reg: HOME IP + mail.tm + email code via REST
|
||||
import json
|
||||
import random
|
||||
import re
|
||||
import string
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from camoufox.sync_api import Camoufox
|
||||
from gh_mail import MailTM
|
||||
|
||||
SIGNUP_URL = "https://gitlab.com/users/sign_up"
|
||||
OUT = str(_w("tmp/bpproxy_run"))
|
||||
ACC = OUT + r"\gitlab_accounts.jsonl"
|
||||
|
||||
FIRST = ["Diego", "Mateo", "Sofia", "Valentina", "Lucas", "Camila", "Martin", "Elena", "Andres", "Isabel", "Javier", "Natalia", "Pablo", "Lucia", "Marco", "Ana"]
|
||||
LAST = ["Costa", "Silva", "Rodriguez", "Martinez", "Lopez", "Garcia", "Pereira", "Fernandez", "Rojas", "Moreno", "Vargas", "Castro", "Ramos", "Suarez", "Medina", "Ortiz"]
|
||||
|
||||
|
||||
def log(m):
|
||||
print(f"[{time.strftime('%H:%M:%S')}] {m}", flush=True)
|
||||
|
||||
|
||||
def save(**kw):
|
||||
kw["ts"] = time.strftime("%Y-%m-%d %H:%M:%S")
|
||||
with open(ACC, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(kw, ensure_ascii=False) + "\n")
|
||||
|
||||
|
||||
mail = MailTM()
|
||||
mb = mail.create()
|
||||
if not mb:
|
||||
print("FATAL: mailbox")
|
||||
sys.exit(2)
|
||||
addr, mailpass, token = mb["address"], mb["password"], mb["token"]
|
||||
log(f"mailbox: {addr}")
|
||||
|
||||
first, last = random.choice(FIRST), random.choice(LAST)
|
||||
username = (first.lower() + last.lower() + random.choice(["", "dev", "42", "77"]) + "".join(random.choices(string.digits, k=2)))[:28]
|
||||
password = "Gl#" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!7"
|
||||
log(f"account: {username}")
|
||||
|
||||
with Camoufox(headless=True, humanize=True) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(SIGNUP_URL, timeout=90000, wait_until="domcontentloaded")
|
||||
page.wait_for_selector("#new_user_email", timeout=25000)
|
||||
time.sleep(3)
|
||||
|
||||
for sel, val, d in [("#new_user_first_name", first, 0.5), ("#new_user_last_name", last, 0.4),
|
||||
("#new_user_username", username, 0.6), ("#new_user_email", addr, 0.6),
|
||||
("#new_user_password", password, 0.8)]:
|
||||
try:
|
||||
page.fill(sel, val, timeout=8000)
|
||||
time.sleep(d)
|
||||
except Exception as e:
|
||||
log(f"fill {sel}: ERR {str(e)[:60]}")
|
||||
time.sleep(1)
|
||||
|
||||
try:
|
||||
page.click("button[type=submit], input[type=submit]", timeout=10000)
|
||||
except Exception:
|
||||
page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('.btn-confirm') || document.querySelector('button'); if (b) b.click(); })()")
|
||||
time.sleep(6)
|
||||
|
||||
# CF interstitial?
|
||||
for _ in range(12):
|
||||
try:
|
||||
body = page.evaluate("document.body.innerText.slice(0,300)") or ""
|
||||
except Exception:
|
||||
body = ""
|
||||
if re.search(r"Just a moment|checking your browser|verifies that you", body, re.I):
|
||||
time.sleep(4)
|
||||
continue
|
||||
break
|
||||
|
||||
st = page.evaluate("(() => ({url: location.href, arkose: !!document.querySelector('iframe[src*=arkoselabs]'), body: document.body.innerText.slice(0,400)}))()")
|
||||
log(f"after submit: {st['url'][:90]} arkose={st['arkose']}")
|
||||
log("BODY: " + st["body"][:250].replace("\n", " | "))
|
||||
|
||||
if "identity_verification" in st["url"]:
|
||||
log("flow: identity_verification")
|
||||
# click "Send code" if no input yet
|
||||
has_input = page.evaluate("(() => !!document.querySelector('input[inputmode=numeric], input[name*=code i], input[id*=code i], input[type=tel]'))()")
|
||||
if not has_input:
|
||||
sb = page.evaluate("""(() => { const btns = Array.from(document.querySelectorAll('button, a')); const b = btns.find(x => /Send|Get|Code|Verif|Enviar/i.test((x.innerText||''))); if (b) { b.click(); return (b.innerText||'').trim(); } return null; })()""")
|
||||
log(f"clicked send: {sb}")
|
||||
time.sleep(6)
|
||||
|
||||
code = mail.wait_code(token, sender_hint="gitlab", timeout_sec=300)
|
||||
log(f"code: {code}")
|
||||
if not code:
|
||||
save(status="no_code", username=username, password=password, email=addr)
|
||||
page.screenshot(path=OUT + r"\gl_home_nocode.png")
|
||||
sys.exit(4)
|
||||
|
||||
fr = page.evaluate("""(code) => {
|
||||
const cands = ['input[name*=code i]','input[id*=code i]','input[name*=verification i]','input[id*=verification i]','input[autocomplete=one-time-code]','input[inputmode=numeric]','input[type=tel]'];
|
||||
let el = null;
|
||||
for (const c of cands) { el = document.querySelector(c); if (el) break; }
|
||||
if (!el) return {ok:false};
|
||||
el.focus(); el.value = code;
|
||||
el.dispatchEvent(new Event('input', {bubbles:true}));
|
||||
el.dispatchEvent(new Event('change', {bubbles:true}));
|
||||
return {ok:true, name: el.name};
|
||||
}""", code)
|
||||
log(f"code fill: {json.dumps(fr)}")
|
||||
time.sleep(1.2)
|
||||
page.evaluate("(() => { const b = document.querySelector('button[type=submit]') || document.querySelector('.btn-confirm'); if (b) b.click(); })()")
|
||||
time.sleep(9)
|
||||
|
||||
s2 = page.evaluate("(() => ({url: location.href, body: document.body.innerText.slice(0,800)}))()")
|
||||
log("STEP2 url=" + s2["url"][:90])
|
||||
log("STEP2 BODY: " + s2["body"][:500].replace("\n", " | "))
|
||||
page.screenshot(path=OUT + r"\gl_home_step2.png")
|
||||
save(status="iv_done", username=username, password=password, email=addr,
|
||||
mail_token=token, step2_url=s2["url"], step2_body=s2["body"][:300])
|
||||
print(json.dumps({"username": username, "password": password, "email": addr, "mail_token": token,
|
||||
"step2_url": s2["url"], "step2_body": s2["body"][:200]}))
|
||||
else:
|
||||
page.screenshot(path=OUT + r"\gl_home_state.png")
|
||||
save(status="unexpected", username=username, password=password, email=addr,
|
||||
page_url=st["url"], body=st["body"][:200])
|
||||
print(json.dumps({"username": username, "password": password, "email": addr, "state": st["url"], "body": st["body"][:200]}))
|
||||
@@ -0,0 +1,116 @@
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import struct
|
||||
import sys
|
||||
import zlib
|
||||
|
||||
path = sys.argv[1] if len(sys.argv) > 1 else str(_w("tmp/bpproxy_run/cb_captcha.png"))
|
||||
data = open(path, "rb").read()
|
||||
assert data[:8] == b"\x89PNG\r\n\x1a\n", "not PNG"
|
||||
|
||||
pos = 8
|
||||
idat = b""
|
||||
plte = None
|
||||
trns = None
|
||||
while pos < len(data):
|
||||
(ln,) = struct.unpack(">I", data[pos : pos + 4])
|
||||
typ = data[pos + 4 : pos + 8]
|
||||
chunk = data[pos + 8 : pos + 8 + ln]
|
||||
if typ == b"IHDR":
|
||||
w, h, depth, ctype, _, _, _ = struct.unpack(">IIBBBBB", chunk)
|
||||
elif typ == b"IDAT":
|
||||
idat += chunk
|
||||
elif typ == b"PLTE":
|
||||
plte = chunk
|
||||
elif typ == b"tRNS":
|
||||
trns = chunk
|
||||
pos += 12 + ln
|
||||
|
||||
assert depth == 8, f"depth {depth} unsupported"
|
||||
raw = zlib.decompress(idat)
|
||||
bpp = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}[ctype]
|
||||
stride = w * bpp
|
||||
px = bytearray(h * stride)
|
||||
|
||||
# unfilter
|
||||
ri = 0
|
||||
prev = bytearray(stride)
|
||||
for y in range(h):
|
||||
f = raw[ri]
|
||||
ri += 1
|
||||
line = bytearray(raw[ri : ri + stride])
|
||||
ri += stride
|
||||
if f == 1:
|
||||
for i in range(bpp, stride):
|
||||
line[i] = (line[i] + line[i - bpp]) & 255
|
||||
elif f == 2:
|
||||
for i in range(stride):
|
||||
line[i] = (line[i] + prev[i]) & 255
|
||||
elif f == 3:
|
||||
for i in range(stride):
|
||||
a = line[i - bpp] if i >= bpp else 0
|
||||
line[i] = (line[i] + ((a + prev[i]) >> 1)) & 255
|
||||
elif f == 4:
|
||||
for i in range(stride):
|
||||
a = line[i - bpp] if i >= bpp else 0
|
||||
b = prev[i]
|
||||
c = prev[i - bpp] if i >= bpp else 0
|
||||
p = a + b - c
|
||||
pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)
|
||||
pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c)
|
||||
line[i] = (line[i] + pr) & 255
|
||||
px[y * stride : (y + 1) * stride] = line
|
||||
prev = line
|
||||
|
||||
def lum(x, y):
|
||||
o = y * stride + x * bpp
|
||||
if ctype == 0:
|
||||
return px[o]
|
||||
if ctype == 2:
|
||||
return (px[o] + px[o + 1] + px[o + 2]) // 3
|
||||
if ctype == 3:
|
||||
idx = px[o]
|
||||
return (plte[idx * 3] + plte[idx * 3 + 1] + plte[idx * 3 + 2]) // 3
|
||||
if ctype == 4:
|
||||
return px[o]
|
||||
if ctype == 6:
|
||||
return (px[o] + px[o + 1] + px[o + 2]) // 3
|
||||
|
||||
# ASCII downsample
|
||||
cols = 110
|
||||
rows = max(1, int(h * (cols / w) * 0.5))
|
||||
for ry in range(rows):
|
||||
y = min(h - 1, int(ry * h / rows))
|
||||
line = []
|
||||
for rx in range(cols):
|
||||
x = min(w - 1, int(rx * w / cols))
|
||||
line.append("#" if lum(x, y) < 128 else ".")
|
||||
print("".join(line))
|
||||
@@ -0,0 +1,18 @@
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
UA = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
|
||||
|
||||
for host in ("https://notabug.org", "https://git.disroot.org", "https://gitea.com",
|
||||
"https://git.tilde.team", "https://git.hardenedbsd.org", "https://framagit.org"):
|
||||
try:
|
||||
req = urllib.request.Request(host + "/user/sign_up", headers=UA)
|
||||
with urllib.request.urlopen(req, timeout=25) as r:
|
||||
html = r.read().decode("utf-8", "ignore")
|
||||
cap = "captcha" in html.lower()
|
||||
fields = [s for s in ("user_name", "email", "password", "retype") if s in html]
|
||||
print(f"{host:34s} {r.status} fields={len(fields)} captcha={cap}")
|
||||
except urllib.error.HTTPError as e:
|
||||
print(f"{host:34s} HTTP {e.code}")
|
||||
except Exception as e:
|
||||
print(f"{host:34s} ERR {str(e)[:60]}")
|
||||
@@ -0,0 +1,123 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Signup in REAL Chrome via EMAIL-CODE method (skip password step entirely)."""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import sys, time, json, random
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from tt_wos_reg2 import voidash_account, device_start, device_poll, voidash_wait_code, pool_append
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
email, _, vsk = voidash_account()
|
||||
print("EMAIL:", email)
|
||||
|
||||
def click_any(page, patterns):
|
||||
els = page.locator("button, a, div[role='button']")
|
||||
for i in range(els.count()):
|
||||
try:
|
||||
t = els.nth(i).inner_text().strip().lower()
|
||||
except Exception:
|
||||
continue
|
||||
for pat in patterns:
|
||||
if pat and pat in t:
|
||||
els.nth(i).click()
|
||||
return t[:60]
|
||||
return None
|
||||
|
||||
dr = device_start()
|
||||
uri = dr["verification_uri_complete"]
|
||||
print("DEVICE:", dr.get("user_code"))
|
||||
|
||||
with sync_playwright() as pw:
|
||||
b = pw.chromium.connect_over_cdp("http://127.0.0.1:9223")
|
||||
ctx = b.contexts[0]
|
||||
page = ctx.new_page()
|
||||
page.goto(uri, wait_until="domcontentloaded", timeout=60000)
|
||||
page.wait_for_timeout(5000)
|
||||
c = click_any(page, ["sign up"])
|
||||
print("signup clicked:", c)
|
||||
page.wait_for_timeout(4000)
|
||||
if page.locator("input[name='first_name']").count():
|
||||
page.locator("input[name='first_name']").first.fill("Nikita")
|
||||
page.locator("input[name='last_name']").first.fill("Orlov")
|
||||
page.locator("input[name='email'], input[type='email']").first.fill(email)
|
||||
page.wait_for_timeout(600)
|
||||
click_any(page, ["continue"])
|
||||
page.wait_for_timeout(5000)
|
||||
body0 = page.inner_text("body")
|
||||
print("AFTER CONTINUE:", body0[:250].replace(chr(10), " | "))
|
||||
# go straight to email-code method (skip password)
|
||||
c = click_any(page, ["continue with email code"])
|
||||
print("code method clicked:", c)
|
||||
page.wait_for_timeout(6000)
|
||||
body = page.inner_text("body")
|
||||
print("SCREEN:", body[:350].replace("\n", " | "))
|
||||
if "access blocked" in body.lower():
|
||||
print("=> RADAR BLOCK on code signup too")
|
||||
page.screenshot(path=str(_w("tmp/tt_shots/chrome_codesignup_blocked.png")))
|
||||
page.close()
|
||||
sys.exit(2)
|
||||
code = voidash_wait_code(vsk, timeout=300)
|
||||
print("CODE:", code)
|
||||
if code:
|
||||
ci = page.locator("input[inputmode='numeric'], input[autocomplete='one-time-code'], input[name*='code'], input[type='text']")
|
||||
n = ci.count()
|
||||
print("inputs:", n)
|
||||
if n >= 6:
|
||||
for i, ch in enumerate(code[:6]):
|
||||
ci.nth(i).fill(ch)
|
||||
elif n >= 1:
|
||||
ci.first.fill(code)
|
||||
page.wait_for_timeout(2000)
|
||||
click_any(page, ["verify", "continue", "sign up", "create"])
|
||||
page.wait_for_timeout(8000)
|
||||
print("FINAL URL:", page.url[:110])
|
||||
print("FINAL:", page.inner_text("body")[:300].replace("\n", " | "))
|
||||
# org creation / device consent steps
|
||||
for pats in (["create workspace", "continue", "next"], ["confirm", "allow", "authorize"]):
|
||||
c = click_any(page, pats)
|
||||
if c:
|
||||
print("clicked:", c)
|
||||
page.wait_for_timeout(5000)
|
||||
page.screenshot(path=str(_w("tmp/tt_shots/chrome_codesignup.png")))
|
||||
page.close()
|
||||
|
||||
try:
|
||||
tokens = device_poll(dr, timeout=120)
|
||||
rec = {"email": email, "org": "reform-org",
|
||||
"access_token": tokens["access_token"], "access_token_len": len(tokens["access_token"]),
|
||||
"refresh_token": tokens.get("refresh_token"),
|
||||
"expires_at": time.time() + int(tokens.get("expires_in") or 3600),
|
||||
"source": "chrome-emailcode-signup", "created": time.strftime("%Y-%m-%d %H:%M:%S")}
|
||||
pool_append(rec)
|
||||
print("=>=> SIGNUP SUCCESS — fresh type.com token in pool")
|
||||
except Exception as e:
|
||||
print("poll fail:", str(e)[:200])
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Signup via REAL Chrome (CDP :9223) — no automation fingerprint, home IP."""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import sys, time, json
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from tt_wos_reg2 import voidash_account, device_start, voidash_wait_code, log
|
||||
import random, string
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
email, _, vsk = voidash_account()
|
||||
password = "Tt" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!9"
|
||||
dr = device_start()
|
||||
uri = dr["verification_uri_complete"]
|
||||
print("EMAIL:", email, "DEVICE:", dr.get("user_code"))
|
||||
|
||||
def click_any(page, patterns):
|
||||
els = page.locator("button, a")
|
||||
for i in range(els.count()):
|
||||
try:
|
||||
t = els.nth(i).inner_text().strip().lower()
|
||||
except Exception:
|
||||
continue
|
||||
for pat in patterns:
|
||||
if pat in t:
|
||||
els.nth(i).click()
|
||||
return t
|
||||
return None
|
||||
|
||||
with sync_playwright() as pw:
|
||||
b = pw.chromium.connect_over_cdp("http://127.0.0.1:9223")
|
||||
ctx = b.contexts[0]
|
||||
page = ctx.new_page()
|
||||
page.goto(uri, wait_until="domcontentloaded", timeout=60000)
|
||||
page.wait_for_timeout(5000)
|
||||
print("URL:", page.url[:100])
|
||||
body = page.inner_text("body")
|
||||
print("TEXT:", body[:250].replace("\n", " | "))
|
||||
c = click_any(page, ["sign up", "registrera", "create account"])
|
||||
print("clicked:", c)
|
||||
page.wait_for_timeout(4000)
|
||||
if page.locator("input[name='first_name']").count():
|
||||
page.locator("input[name='first_name']").first.fill("Nikita")
|
||||
page.locator("input[name='last_name']").first.fill("Orlov")
|
||||
page.locator("input[name='email'], input[type='email']").first.fill(email)
|
||||
page.wait_for_timeout(500)
|
||||
click_any(page, ["continue", "sign up", "next"])
|
||||
page.wait_for_timeout(5000)
|
||||
body = page.inner_text("body")
|
||||
print("TEXT2:", body[:350].replace("\n", " | "))
|
||||
blocked = "access blocked" in body.lower()
|
||||
print("BLOCKED:", blocked)
|
||||
if not blocked and page.locator("input[type='password']").count():
|
||||
page.locator("input[type='password']").first.fill(password)
|
||||
page.wait_for_timeout(600)
|
||||
click_any(page, ["continue", "sign up", "create"])
|
||||
page.wait_for_timeout(6000)
|
||||
body = page.inner_text("body")
|
||||
print("TEXT3:", body[:350].replace("\n", " | "))
|
||||
if "access blocked" not in body.lower():
|
||||
print("PASSWORD STEP PASSED")
|
||||
code = voidash_wait_code(vsk, timeout=300)
|
||||
print("CODE:", code)
|
||||
page.screenshot(path=str(_w("tmp/tt_shots/chrome_signup.png")))
|
||||
page.close()
|
||||
@@ -0,0 +1,103 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Google SSO via real Chrome: device flow -> Continue with Google -> account chooser."""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import sys, time, json
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from tt_wos_reg2 import device_start, device_poll, pool_append
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
def click_any(page, patterns):
|
||||
els = page.locator("button, a, div[role='button'], li")
|
||||
for i in range(els.count()):
|
||||
try:
|
||||
t = els.nth(i).inner_text().strip().lower()
|
||||
except Exception:
|
||||
continue
|
||||
for pat in patterns:
|
||||
if pat and pat in t:
|
||||
els.nth(i).click()
|
||||
return t[:60]
|
||||
return None
|
||||
|
||||
dr = device_start()
|
||||
uri = dr["verification_uri_complete"]
|
||||
print("DEVICE:", dr.get("user_code"))
|
||||
|
||||
with sync_playwright() as pw:
|
||||
b = pw.chromium.connect_over_cdp("http://127.0.0.1:9223")
|
||||
ctx = b.contexts[0]
|
||||
page = ctx.new_page()
|
||||
page.goto(uri, wait_until="domcontentloaded", timeout=60000)
|
||||
page.wait_for_timeout(5000)
|
||||
body = page.inner_text("body")
|
||||
print("LANDING:", body[:200].replace("\n", " | "))
|
||||
c = click_any(page, ["continue with google"])
|
||||
print("google clicked:", c)
|
||||
page.wait_for_timeout(8000)
|
||||
print("URL:", page.url[:110])
|
||||
body = page.inner_text("body")
|
||||
print("GOOGLE SCREEN:", body[:400].replace("\n", " | "))
|
||||
# list accounts shown in chooser
|
||||
accounts = page.locator("[data-email], [data-identifier]")
|
||||
n = accounts.count()
|
||||
print("accounts in chooser:", n)
|
||||
for i in range(min(n, 5)):
|
||||
try:
|
||||
print(" acct:", accounts.nth(i).get_attribute("data-email") or accounts.nth(i).get_attribute("data-identifier"))
|
||||
except Exception:
|
||||
pass
|
||||
if n > 0:
|
||||
accounts.first.click()
|
||||
page.wait_for_timeout(10000)
|
||||
print("AFTER PICK URL:", page.url[:110])
|
||||
print("AFTER PICK:", page.inner_text("body")[:300].replace("\n", " | "))
|
||||
# consent screen?
|
||||
c2 = click_any(page, ["continue", "allow", "accept", "confirm"])
|
||||
print("consent clicked:", c2)
|
||||
page.wait_for_timeout(8000)
|
||||
print("FINAL URL:", page.url[:110])
|
||||
print("FINAL:", page.inner_text("body")[:250].replace("\n", " | "))
|
||||
page.screenshot(path=str(_w("tmp/tt_shots/google_sso.png")))
|
||||
page.close()
|
||||
|
||||
try:
|
||||
tokens = device_poll(dr, timeout=120)
|
||||
rec = {"email": "google-sso", "org": "reform-org",
|
||||
"access_token": tokens["access_token"], "access_token_len": len(tokens["access_token"]),
|
||||
"refresh_token": tokens.get("refresh_token"),
|
||||
"expires_at": time.time() + int(tokens.get("expires_in") or 3600),
|
||||
"source": "google-sso-real-chrome", "created": time.strftime("%Y-%m-%d %H:%M:%S")}
|
||||
pool_append(rec)
|
||||
print("=>=> GOOGLE SSO SUCCESS, token in pool")
|
||||
except Exception as e:
|
||||
print("poll fail:", str(e)[:200])
|
||||
@@ -0,0 +1,135 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Sign IN via EMAIL CODE path only (no password) in real Chrome."""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import sys, time, json, re
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.path.insert(0, str(_REPO))
|
||||
from tt_wos_reg2 import device_start, device_poll, http_json, pool_append
|
||||
from playwright.sync_api import sync_playwright
|
||||
|
||||
acct = json.load(open(str(_d("tmp/type-toolkit/client/acct.json")), encoding="utf-8"))
|
||||
email = acct["email"]
|
||||
mtok = acct.get("mt_token")
|
||||
print("EMAIL:", email)
|
||||
|
||||
def click_any(page, patterns):
|
||||
els = page.locator("button, a")
|
||||
for i in range(els.count()):
|
||||
try:
|
||||
t = els.nth(i).inner_text().strip().lower()
|
||||
except Exception:
|
||||
continue
|
||||
for pat in patterns:
|
||||
if pat in t:
|
||||
els.nth(i).click()
|
||||
return t
|
||||
return None
|
||||
|
||||
def tm_code(timeout=240):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
st, msgs = http_json("GET", "https://api.mail.tm/messages?page=1",
|
||||
headers={"Authorization": "Bearer " + mtok})
|
||||
if st == 200 and isinstance(msgs, dict):
|
||||
for m in (msgs.get("hydra:member") or [])[:5]:
|
||||
st2, full = http_json("GET", "https://api.mail.tm/messages/" + m["id"],
|
||||
headers={"Authorization": "Bearer " + mtok})
|
||||
if st2 == 200 and isinstance(full, dict):
|
||||
text = (full.get("text") or "") + " ".join(str(p) for p in (full.get("html") or []))
|
||||
c = re.search(r"\b(\d{6})\b", text)
|
||||
if c:
|
||||
print("CODE:", c.group(1))
|
||||
return c.group(1)
|
||||
elif st == 401:
|
||||
print("tm token 401")
|
||||
return None
|
||||
time.sleep(5)
|
||||
return None
|
||||
|
||||
dr = device_start()
|
||||
uri = dr["verification_uri_complete"]
|
||||
print("DEVICE:", dr.get("user_code"))
|
||||
|
||||
with sync_playwright() as pw:
|
||||
b = pw.chromium.connect_over_cdp("http://127.0.0.1:9223")
|
||||
ctx = b.contexts[0]
|
||||
page = ctx.new_page()
|
||||
page.goto(uri, wait_until="domcontentloaded", timeout=60000)
|
||||
page.wait_for_timeout(5000)
|
||||
page.locator("input[name='email'], input[type='email']").first.fill(email)
|
||||
page.wait_for_timeout(400)
|
||||
# continue with email (goes to password screen with options)
|
||||
click_any(page, ["continue with email", "continue"])
|
||||
page.wait_for_timeout(5000)
|
||||
body = page.inner_text("body")
|
||||
print("SCREEN:", body[:300].replace("\n", " | "))
|
||||
# choose EMAIL CODE method instead of password
|
||||
c = click_any(page, ["email sign-in code", "continue with email code", "use email code"])
|
||||
print("method clicked:", c)
|
||||
page.wait_for_timeout(5000)
|
||||
body = page.inner_text("body")
|
||||
print("AFTER METHOD:", body[:300].replace("\n", " | "))
|
||||
if "access blocked" in body.lower():
|
||||
print("=> BLOCKED even on email-code method")
|
||||
page.close()
|
||||
sys.exit(2)
|
||||
code = tm_code()
|
||||
if code:
|
||||
ci = page.locator("input[inputmode='numeric'], input[autocomplete='one-time-code'], input[name*='code'], input[type='text']")
|
||||
n = ci.count()
|
||||
print("code inputs:", n)
|
||||
if n >= 6:
|
||||
for i, ch in enumerate(code[:6]):
|
||||
ci.nth(i).fill(ch)
|
||||
elif n >= 1:
|
||||
ci.first.fill(code)
|
||||
page.wait_for_timeout(2000)
|
||||
click_any(page, ["verify", "continue", "sign in"])
|
||||
page.wait_for_timeout(8000)
|
||||
print("FINAL URL:", page.url[:100])
|
||||
print("FINAL TEXT:", page.inner_text("body")[:250].replace("\n", " | "))
|
||||
click_any(page, ["confirm", "allow", "continue", "authorize"])
|
||||
page.wait_for_timeout(4000)
|
||||
page.screenshot(path=str(_w("tmp/tt_shots/chrome_code_signin.png")))
|
||||
page.close()
|
||||
|
||||
try:
|
||||
tokens = device_poll(dr, timeout=120)
|
||||
rec = {"email": email, "org": "reform-org",
|
||||
"access_token": tokens["access_token"], "access_token_len": len(tokens["access_token"]),
|
||||
"refresh_token": tokens.get("refresh_token"),
|
||||
"expires_at": time.time() + int(tokens.get("expires_in") or 3600),
|
||||
"source": "device-signin-emailcode", "created": time.strftime("%Y-%m-%d %H:%M:%S")}
|
||||
pool_append(rec)
|
||||
print("=>=> SUCCESS fresh tokens in pool")
|
||||
except Exception as e:
|
||||
print("poll fail:", str(e)[:200])
|
||||
@@ -0,0 +1,412 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tt_wos_reg2.py — type.com autoreg v3 (WorkOS AuthKit signup path, browserless-captcha-free).
|
||||
|
||||
Flow (live-verified 2026-10-07):
|
||||
1. mail.tm account (dynamic domain)
|
||||
2. POST api.workos.com/user_management/authorize/device -> device_code + verification_uri_complete
|
||||
3. patchright: /sign-up -> first/last/email -> Continue
|
||||
4. /sign-up/password -> password (>=10 chars) -> Continue
|
||||
5. email verification code -> mail.tm poll -> enter
|
||||
6. device poll -> access_token + refresh_token
|
||||
7. save to server/pool.json (gateway :8311 compatible)
|
||||
|
||||
Usage: python tt_wos_reg2.py [--headless] [--org reform-org]
|
||||
"""
|
||||
# __portable_paths__ (auto-injected: portable, env-overridable paths)
|
||||
import os as _pos, sys as _psys
|
||||
from pathlib import Path as _PPath
|
||||
_ROOT = _PPath(__file__).resolve().parent
|
||||
_REPO = _ROOT
|
||||
for _ in range(4):
|
||||
if (_REPO / ".git").exists() or (_REPO / "README.md").exists():
|
||||
break
|
||||
if _REPO.parent == _REPO:
|
||||
break
|
||||
_REPO = _REPO.parent
|
||||
_DATA = _PPath(_pos.environ.get("TOOLKIT_DATA", str(_REPO / "data")))
|
||||
_WORK = _PPath(_pos.environ.get("TOOLKIT_WORK", str(_REPO / "_work")))
|
||||
try:
|
||||
_DATA.mkdir(parents=True, exist_ok=True)
|
||||
_WORK.mkdir(parents=True, exist_ok=True)
|
||||
except Exception:
|
||||
pass
|
||||
_PY = _pos.environ.get("PYTHON_BIN") or _psys.executable
|
||||
_USERPROFILE = _pos.environ.get("USERPROFILE") or str(_PPath.home())
|
||||
def _d(name, env=None):
|
||||
"""Data-file path under ./data (or $TOOLKIT_DATA); optional per-file env override."""
|
||||
if env and _pos.environ.get(env):
|
||||
return _PPath(_pos.environ[env])
|
||||
return _DATA / name
|
||||
def _w(name=""):
|
||||
"""Work-dir path under ./_work (or $TOOLKIT_WORK)."""
|
||||
return (_WORK / name) if name else _WORK
|
||||
# --- end portable prelude ---
|
||||
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import re
|
||||
import string
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
ROOT = str(_d("tmp/type-toolkit"))
|
||||
POOL_PATH = os.path.join(ROOT, "server", "pool.json")
|
||||
CLIENT_ID = "client_01K5GFDDKQWV8MM9FSRZS3YNNN"
|
||||
WOS_DEVICE = "https://api.workos.com/user_management/authorize/device"
|
||||
WOS_AUTH = "https://api.workos.com/user_management/authenticate"
|
||||
DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"
|
||||
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/129.0.0.0 Safari/537.36"
|
||||
|
||||
FIRST = ["Alex", "Sam", "Jordan", "Taylor", "Morgan", "Casey", "Riley", "Jamie", "Drew", "Quinn", "Nikita", "Artem", "Oleg", "Ivan", "Max", "Leo", "Kai", "Ren"]
|
||||
LAST = ["Miller", "Stone", "Frost", "Vale", "Cross", "Webb", "Hale", "Reed", "Cole", "Ward", "Fox", "Lane", "Petrov", "Volkov", "Orlov", "Sokol"]
|
||||
|
||||
|
||||
def log(*a):
|
||||
print(time.strftime("[%H:%M:%S]"), *a, flush=True)
|
||||
|
||||
|
||||
def http_json(method, url, body=None, form=None, headers=None, timeout=30):
|
||||
h = {"User-Agent": UA}
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
if form is not None:
|
||||
data = urllib.parse.urlencode(form).encode()
|
||||
h["Content-Type"] = "application/x-www-form-urlencoded"
|
||||
if headers:
|
||||
h.update(headers)
|
||||
req = urllib.request.Request(url, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
raw = r.read()
|
||||
try:
|
||||
return r.status, json.loads(raw)
|
||||
except Exception:
|
||||
return r.status, raw.decode(errors="replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
raw = e.read()
|
||||
try:
|
||||
return e.code, json.loads(raw)
|
||||
except Exception:
|
||||
return e.code, raw.decode(errors="replace")[:300]
|
||||
except Exception as e:
|
||||
return 0, str(e)[:200]
|
||||
|
||||
|
||||
VOIDASH_API = "https://api.voidash.com/api/v1"
|
||||
VOIDASH_DOMAINS = ["govno.eu.cc", "musor.eu.cc", "pomoi.eu.cc"]
|
||||
|
||||
|
||||
def voidash_account():
|
||||
"""Create a Voidash inbox on a custom eu.cc domain. Returns (email, None, session_key)."""
|
||||
for dom in VOIDASH_DOMAINS:
|
||||
st, r = http_json("POST", VOIDASH_API + "/inboxes", body={"domain": dom})
|
||||
if st in (200, 201) and isinstance(r, dict):
|
||||
sk = r.get("session_key") or r.get("sessionKey") or r.get("token")
|
||||
email = r.get("address") or r.get("email")
|
||||
if email and sk:
|
||||
log("voidash inbox:", email)
|
||||
return email, None, sk
|
||||
raise RuntimeError("voidash create failed for all domains")
|
||||
|
||||
|
||||
def voidash_wait_code(sk, timeout=300):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
st, r = http_json("GET", VOIDASH_API + "/messages", headers={"Authorization": "Bearer " + sk})
|
||||
if st == 200:
|
||||
items = r if isinstance(r, list) else (r.get("messages") or r.get("data") or r.get("items") or [])
|
||||
for m in items:
|
||||
mid = m.get("id") or m.get("_id")
|
||||
st2, full = http_json("GET", VOIDASH_API + "/messages/" + str(mid),
|
||||
headers={"Authorization": "Bearer " + sk})
|
||||
src = full if isinstance(full, dict) else m
|
||||
text = (src.get("text") or src.get("body") or src.get("html") or "")
|
||||
if isinstance(text, list):
|
||||
text = " ".join(str(x) for x in text)
|
||||
code = re.search(r"\b(\d{6})\b", text)
|
||||
if code:
|
||||
log("code from voidash:", code.group(1))
|
||||
return code.group(1)
|
||||
time.sleep(6)
|
||||
return None
|
||||
|
||||
|
||||
def imap_tonline_account():
|
||||
"""Take a t-online mailbox from the pool; return (email, password)."""
|
||||
pool_file = str(_d("Desktop/avtoreg/working_mails.txt","MAIL_POOL"))
|
||||
lines = [l.strip() for l in open(pool_file, encoding="utf-8")
|
||||
if l.strip() and ":" in l and not l.startswith("#")]
|
||||
random.shuffle(lines)
|
||||
email, _, pwd = lines[0].partition(":")
|
||||
log("t-online mailbox:", email[:3] + "***")
|
||||
return email, pwd.strip()
|
||||
|
||||
|
||||
def imap_wait_code(email, pwd, timeout=300):
|
||||
"""Poll t-online IMAP for a 6-digit WorkOS/Type code."""
|
||||
import imaplib
|
||||
import email as emaillib
|
||||
host = "secureimap.t-online.de"
|
||||
t0 = time.time()
|
||||
conn = None
|
||||
while time.time() - t0 < timeout:
|
||||
try:
|
||||
conn = imaplib.IMAP4_SSL(host, 993)
|
||||
conn.login(email, pwd)
|
||||
conn.select("INBOX")
|
||||
typ, data = conn.search(None, "UNSEEN")
|
||||
ids = data[0].split()
|
||||
for num in ids[-10:]:
|
||||
typ, msgdata = conn.fetch(num, "(RFC822)")
|
||||
raw = msgdata[0][1]
|
||||
msg = emaillib.message_from_bytes(raw)
|
||||
subj = msg.get("Subject", "") + " " + msg.get("From", "")
|
||||
if not re.search(r"workos|type", subj, re.I):
|
||||
continue
|
||||
body = ""
|
||||
if msg.is_multipart():
|
||||
for part in msg.walk():
|
||||
if part.get_content_type() == "text/plain":
|
||||
body += part.get_payload(decode=True).decode(errors="replace")
|
||||
else:
|
||||
body = msg.get_payload(decode=True).decode(errors="replace")
|
||||
code = re.search(r"\b(\d{6})\b", body)
|
||||
if code:
|
||||
log("code from IMAP:", code.group(1), "| subj:", subj[:60])
|
||||
conn.logout()
|
||||
return code.group(1)
|
||||
conn.logout()
|
||||
except Exception as e:
|
||||
log("imap err:", str(e)[:120])
|
||||
time.sleep(6)
|
||||
return None
|
||||
|
||||
|
||||
def mailtm_wait_code(mtok, timeout=240):
|
||||
t0 = time.time()
|
||||
while time.time() - t0 < timeout:
|
||||
st, msgs = http_json("GET", "https://api.mail.tm/messages?page=1",
|
||||
headers={"Authorization": "Bearer " + mtok})
|
||||
if st == 200 and isinstance(msgs, dict):
|
||||
for m in msgs.get("hydra:member") or []:
|
||||
st2, full = http_json("GET", "https://api.mail.tm/messages/" + m["id"],
|
||||
headers={"Authorization": "Bearer " + mtok})
|
||||
if st2 == 200 and isinstance(full, dict):
|
||||
text = (full.get("text") or "") + " ".join(str(p) for p in (full.get("html") or []))
|
||||
code = re.search(r"\b(\d{6})\b", text)
|
||||
if code:
|
||||
log("code from mail:", code.group(1), "| subj:", (full.get("subject") or "")[:60])
|
||||
return code.group(1)
|
||||
time.sleep(5)
|
||||
return None
|
||||
|
||||
|
||||
def device_start():
|
||||
st, dr = http_json("POST", WOS_DEVICE, form={"client_id": CLIENT_ID})
|
||||
if st != 200 or not isinstance(dr, dict) or "device_code" not in dr:
|
||||
raise RuntimeError("workos device %s: %s" % (st, str(dr)[:200]))
|
||||
log("device:", dr.get("user_code"))
|
||||
return dr
|
||||
|
||||
|
||||
def device_poll(dr, timeout=600):
|
||||
t0 = time.time()
|
||||
interval = int(dr.get("interval") or 5)
|
||||
while time.time() - t0 < timeout:
|
||||
time.sleep(interval)
|
||||
st, r = http_json("POST", WOS_AUTH, form={
|
||||
"client_id": CLIENT_ID, "device_code": dr["device_code"], "grant_type": DEVICE_GRANT})
|
||||
if st == 200 and isinstance(r, dict) and r.get("access_token"):
|
||||
return r
|
||||
err = r.get("error") if isinstance(r, dict) else None
|
||||
if err == "authorization_pending":
|
||||
continue
|
||||
if err == "slow_down":
|
||||
interval += 5
|
||||
continue
|
||||
if err:
|
||||
raise RuntimeError("device poll: %s %s" % (err, str(r)[:150]))
|
||||
raise RuntimeError("device poll timeout")
|
||||
|
||||
|
||||
def click_btn(page, texts):
|
||||
btns = page.locator("button")
|
||||
for i in range(btns.count()):
|
||||
try:
|
||||
t = btns.nth(i).inner_text().strip().lower()
|
||||
except Exception:
|
||||
continue
|
||||
for want in texts:
|
||||
if want in t:
|
||||
btns.nth(i).click()
|
||||
return t
|
||||
return None
|
||||
|
||||
|
||||
def authkit_signup(uri, email, password, first, last, code_getter, headless=True, proxy=None):
|
||||
"""Camoufox (anti-detect Firefox) — WorkOS Radar blocks plain Chromium."""
|
||||
from camoufox.sync_api import Camoufox
|
||||
kw = {"headless": headless}
|
||||
if proxy:
|
||||
kw["proxy"] = {"server": proxy}
|
||||
kw["geoip"] = True
|
||||
with Camoufox(**kw) as browser:
|
||||
page = browser.new_page()
|
||||
page.goto(uri, wait_until="domcontentloaded", timeout=60000)
|
||||
page.wait_for_timeout(3500)
|
||||
|
||||
# landing -> Sign up
|
||||
page.locator("a:has-text('Sign up'), button:has-text('Sign up')").first.click()
|
||||
page.wait_for_timeout(3000)
|
||||
log("signup form url:", page.url[:90])
|
||||
|
||||
# names + email
|
||||
page.locator("input[name='first_name']").first.fill(first)
|
||||
page.locator("input[name='last_name']").first.fill(last)
|
||||
page.locator("input[name='email'], input[type='email']").first.fill(email)
|
||||
page.wait_for_timeout(400)
|
||||
clicked = click_btn(page, ["continue", "sign up", "create"])
|
||||
log("step1 clicked:", clicked)
|
||||
page.wait_for_timeout(4500)
|
||||
|
||||
# password step OR email-code option — prefer email code (no password policy / radar)
|
||||
body0 = page.inner_text("body")
|
||||
log("after step1 url:", page.url[:100])
|
||||
if "Continue with email code" in body0:
|
||||
page.locator("button:has-text('Continue with email code'), a:has-text('Continue with email code')").first.click()
|
||||
log("chose email-code path")
|
||||
page.wait_for_timeout(5000)
|
||||
elif page.locator("input[type='password']").count():
|
||||
page.locator("input[type='password']").first.fill(password)
|
||||
page.wait_for_timeout(300)
|
||||
clicked = click_btn(page, ["continue", "sign up", "create"])
|
||||
log("step2 clicked:", clicked)
|
||||
page.wait_for_timeout(5000)
|
||||
txt = page.inner_text("body")[:300].replace("\n", " | ")
|
||||
log("page text:", txt)
|
||||
if "access blocked" in txt.lower():
|
||||
raise RuntimeError("Radar: Access blocked")
|
||||
|
||||
# email verification code step
|
||||
code = None
|
||||
deadline = time.time() + 300
|
||||
while time.time() < deadline:
|
||||
body = page.inner_text("body").lower()
|
||||
inputs = page.locator("input")
|
||||
code_inputs = page.locator("input[inputmode='numeric'], input[autocomplete='one-time-code'], input[name*='code']")
|
||||
if "code" in body and (code_inputs.count() or "verification" in body or "check your" in body):
|
||||
code = code_getter()
|
||||
if not code:
|
||||
raise RuntimeError("no email code arrived")
|
||||
n = code_inputs.count()
|
||||
if n >= 6:
|
||||
for i, ch in enumerate(code[:6]):
|
||||
code_inputs.nth(i).fill(ch)
|
||||
elif n >= 1:
|
||||
code_inputs.first.fill(code)
|
||||
else:
|
||||
vis = page.locator("input[type='text']:visible, input:not([type='hidden']):visible")
|
||||
if vis.count():
|
||||
vis.first.fill(code)
|
||||
page.wait_for_timeout(1200)
|
||||
click_btn(page, ["verify", "continue", "submit", "confirm"])
|
||||
page.wait_for_timeout(6000)
|
||||
log("code submitted, url:", page.url[:100])
|
||||
break
|
||||
# maybe already through (device confirmed screen)
|
||||
if "confirmed" in body or "success" in body or "you can close" in body or "return to" in body:
|
||||
log("device confirmed screen:", body[:120])
|
||||
break
|
||||
page.wait_for_timeout(3000)
|
||||
else:
|
||||
raise RuntimeError("no code step detected")
|
||||
|
||||
# final: device consent screen may need a click
|
||||
for t in ["confirm", "allow", "continue", "authorize"]:
|
||||
if click_btn(page, [t]):
|
||||
log("final click:", t)
|
||||
page.wait_for_timeout(3000)
|
||||
break
|
||||
log("final url:", page.url[:100], "| text:", page.inner_text("body")[:200].replace("\n", " | "))
|
||||
|
||||
|
||||
def pool_append(acct):
|
||||
pool = []
|
||||
if os.path.exists(POOL_PATH):
|
||||
try:
|
||||
pool = json.load(open(POOL_PATH, encoding="utf-8"))
|
||||
except Exception:
|
||||
pool = []
|
||||
pool.append(acct)
|
||||
json.dump(pool, open(POOL_PATH, "w", encoding="utf-8"), indent=2, ensure_ascii=False)
|
||||
log("pool:", len(pool), "accounts")
|
||||
|
||||
|
||||
def main():
|
||||
org = "reform-org"
|
||||
headless = "--headless" in sys.argv or True
|
||||
if "--org" in sys.argv:
|
||||
org = sys.argv[sys.argv.index("--org") + 1]
|
||||
|
||||
email, mpwd, vsk = voidash_account()
|
||||
password = "Tt" + "".join(random.choices(string.ascii_letters + string.digits, k=12)) + "!9"
|
||||
first, last = random.choice(FIRST), random.choice(LAST)
|
||||
dr = device_start()
|
||||
|
||||
proxies = []
|
||||
if "--proxy" in sys.argv:
|
||||
proxies = [sys.argv[sys.argv.index("--proxy") + 1]]
|
||||
elif os.path.exists(str(_d("tmp/tt_live_px.json"))):
|
||||
proxies = json.load(open(str(_d("tmp/tt_live_px.json")), encoding="utf-8"))
|
||||
log("proxies:", len(proxies))
|
||||
|
||||
last_err = ""
|
||||
for px in proxies:
|
||||
try:
|
||||
authkit_signup(dr["verification_uri_complete"], email, password, first, last,
|
||||
lambda: voidash_wait_code(vsk, timeout=300), headless=headless, proxy=px)
|
||||
last_err = ""
|
||||
break
|
||||
except Exception as e:
|
||||
last_err = str(e)[:200]
|
||||
log("proxy", px[:30], "FAIL:", last_err)
|
||||
if not proxies:
|
||||
try:
|
||||
authkit_signup(dr["verification_uri_complete"], email, password, first, last,
|
||||
lambda: voidash_wait_code(vsk, timeout=300), headless=headless)
|
||||
except Exception as e:
|
||||
log("browser FAIL:", str(e)[:300])
|
||||
|
||||
try:
|
||||
tokens = device_poll(dr, timeout=240)
|
||||
except Exception as e:
|
||||
log("poll FAIL:", str(e)[:200])
|
||||
pool_append({"email": email, "voidash_session": vsk, "workos_password": password,
|
||||
"first": first, "last": last, "org": org,
|
||||
"device_user_code": dr.get("user_code"), "status": "incomplete",
|
||||
"created": time.strftime("%Y-%m-%d %H:%M:%S")})
|
||||
sys.exit(1)
|
||||
|
||||
acct = {
|
||||
"email": email, "voidash_session": vsk, "workos_password": password,
|
||||
"first": first, "last": last, "org": org,
|
||||
"access_token": tokens["access_token"], "access_token_len": len(tokens["access_token"]),
|
||||
"refresh_token": tokens.get("refresh_token"),
|
||||
"expires_at": time.time() + int(tokens.get("expires_in") or 3600),
|
||||
"source": "workos-authkit-signup", "created": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
}
|
||||
pool_append(acct)
|
||||
log("SUCCESS:", email, "| token len", len(tokens["access_token"]))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user