"""Italy final-stage building blocks shared by production and local validation. ReservationSnapshot is an internal read-port contract, NOT a discovered website schema. A real adapter must prove identity, status and pagination completeness before this module can be enabled. Attempts are process-local; the existing Booker task pause handles uncertain outcomes. No automatic retry is provided. The opt-in local evidence gate adds a checkout-local fence and human confirmation; it observes unknown receipts without claiming that production success is proven. """ from __future__ import annotations import json import re import threading import time from dataclasses import dataclass, field from datetime import date from enum import Enum from typing import Callable from urllib.parse import parse_qsl, urljoin from plugins.ita_calendar_book import SLOT_SELECTION_SCRIPT, verify_precommit_selection from plugins.ita_calendar_query import CALENDAR_PATH, listen_once, same_origin_path from plugins.ita_protocol import CalendarDay, MAX_PROTOCOL_PAYLOAD_CHARS, PrecommitApproval, SlotCandidate from vs_types import VSBookResult, BookingOutcomeUnknownError FINAL_PATH = "/BookingCalendar/InsertNewBooking" class FinalBookingError(RuntimeError): """Fixed messages only: do not include page text, requests or credentials.""" class FinalOutcomeUnknown(FinalBookingError, BookingOutcomeUnknownError): def __init__(self): super().__init__("Italy final outcome requires read-only reconciliation") class ReservationState(str, Enum): ACTIVE = "active" CANCELLED = "cancelled" WAITLIST = "waitlist" UNKNOWN = "unknown" class SubmissionSignal(str, Enum): ACCEPTED = "accepted_hint" REJECTED = "rejected_hint" UNKNOWN = "unknown" def _text(value: object) -> bool: return (isinstance(value, str) and 0 < len(value) <= 256 and value == value.strip() and not any(ord(ch) < 32 or ord(ch) == 127 for ch in value)) @dataclass(frozen=True, slots=True) class FinalTarget: applicant: str = field(repr=False) session_key: str = field(repr=False) tab_id: str = field(repr=False) routing_key: str service_id: str = field(repr=False) runtime_service: str = field(repr=False) approval: PrecommitApproval = field(repr=False) service_name: str | None = field(default=None, repr=False) def __post_init__(self): if not all(_text(getattr(self, key)) for key in ( "applicant", "session_key", "tab_id", "routing_key", "service_id", "runtime_service", )): raise FinalBookingError("Italy final target identity is invalid") if not isinstance(self.approval, PrecommitApproval): raise FinalBookingError("Italy final requires a Book precommit approval") if self.service_name is not None and not _text(self.service_name): raise FinalBookingError("Italy final displayed service is invalid") day, slot = self.approval.calendar_day, self.approval.candidate if (not isinstance(day, CalendarDay) or not isinstance(slot, SlotCandidate) or day.day != slot.day or not day.is_available or not slot.is_available): raise FinalBookingError("Italy final target inventory is inconsistent") @dataclass(frozen=True, slots=True, repr=False) class VerifiedSubmission: """Native POST matched this exact session/tab/precommit; not a receipt field. Created from an observed packet, even when its RESPONSE schema is unknown. A caller must also enforce the one-request audit before passing it to a read port. """ target: FinalTarget @dataclass(frozen=True, slots=True) class ReservationRecord: """Normalized by a verified, identity-bound site reader. time_label is an independently evidenced selected interval, not an interval inferred from appointment_time. A real receipt may expose only the assigned HH:mm time. That is enough to preserve cancelled history, not prove a new record belongs to the selected slot. Cancelled history may have an unbound service_id only with a fingerprint retaining all observed business facts. This exception never establishes a target-service or selected-slot binding. submission is a separate verified native-request witness, used by the bound real read port for new active receipts. It never rewrites the receipt fields. """ reference: str = field(repr=False) service_id: str | None = field(repr=False) day: date time_label: str | None state: ReservationState appointment_time: str | None = None receipt_fingerprint: str | None = field(default=None, repr=False) submission: VerifiedSubmission | None = field(default=None, repr=False) def _valid_receipt_time(record: ReservationRecord) -> bool: interval, assigned = record.time_label, record.appointment_time if interval is None and assigned is None: return False if interval is not None and ( not isinstance(interval, str) 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 or interval[:5] >= interval[-5:] ): return False assigned_valid = assigned is None or ( isinstance(assigned, str) and re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", assigned) is not None ) if not assigned_valid: return False # Negative consistency check only: containment never creates a binding. return interval is None or assigned is None or interval[:5] <= assigned <= interval[-5:] @dataclass(frozen=True, slots=True) class ReservationSnapshot: applicant: str = field(repr=False) session_key: str = field(repr=False) captured_at: float complete: bool records: tuple[ReservationRecord, ...] = field(repr=False) # Reuse the actual slot readback JS in the same synchronous browser turn as the # native final click, so a Python/browser round trip cannot select another slot. # Never reconstruct the POST payload: the website handler remains its owner. NATIVE_FINAL_SCRIPT = r""" /* coordinate:ita-native-final-once */ const [serviceId, day, dailyId, timeLabel, capacity] = arguments; const state = (function () { """ + SLOT_SELECTION_SCRIPT + r""" }).apply(null, [serviceId, day, dailyId, timeLabel, capacity, false]); const positive = ['runtimeMatches', 'finalGuarded', 'firstSelectedMatches', 'dayPositive', 'candidateReady', 'activeIsCandidate', 'activeIdMatches', 'activeDayMatches', 'activeTimeMatches', 'activeCapacityMatches']; const negative = ['dayDisabled', 'dayNegative', 'activeUnavailable', 'activeRedDot', 'clicked']; const ready = positive.every(k => state[k] === true) && negative.every(k => state[k] === false) && ['matchingDateCount', 'candidateCount', 'activeCount', 'activeInputCount'].every(k => state[k] === 1) && JSON.stringify(state.timelineDays) === JSON.stringify([day]) && JSON.stringify(state.contentDays) === JSON.stringify([day]); const buttons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp')); if (!ready || buttons.length !== 1 || !buttons[0].isConnected || buttons[0].dataset.coordinateFinalAttemptConsumed) return {clicked: false}; const button = buttons[0]; button.dataset.coordinateFinalAttemptConsumed = 'true'; try { button.disabled = false; button.removeAttribute('aria-disabled'); button.click(); return {clicked: true}; } finally { button.disabled = true; button.setAttribute('aria-disabled', 'true'); button.dataset.coordinateFinalGuard = 'enabled'; } """ def _unique_object(pairs): result = {} for key, value in pairs: if key in result: raise ValueError("duplicate field") result[key] = value return result def inspect_final_packet(packet: object, target: FinalTarget) -> tuple[SubmissionSignal, VerifiedSubmission | None, str]: """Validate the observed request before interpreting a response as a hint. Invalid metadata/HTTP/schema is UNKNOWN after a write, not a retryable authentication/no-slot error. Never expose the raw server errorMessage. """ evidence = None reason = "request_metadata" try: path, parsed = same_origin_path(packet.url) if (path != FINAL_PATH or parsed.query or parsed.fragment or packet.method != "POST" or packet.tab_id != target.tab_id or getattr(packet, "is_failed", False)): return SubmissionSignal.UNKNOWN, None, reason reason = "request_fields" body = packet.request.postData if isinstance(body, str) and len(body) <= MAX_PROTOCOL_PAYLOAD_CHARS: body = _unique_object(parse_qsl(body, keep_blank_values=True, strict_parsing=True)) if not isinstance(body, dict) or set(body) != { "idCalendarioGiornaliero", "selectedDay", "selectedHour", } or any(not isinstance(value, str) for value in body.values()): return SubmissionSignal.UNKNOWN, None, reason reason = "request_selection" slot = target.approval.candidate if body["idCalendarioGiornaliero"] != slot.daily_calendar_id or body["selectedDay"] != slot.day.isoformat(): return SubmissionSignal.UNKNOWN, None, reason compact = lambda value: re.sub(r"\s+", "", value) if compact(body["selectedHour"]) != compact(f"{slot.time_label}({slot.slots_free})"): return SubmissionSignal.UNKNOWN, None, reason evidence = VerifiedSubmission(target) reason = "response_metadata" response = packet.response if type(response.status) is not int or response.status != 200: return SubmissionSignal.UNKNOWN, evidence, reason response_url = getattr(response, "url", None) if response_url: response_path, response_parsed = same_origin_path(response_url) if response_path != FINAL_PATH or response_parsed.query or response_parsed.fragment: return SubmissionSignal.UNKNOWN, evidence, reason reason = "response_body" raw = response.raw_body if not isinstance(raw, str) or not 0 < len(raw) <= MAX_PROTOCOL_PAYLOAD_CHARS: return SubmissionSignal.UNKNOWN, evidence, reason data = json.loads(raw, object_pairs_hook=_unique_object) reason = "response_fields" if not isinstance(data, dict) or not {"errorMessage", "url"} <= set(data): return SubmissionSignal.UNKNOWN, evidence, reason error, destination = data["errorMessage"], data["url"] if not isinstance(error, str) or not _text(destination): return SubmissionSignal.UNKNOWN, evidence, reason reason = "response_destination" same_origin_path(urljoin(packet.url, destination)) return (SubmissionSignal.REJECTED if error.strip() else SubmissionSignal.ACCEPTED), evidence, "recognized" except Exception: return SubmissionSignal.UNKNOWN, evidence, reason def classify_final_packet(packet: object, target: FinalTarget) -> SubmissionSignal: return inspect_final_packet(packet, target)[0] class NativeFinalSubmitter: """One native click with the existing listener; no navigation/retry/OTP. A process-local latch is not a durable task fence. Production reaches this adapter only with explicit final-submit configuration; default pre-final CLIs never call it. The opt-in local evidence gate has its own persistent fence. """ def __init__(self, page: object, target: FinalTarget, session_is_current: Callable[[], bool]): self.page, self.target, self.session_is_current = page, target, session_is_current self._lock = threading.Lock() self._consumed = False self.submitted_selection: VerifiedSubmission | None = None self.diagnostic = {"requestMatched": False, "reason": "not_observed"} def __call__(self) -> SubmissionSignal: with self._lock: if self._consumed: raise FinalBookingError("Italy native final attempt is already consumed") self._consumed = True target = self.target def require_context(): if (self.session_is_current() is not True or self.page.tab_id != target.tab_id or same_origin_path(self.page.url)[0] != CALENDAR_PATH): raise FinalBookingError("Italy native final context changed") def action(): require_context() slot = target.approval.candidate raw = self.page.run_js( NATIVE_FINAL_SCRIPT, target.runtime_service, slot.day.isoformat(), slot.daily_calendar_id, slot.time_label, slot.slots_free, ) if raw != {"clicked": True} or type(raw.get("clicked")) is not bool: raise FinalBookingError("Italy native final click was not acknowledged") try: require_context() verify_precommit_selection(self.page, runtime_service=target.runtime_service, approval=target.approval) packet = listen_once(self.page, target=FINAL_PATH, method="POST", action=action, timeout=30) signal, self.submitted_selection, reason = inspect_final_packet(packet, target) self.diagnostic = {"requestMatched": self.submitted_selection is not None, "reason": reason} return signal except Exception: # A lost browser acknowledgement can follow a committed write. self.diagnostic = {"requestMatched": False, "reason": "native_or_listener_error"} return SubmissionSignal.UNKNOWN class FinalBookingAttempt: """Single-use orchestration; reconciliation only after a possible write. read_reservations must perform a fresh, complete, read-only site read bound to this applicant/session. The real read port accepts only empty/cancelled baselines, then binds new confirmed receipts to a verified native request. submit_native is an injected NativeFinalSubmitter (or an offline test double), not an HTTP replay function. Context checks must work after a same-session redirect. """ def __init__( self, target: FinalTarget, *, read_reservations: Callable[[], ReservationSnapshot], submit_native: Callable[[], SubmissionSignal], session_is_current: Callable[[], bool], ): if not isinstance(target, FinalTarget) or not all(callable(item) for item in ( read_reservations, submit_native, session_is_current, )): raise FinalBookingError("Italy final adapters are required") self.target = target self._read_reservations = read_reservations self._submit_native = submit_native self._session_is_current = session_is_current self._lock = threading.Lock() self._state = "ready" self._signal = SubmissionSignal.UNKNOWN self._before: ReservationSnapshot | None = None @property def state(self) -> str: return self._state def _require_context(self): if self._session_is_current() is not True: raise FinalBookingError("Italy final applicant or Session changed") def _read(self) -> ReservationSnapshot: self._require_context() started = time.monotonic() snapshot = self._read_reservations() self._require_context() now = time.monotonic() if (not isinstance(snapshot, ReservationSnapshot) or snapshot.complete is not True or snapshot.applicant != self.target.applicant or snapshot.session_key != self.target.session_key or type(snapshot.captured_at) not in (int, float) or not started <= snapshot.captured_at <= now or not isinstance(snapshot.records, tuple) or len(snapshot.records) > 512): raise FinalBookingError("Italy reservation snapshot is incomplete or not current") seen = set() for record in snapshot.records: if (not isinstance(record, ReservationRecord) or not _text(record.reference) or record.reference in seen or type(record.day) is not date or not _valid_receipt_time(record) or not isinstance(record.state, ReservationState) or record.state is ReservationState.UNKNOWN): raise FinalBookingError("Italy reservation records require verified identity and status") fingerprint = record.receipt_fingerprint if fingerprint is not None and (not isinstance(fingerprint, str) or re.fullmatch(r"[0-9a-f]{64}", fingerprint) is None): raise FinalBookingError("Italy receipt fingerprint is invalid") if record.submission is not None and not self._submitted_binding(record): raise FinalBookingError("Italy receipt submission evidence does not match this attempt") if not _text(record.service_id) and not ( record.service_id is None and fingerprint is not None and (record.state is ReservationState.CANCELLED or self._submitted_binding(record))): raise FinalBookingError("Italy live reservation service binding is unverified") seen.add(record.reference) return snapshot def _submitted_binding(self, record: ReservationRecord) -> bool: slot = self.target.approval.candidate return (self._state in {"submitted", "unknown"} and isinstance(record.submission, VerifiedSubmission) and record.submission.target == self.target and _text(self.target.service_name) and record.state is ReservationState.ACTIVE and record.service_id is None and record.time_label is None and record.receipt_fingerprint is not None and record.day == slot.day and isinstance(record.appointment_time, str) and slot.time_label[:5] <= record.appointment_time <= slot.time_label[-5:]) def _live(self, snapshot: ReservationSnapshot) -> list[ReservationRecord]: return [record for record in snapshot.records if (record.service_id == self.target.service_id or self._submitted_binding(record)) and record.state in {ReservationState.ACTIVE, ReservationState.WAITLIST}] def execute(self, *, enabled: bool = False) -> VSBookResult: if enabled is not True: raise FinalBookingError("Italy final submission is disabled") if not self._lock.acquire(blocking=False): raise FinalBookingError("Italy final attempt is already running") try: if self._state != "ready": raise FinalBookingError("Italy final attempt is already consumed") self._state = "checking" try: self._before = self._read() self._require_context() except Exception: self._state = "blocked" raise FinalBookingError("Italy final preflight blocked; no submission attempted") from None if self._live(self._before): self._state = "blocked" raise FinalBookingError("Italy service already has an active reservation or waitlist") self._state = "submitted" try: signal = self._submit_native() self._signal = signal if isinstance(signal, SubmissionSignal) else SubmissionSignal.UNKNOWN except Exception: self._signal = SubmissionSignal.UNKNOWN return self._reconcile() finally: # Ctrl-C/SystemExit must not make a possibly dispatched write look # unattempted, nor make read-only reconciliation impossible. if self._state == "submitted": self._state = "unknown" elif self._state == "checking": self._state = "blocked" self._lock.release() def reconcile(self) -> VSBookResult: """One read-only check. Never enters the native submit path.""" if not self._lock.acquire(blocking=False): raise FinalBookingError("Italy final attempt is already running") try: if self._state != "unknown": raise FinalBookingError("Italy final attempt does not need reconciliation") return self._reconcile() finally: self._lock.release() def _reconcile(self) -> VSBookResult: self._state = "unknown" try: after = self._read() live = self._live(after) before = {record.reference: record for record in self._before.records} after_by_id = {record.reference: record for record in after.records} # Missing/modified history and unrelated new rows make attribution # ambiguous. Do not equate a count increment with this appointment. if any(after_by_id.get(key) != value for key, value in before.items()): raise FinalOutcomeUnknown() new = [record for record in after.records if record.reference not in before] slot = self.target.approval.candidate if (len(new) == 1 and len(live) == 1 and new[0] == live[0] and live[0].state is ReservationState.ACTIVE and live[0].day == slot.day and (live[0].time_label == slot.time_label or self._submitted_binding(live[0])) and self._signal is not SubmissionSignal.REJECTED): self._state = "confirmed" return VSBookResult( success=True, account=self.target.applicant, urn=live[0].reference, book_date=slot.day.isoformat(), book_time=live[0].appointment_time or slot.time_label, ) if not new and not live and self._signal is SubmissionSignal.REJECTED: self._state = "rejected" return VSBookResult(success=False, label="italy-final-rejected") except Exception: pass self._state = "unknown" raise FinalOutcomeUnknown() from None