ita_calendar_session.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. """Shared Italy form preparation and passive request audit.
  2. Extracted from the real-tested Calendar gate. Production and diagnostic tools
  3. use the same protocol; no tool imports, credentials, or network calls on import.
  4. """
  5. from __future__ import annotations
  6. import json
  7. import time
  8. from enum import Enum
  9. from threading import Lock
  10. from urllib.parse import parse_qs, urljoin, urlparse
  11. from plugins.ita_calendar_query import (
  12. AVAILABILITY_PATH, CALENDAR_PATH, CalendarGateError,
  13. header_value as _header, same_origin_path as _same_origin_path,
  14. )
  15. from plugins.ita_protocol import ItaRouteConfig
  16. OTP_PATH = "/BookingCalendar/GenerateOTP"
  17. def booking_preflight_state(raw: object) -> str:
  18. """Classify observed readiness, not the unknown cause of a widget failure."""
  19. if not isinstance(raw, dict):
  20. return "snapshot_unavailable"
  21. token, disabled = raw.get("turnstileTokenPresent"), raw.get("avantiDisabled")
  22. if type(token) is not bool or type(disabled) is not bool:
  23. return "invalid_snapshot"
  24. if not token:
  25. return "turnstile_and_avanti_pending" if disabled else "turnstile_token_pending"
  26. return "avanti_disabled" if disabled else "ready"
  27. def safe_booking_preflight_diagnostic(raw: object, *, stage, outcome: str) -> dict:
  28. """Only bounded booleans/counts and fixed categories; never token/value/HTML."""
  29. snapshot = raw if isinstance(raw, dict) else {}
  30. result = {
  31. "contract": "ita-book-preflight-v2",
  32. "stage": stage.value if isinstance(stage, BookingPreflightStage) else "invalid",
  33. "outcome": outcome if outcome in {"ready", "waiting", "rejected", "timeout", "read_failed"} else "invalid",
  34. "state": booking_preflight_state(raw),
  35. }
  36. for key in ("pathMatches", "formPresent", "privacyChecked", "otpDisabled", "otpValuePresent",
  37. "turnstileTokenPresent", "avantiDisabled", "turnstileApiPresent",
  38. "turnstileScriptPresent", "documentVisible"):
  39. value = snapshot.get(key)
  40. result[key] = value if type(value) is bool else None
  41. for key in ("turnstileCount", "avantiButtonCount", "unknownRequiredCount"):
  42. value = snapshot.get(key)
  43. result[key] = value if type(value) is int and 0 <= value <= 1000 else None
  44. return result
  45. def _print_booking_preflight_diagnostic(raw: object, *, stage, outcome: str) -> None:
  46. print("ITA_BOOK_PREFLIGHT_DIAGNOSTIC=" + json.dumps(
  47. safe_booking_preflight_diagnostic(raw, stage=stage, outcome=outcome), sort_keys=True,
  48. ), flush=True)
  49. def wait_for_booking_preflight(
  50. page: object,
  51. *,
  52. script: str,
  53. stage: BookingPreflightStage = None,
  54. timeout: float = 120,
  55. diagnostic=None,
  56. wait_action=None,
  57. check_current=None,
  58. ) -> dict[str, object]:
  59. """Wait without relaxing structure; optional bounded form interaction.
  60. An interaction return value is never evidence of readiness: only the next
  61. validated site snapshot can permit OTP/AVANTI. No recovery is enabled by
  62. default; callers must explicitly supply their preparation recovery.
  63. """
  64. stage = stage if stage is not None else BookingPreflightStage.BEFORE_OTP_SEND
  65. report = diagnostic or _print_booking_preflight_diagnostic
  66. started = time.monotonic()
  67. deadline = started + timeout
  68. announced = False
  69. raw = None
  70. last_state = None
  71. next_report = started
  72. while (now := time.monotonic()) < deadline:
  73. if check_current is not None:
  74. check_current()
  75. try:
  76. raw = page.run_js(script)
  77. except Exception:
  78. report(None, stage=stage, outcome="read_failed")
  79. raise CalendarGateError("Italy booking preflight read_failed") from None
  80. if check_current is not None:
  81. check_current()
  82. try:
  83. _validate_preflight_except_dynamic_token(raw, stage=stage)
  84. except CalendarGateError:
  85. report(
  86. raw,
  87. stage=stage,
  88. outcome="rejected",
  89. )
  90. raise
  91. if raw.get("turnstileTokenPresent") and not raw.get("avantiDisabled"):
  92. try:
  93. validate_booking_preflight(raw, stage=stage)
  94. except CalendarGateError:
  95. report(
  96. raw,
  97. stage=stage,
  98. outcome="rejected",
  99. )
  100. raise
  101. report(
  102. raw,
  103. stage=stage,
  104. outcome="ready",
  105. )
  106. return raw
  107. if not announced:
  108. print("ITA_BOOK_WAITING_FOR_FORM: watch the opened browser; complete any human verification. "
  109. "Do not click OTP, AVANTI, or final Prenota.", flush=True)
  110. announced = True
  111. state = booking_preflight_state(raw)
  112. if state != last_state or now >= next_report:
  113. report(raw, stage=stage, outcome="waiting")
  114. last_state, next_report = state, now + 15
  115. if wait_action is not None:
  116. wait_action(raw, stage=stage, elapsed=now - started, remaining=deadline - now)
  117. time.sleep(0.5)
  118. report(raw, stage=stage, outcome="timeout")
  119. raise CalendarGateError(f"Italy booking preflight timed out: {booking_preflight_state(raw)}")
  120. def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
  121. """Check scope before the reused script changes any visible form control."""
  122. prefix = """
  123. /* coordinate:ita-book-gate-form-boundary */
  124. const bookGateForms = document.querySelectorAll('#bookingForm');
  125. const bookGateForm = bookGateForms.length === 1 ? bookGateForms[0] : null;
  126. let bookGateAction = null;
  127. try { bookGateAction = bookGateForm ? new URL(bookGateForm.action, location.href) : null; }
  128. catch (_) {}
  129. if (location.origin !== 'https://prenotami.esteri.it' ||
  130. location.pathname !== BOOK_GATE_PATH || !bookGateForm ||
  131. bookGateForm.method.toUpperCase() !== 'POST' ||
  132. bookGateForm.enctype !== 'multipart/form-data' ||
  133. !bookGateAction || bookGateAction.origin !== location.origin ||
  134. bookGateAction.pathname !== BOOK_GATE_PATH || bookGateAction.search || bookGateAction.hash ||
  135. bookGateForm.querySelectorAll('input[type="file"]').length !== 0) {
  136. return {pathMatches: false, formPresent: false};
  137. }
  138. """.replace("BOOK_GATE_PATH", json.dumps(booking_path))
  139. return prefix + _booking_preflight_script(route, booking_path)
  140. class BookingPreflightStage(Enum):
  141. BEFORE_OTP_SEND = "before_otp_send"
  142. AFTER_OTP_SEND = "after_otp_send"
  143. class CalendarRequestAudit:
  144. """Passively count business requests across refreshes; never retain bodies.
  145. The production page.listen owns a separate CDP connection. This diagnostic
  146. callback uses the page driver and refuses to replace an existing handler.
  147. It never enables Fetch interception or changes any browser request.
  148. """
  149. EVENT = "Network.requestWillBeSent"
  150. def __init__(self, page: object, *, include_time_slots: bool = False) -> None:
  151. self.page = page
  152. self.driver = page.driver
  153. self._callback = self._on_request
  154. self._lock = Lock()
  155. self._started = False
  156. self._invalid_event = False
  157. self._counts = {
  158. "otpRequests": 0,
  159. "avantiPosts": 0,
  160. "availabilityRequests": 0,
  161. "finalRequests": 0,
  162. }
  163. if include_time_slots:
  164. self._counts["timeSlotRequests"] = 0
  165. def enable_time_slot_counting(self) -> None:
  166. """Opt in for the soak; existing gate counter shapes stay unchanged."""
  167. with self._lock:
  168. self._counts.setdefault("timeSlotRequests", 0)
  169. def start(self) -> None:
  170. if self._started:
  171. raise CalendarGateError("Passive request audit was already started")
  172. for name in ("event_handlers", "immediate_event_handlers"):
  173. handlers = getattr(self.driver, name, None)
  174. if not isinstance(handlers, dict) or self.EVENT in handlers:
  175. raise CalendarGateError(
  176. "Passive request audit cannot replace an existing callback"
  177. )
  178. self.driver.set_callback(self.EVENT, self._callback, immediate=True)
  179. self._started = True
  180. try:
  181. self.page.run_cdp("Network.enable")
  182. except Exception:
  183. self.stop()
  184. raise
  185. def stop(self) -> None:
  186. if not self._started:
  187. return
  188. if self.driver.immediate_event_handlers.get(self.EVENT) is not self._callback:
  189. raise CalendarGateError("Passive request audit callback changed")
  190. self.driver.set_callback(self.EVENT, None, immediate=True)
  191. self._started = False
  192. def _on_request(self, **event: object) -> None:
  193. request = event.get("request")
  194. if (
  195. not isinstance(request, dict)
  196. or not isinstance(request.get("url"), str)
  197. or not isinstance(request.get("method"), str)
  198. ):
  199. with self._lock:
  200. self._invalid_event = True
  201. return
  202. try:
  203. path, _ = _same_origin_path(request["url"])
  204. except CalendarGateError:
  205. return
  206. method = request["method"].upper()
  207. key = None
  208. if path == OTP_PATH:
  209. key = "otpRequests"
  210. elif path == "/BookingCalendar/InsertNewBooking":
  211. key = "finalRequests"
  212. elif method == "POST" and path.startswith("/Services/Booking/"):
  213. key = "avantiPosts"
  214. elif path == AVAILABILITY_PATH:
  215. key = "availabilityRequests"
  216. elif path == "/BookingCalendar/RetrieveTimeSlots" and "timeSlotRequests" in self._counts:
  217. key = "timeSlotRequests"
  218. if key is not None:
  219. with self._lock:
  220. self._counts[key] += 1
  221. def require_active_on(self, page: object) -> None:
  222. """Validate a borrowed audit without registering or removing callbacks."""
  223. if self.page is not page or self.driver is not getattr(page, "driver", None):
  224. raise CalendarGateError("Passive request audit belongs to another page or driver")
  225. if not self._started or self.driver.is_running is not True:
  226. raise CalendarGateError("Passive request audit is not connected")
  227. immediate = getattr(self.driver, "immediate_event_handlers", None)
  228. regular = getattr(self.driver, "event_handlers", None)
  229. if (not isinstance(immediate, dict) or immediate.get(self.EVENT) is not self._callback
  230. or not isinstance(regular, dict) or self.EVENT in regular):
  231. raise CalendarGateError("Passive request audit callback changed")
  232. def snapshot(self) -> dict[str, int]:
  233. self.require_active_on(self.page)
  234. with self._lock:
  235. if self._invalid_event:
  236. raise CalendarGateError("Passive request audit received an invalid event")
  237. return dict(self._counts)
  238. def retained_snapshot(self) -> dict[str, int]:
  239. """Best-effort last observed counters, not proof after a disconnect."""
  240. with self._lock:
  241. if self._invalid_event:
  242. raise CalendarGateError("Passive request audit received an invalid event")
  243. return dict(self._counts)
  244. def settled_snapshot(self, *, timeout: float = 3) -> dict[str, int]:
  245. # A read-only CDP round trip plus a bounded stable-count window lets
  246. # already-arriving callbacks catch up before a per-query comparison.
  247. self.page.run_cdp("Page.getFrameTree")
  248. deadline = time.monotonic() + timeout
  249. previous = self.snapshot()
  250. stable_since = time.monotonic()
  251. while time.monotonic() < deadline:
  252. time.sleep(0.1)
  253. current = self.snapshot()
  254. if current != previous:
  255. previous = current
  256. stable_since = time.monotonic()
  257. elif time.monotonic() - stable_since >= 0.3:
  258. return current
  259. raise CalendarGateError("Passive business-request counts did not settle")
  260. def validate_otp_packet(packet: object, *, service_id: int) -> None:
  261. path, parsed = _same_origin_path(packet.url)
  262. if str(packet.method).upper() != "GET" or path != OTP_PATH:
  263. raise CalendarGateError("OTP request method or path changed")
  264. if parse_qs(parsed.query) != {"ServiceID": [str(service_id)]}:
  265. raise CalendarGateError("OTP request service id changed")
  266. if packet.response.status != 200:
  267. raise CalendarGateError("OTP response status was not 200")
  268. raw_body = packet.response.raw_body
  269. if not isinstance(raw_body, str):
  270. raise CalendarGateError("OTP response body type changed")
  271. try:
  272. decoded = json.loads(raw_body)
  273. except json.JSONDecodeError as exc:
  274. raise CalendarGateError("OTP response was not the observed JSON string") from exc
  275. if decoded != "SENT":
  276. raise CalendarGateError("OTP response did not confirm SENT")
  277. def validate_avanti_packet(
  278. packet: object,
  279. *,
  280. booking_path: str,
  281. final_page_url: str,
  282. ) -> str:
  283. path, request_url = _same_origin_path(packet.url)
  284. if (
  285. str(packet.method).upper() != "POST"
  286. or path != booking_path
  287. or request_url.query
  288. or request_url.fragment
  289. ):
  290. raise CalendarGateError("AVANTI request method or path changed")
  291. status = packet.response.status
  292. if status == 302:
  293. raw_location = _header(packet.response.headers, "location")
  294. redirect_path, _ = _same_origin_path(
  295. urljoin("https://prenotami.esteri.it", raw_location)
  296. )
  297. if redirect_path != CALENDAR_PATH:
  298. raise CalendarGateError("AVANTI redirect did not target Calendar")
  299. transition_mode = "direct_302"
  300. elif status == 200:
  301. response_path, _ = _same_origin_path(
  302. getattr(packet.response, "url", "")
  303. )
  304. if response_path != CALENDAR_PATH:
  305. raise CalendarGateError(
  306. "AVANTI followed response did not target Calendar"
  307. )
  308. transition_mode = "followed_redirect_200"
  309. else:
  310. raise CalendarGateError(
  311. "AVANTI response status was not an allowed redirect representation"
  312. )
  313. final_path, _ = _same_origin_path(final_page_url)
  314. if final_path != CALENDAR_PATH:
  315. raise CalendarGateError("AVANTI browser did not finish on Calendar")
  316. return transition_mode
  317. def validate_booking_preflight(
  318. raw: object,
  319. *,
  320. stage: BookingPreflightStage = BookingPreflightStage.BEFORE_OTP_SEND,
  321. ) -> None:
  322. """Validate shared form shape and the stage-sensitive OTP-send control."""
  323. if not isinstance(raw, dict):
  324. raise CalendarGateError("Booking preflight did not return an object")
  325. if not isinstance(stage, BookingPreflightStage):
  326. raise CalendarGateError("Booking preflight stage is invalid")
  327. true_fields = (
  328. "pathMatches",
  329. "formPresent",
  330. "bookingTypeOptionMatched",
  331. "purposeOptionMatched",
  332. "bookingVisibleMatches",
  333. "bookingHiddenMatches",
  334. "companionsHiddenIsZero",
  335. "purposeVisibleMatches",
  336. "purposeHiddenIsPreSubmit",
  337. "privacyChecked",
  338. "turnstileTokenPresent",
  339. )
  340. for field_name in true_fields:
  341. if raw.get(field_name) is not True:
  342. raise CalendarGateError(
  343. f"Booking preflight rejected {field_name}"
  344. )
  345. for field_name in (
  346. "otpInputCount",
  347. "otpButtonCount",
  348. "avantiButtonCount",
  349. "turnstileCount",
  350. ):
  351. if raw.get(field_name) != 1:
  352. raise CalendarGateError(
  353. f"Booking preflight rejected {field_name}"
  354. )
  355. otp_disabled = raw.get("otpDisabled")
  356. if not isinstance(otp_disabled, bool) or (
  357. stage is BookingPreflightStage.BEFORE_OTP_SEND
  358. and otp_disabled
  359. ):
  360. raise CalendarGateError(
  361. "Booking preflight rejected otpDisabled"
  362. )
  363. if raw.get("avantiDisabled") is not False:
  364. raise CalendarGateError(
  365. "Booking preflight rejected avantiDisabled"
  366. )
  367. otp_value_present = raw.get("otpValuePresent")
  368. expected_otp_value_present = (
  369. stage is BookingPreflightStage.AFTER_OTP_SEND
  370. )
  371. if (
  372. not isinstance(otp_value_present, bool)
  373. or otp_value_present is not expected_otp_value_present
  374. ):
  375. raise CalendarGateError(
  376. "Booking preflight rejected otpValuePresent"
  377. )
  378. if raw.get("unknownRequiredCount") != 0:
  379. raise CalendarGateError(
  380. "Booking preflight rejected unknownRequiredCount"
  381. )
  382. def _booking_preflight_script(
  383. route: ItaRouteConfig,
  384. booking_path: str,
  385. ) -> str:
  386. if route.booking_type is None or route.purpose is None:
  387. raise CalendarGateError("Q-CAL route is missing form controls")
  388. config = {
  389. "bookingPath": booking_path,
  390. "bookingTypeId": route.booking_type.control_id,
  391. "bookingTypeValue": route.booking_type.value,
  392. "bookingTypeLabels": list(route.booking_type.labels),
  393. "purposeId": route.purpose.control_id,
  394. "purposeValue": route.purpose.value,
  395. "purposeLabels": list(route.purpose.labels),
  396. }
  397. config_json = json.dumps(config, ensure_ascii=False)
  398. return f"""
  399. /* coordinate:ita-qcal-booking-preflight */
  400. const cfg = {config_json};
  401. const normalize = (value) => String(value || '')
  402. .replace(/\\s+/g, ' ').trim().toLocaleLowerCase();
  403. const form = document.querySelector('#bookingForm');
  404. const booking = document.getElementById(cfg.bookingTypeId);
  405. const purpose = document.getElementById(cfg.purposeId);
  406. const bookingOption = booking
  407. ? Array.from(booking.options).find(
  408. (option) => option.value === cfg.bookingTypeValue
  409. )
  410. : null;
  411. const purposeOption = purpose
  412. ? Array.from(purpose.options).find(
  413. (option) => option.value === cfg.purposeValue
  414. )
  415. : null;
  416. const bookingLabels = cfg.bookingTypeLabels.map(normalize);
  417. const purposeLabels = cfg.purposeLabels.map(normalize);
  418. const bookingTypeOptionMatched = Boolean(
  419. bookingOption && bookingLabels.includes(normalize(bookingOption.textContent))
  420. );
  421. const purposeOptionMatched = Boolean(
  422. purposeOption && purposeLabels.includes(normalize(purposeOption.textContent))
  423. );
  424. if (bookingTypeOptionMatched && booking.value !== cfg.bookingTypeValue) {{
  425. booking.value = cfg.bookingTypeValue;
  426. booking.dispatchEvent(new Event('change', {{bubbles: true}}));
  427. }}
  428. if (purposeOptionMatched && purpose.value !== cfg.purposeValue) {{
  429. purpose.value = cfg.purposeValue;
  430. purpose.dispatchEvent(new Event('change', {{bubbles: true}}));
  431. }}
  432. const privacy = document.getElementById('PrivacyCheck');
  433. if (privacy && !privacy.checked) privacy.click();
  434. const allowedRequiredIds = new Set([
  435. cfg.bookingTypeId,
  436. cfg.purposeId,
  437. 'otp-input',
  438. 'PrivacyCheck',
  439. 'hiddenTipoPrenotazione',
  440. 'numAccSelected',
  441. 'hiddenSelezionato_0',
  442. ]);
  443. const allowedRequiredNames = new Set([
  444. 'otp-input',
  445. 'PrivacyCheck',
  446. 'cf-turnstile-response',
  447. '__RequestVerificationToken',
  448. ]);
  449. const unknownRequired = form
  450. ? Array.from(form.querySelectorAll('[required]')).filter((element) =>
  451. !allowedRequiredIds.has(element.id) &&
  452. !allowedRequiredNames.has(element.name)
  453. )
  454. : [];
  455. const bookingHidden = document.getElementById('hiddenTipoPrenotazione');
  456. const companionsHidden = document.getElementById('numAccSelected');
  457. const purposeHidden = document.getElementById('hiddenSelezionato_0');
  458. const otpInputs = document.querySelectorAll('#otp-input');
  459. const otpButtons = document.querySelectorAll('#otp-send');
  460. const avantiButtons = document.querySelectorAll('#btnAvanti');
  461. const turnstile = document.querySelectorAll(
  462. 'input[name="cf-turnstile-response"]'
  463. );
  464. return {{
  465. pathMatches: window.location.pathname === cfg.bookingPath,
  466. formPresent: Boolean(form),
  467. bookingTypeOptionMatched,
  468. purposeOptionMatched,
  469. bookingVisibleMatches: Boolean(
  470. booking && booking.value === cfg.bookingTypeValue
  471. ),
  472. bookingHiddenMatches: Boolean(
  473. bookingHidden && bookingHidden.value === cfg.bookingTypeValue
  474. ),
  475. companionsHiddenIsZero: Boolean(
  476. companionsHidden && companionsHidden.value === '0'
  477. ),
  478. purposeVisibleMatches: Boolean(
  479. purpose && purpose.value === cfg.purposeValue
  480. ),
  481. purposeHiddenIsPreSubmit: Boolean(
  482. purposeHidden && ['0', cfg.purposeValue].includes(purposeHidden.value)
  483. ),
  484. privacyChecked: Boolean(privacy && privacy.checked),
  485. otpInputCount: otpInputs.length,
  486. otpValuePresent: Boolean(
  487. otpInputs.length === 1 && String(otpInputs[0].value || '').trim()
  488. ),
  489. otpButtonCount: otpButtons.length,
  490. otpDisabled: otpButtons.length === 1 ? otpButtons[0].disabled : null,
  491. avantiButtonCount: avantiButtons.length,
  492. avantiDisabled:
  493. avantiButtons.length === 1 ? avantiButtons[0].disabled : null,
  494. turnstileCount: turnstile.length,
  495. turnstileTokenPresent: Boolean(
  496. turnstile.length === 1 && turnstile[0].value
  497. ),
  498. turnstileApiPresent: Boolean(window.turnstile),
  499. turnstileScriptPresent: Boolean(document.querySelector(
  500. 'script[src^="https://challenges.cloudflare.com/turnstile/"]'
  501. )),
  502. documentVisible: document.visibilityState === 'visible',
  503. unknownRequiredCount: unknownRequired.length,
  504. }};
  505. """
  506. def _validate_preflight_except_dynamic_token(
  507. raw: object,
  508. *,
  509. stage: BookingPreflightStage,
  510. ) -> None:
  511. if not isinstance(raw, dict):
  512. raise CalendarGateError("Booking preflight did not return an object")
  513. for key in ("turnstileTokenPresent", "avantiDisabled"):
  514. if type(raw.get(key)) is not bool:
  515. raise CalendarGateError(f"Booking preflight rejected {key}")
  516. candidate = dict(raw)
  517. candidate["turnstileTokenPresent"] = True
  518. candidate["avantiDisabled"] = False
  519. validate_booking_preflight(candidate, stage=stage)
  520. def _wait_for_calendar(page: object, timeout: float = 30) -> None:
  521. deadline = time.monotonic() + timeout
  522. while time.monotonic() < deadline:
  523. if (urlparse(str(page.url or "")).path.rstrip("/") or "/") == CALENDAR_PATH:
  524. page.wait.doc_loaded()
  525. return
  526. time.sleep(0.25)
  527. raise CalendarGateError("AVANTI did not reach Calendar before timeout")
  528. def _element_or_fail(page: object, selector: str) -> object:
  529. element = page.ele(selector, timeout=5)
  530. if not element:
  531. raise CalendarGateError(f"Required element is missing: {selector}")
  532. return element
  533. def _read_manual_otp() -> str:
  534. otp = input(
  535. "Italy booking OTP "
  536. "(visible; terminal scrollback may retain it): "
  537. ).strip()
  538. if not otp.isdigit() or not 4 <= len(otp) <= 12:
  539. raise CalendarGateError("OTP must be 4-12 digits")
  540. return otp
  541. def _enter_otp(plugin: object, otp: str) -> None:
  542. """Focus, type, and compare in-page without returning the OTP value."""
  543. otp_input = _element_or_fail(plugin.page, "#otp-input")
  544. plugin.mouse.human_click_ele(otp_input)
  545. otp_input.input(otp, clear=True)
  546. value_matches = otp_input.run_js(
  547. "return this.value === arguments[0];",
  548. otp,
  549. )
  550. if value_matches is not True:
  551. raise CalendarGateError("OTP DOM write verification failed")
  552. print("ITA_QCAL_OTP_DOM_WRITE_VERIFIED matched=true")