ita_keygen.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. #!/usr/bin/env python3
  2. """
  3. keygens/ita_keygen.py
  4. 意大利 Prenot@Mi (https://prenotami.esteri.it/) 自动注册机器人。
  5. 功能:
  6. 1. 自动生成爱尔兰都柏林本地化人设与 @text.skin 邮箱凭据;
  7. 2. 驱动 Chromium 浏览器打开 https://prenotami.esteri.it/Account/Register;
  8. 3. 自动关闭引导弹窗,填入 14 项完整表单字段,包括密码前端加密与下拉映射;
  9. 4. 自动等待并穿透 Cloudflare Turnstile 人机验证盾;
  10. 5. 提交表单并等待跳转至 /Account/SentEmail;
  11. 6. 调用云端邮件接口轮询激活邮件,提取 ConfirmEmail 链接并在浏览器中打开完成激活;
  12. 7. 激活成功后自动上报账号到云端账号池(默认 ie.it.sentinel)。
  13. 使用方法:
  14. .venv/bin/python keygens/ita_keygen.py --dry-run # 仅填表与盾测试,不最终提交
  15. .venv/bin/python keygens/ita_keygen.py --target 1 # 真实注册 1 个账号并入库
  16. .venv/bin/python keygens/ita_keygen.py --target 5 # 批量注册 5 个账号
  17. """
  18. import os
  19. import sys
  20. import re
  21. import json
  22. import time
  23. import random
  24. import string
  25. import logging
  26. import argparse
  27. import requests
  28. import uuid
  29. import shutil
  30. from datetime import datetime, timezone, timedelta
  31. # 切换项目根路径
  32. PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  33. if PROJECT_ROOT not in sys.path:
  34. sys.path.insert(0, PROJECT_ROOT)
  35. from DrissionPage import ChromiumPage
  36. from DrissionPage.errors import PageDisconnectedError, AlertExistsError
  37. from utils.plugin_utils import init_chromium_options, get_free_port
  38. from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
  39. from utils.mouse import HumanMouse
  40. from utils.keyboard import HumanKeyboard
  41. from core_types import Proxy
  42. logging.basicConfig(
  43. level=logging.INFO,
  44. format='%(asctime)s [%(levelname)s] %(message)s',
  45. datefmt='%H:%M:%S'
  46. )
  47. logger = logging.getLogger("ItaRegistrar")
  48. # 常量配置
  49. HOME_URL = "https://prenotami.esteri.it/"
  50. REGISTER_URL = "https://prenotami.esteri.it/Account/Register"
  51. DEFAULT_POOL_NAME = "ie.it.sentinel"
  52. DEFAULT_MASTER_EMAIL = "hujiarui8@gmail.com"
  53. DEFAULT_UPLOAD_URL = "https://api.text.skin/api/account/add"
  54. DEFAULT_UPLOAD_TOKEN = "tok_e946329a60ff45ba807f3f41b0e8b7fc"
  55. DEFAULT_EMAIL_FETCH_URL = "https://api.text.skin/api/email-authorizations/fetch"
  56. DEFAULT_ADDRESS_FILE = os.path.join(PROJECT_ROOT, "data", "random-ireland-address-2026-09-22.json")
  57. EMAIL_SENDER = "noreply-prenotami at esteri.it"
  58. # 爱尔兰本土常见名库(男女合集)
  59. IRISH_FIRST_NAMES = [
  60. "Cillian", "Aoife", "Conor", "Saoirse", "Liam", "Niamh", "Fionn", "Ciara",
  61. "Sean", "Roisin", "Eoin", "Orla", "Oisin", "Maeve", "Patrick", "Darragh",
  62. "Cian", "Siobhan", "Ronan", "Aisling", "Tadhg", "Clodagh", "Cathal", "Sinead",
  63. "Cormac", "Fiona", "Niall", "Grainne", "Colm", "Deirdre", "Brian", "Emer",
  64. "Aidan", "Sorcha", "Caoimhe", "Padraig", "Daithi", "Donnacha", "Rory", "Finbar"
  65. ]
  66. # 爱尔兰本土常见姓氏库
  67. IRISH_LAST_NAMES = [
  68. "Murphy", "Kelly", "OBrien", "Walsh", "Smith", "ONeill", "Gallagher",
  69. "Doyle", "McCarthy", "Byrne", "Ryan", "Quinn", "Lynch", "Brennan",
  70. "Daly", "Nolan", "Connolly", "Higgins", "Flynn", "Kavanagh", "Cullen",
  71. "Connors", "Dunne", "Kennedy", "Maguire", "Maher", "Sweeney", "Farrell",
  72. "OConnor", "ODwyer", "OShea", "Keane", "Power", "Fitzgerald", "Brady"
  73. ]
  74. # 爱尔兰本土主要城镇/出生地
  75. IRISH_BIRTH_PLACES = [
  76. "Dublin", "Cork", "Galway", "Limerick", "Waterford", "Drogheda",
  77. "Dundalk", "Swords", "Bray", "Navan", "Kilkenny", "Ennis", "Carlow",
  78. "Tralee", "Newbridge", "Portlaoise", "Athlone", "Mullingar", "Wexford",
  79. "Sligo", "Clonmel", "Letterkenny", "Killarney", "Castlebar", "Tullamore"
  80. ]
  81. # 备用爱尔兰常用街道(当 JSON 地址耗尽或不存在时动态生成不重复地址)
  82. BACKUP_STREETS = [
  83. "Grafton Street", "O'Connell Street", "Henry Street", "Dame Street",
  84. "Dawson Street", "Kildare Street", "Baggot Street", "Leeson Street",
  85. "Patrick Street", "Oliver Plunkett Street", "Shop Street", "Eyre Square",
  86. "O'Connell Avenue", "George's Street", "The Quay", "Main Street",
  87. "Church Street", "High Street", "Castle Street", "Market Square"
  88. ]
  89. BACKUP_CITIES_POSTCODES = [
  90. ("Dublin", "D02"), ("Dublin", "D01"), ("Dublin", "D04"), ("Dublin", "D08"),
  91. ("Cork", "T12"), ("Galway", "H91"), ("Limerick", "V94"), ("Waterford", "X91")
  92. ]
  93. class ItaRegistrationBot:
  94. def __init__(self, args):
  95. self.args = args
  96. self.page = None
  97. self.tunnel = None
  98. self.workspace = os.path.join(PROJECT_ROOT, "data", "temp_reg_browser")
  99. # 去重追踪集合
  100. self.used_emails = set()
  101. self.used_passwords = set()
  102. self.used_phones = set()
  103. self.used_addresses = set()
  104. # 加载外部地址池
  105. self.address_pool = self._load_address_pool()
  106. def _log(self, msg: str):
  107. logger.info(f"[ItaBot] {msg}")
  108. def _load_address_pool(self) -> list:
  109. """加载提供的 JSON 地址文件"""
  110. addr_file = getattr(self.args, "address_file", DEFAULT_ADDRESS_FILE)
  111. pool = []
  112. if os.path.exists(addr_file):
  113. try:
  114. with open(addr_file, "r", encoding="utf-8") as f:
  115. raw_data = json.load(f)
  116. if isinstance(raw_data, list):
  117. for item in raw_data:
  118. street = item.get("streetAddress") or item.get("address")
  119. city = item.get("city") or "Dublin"
  120. cap = item.get("postcode") or item.get("cap") or "D02 YF90"
  121. dob = item.get("dateOfBirth")
  122. if street:
  123. pool.append({
  124. "street": street,
  125. "city": city,
  126. "cap": cap,
  127. "dob": dob
  128. })
  129. self._log(f"Loaded {len(pool)} addresses from {os.path.basename(addr_file)}")
  130. except Exception as e:
  131. self._log(f"Failed to load address file {addr_file}: {e}")
  132. else:
  133. self._log(f"Address file {addr_file} not found, will use dynamic generator.")
  134. random.shuffle(pool)
  135. return pool
  136. def _get_unique_address(self) -> tuple:
  137. """获取一个唯一的爱尔兰地址 (street, city, cap, optional_dob)"""
  138. # 1. 优先从加载的 JSON 地址池中消耗
  139. while self.address_pool:
  140. item = self.address_pool.pop(0)
  141. key = f"{item['street']}|{item['city']}|{item['cap']}".lower()
  142. if key not in self.used_addresses:
  143. self.used_addresses.add(key)
  144. return item['street'], item['city'], item['cap'], item.get('dob')
  145. # 2. 地址池耗尽或不存在时,生成动态且不重复的真实爱尔兰地址
  146. for _ in range(100):
  147. num = random.randint(1, 380)
  148. street_name = random.choice(BACKUP_STREETS)
  149. street = f"{num} {street_name}"
  150. city, prefix = random.choice(BACKUP_CITIES_POSTCODES)
  151. eir_suffix = "".join(random.choices(string.ascii_uppercase + string.digits, k=4))
  152. cap = f"{prefix} {eir_suffix}"
  153. key = f"{street}|{city}|{cap}".lower()
  154. if key not in self.used_addresses:
  155. self.used_addresses.add(key)
  156. return street, city, cap, None
  157. # 兜底保底
  158. rand_id = "".join(random.choices(string.digits, k=4))
  159. return f"{rand_id} Grafton Street", "Dublin", "D02 YF90", None
  160. def _generate_unique_password(self) -> str:
  161. """
  162. 生成严格满足 Prenot@Mi 规范的高强度且不重复的密码:
  163. 8-20 位,至少包含大写、小写、数字、特殊符号
  164. """
  165. for _ in range(100):
  166. uppers = "".join(random.choices(string.ascii_uppercase, k=2))
  167. lowers = "".join(random.choices(string.ascii_lowercase, k=6))
  168. digits = "".join(random.choices(string.digits, k=3))
  169. symbol = random.choice(["!", "@", "#", "$", "%", "*"])
  170. chars = list(uppers + lowers + digits + symbol)
  171. random.shuffle(chars)
  172. pwd = "".join(chars)
  173. if pwd not in self.used_passwords:
  174. self.used_passwords.add(pwd)
  175. return pwd
  176. return f"ItaPass@{random.randint(1000, 9999)}!"
  177. def _generate_unique_phone(self) -> str:
  178. """随机生成合法且不重复的爱尔兰手机号(9位:83/85/86/87/89开头)"""
  179. for _ in range(100):
  180. mobile_prefix = random.choice(["83", "85", "86", "87", "89"])
  181. suffix = "".join(random.choices(string.digits, k=7))
  182. phone = f"{mobile_prefix}{suffix}"
  183. if phone not in self.used_phones:
  184. self.used_phones.add(phone)
  185. return phone
  186. return f"85{random.randint(1000000, 9999999)}"
  187. def _generate_birth_date(self, dob_candidate: str = None) -> str:
  188. """生成确保年龄 > 20 岁的生日(格式:dd/mm/yyyy)"""
  189. if dob_candidate:
  190. # 尝试转换 YYYY-MM-DD 为 dd/mm/yyyy
  191. try:
  192. parts = dob_candidate.strip().split("-")
  193. if len(parts) == 3:
  194. y, m, d = int(parts[0]), int(parts[1]), int(parts[2])
  195. # 确保当前年份(2026)时年龄 > 20(出生年 <= 2005)
  196. if y <= 2005:
  197. return f"{d:02d}/{m:02d}/{y}"
  198. except Exception:
  199. pass
  200. # 随机出生年(1972 - 2004,确保当前年龄在 22 到 54 岁之间)
  201. year = random.randint(1972, 2004)
  202. month = random.randint(1, 12)
  203. day = random.randint(1, 28)
  204. return f"{day:02d}/{month:02d}/{year}"
  205. def generate_account_profile(self) -> dict:
  206. """生成全面满足本土化、年龄>20、地址不重复、密码不重复、随机手机号的账号数据"""
  207. first_name = random.choice(IRISH_FIRST_NAMES)
  208. last_name = random.choice(IRISH_LAST_NAMES)
  209. birth_place = random.choice(IRISH_BIRTH_PLACES)
  210. # 确保邮箱唯一且与姓名契合
  211. clean_first = re.sub(r"[^a-z0-9]", "", first_name.lower())
  212. clean_last = re.sub(r"[^a-z0-9]", "", last_name.lower())
  213. rand_num = random.randint(1000, 9999)
  214. email = f"{clean_first}{clean_last}{rand_num}@{self.args.email_domain}"
  215. while email in self.used_emails:
  216. rand_num = random.randint(1000, 9999)
  217. email = f"{clean_first}{clean_last}{rand_num}@{self.args.email_domain}"
  218. self.used_emails.add(email)
  219. # 唯一强密码
  220. password = self._generate_unique_password()
  221. # 唯一真实地址(优先从 json 加载)
  222. address, town, cap, dob_from_addr = self._get_unique_address()
  223. # 年龄 > 20 岁生日 (dd/mm/yyyy)
  224. birth_date = self._generate_birth_date(dob_from_addr)
  225. # 随机爱尔兰手机号
  226. phone = self._generate_unique_phone()
  227. return {
  228. "first_name": first_name,
  229. "last_name": last_name,
  230. "birth_place": birth_place,
  231. "birth_date": birth_date,
  232. "email": email,
  233. "password": password,
  234. "address": address,
  235. "cap": cap,
  236. "town": town,
  237. "nation_value": "103", # IRLANDA
  238. "prefix": "353",
  239. "phone": phone,
  240. "consulate_value": "101", # IRLANDA DUBLINO AMBASCIATA D'ITALIA
  241. }
  242. def _init_browser(self):
  243. """初始化 ChromiumPage"""
  244. session_id = uuid.uuid4().hex[:8]
  245. self.workspace = os.path.join(PROJECT_ROOT, "data", "temp_reg_browser", f"session_{session_id}")
  246. os.makedirs(self.workspace, exist_ok=True)
  247. proxy_obj = None
  248. if self.args.proxy:
  249. proxy_clean = self.args.proxy.replace("http://", "").replace("https://", "")
  250. parts = proxy_clean.split(":")
  251. if len(parts) == 2:
  252. proxy_obj = Proxy(ip=parts[0], port=int(parts[1]), proto="http")
  253. elif len(parts) == 4:
  254. proxy_obj = Proxy(ip=parts[0], port=int(parts[1]), username=parts[2], password=parts[3], proto="http")
  255. co, self.tunnel = init_chromium_options(
  256. user_data_path=self.workspace,
  257. username_seed=f"ita_reg_{uuid.uuid4().hex[:8]}",
  258. proxy=proxy_obj,
  259. headless=self.args.headless,
  260. window_size="1440,900",
  261. logger=self._log
  262. )
  263. self.page = ChromiumPage(co)
  264. self.page.set.timeouts(page_load=self.args.timeout, script=self.args.timeout)
  265. try:
  266. self.page.run_cdp(
  267. "Page.addScriptToEvaluateOnNewDocument",
  268. source="window.alert = function(msg){ console.log('[Alert suppressed]:', msg); };"
  269. )
  270. except Exception as e:
  271. self._log(f"CDP alert suppression non-fatal: {e}")
  272. # 初始化高仿真拟人鼠标与键盘控制器
  273. self.mouse = HumanMouse(self.page, debug=False)
  274. self.keyboard = HumanKeyboard(self.page)
  275. try:
  276. viewport = self.page.rect.viewport_size
  277. self.mouse.move(random.randint(50, max(60, viewport[0] - 50)), random.randint(50, max(60, viewport[1] - 50)))
  278. except Exception:
  279. pass
  280. def _close_welcome_modal(self):
  281. """关闭初始引导弹窗 #register-modal"""
  282. try:
  283. close_btn = self.page.ele('#register-modal button.close', timeout=2)
  284. if close_btn and close_btn.states.is_displayed:
  285. self._log("Closing #register-modal via close button...")
  286. close_btn.click()
  287. time.sleep(1)
  288. # 原生 DOM 彻底清理 modal 遮罩,无需强赖 jQuery
  289. self.page.run_js('''
  290. const modal = document.getElementById("register-modal");
  291. if (modal) {
  292. modal.style.display = "none";
  293. modal.classList.remove("show");
  294. }
  295. document.querySelectorAll(".modal-backdrop").forEach(b => b.remove());
  296. document.body.classList.remove("modal-open");
  297. if (window.$ && typeof $("#register-modal").modal === "function") {
  298. try { $("#register-modal").modal("hide"); } catch(e){}
  299. }
  300. ''')
  301. time.sleep(0.5)
  302. except Exception as e:
  303. self._log(f"Modal check non-fatal: {e}")
  304. def _fill_registration_form(self, acc: dict):
  305. """填入 14 项完整表单(深度拟人化鼠标点击 + 键盘击键)"""
  306. self._log(f"Filling personal info for {acc['first_name']} {acc['last_name']} ({acc['email']}) with human-like mouse & keyboard...")
  307. def _human_input(selector, val):
  308. el = self.page.ele(selector, timeout=5)
  309. if el:
  310. try:
  311. self.mouse.human_click_ele(el)
  312. except Exception:
  313. try:
  314. el.click()
  315. except Exception:
  316. pass
  317. time.sleep(random.uniform(0.1, 0.25))
  318. el.clear()
  319. self.keyboard.type_text(val, humanize=True)
  320. time.sleep(random.uniform(0.15, 0.35))
  321. else:
  322. self._log(f"Warning: selector {selector} not found")
  323. # 文本项 (姓名、出生地)
  324. _human_input('#Name', acc['first_name'])
  325. _human_input('#Surname', acc['last_name'])
  326. _human_input('#BirthPlace', acc['birth_place'])
  327. # Flatpickr 出生日期 (鼠标点击输入框 + 原生 DOM 驱动)
  328. bdate_el = self.page.ele('#BirthDate', timeout=5)
  329. if bdate_el:
  330. try:
  331. self.mouse.human_click_ele(bdate_el)
  332. except Exception:
  333. pass
  334. self.page.run_js('''
  335. const d = arguments[0];
  336. const el = document.getElementById("BirthDate");
  337. if (el) {
  338. el.value = d;
  339. if (el._flatpickr) {
  340. try { el._flatpickr.setDate(d, true); } catch(e){}
  341. }
  342. el.dispatchEvent(new Event('input', {bubbles: true}));
  343. el.dispatchEvent(new Event('change', {bubbles: true}));
  344. }
  345. if (window.$) {
  346. try { $("#BirthDate").val(d).trigger("change"); } catch(e){}
  347. }
  348. ''', acc['birth_date'])
  349. time.sleep(random.uniform(0.2, 0.4))
  350. # 账号凭据 (邮箱、密码、确认密码)
  351. _human_input('#Email', acc['email'])
  352. _human_input('#Password1', acc['password'])
  353. _human_input('#ConfirmPassword1', acc['password'])
  354. # 地址与邮编
  355. _human_input('#HomeAddress', acc['address'])
  356. _human_input('#CAP', acc['cap'])
  357. _human_input('#Town', acc['town'])
  358. # 国家下拉框 (Nation=103 / IRLANDA)
  359. nation_el = self.page.ele('#Nation', timeout=5)
  360. if nation_el:
  361. try:
  362. self.mouse.human_click_ele(nation_el)
  363. except Exception:
  364. pass
  365. self.page.run_js('''
  366. const nVal = arguments[0];
  367. const sel = document.getElementById("Nation");
  368. if (sel) {
  369. sel.value = nVal;
  370. sel.dispatchEvent(new Event('change', {bubbles: true}));
  371. }
  372. if (window.$ && typeof $("#Nation").selectpicker === "function") {
  373. try { $("#Nation").val(nVal).selectpicker("refresh").trigger("change"); } catch(e){}
  374. }
  375. ''', acc['nation_value'])
  376. time.sleep(random.uniform(0.3, 0.6))
  377. # 手机号与区号
  378. pref_el = self.page.ele('#prefix', timeout=5)
  379. if pref_el:
  380. try:
  381. self.mouse.human_click_ele(pref_el)
  382. except Exception:
  383. pass
  384. self.page.run_js('''
  385. const pref = arguments[0];
  386. const el = document.getElementById("prefix");
  387. if (el) {
  388. el.value = pref;
  389. el.dispatchEvent(new Event('change', {bubbles: true}));
  390. el.dispatchEvent(new Event('input', {bubbles: true}));
  391. }
  392. if (window.$) {
  393. try { $("#prefix").val(pref).trigger("change"); } catch(e){}
  394. }
  395. ''', acc['prefix'])
  396. _human_input('#PhoneNumber', acc['phone'])
  397. # 使馆下拉框 (Consulate=101 / IRLANDA DUBLINO AMBASCIATA D'ITALIA)
  398. consulate_el = self.page.ele('#Consulate', timeout=5)
  399. if not consulate_el:
  400. raise ValueError("Registration consulate selector is missing")
  401. # Use the select API without leaving a native dropdown open while filling
  402. # subsequent controls; the caller also verifies the selected consulate.
  403. consulate_el.select.by_value(acc['consulate_value'])
  404. time.sleep(random.uniform(0.3, 0.6))
  405. # 勾选隐私协议
  406. agreement = self.page.ele('#PersonalDataAgreement', timeout=5)
  407. if agreement and not agreement.states.is_checked:
  408. try:
  409. self.mouse.human_click_ele(agreement)
  410. except Exception:
  411. agreement.click()
  412. self.page.run_js('''
  413. const agree = document.getElementById("PersonalDataAgreement");
  414. if (agree && !agree.checked) {
  415. agree.checked = true;
  416. agree.dispatchEvent(new Event('change', {bubbles: true}));
  417. }
  418. if (window.$) {
  419. try { $("#PersonalDataAgreement").prop("checked", true).trigger("change"); } catch(e){}
  420. }
  421. ''')
  422. time.sleep(random.uniform(0.4, 0.8))
  423. self._log("All 14 form fields populated successfully with realistic human interactions.")
  424. def _wait_and_bypass_turnstile(self, max_wait: int = 90) -> bool:
  425. """等待或穿透 Cloudflare Turnstile 人机验证(对齐 plugins/ita_plugin.py 标准策略)"""
  426. self._log("Waiting for Cloudflare Turnstile verification...")
  427. start_t = time.time()
  428. last_logged = 0
  429. bypasser = CloudflareBypasser(self.page, log=True, logger=self._log)
  430. click_attempted_basic = False
  431. # 平滑滚动使 Turnstile 容器处于视口中央,激活前台渲染
  432. try:
  433. self.page.run_js('''
  434. const cf = document.querySelector(".cf-turnstile");
  435. if (cf) cf.scrollIntoView({behavior: "smooth", block: "center"});
  436. ''')
  437. time.sleep(0.5)
  438. # 拟人化鼠标移至 Turnstile 区域,提供生物特征活跃度
  439. cf_ele = self.page.ele('.cf-turnstile', timeout=1)
  440. if cf_ele and hasattr(self, 'mouse'):
  441. rect = cf_ele.rect
  442. mid_x = rect.location[0] + rect.size[0] / 2
  443. mid_y = rect.location[1] + rect.size[1] / 2
  444. self.mouse.move(mid_x, mid_y)
  445. except Exception as e:
  446. self._log(f"Turnstile viewport scroll non-fatal: {e}")
  447. while time.time() - start_t < max_wait:
  448. # 处理可能残留的 alert 弹窗
  449. try:
  450. if self.page.states.has_alert:
  451. self.page.handle_alert(accept=True)
  452. except Exception:
  453. pass
  454. # 1. 检查页面中 Turnstile token 是否已就绪,以及提交按钮状态
  455. status = self.page.run_js('''
  456. const el = document.querySelector('input[name="cf-turnstile-response"]');
  457. const btn = document.getElementById("btnRegister");
  458. let resp = "";
  459. if (el && el.value) {
  460. resp = el.value;
  461. } else if (typeof turnstile !== "undefined") {
  462. try {
  463. resp = turnstile.getResponse() || "";
  464. } catch(e){}
  465. }
  466. return {
  467. token: resp,
  468. btn_disabled: btn ? btn.disabled : true
  469. };
  470. ''') or {}
  471. token = status.get("token", "")
  472. btn_disabled = status.get("btn_disabled", True)
  473. # 只要拿到 token 或者按钮已经解除 disabled,都代表 Turnstile 成功
  474. if token or not btn_disabled:
  475. token_disp = token[:20] if token else "already_unlocked"
  476. self._log(f"✅ Cloudflare Turnstile verified successfully (token: {token_disp}...).")
  477. # 确保提交按钮解除 disabled 并调用回调
  478. self.page.run_js('''
  479. const btn = document.getElementById("btnRegister");
  480. if (btn) btn.disabled = false;
  481. if (typeof turnstileCallback === "function") {
  482. try { turnstileCallback(); } catch(e){}
  483. }
  484. if (window.$) {
  485. try { $("#btnRegister").prop("disabled", false); } catch(e){}
  486. }
  487. ''')
  488. return True
  489. elapsed = int(time.time() - start_t)
  490. if elapsed - last_logged >= 5:
  491. last_logged = elapsed
  492. self._log(f"Waiting for Turnstile... ({elapsed}s/{max_wait}s, URL: {self.page.url})")
  493. # 策略:严格对齐 plugins/ita_plugin.py
  494. # 1. 前 5 秒被动等待(TURNSTILE_PASSIVE_SECONDS = 5)
  495. # 2. 5 秒后尝试一次定向穿透点击(is_dfs=False,耗时 <0.2s,不进行耗时阻塞的全局 DFS)
  496. if elapsed >= 5 and not click_attempted_basic:
  497. click_attempted_basic = True
  498. self._log("Turnstile pending after 5s. Triggering CloudflareBypasser targeted click (is_dfs=False)...")
  499. try:
  500. clicked = bypasser.click_verification_button(is_dfs=False)
  501. self._log(f"CloudflareBypasser targeted click result: {clicked}")
  502. except Exception as e:
  503. self._log(f"CloudflareBypasser click error: {e}")
  504. time.sleep(1.0)
  505. self._log(f"⚠️ Turnstile not resolved within {max_wait}s.")
  506. return False
  507. def _fetch_activation_link(self, email: str, sent_at_utc: str, max_wait: int = 120) -> str:
  508. """通过云端 API 轮询激活邮件并提取 ConfirmEmail 链接"""
  509. self._log(f"Polling cloud API for activation email to {email} (since UTC {sent_at_utc})...")
  510. start_time = time.time()
  511. headers = {
  512. "Authorization": f"Bearer {self.args.upload_token}",
  513. "Accept": "application/json"
  514. }
  515. # SimpleLogin 转发会把发件人改写为包含 'at' 的格式: "Prenotami - noreply-prenotami at esteri.it"
  516. # 经实机验证,直接以 "noreply-prenotami at esteri.it" 查收件人,不加多余关键词,5秒内即可命中
  517. sender_candidates = [
  518. "noreply-prenotami at esteri.it",
  519. "noreply-prenotami@esteri.it"
  520. ]
  521. while time.time() - start_time < max_wait:
  522. for sdr in sender_candidates:
  523. params = {
  524. "email": self.args.master_email,
  525. "sender": sdr,
  526. "recipient": email,
  527. "sentDate": sent_at_utc,
  528. "expiry": "3600",
  529. "onlyText": False
  530. }
  531. try:
  532. resp = requests.post(self.args.email_fetch_url, headers=headers, params=params, json={}, timeout=25)
  533. if resp.status_code == 200:
  534. data = resp.json()
  535. if data.get("code") == 0:
  536. body = data.get("data", {}).get("body", "")
  537. match = re.search(r'https?://prenotami\.esteri\.it/Account/ConfirmEmail\?[^\s"\'<>]+', body)
  538. if match:
  539. link = match.group(0).replace("http://", "https://")
  540. self._log(f"✅ Found activation link: {link}")
  541. return link
  542. except requests.exceptions.Timeout:
  543. pass
  544. except Exception as e:
  545. self._log(f"Email poll exception ({sdr}): {e}")
  546. elapsed = int(time.time() - start_time)
  547. self._log(f"Waiting for activation email to arrive... ({elapsed}s/{max_wait}s)")
  548. time.sleep(3)
  549. return ""
  550. def _activate_account_in_browser(self, link: str) -> bool:
  551. """在当前浏览器会话中打开激活链接"""
  552. self._log(f"Opening activation link in browser session: {link}")
  553. try:
  554. activate_tab = self.page.new_tab(link)
  555. except Exception as e:
  556. self._log(f"Failed to open new tab, navigating in current page: {e}")
  557. self.page.get(link)
  558. activate_tab = self.page
  559. try:
  560. time.sleep(5)
  561. curr_url = ""
  562. curr_html = ""
  563. try:
  564. curr_url = activate_tab.url or ""
  565. curr_html = activate_tab.html or ""
  566. except Exception:
  567. pass
  568. if "radware" in curr_html.lower() and "captcha" in curr_html.lower():
  569. self._log("Radware challenge encountered on activation, waiting 6s...")
  570. time.sleep(6)
  571. try:
  572. curr_url = activate_tab.url or ""
  573. except Exception:
  574. pass
  575. self._log(f"Activation tab reached URL: {curr_url}")
  576. return True
  577. finally:
  578. if activate_tab != self.page:
  579. try:
  580. activate_tab.close()
  581. except Exception:
  582. pass
  583. def upload_account_to_server(self, acc: dict) -> bool:
  584. """将激活后的账号上报至云端数据库"""
  585. self._log(f"Uploading account {acc['email']} to pool {self.args.pool_name}...")
  586. headers = {
  587. "Authorization": f"Bearer {self.args.upload_token}",
  588. "Content-Type": "application/json",
  589. "Accept": "application/json"
  590. }
  591. payload = {
  592. "pool_name": self.args.pool_name,
  593. "username": acc["email"],
  594. "password": acc["password"],
  595. "extra_data": {
  596. "full_name": f"{acc['first_name']} {acc['last_name']}",
  597. "birth_date": acc["birth_date"],
  598. "birth_place": acc["birth_place"],
  599. "address": acc["address"],
  600. "cap": acc["cap"],
  601. "town": acc["town"],
  602. "mobile": f"+{acc['prefix']}{acc['phone']}",
  603. "consulate": "IRLANDA DUBLINO AMBASCIATA D'ITALIA",
  604. "created_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  605. },
  606. "status": "active"
  607. }
  608. try:
  609. resp = requests.post(self.args.upload_url, json=payload, headers=headers, timeout=15)
  610. if resp.status_code == 200 and resp.json().get("code") == 0:
  611. self._log(f"✅ Successfully registered and uploaded account: {acc['email']}")
  612. return True
  613. else:
  614. self._log(f"❌ Upload failed: Status {resp.status_code}, Body: {resp.text}")
  615. return False
  616. except Exception as e:
  617. self._log(f"❌ Upload error: {e}")
  618. return False
  619. def run_single(self, account_profile=None, *, upload=True) -> bool:
  620. """注册一个账户;真实申请人由调用方提供完整资料,并单独保存凭据。"""
  621. if account_profile is not None and upload:
  622. raise ValueError("Applicant registration requires upload=False; do not add it to the sentinel pool")
  623. acc = dict(account_profile) if account_profile is not None else self.generate_account_profile()
  624. self._log("=" * 65)
  625. self._log(f"Starting Registration: {acc['first_name']} {acc['last_name']} | {acc['email']}")
  626. self._log("=" * 65)
  627. try:
  628. self._init_browser()
  629. # 1. 先访问首页建立合法会话与安全 Cookie(绕过直接冷启动注册页时的 Radware 防火墙拦截)
  630. self._log(f"Establishing session on home page {HOME_URL}...")
  631. self.page.get(HOME_URL)
  632. time.sleep(3)
  633. # 2. 跳转至注册页面
  634. self._log(f"Navigating to registration page {REGISTER_URL}...")
  635. self.page.get(REGISTER_URL)
  636. time.sleep(3)
  637. # 3. 检查是否出现 Radware 拦截
  638. curr_url = self.page.url or ""
  639. if "perfdrive" in curr_url or "validate" in curr_url:
  640. self._log("⚠️ Encountered Radware challenge, waiting 5s...")
  641. time.sleep(5)
  642. # 4. 关闭初始引导弹窗
  643. self._close_welcome_modal()
  644. # 5. 确保表单核心元素已就绪
  645. if not self.page.wait.ele_displayed('#Name', timeout=15):
  646. self._close_welcome_modal()
  647. if not self.page.wait.ele_displayed('#Name', timeout=10):
  648. self._log(f"❌ Form element #Name not displayed. Current URL: {self.page.url}")
  649. return False
  650. self._fill_registration_form(acc)
  651. # 等待 Turnstile 验证(对齐 ita_plugin 预留充裕人机挑战交互窗口)
  652. turnstile_ok = self._wait_and_bypass_turnstile(max_wait=90)
  653. if not turnstile_ok:
  654. self._log("❌ Turnstile verification failed. Aborting current attempt.")
  655. return False
  656. if self.args.dry_run:
  657. self._log("🔍 [DRY-RUN] Form filled and Turnstile verified. Skipping submit & upload.")
  658. time.sleep(5)
  659. return True
  660. # 拟人化提交点击
  661. self._log("Preparing form submission...")
  662. sent_at_utc = (datetime.now(timezone.utc) - timedelta(minutes=5)).strftime("%Y-%m-%d %H:%M:%S")
  663. # 确保隐藏字段 Password / ConfirmPassword / hiddenOtherMailOrPhone 深度同步
  664. self.page.run_js('''
  665. const pw = arguments[0];
  666. const pEl = document.getElementById("Password");
  667. const cpEl = document.getElementById("ConfirmPassword");
  668. if (pEl) pEl.value = btoa(pw);
  669. if (cpEl) cpEl.value = btoa(pw);
  670. const omEl = document.getElementById("OtherMailOrPhone");
  671. const homEl = document.getElementById("hiddenOtherMailOrPhone");
  672. if (omEl && homEl) homEl.value = omEl.value;
  673. ''', acc['password'])
  674. btn_submit = self.page.ele('#btnRegister', timeout=10)
  675. if not btn_submit:
  676. self._log("❌ Could not find submit button #btnRegister")
  677. return False
  678. self._log("Simulating human pre-submit check (0.8 ~ 1.5s)...")
  679. time.sleep(random.uniform(0.8, 1.5))
  680. self._log("Submitting form with HumanMouse click...")
  681. try:
  682. self.mouse.human_click_ele(btn_submit)
  683. except Exception as e:
  684. self._log(f"Human click fallback: {e}")
  685. try:
  686. btn_submit.click()
  687. except Exception:
  688. pass
  689. # 等待跳转至 SentEmail(捕获 PageDisconnectedError 并在页面导航重连后自愈)
  690. reached_sent_email = False
  691. start_submit_wait = time.time()
  692. max_submit_wait = 45
  693. while time.time() - start_submit_wait < max_submit_wait:
  694. time.sleep(1.5)
  695. # 处理可能出现的 Alert 弹窗
  696. try:
  697. if self.page.states.has_alert:
  698. alert_msg = self.page.states.has_alert
  699. self._log(f"Handling browser alert: {alert_msg}")
  700. self.page.handle_alert(accept=True)
  701. except Exception:
  702. pass
  703. # 安全读取当前页面 URL
  704. curr_url = ""
  705. try:
  706. curr_url = self.page.url or ""
  707. except PageDisconnectedError:
  708. self._log("Page disconnected during POST navigation, waiting 2s for tab reconnect...")
  709. time.sleep(2)
  710. try:
  711. self.page.reconnect(wait=0.5)
  712. curr_url = self.page.url or ""
  713. except Exception:
  714. pass
  715. except Exception as e:
  716. self._log(f"Waiting for URL change ({e})...")
  717. if "SentEmail" in curr_url:
  718. self._log(f"✅ Reached SentEmail confirmation page: {curr_url}")
  719. reached_sent_email = True
  720. break
  721. # 若超过 8 秒仍在 Register 页且未发生跳转,触发 JS submit 兜底
  722. if account_profile is None and "Register" in curr_url and (time.time() - start_submit_wait > 8):
  723. self._log("Register page still active after 8s, triggering direct submit fallback...")
  724. try:
  725. self.page.run_js('''
  726. const form = document.getElementById("register-form");
  727. if (form) {
  728. if (window.$ && typeof $("#btnRegister").click === "function") {
  729. try { $("#btnRegister").click(); } catch(e){}
  730. } else {
  731. try { form.submit(); } catch(e){}
  732. }
  733. }
  734. ''')
  735. except Exception:
  736. pass
  737. if not reached_sent_email:
  738. curr_u = ""
  739. try:
  740. curr_u = self.page.url
  741. except Exception:
  742. pass
  743. self._log(f"⚠️ Page did not clearly show SentEmail, current url: {curr_u}")
  744. # 轮询获取激活链接
  745. link = self._fetch_activation_link(acc['email'], sent_at_utc, max_wait=120)
  746. if not link:
  747. self._log(f"❌ Failed to receive activation email for {acc['email']}.")
  748. return False
  749. # 打开链接激活
  750. activated = self._activate_account_in_browser(link)
  751. if not activated:
  752. self._log(f"❌ Activation tab failed for {acc['email']}.")
  753. return False
  754. # 上报入库
  755. return self.upload_account_to_server(acc) if upload else True
  756. finally:
  757. self.cleanup()
  758. def cleanup(self):
  759. """释放浏览器与临时目录"""
  760. if self.page:
  761. try:
  762. self.page.quit()
  763. except Exception:
  764. pass
  765. self.page = None
  766. if self.tunnel:
  767. try:
  768. self.tunnel.stop()
  769. except Exception:
  770. pass
  771. self.tunnel = None
  772. if hasattr(self, 'workspace') and self.workspace and os.path.exists(self.workspace):
  773. try:
  774. shutil.rmtree(self.workspace, ignore_errors=True)
  775. except Exception:
  776. pass
  777. def parse_args():
  778. parser = argparse.ArgumentParser(description="Prenot@Mi 意大利签证账号全自动注册机器人")
  779. parser.add_argument("--target", type=int, default=1, help="需要成功注册的账号数量")
  780. parser.add_argument("--interval", type=int, default=600, help="账号注册之间的冷却等待时间(秒,默认 600 秒即 10 分钟)")
  781. parser.add_argument("--proxy", type=str, default="http://127.0.0.1:7897", help="代理服务器地址 (如 http://127.0.0.1:7897)")
  782. parser.add_argument("--pool-name", type=str, default=DEFAULT_POOL_NAME, help="云端账号池名称")
  783. parser.add_argument("--master-email", type=str, default=DEFAULT_MASTER_EMAIL, help="接收验证邮件的主邮箱")
  784. parser.add_argument("--email-domain", type=str, default="text.skin", help="生成的邮箱域名")
  785. parser.add_argument("--address-file", type=str, default=DEFAULT_ADDRESS_FILE, help="真实爱尔兰地址 JSON 文件路径")
  786. parser.add_argument("--upload-url", type=str, default=DEFAULT_UPLOAD_URL, help="账号上报接口 URL")
  787. parser.add_argument("--upload-token", type=str, default=DEFAULT_UPLOAD_TOKEN, help="接口 Bearer Token")
  788. parser.add_argument("--email-fetch-url", type=str, default=DEFAULT_EMAIL_FETCH_URL, help="邮件读取接口 URL")
  789. parser.add_argument("--timeout", type=int, default=40, help="页面加载与交互超时时间(秒)")
  790. parser.add_argument("--headless", action="store_true", help="是否以无头模式运行")
  791. parser.add_argument("--dry-run", action="store_true", help="演练模式:填写表单与过盾,不点击最终提交与入库")
  792. return parser.parse_args()
  793. def main():
  794. args = parse_args()
  795. bot = ItaRegistrationBot(args)
  796. target_success = args.target
  797. max_attempts = max(args.target * 2, args.target + 3)
  798. attempt = 0
  799. success_count = 0
  800. fail_count = 0
  801. print("=" * 70)
  802. print("🇮🇹 [Prenot@Mi Registration Bot] 自动化注册任务启动")
  803. print(f"目标成功数量: {target_success} | 冷却间隔: {args.interval}s ({args.interval // 60}m) | 账号池: {args.pool_name}")
  804. print(f"演练模式: {args.dry_run} | 网络代理: {args.proxy} | 邮件主箱: {args.master_email}")
  805. print("=" * 70)
  806. while success_count < target_success and attempt < max_attempts:
  807. attempt += 1
  808. logger.info(f"=== [Attempt {attempt} | Success Progress: {success_count}/{target_success}] Starting Registration ===")
  809. ok = bot.run_single()
  810. if ok:
  811. success_count += 1
  812. logger.info(f"✅ [Account {success_count}/{target_success}] Registration Succeeded! (Total Success: {success_count}, Failed: {fail_count})")
  813. else:
  814. fail_count += 1
  815. logger.warning(f"❌ [Attempt {attempt}] Registration Failed! (Total Success: {success_count}, Failed: {fail_count})")
  816. # 若尚未达成目标数量,进入冷却等待(默认 10 分钟)
  817. if success_count < target_success and attempt < max_attempts:
  818. wait_sec = args.interval
  819. logger.info(f"⏳ Cooldown: Waiting {wait_sec}s ({wait_sec // 60}m) before next registration attempt...")
  820. remain = wait_sec
  821. while remain > 0:
  822. sleep_chunk = min(30, remain)
  823. time.sleep(sleep_chunk)
  824. remain -= sleep_chunk
  825. if remain > 0 and remain % 60 == 0:
  826. logger.info(f"⏳ Cooldown in progress: {remain}s ({remain // 60}m) remaining before next attempt...")
  827. print("\n" + "=" * 70)
  828. print("🎯 [注册任务结束汇总]")
  829. print(f"目标数量: {target_success} | 实际尝试: {attempt} | 成功: {success_count} | 失败: {fail_count}")
  830. print("=" * 70)
  831. if __name__ == "__main__":
  832. main()