ita_booking_final.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. """Italy final-stage building blocks shared by production and local validation.
  2. ReservationSnapshot is an internal read-port contract, NOT a discovered website
  3. schema. A real adapter must prove identity, status and pagination completeness
  4. before this module can be enabled. Attempts are process-local; the existing
  5. Booker task pause handles uncertain outcomes. No automatic retry is provided.
  6. The opt-in local evidence gate adds a checkout-local fence and human confirmation;
  7. it observes unknown receipts without claiming that production success is proven.
  8. """
  9. from __future__ import annotations
  10. import json
  11. import re
  12. import threading
  13. import time
  14. from dataclasses import dataclass, field
  15. from datetime import date
  16. from enum import Enum
  17. from typing import Callable
  18. from urllib.parse import parse_qsl, urljoin
  19. from plugins.ita_calendar_book import SLOT_SELECTION_SCRIPT, verify_precommit_selection
  20. from plugins.ita_calendar_query import CALENDAR_PATH, listen_once, same_origin_path
  21. from plugins.ita_protocol import CalendarDay, MAX_PROTOCOL_PAYLOAD_CHARS, PrecommitApproval, SlotCandidate
  22. from vs_types import VSBookResult, BookingOutcomeUnknownError
  23. FINAL_PATH = "/BookingCalendar/InsertNewBooking"
  24. class FinalBookingError(RuntimeError):
  25. """Fixed messages only: do not include page text, requests or credentials."""
  26. class FinalOutcomeUnknown(FinalBookingError, BookingOutcomeUnknownError):
  27. def __init__(self):
  28. super().__init__("Italy final outcome requires read-only reconciliation")
  29. class ReservationState(str, Enum):
  30. ACTIVE = "active"
  31. CANCELLED = "cancelled"
  32. WAITLIST = "waitlist"
  33. UNKNOWN = "unknown"
  34. class SubmissionSignal(str, Enum):
  35. ACCEPTED = "accepted_hint"
  36. REJECTED = "rejected_hint"
  37. UNKNOWN = "unknown"
  38. def _text(value: object) -> bool:
  39. return (isinstance(value, str) and 0 < len(value) <= 256 and value == value.strip()
  40. and not any(ord(ch) < 32 or ord(ch) == 127 for ch in value))
  41. @dataclass(frozen=True, slots=True)
  42. class FinalTarget:
  43. applicant: str = field(repr=False)
  44. session_key: str = field(repr=False)
  45. tab_id: str = field(repr=False)
  46. routing_key: str
  47. service_id: str = field(repr=False)
  48. runtime_service: str = field(repr=False)
  49. approval: PrecommitApproval = field(repr=False)
  50. service_name: str | None = field(default=None, repr=False)
  51. def __post_init__(self):
  52. if not all(_text(getattr(self, key)) for key in (
  53. "applicant", "session_key", "tab_id", "routing_key", "service_id", "runtime_service",
  54. )):
  55. raise FinalBookingError("Italy final target identity is invalid")
  56. if not isinstance(self.approval, PrecommitApproval):
  57. raise FinalBookingError("Italy final requires a Book precommit approval")
  58. if self.service_name is not None and not _text(self.service_name):
  59. raise FinalBookingError("Italy final displayed service is invalid")
  60. day, slot = self.approval.calendar_day, self.approval.candidate
  61. if (not isinstance(day, CalendarDay) or not isinstance(slot, SlotCandidate)
  62. or day.day != slot.day or not day.is_available or not slot.is_available):
  63. raise FinalBookingError("Italy final target inventory is inconsistent")
  64. @dataclass(frozen=True, slots=True, repr=False)
  65. class VerifiedSubmission:
  66. """Native POST matched this exact session/tab/precommit; not a receipt field.
  67. Created from an observed packet, even when its RESPONSE schema is unknown.
  68. A caller must also enforce the one-request audit before passing it to a read port.
  69. """
  70. target: FinalTarget
  71. @dataclass(frozen=True, slots=True)
  72. class ReservationRecord:
  73. """Normalized by a verified, identity-bound site reader.
  74. time_label is an independently evidenced selected interval, not an interval
  75. inferred from appointment_time. A real receipt may expose only the assigned
  76. HH:mm time. That is enough to preserve cancelled history, not prove a new
  77. record belongs to the selected slot. Cancelled history may have an unbound
  78. service_id only with a fingerprint retaining all observed business facts.
  79. This exception never establishes a target-service or selected-slot binding.
  80. submission is a separate verified native-request witness, used by the bound
  81. real read port for new active receipts. It never rewrites the receipt fields.
  82. """
  83. reference: str = field(repr=False)
  84. service_id: str | None = field(repr=False)
  85. day: date
  86. time_label: str | None
  87. state: ReservationState
  88. appointment_time: str | None = None
  89. receipt_fingerprint: str | None = field(default=None, repr=False)
  90. submission: VerifiedSubmission | None = field(default=None, repr=False)
  91. def _valid_receipt_time(record: ReservationRecord) -> bool:
  92. interval, assigned = record.time_label, record.appointment_time
  93. if interval is None and assigned is None:
  94. return False
  95. if interval is not None and (
  96. not isinstance(interval, str)
  97. or re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9] - (?:[01][0-9]|2[0-3]):[0-5][0-9]", interval) is None
  98. or interval[:5] >= interval[-5:]
  99. ):
  100. return False
  101. assigned_valid = assigned is None or (
  102. isinstance(assigned, str)
  103. and re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", assigned) is not None
  104. )
  105. if not assigned_valid:
  106. return False
  107. # Negative consistency check only: containment never creates a binding.
  108. return interval is None or assigned is None or interval[:5] <= assigned <= interval[-5:]
  109. @dataclass(frozen=True, slots=True)
  110. class ReservationSnapshot:
  111. applicant: str = field(repr=False)
  112. session_key: str = field(repr=False)
  113. captured_at: float
  114. complete: bool
  115. records: tuple[ReservationRecord, ...] = field(repr=False)
  116. # Reuse the actual slot readback JS in the same synchronous browser turn as the
  117. # native final click, so a Python/browser round trip cannot select another slot.
  118. # Never reconstruct the POST payload: the website handler remains its owner.
  119. NATIVE_FINAL_SCRIPT = r"""
  120. /* coordinate:ita-native-final-once */
  121. const [serviceId, day, dailyId, timeLabel, capacity] = arguments;
  122. const state = (function () {
  123. """ + SLOT_SELECTION_SCRIPT + r"""
  124. }).apply(null, [serviceId, day, dailyId, timeLabel, capacity, false]);
  125. const positive = ['runtimeMatches', 'finalGuarded', 'firstSelectedMatches',
  126. 'dayPositive', 'candidateReady', 'activeIsCandidate', 'activeIdMatches',
  127. 'activeDayMatches', 'activeTimeMatches', 'activeCapacityMatches'];
  128. const negative = ['dayDisabled', 'dayNegative', 'activeUnavailable', 'activeRedDot', 'clicked'];
  129. const ready = positive.every(k => state[k] === true) && negative.every(k => state[k] === false) &&
  130. ['matchingDateCount', 'candidateCount', 'activeCount', 'activeInputCount'].every(k => state[k] === 1) &&
  131. JSON.stringify(state.timelineDays) === JSON.stringify([day]) &&
  132. JSON.stringify(state.contentDays) === JSON.stringify([day]);
  133. const buttons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
  134. if (!ready || buttons.length !== 1 || !buttons[0].isConnected ||
  135. buttons[0].dataset.coordinateFinalAttemptConsumed) return {clicked: false};
  136. const button = buttons[0];
  137. button.dataset.coordinateFinalAttemptConsumed = 'true';
  138. try {
  139. button.disabled = false;
  140. button.removeAttribute('aria-disabled');
  141. button.click();
  142. return {clicked: true};
  143. } finally {
  144. button.disabled = true;
  145. button.setAttribute('aria-disabled', 'true');
  146. button.dataset.coordinateFinalGuard = 'enabled';
  147. }
  148. """
  149. def _unique_object(pairs):
  150. result = {}
  151. for key, value in pairs:
  152. if key in result:
  153. raise ValueError("duplicate field")
  154. result[key] = value
  155. return result
  156. def inspect_final_packet(packet: object, target: FinalTarget) -> tuple[SubmissionSignal, VerifiedSubmission | None, str]:
  157. """Validate the observed request before interpreting a response as a hint.
  158. Invalid metadata/HTTP/schema is UNKNOWN after a write, not a retryable
  159. authentication/no-slot error. Never expose the raw server errorMessage.
  160. """
  161. evidence = None
  162. reason = "request_metadata"
  163. try:
  164. path, parsed = same_origin_path(packet.url)
  165. if (path != FINAL_PATH or parsed.query or parsed.fragment or packet.method != "POST"
  166. or packet.tab_id != target.tab_id or getattr(packet, "is_failed", False)):
  167. return SubmissionSignal.UNKNOWN, None, reason
  168. reason = "request_fields"
  169. body = packet.request.postData
  170. if isinstance(body, str) and len(body) <= MAX_PROTOCOL_PAYLOAD_CHARS:
  171. body = _unique_object(parse_qsl(body, keep_blank_values=True, strict_parsing=True))
  172. if not isinstance(body, dict) or set(body) != {
  173. "idCalendarioGiornaliero", "selectedDay", "selectedHour",
  174. } or any(not isinstance(value, str) for value in body.values()):
  175. return SubmissionSignal.UNKNOWN, None, reason
  176. reason = "request_selection"
  177. slot = target.approval.candidate
  178. if body["idCalendarioGiornaliero"] != slot.daily_calendar_id or body["selectedDay"] != slot.day.isoformat():
  179. return SubmissionSignal.UNKNOWN, None, reason
  180. compact = lambda value: re.sub(r"\s+", "", value)
  181. if compact(body["selectedHour"]) != compact(f"{slot.time_label}({slot.slots_free})"):
  182. return SubmissionSignal.UNKNOWN, None, reason
  183. evidence = VerifiedSubmission(target)
  184. reason = "response_metadata"
  185. response = packet.response
  186. if type(response.status) is not int or response.status != 200:
  187. return SubmissionSignal.UNKNOWN, evidence, reason
  188. response_url = getattr(response, "url", None)
  189. if response_url:
  190. response_path, response_parsed = same_origin_path(response_url)
  191. if response_path != FINAL_PATH or response_parsed.query or response_parsed.fragment:
  192. return SubmissionSignal.UNKNOWN, evidence, reason
  193. reason = "response_body"
  194. raw = response.raw_body
  195. if not isinstance(raw, str) or not 0 < len(raw) <= MAX_PROTOCOL_PAYLOAD_CHARS:
  196. return SubmissionSignal.UNKNOWN, evidence, reason
  197. data = json.loads(raw, object_pairs_hook=_unique_object)
  198. reason = "response_fields"
  199. if not isinstance(data, dict) or not {"errorMessage", "url"} <= set(data):
  200. return SubmissionSignal.UNKNOWN, evidence, reason
  201. error, destination = data["errorMessage"], data["url"]
  202. if not isinstance(error, str) or not _text(destination):
  203. return SubmissionSignal.UNKNOWN, evidence, reason
  204. reason = "response_destination"
  205. same_origin_path(urljoin(packet.url, destination))
  206. return (SubmissionSignal.REJECTED if error.strip() else SubmissionSignal.ACCEPTED), evidence, "recognized"
  207. except Exception:
  208. return SubmissionSignal.UNKNOWN, evidence, reason
  209. def classify_final_packet(packet: object, target: FinalTarget) -> SubmissionSignal:
  210. return inspect_final_packet(packet, target)[0]
  211. class NativeFinalSubmitter:
  212. """One native click with the existing listener; no navigation/retry/OTP.
  213. A process-local latch is not a durable task fence. Production reaches this
  214. adapter only with explicit final-submit configuration; default pre-final
  215. CLIs never call it. The opt-in local evidence gate has its own persistent fence.
  216. """
  217. def __init__(self, page: object, target: FinalTarget, session_is_current: Callable[[], bool]):
  218. self.page, self.target, self.session_is_current = page, target, session_is_current
  219. self._lock = threading.Lock()
  220. self._consumed = False
  221. self.submitted_selection: VerifiedSubmission | None = None
  222. self.diagnostic = {"requestMatched": False, "reason": "not_observed"}
  223. def __call__(self) -> SubmissionSignal:
  224. with self._lock:
  225. if self._consumed:
  226. raise FinalBookingError("Italy native final attempt is already consumed")
  227. self._consumed = True
  228. target = self.target
  229. def require_context():
  230. if (self.session_is_current() is not True or self.page.tab_id != target.tab_id
  231. or same_origin_path(self.page.url)[0] != CALENDAR_PATH):
  232. raise FinalBookingError("Italy native final context changed")
  233. def action():
  234. require_context()
  235. slot = target.approval.candidate
  236. raw = self.page.run_js(
  237. NATIVE_FINAL_SCRIPT, target.runtime_service, slot.day.isoformat(),
  238. slot.daily_calendar_id, slot.time_label, slot.slots_free,
  239. )
  240. if raw != {"clicked": True} or type(raw.get("clicked")) is not bool:
  241. raise FinalBookingError("Italy native final click was not acknowledged")
  242. try:
  243. require_context()
  244. verify_precommit_selection(self.page, runtime_service=target.runtime_service, approval=target.approval)
  245. packet = listen_once(self.page, target=FINAL_PATH, method="POST", action=action, timeout=30)
  246. signal, self.submitted_selection, reason = inspect_final_packet(packet, target)
  247. self.diagnostic = {"requestMatched": self.submitted_selection is not None, "reason": reason}
  248. return signal
  249. except Exception:
  250. # A lost browser acknowledgement can follow a committed write.
  251. self.diagnostic = {"requestMatched": False, "reason": "native_or_listener_error"}
  252. return SubmissionSignal.UNKNOWN
  253. class FinalBookingAttempt:
  254. """Single-use orchestration; reconciliation only after a possible write.
  255. read_reservations must perform a fresh, complete, read-only site read bound
  256. to this applicant/session. The real read port accepts only empty/cancelled
  257. baselines, then binds new confirmed receipts to a verified native request. submit_native
  258. is an injected NativeFinalSubmitter (or an offline test double), not an HTTP
  259. replay function. Context checks must work after a same-session redirect.
  260. """
  261. def __init__(
  262. self, target: FinalTarget, *, read_reservations: Callable[[], ReservationSnapshot],
  263. submit_native: Callable[[], SubmissionSignal], session_is_current: Callable[[], bool],
  264. ):
  265. if not isinstance(target, FinalTarget) or not all(callable(item) for item in (
  266. read_reservations, submit_native, session_is_current,
  267. )):
  268. raise FinalBookingError("Italy final adapters are required")
  269. self.target = target
  270. self._read_reservations = read_reservations
  271. self._submit_native = submit_native
  272. self._session_is_current = session_is_current
  273. self._lock = threading.Lock()
  274. self._state = "ready"
  275. self._signal = SubmissionSignal.UNKNOWN
  276. self._before: ReservationSnapshot | None = None
  277. @property
  278. def state(self) -> str:
  279. return self._state
  280. def _require_context(self):
  281. if self._session_is_current() is not True:
  282. raise FinalBookingError("Italy final applicant or Session changed")
  283. def _read(self) -> ReservationSnapshot:
  284. self._require_context()
  285. started = time.monotonic()
  286. snapshot = self._read_reservations()
  287. self._require_context()
  288. now = time.monotonic()
  289. if (not isinstance(snapshot, ReservationSnapshot) or snapshot.complete is not True
  290. or snapshot.applicant != self.target.applicant or snapshot.session_key != self.target.session_key
  291. or type(snapshot.captured_at) not in (int, float) or not started <= snapshot.captured_at <= now
  292. or not isinstance(snapshot.records, tuple) or len(snapshot.records) > 512):
  293. raise FinalBookingError("Italy reservation snapshot is incomplete or not current")
  294. seen = set()
  295. for record in snapshot.records:
  296. if (not isinstance(record, ReservationRecord) or not _text(record.reference)
  297. or record.reference in seen or type(record.day) is not date
  298. or not _valid_receipt_time(record)
  299. or not isinstance(record.state, ReservationState) or record.state is ReservationState.UNKNOWN):
  300. raise FinalBookingError("Italy reservation records require verified identity and status")
  301. fingerprint = record.receipt_fingerprint
  302. if fingerprint is not None and (not isinstance(fingerprint, str) or
  303. re.fullmatch(r"[0-9a-f]{64}", fingerprint) is None):
  304. raise FinalBookingError("Italy receipt fingerprint is invalid")
  305. if record.submission is not None and not self._submitted_binding(record):
  306. raise FinalBookingError("Italy receipt submission evidence does not match this attempt")
  307. if not _text(record.service_id) and not (
  308. record.service_id is None and fingerprint is not None and
  309. (record.state is ReservationState.CANCELLED or self._submitted_binding(record))):
  310. raise FinalBookingError("Italy live reservation service binding is unverified")
  311. seen.add(record.reference)
  312. return snapshot
  313. def _submitted_binding(self, record: ReservationRecord) -> bool:
  314. slot = self.target.approval.candidate
  315. return (self._state in {"submitted", "unknown"} and
  316. isinstance(record.submission, VerifiedSubmission) and
  317. record.submission.target == self.target and _text(self.target.service_name) and
  318. record.state is ReservationState.ACTIVE and record.service_id is None and
  319. record.time_label is None and record.receipt_fingerprint is not None and
  320. record.day == slot.day and isinstance(record.appointment_time, str) and
  321. slot.time_label[:5] <= record.appointment_time <= slot.time_label[-5:])
  322. def _live(self, snapshot: ReservationSnapshot) -> list[ReservationRecord]:
  323. return [record for record in snapshot.records if (record.service_id == self.target.service_id or
  324. self._submitted_binding(record))
  325. and record.state in {ReservationState.ACTIVE, ReservationState.WAITLIST}]
  326. def execute(self, *, enabled: bool = False) -> VSBookResult:
  327. if enabled is not True:
  328. raise FinalBookingError("Italy final submission is disabled")
  329. if not self._lock.acquire(blocking=False):
  330. raise FinalBookingError("Italy final attempt is already running")
  331. try:
  332. if self._state != "ready":
  333. raise FinalBookingError("Italy final attempt is already consumed")
  334. self._state = "checking"
  335. try:
  336. self._before = self._read()
  337. self._require_context()
  338. except Exception:
  339. self._state = "blocked"
  340. raise FinalBookingError("Italy final preflight blocked; no submission attempted") from None
  341. if self._live(self._before):
  342. self._state = "blocked"
  343. raise FinalBookingError("Italy service already has an active reservation or waitlist")
  344. self._state = "submitted"
  345. try:
  346. signal = self._submit_native()
  347. self._signal = signal if isinstance(signal, SubmissionSignal) else SubmissionSignal.UNKNOWN
  348. except Exception:
  349. self._signal = SubmissionSignal.UNKNOWN
  350. return self._reconcile()
  351. finally:
  352. # Ctrl-C/SystemExit must not make a possibly dispatched write look
  353. # unattempted, nor make read-only reconciliation impossible.
  354. if self._state == "submitted":
  355. self._state = "unknown"
  356. elif self._state == "checking":
  357. self._state = "blocked"
  358. self._lock.release()
  359. def reconcile(self) -> VSBookResult:
  360. """One read-only check. Never enters the native submit path."""
  361. if not self._lock.acquire(blocking=False):
  362. raise FinalBookingError("Italy final attempt is already running")
  363. try:
  364. if self._state != "unknown":
  365. raise FinalBookingError("Italy final attempt does not need reconciliation")
  366. return self._reconcile()
  367. finally:
  368. self._lock.release()
  369. def _reconcile(self) -> VSBookResult:
  370. self._state = "unknown"
  371. try:
  372. after = self._read()
  373. live = self._live(after)
  374. before = {record.reference: record for record in self._before.records}
  375. after_by_id = {record.reference: record for record in after.records}
  376. # Missing/modified history and unrelated new rows make attribution
  377. # ambiguous. Do not equate a count increment with this appointment.
  378. if any(after_by_id.get(key) != value for key, value in before.items()):
  379. raise FinalOutcomeUnknown()
  380. new = [record for record in after.records if record.reference not in before]
  381. slot = self.target.approval.candidate
  382. if (len(new) == 1 and len(live) == 1 and new[0] == live[0]
  383. and live[0].state is ReservationState.ACTIVE and live[0].day == slot.day
  384. and (live[0].time_label == slot.time_label or self._submitted_binding(live[0]))
  385. and self._signal is not SubmissionSignal.REJECTED):
  386. self._state = "confirmed"
  387. return VSBookResult(
  388. success=True, account=self.target.applicant, urn=live[0].reference,
  389. book_date=slot.day.isoformat(), book_time=live[0].appointment_time or slot.time_label,
  390. )
  391. if not new and not live and self._signal is SubmissionSignal.REJECTED:
  392. self._state = "rejected"
  393. return VSBookResult(success=False, label="italy-final-rejected")
  394. except Exception:
  395. pass
  396. self._state = "unknown"
  397. raise FinalOutcomeUnknown() from None