cometapi autoreg: Castle via CDP, org fix, sequential wave (43 accounts verified)
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
import json, re, time, sys, os, imaplib, email, requests
|
||||
from email.header import decode_header
|
||||
|
||||
KEY2CAP = os.environ.get("TWOCAPTCHA_KEY", "")
|
||||
SITE = "0x4AAAAAABDUjQJBI2lFYkkW"
|
||||
CASTLE_MOD = "/console/assets/castle.umd-Cdx-vt7N.js"
|
||||
GM_USER = os.environ.get("COMET_GMAIL_USER", "")
|
||||
GM_PASS = os.environ.get("COMET_GMAIL_PASS", "")
|
||||
BASE = "https://www.cometapi.com"
|
||||
LOG = open(r"C:\Users\User\tmp\cometapi\chrome.log", "a", encoding="utf-8")
|
||||
|
||||
|
||||
def log(*a):
|
||||
s = " ".join(str(x) for x in a)
|
||||
print(s, flush=True)
|
||||
LOG.write(time.strftime("[%H:%M:%S] ") + s + "\n"); LOG.flush()
|
||||
|
||||
|
||||
def dh(v):
|
||||
try:
|
||||
return "".join(x.decode(e or "utf-8", "ignore") if isinstance(x, bytes) else x for x, e in decode_header(v))
|
||||
except Exception:
|
||||
return str(v)
|
||||
|
||||
|
||||
def solve():
|
||||
s = requests.Session()
|
||||
r = s.post("https://api.2captcha.com/createTask", json={"clientKey": KEY2CAP, "task": {
|
||||
"type": "TurnstileTaskProxyless", "websiteURL": BASE + "/console/login",
|
||||
"websiteKey": SITE,
|
||||
"userAgent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
|
||||
"action": "login"}}, timeout=30).json()
|
||||
tid = r.get("taskId")
|
||||
log("captcha", tid or str(r)[:100])
|
||||
if not tid:
|
||||
return None
|
||||
for _ in range(60):
|
||||
time.sleep(5)
|
||||
res = s.post("https://api.2captcha.com/getTaskResult", json={"clientKey": KEY2CAP, "taskId": tid}, timeout=30).json()
|
||||
if res.get("status") == "ready":
|
||||
return res["solution"]["token"]
|
||||
if res.get("errorId"):
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def gmail_last_uid(addr):
|
||||
try:
|
||||
M = imaplib.IMAP4_SSL("imap.gmail.com", 993, timeout=30)
|
||||
M.login(GM_USER, GM_PASS); M.select("INBOX", readonly=True)
|
||||
t, d = M.search(None, "X-GM-RAW", '"to:%s newer_than:1d"' % addr)
|
||||
ids = [int(x) for x in d[0].split()] or [0]
|
||||
M.logout(); return max(ids)
|
||||
except Exception as e:
|
||||
log("imap base", repr(e)[:80]); return 0
|
||||
|
||||
|
||||
def gmail_code(addr, since, timeout=240):
|
||||
end = time.time() + timeout
|
||||
while time.time() < end:
|
||||
try:
|
||||
M = imaplib.IMAP4_SSL("imap.gmail.com", 993, timeout=30)
|
||||
M.login(GM_USER, GM_PASS)
|
||||
M.select("INBOX", readonly=True)
|
||||
t, d = M.search(None, "X-GM-RAW", '"to:%s newer_than:1d"' % addr)
|
||||
ids = [int(x) for x in d[0].split()]
|
||||
ids = [i for i in ids if i > since][-25:]
|
||||
for i in reversed(ids):
|
||||
raw = M.fetch(str(i).encode(), "(BODY.PEEK[])")[1][0][1]
|
||||
msg = email.message_from_bytes(raw)
|
||||
subj = dh(str(msg.get("Subject", "")))
|
||||
m = re.search(r"(\d{6})", subj)
|
||||
if m:
|
||||
log("mail:", subj[:70]); M.logout(); return m.group(1)
|
||||
M.logout()
|
||||
except Exception as e:
|
||||
log("imap", repr(e)[:80])
|
||||
time.sleep(6)
|
||||
return None
|
||||
|
||||
|
||||
def chrome_exe():
|
||||
for c in [r"C:\Program Files\Google\Chrome\Application\chrome.exe",
|
||||
os.path.join(os.environ.get("LOCALAPPDATA", ""), r"Google\Chrome\Application\chrome.exe"),
|
||||
r"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"]:
|
||||
if os.path.exists(c):
|
||||
return c
|
||||
return None
|
||||
|
||||
|
||||
def main(addr):
|
||||
from playwright.sync_api import sync_playwright
|
||||
res = {"email": addr}
|
||||
with sync_playwright() as pw:
|
||||
px = os.environ.get("COMET_PROXY", "").strip()
|
||||
launch_kw = dict(executable_path=chrome_exe(), headless=False,
|
||||
args=["--disable-blink-features=AutomationControlled"])
|
||||
if px:
|
||||
launch_kw["proxy"] = {"server": px}
|
||||
br = pw.chromium.launch(**launch_kw)
|
||||
ctx = br.new_context(locale="en-US", viewport={"width": 1366, "height": 900})
|
||||
pg = ctx.new_page()
|
||||
pg.goto(BASE + "/console/login", wait_until="domcontentloaded", timeout=90000)
|
||||
pg.wait_for_timeout(6000)
|
||||
pk = pg.evaluate("async()=>{const r=await fetch('/api/status');const j=await r.json();return j.data.castle_publishable_key||''}")
|
||||
log("castle_pk:", pk)
|
||||
pg.evaluate("(v)=>{window.__pk=v}", pk)
|
||||
|
||||
base_uid = gmail_last_uid(addr)
|
||||
log("baseline uid", base_uid)
|
||||
cap = solve()
|
||||
v = pg.evaluate("""async ([email, tok]) => {
|
||||
const r = await fetch('/api/verification?email=' + encodeURIComponent(email) + '&turnstile=' + encodeURIComponent(tok));
|
||||
return [r.status, await r.text()];
|
||||
}""", [addr, cap])
|
||||
log("verify:", v)
|
||||
res["verify"] = v
|
||||
if '"success":true' not in v[1]:
|
||||
br.close(); return res
|
||||
code = gmail_code(addr, base_uid)
|
||||
log("code:", code)
|
||||
if not code:
|
||||
br.close(); return res
|
||||
cap2 = solve()
|
||||
out = pg.evaluate("""async ([email, code, tok, mod]) => {
|
||||
const log = [];
|
||||
let ct = '';
|
||||
try {
|
||||
const m = await import(mod);
|
||||
const c = m.c || m.default;
|
||||
const client = c.configure({ pk: window.__pk });
|
||||
ct = await client.createRequestToken();
|
||||
log.push('ctlen:' + (ct || '').length);
|
||||
} catch (e) { log.push('CERR:' + String((e && e.message) || e)); }
|
||||
const r = await fetch('/api/user/login?turnstile=' + encodeURIComponent(tok), {
|
||||
method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email: email, verification_code: code, castle_request_token: ct,
|
||||
aff_code: '', ref: null, landing_page: null, referrer: null })
|
||||
});
|
||||
const txt = await r.text();
|
||||
log.push('login:' + r.status + ':' + txt.slice(0, 1500));
|
||||
return log;
|
||||
}""", [addr, code, cap2, CASTLE_MOD])
|
||||
log("LOGIN OUT:", " || ".join(out))
|
||||
res["login"] = out
|
||||
res["cookies"] = {c["name"]: c["value"] for c in ctx.cookies() if "cometapi" in c["domain"]}
|
||||
ok = any('"success":true' in x for x in out)
|
||||
me = pg.evaluate("async()=>{const r=await fetch('/api/user/self');return [r.status, await r.text()]}")
|
||||
log("self:", me[1][:600])
|
||||
res["self"] = me[1]
|
||||
if ok:
|
||||
tk = pg.evaluate("""async()=>{
|
||||
const me = await (await fetch('/api/user/self')).json();
|
||||
const ol = (me.data && me.data.org_list) || [];
|
||||
let oid=null, wid=null;
|
||||
if (ol.length) { const o = ol.find(x=>x.state==='active')||ol[0]; oid = o.id;
|
||||
const wl = o.workspace_list||[]; wid = wl.length ? (wl.find(x=>x.state==='active')||wl[0]).id : o.id; }
|
||||
if (!oid) { try { const o = await (await fetch('/api/organization')).json();
|
||||
const arr = o.data||[]; if (arr.length) { oid = arr[0].id; const wl=arr[0].workspace_list||[]; wid = wl.length?wl[0].id:oid; } } catch(e){} }
|
||||
const H = {'Content-Type':'application/json'};
|
||||
if (oid) { H['X-Organization-Id']=String(oid); H['X-Workspace-Id']=String(wid||oid); }
|
||||
const r = await fetch('/api/token', {method:'POST', headers:H,
|
||||
body: JSON.stringify({name:'main', remain_quota:0, expired_time:-1, unlimited_quota:true,
|
||||
model_limits_enabled:false, model_limits:'', allow_ips:'', group:''})});
|
||||
const a = await r.text();
|
||||
const b = await (await fetch('/api/token?p=0&size=10', {headers:H})).text();
|
||||
const c = await (await fetch('/api/user/self')).text();
|
||||
return [a.slice(0,500), b.slice(0,1800), c.slice(0,1500), String(oid), String(wid)];
|
||||
}""")
|
||||
log("TOKEN CREATE:", tk[0])
|
||||
log("TOKEN LIST:", tk[1][:1200])
|
||||
log("SELF AFTER:", tk[2][:900])
|
||||
log("ORG/WS:", tk[3], tk[4])
|
||||
res["token_create"] = tk[0]; res["token_list"] = tk[1]; res["self_after"] = tk[2]
|
||||
res["org"] = tk[3]; res["ws"] = tk[4]
|
||||
m = re.search(r'"key":"([^"]+)"', tk[0])
|
||||
if m:
|
||||
k = m.group(1)
|
||||
res["key"] = k if k.startswith("sk-") else "sk-" + k
|
||||
log("KEY", res["key"])
|
||||
probe = {}
|
||||
for path in ["/console/register", "/console/token", "/console/personal"]:
|
||||
try:
|
||||
pg.goto(BASE + path, wait_until="domcontentloaded", timeout=60000)
|
||||
pg.wait_for_timeout(5000)
|
||||
txt = pg.inner_text("body")[:1200]
|
||||
btns = pg.evaluate("JSON.stringify([...document.querySelectorAll('button,a')].map(e=>e.innerText.trim()).filter(Boolean).slice(0,40))")
|
||||
probe[path] = {"url": pg.url, "text": txt, "buttons": btns}
|
||||
log("UI", path, "->", pg.url, "|", txt[:160].replace("\n", " | "))
|
||||
except Exception as e:
|
||||
probe[path] = {"err": str(e)[:120]}
|
||||
res["ui_probe"] = probe
|
||||
br.close()
|
||||
return res
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
a = sys.argv[1]
|
||||
r = main(a)
|
||||
open(r"C:\Users\User\tmp\cometapi\chrome_result_%s.json" % re.sub(r"\W+", "_", a), "w", encoding="utf-8").write(
|
||||
json.dumps(r, ensure_ascii=False, indent=1))
|
||||
if r.get("key"):
|
||||
open(r"C:\Users\User\tmp\cometapi\keys.jsonl", "a", encoding="utf-8").write(
|
||||
json.dumps({"email": a, "key": r["key"], "ts": int(time.time())}) + "\n")
|
||||
log("DONE", r.get("key"))
|
||||
Reference in New Issue
Block a user