#!/usr/bin/env python3 """Accept the receipt reader against an existing receipt; never book. Default is a local preflight. --run uses a temporary applicant browser and only reads Reservation -> one cancelled detail -> Reservation after login. Neither raw receipts nor original exception messages are written to the console/files. --expect-confirmed instead checks one unique confirmed receipt matching the explicit date, assigned time and displayed service. This is existing-receipt verification, NOT attribution to a prior booking attempt or runtime service ID. """ from __future__ import annotations import argparse import hashlib import json import os import re import sys from datetime import date from pathlib import Path from typing import Mapping REPO_ROOT = Path(__file__).resolve().parents[1] if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) from plugins.ita_plugin import ReservationState from plugins.ita_plugin import same_origin_path from plugins.ita_plugin import ItaPlugin, SERVICES_PROBE_QUERY_MODE from plugins.ita_plugin import ( ReservationReadError, read_reservation_detail, read_reservation_listing, read_reservation_date_diagnostic, ) from tools.debug_ita_calendar_gate import CalendarRequestAudit from tools.debug_ita_session import ( DebugConfigurationError, _get_credentials, build_plugin_config, resolve_chrome_path, ) CONTRACT = "receipt-readonly-confirmed-v4" LIST_URL = "https://prenotami.esteri.it/Reservation" COUNTERS = frozenset(("otpRequests", "avantiPosts", "availabilityRequests", "timeSlotRequests", "finalRequests")) CONFIG_ENV_KEYS = frozenset(( "ITA_PROXY_IP", "ITA_PROXY_PORT", "ITA_PROXY_PROTO", "ITA_PROXY_USERNAME", "ITA_PROXY_PASSWORD", "ITA_PROXY_ID", "MIHOMO_BIN", "ITA_SESSION_MAX_LIFE", )) READ_REASONS = frozenset(( "field_invalid", "date_unrecognized", "time_unrecognized", "detail_url_invalid", "detail_schema_changed", "fields_ambiguous", "status_code_invalid", "coverage_invalid", "coverage_incomplete", "pagination_invalid", "list_schema_changed", "table_ambiguous", "headers_changed", "waitlist_ambiguous", "waitlist_schema_unverified", "row_nodes_incomplete", "row_schema_changed", "duplicate_record", "wrong_page", "context_changed", "not_ready", "page_read_rejected", "browser_read_failed", "wait_config_invalid", "stability_timeout", )) class ReceiptGateError(ValueError): pass def source_fingerprint() -> str: digest = hashlib.sha256() for name in ( "tools/debug_ita_reservation.py", "plugins/ita_plugin.py", "plugins/ita_plugin.py", "plugins/ita_plugin.py", "plugins/ita_plugin.py", "plugins/ita_plugin.py", "plugins/ita_plugin.py", "tools/debug_ita_session.py", "tools/debug_ita_calendar_gate.py", ): digest.update(name.encode()) digest.update((REPO_ROOT / name).read_bytes()) return digest.hexdigest()[:12] def build_receipt_config(env: Mapping[str, str], *, username: str, password: str): # Explicit projection: saved Query accounts, persistent profiles, debug and # regional/service settings must not leak into this applicant-only reader. projected = {key: env[key] for key in CONFIG_ENV_KEYS if key in env} config = build_plugin_config(projected, username=username, password=password) config.free_config = {"query_mode": SERVICES_PROBE_QUERY_MODE, "final_submit_enabled": False} return config def _check(condition: bool, reason: str) -> None: if not condition: raise ReceiptGateError(reason) def _check_page_url(page, expected: str) -> None: try: path, parsed = same_origin_path(page.url) except Exception: raise ReceiptGateError("navigation_rejected") from None _check(page.url == expected and not parsed.query and not parsed.fragment and bool(path), "navigation_rejected") def run_receipt_gate(env: Mapping[str, str], *, execute: bool = False, non_interactive: bool = False, expect_confirmed: bool = False, expected_date: str | None = None, expected_time: str | None = None, expected_service: str | None = None) -> int: plugin = audit = None audit_started = False previous_chrome = os.environ.get("CHROME_BIN") chrome_changed = False result = { "contract": CONTRACT, "passed": False, "exitCode": 1, "stage": "preflight", "reason": "", "listReady": False, "cancelledDetailMatched": False, "listUnchanged": False, "reservationCountBefore": None, "reservationCountAfter": None, "postLoginBusinessRequests": None, "cleanupOk": False, "auditVerified": False, "finalSubmissionEnabled": False, "dateDiagnostic": None, "confirmedDetailMatched": False, "existingReservationConfirmed": False, "bookingAttemptAttributed": False, "confirmedReceipt": None, } def verify_audit(): result["auditVerified"] = False try: counts = audit.settled_snapshot() except Exception: raise ReceiptGateError("audit_unavailable") from None _check(isinstance(counts, dict) and set(counts) == COUNTERS and all(type(v) is int and v >= 0 for v in counts.values()), "audit_unavailable") result["postLoginBusinessRequests"] = counts _check(all(v == 0 for v in counts.values()), "unexpected_business_request") result["auditVerified"] = True try: _check(all(type(v) is bool for v in (execute, non_interactive, expect_confirmed)), "invalid_execution_flag") print(f"ITA_RECEIPT_TOOL_CONTRACT version={CONTRACT} source_sha256={source_fingerprint()}", flush=True) expected_day = None if expect_confirmed: try: expected_day = date.fromisoformat(expected_date) valid = (expected_day.isoformat() == expected_date and isinstance(expected_time, str) and re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", expected_time) is not None and isinstance(expected_service, str) and 0 < len(expected_service) <= 256 and expected_service == expected_service.strip() and all(ord(c) >= 32 and ord(c) != 127 for c in expected_service)) except (TypeError, ValueError): valid = False _check(valid, "confirmed_expectations_invalid") else: _check(all(v is None for v in (expected_date, expected_time, expected_service)), "confirmed_expectations_without_mode") chrome = resolve_chrome_path(env) build_receipt_config(env, username="preflight@example.invalid", password="placeholder") if not execute: print("ITA_RECEIPT_PREFLIGHT_OK external_requests=0 credentials_read=false browser_created=false") return 0 result["stage"] = "credentials" username, password = _get_credentials({ "ITA_USERNAME": env.get("ITA_BOOK_USERNAME", ""), "ITA_PASSWORD": env.get("ITA_BOOK_PASSWORD", ""), }, non_interactive=non_interactive) config = build_receipt_config(env, username=username, password=password) result["stage"] = "login" os.environ["CHROME_BIN"] = str(chrome) chrome_changed = True plugin = ItaPlugin(group_id="ita-receipt-readonly") plugin.set_log(lambda _message: None) plugin.set_config(config) print("ITA_RECEIPT_LOGIN_START profile=temporary role=applicant", flush=True) plugin.create_session() page = plugin.page _check_page_url(page, "https://prenotami.esteri.it/UserArea") _check(bool(page.ele(".app-menu", timeout=0.5)) and bool(page.ele("@href=/Services", timeout=0.5)), "login_unverified") tab_id, generation = page.tab_id, plugin.session_create_time account_name = config.account.username _check(isinstance(tab_id, str) and bool(tab_id) and generation > 0, "context_changed") def verify_context(): _check(plugin.page is page and page.tab_id == tab_id and plugin.session_create_time == generation and plugin.config.account.username == account_name and plugin._persistent_profile_path is None and plugin.free_config == {"query_mode": SERVICES_PROBE_QUERY_MODE, "final_submit_enabled": False}, "context_changed") def navigate(url): verify_context() _check(page.get(url, retry=0, timeout=30) is not False, "navigation_failed") verify_context() _check_page_url(page, url) verify_context() print("ITA_RECEIPT_LOGIN_OK", flush=True) result["stage"] = "audit_start" audit = CalendarRequestAudit(page, include_time_slots=True) audit.start() audit_started = True result["stage"] = "list_before" navigate(LIST_URL) before = read_reservation_listing(page) verify_context() verify_audit() result.update(listReady=True, reservationCountBefore=len(before.rows)) if expect_confirmed: candidates = [row for row in before.rows if row.state is ReservationState.ACTIVE and row.day == expected_day and row.appointment_time == expected_time and row.service_name == expected_service] _check(len(candidates) == 1, "confirmed_sample_missing" if not candidates else "confirmed_sample_ambiguous") sample = candidates[0] else: sample = next((row for row in before.rows if row.state is ReservationState.CANCELLED), None) _check(sample is not None, "cancelled_sample_missing") result["stage"] = "confirmed_detail" if expect_confirmed else "cancelled_detail" # The actual link has already passed the receipt adapter's strict URL validation. navigate(sample.detail_url) receipt = read_reservation_detail(page) verify_context() verify_audit() wanted_state = ReservationState.ACTIVE if expect_confirmed else ReservationState.CANCELLED wanted_code = "2" if expect_confirmed else "3" _check(receipt.state is wanted_state and receipt.status_code == wanted_code and receipt.booking_type == "Prenotazione Singola" and all(getattr(receipt, field) == getattr(sample, field) for field in ( "reference", "office", "service_name", "day", "appointment_time", "status_text")), "confirmed_detail_mismatch" if expect_confirmed else "cancelled_detail_mismatch") if expect_confirmed: result["confirmedDetailMatched"] = True result["confirmedReceipt"] = { "date": receipt.day.isoformat(), "assignedTime": receipt.appointment_time, "state": receipt.state.value, "statusText": receipt.status_text, "statusCode": receipt.status_code, "singleBooking": True, "serviceDisplayMatches": True, } else: result["cancelledDetailMatched"] = True result["stage"] = "list_after" navigate(LIST_URL) after = read_reservation_listing(page) verify_context() verify_audit() result["reservationCountAfter"] = len(after.rows) _check({r.reference: r for r in before.rows} == {r.reference: r for r in after.rows} and before.waitlist_count == after.waitlist_count, "listing_changed") result.update(listUnchanged=True, stage="completed", exitCode=0) except KeyboardInterrupt: result.update(reason="interrupted", exitCode=130) except DebugConfigurationError: result.update(reason="configuration_rejected") except ReservationReadError as exc: result.update(reason=exc.reason if exc.reason in READ_REASONS else "receipt_read_rejected") if exc.reason == "date_unrecognized" and result["stage"] in ("list_before", "list_after"): try: verify_context() result["dateDiagnostic"] = read_reservation_date_diagnostic(page) verify_context() except Exception: result["dateDiagnostic"] = {"available": False} except ReceiptGateError as exc: # Only fixed reasons constructed above, not raw website/browser exceptions. safe = {"navigation_rejected", "navigation_failed", "invalid_execution_flag", "login_unverified", "context_changed", "audit_unavailable", "unexpected_business_request", "cancelled_sample_missing", "cancelled_detail_mismatch", "listing_changed", "confirmed_expectations_invalid", "confirmed_expectations_without_mode", "confirmed_sample_missing", "confirmed_sample_ambiguous", "confirmed_detail_mismatch"} result.update(reason=str(exc) if str(exc) in safe else "gate_rejected") except Exception: result.update(reason="stage_failed") finally: if audit_started: try: verify_audit() except Exception as exc: result.update(exitCode=1 if result["exitCode"] == 0 else result["exitCode"]) if not result["reason"]: result["reason"] = ("unexpected_business_request" if isinstance(exc, ReceiptGateError) and str(exc) == "unexpected_business_request" else "audit_unavailable") if audit is not None: try: audit.stop() except Exception: result.update(exitCode=1, auditVerified=False, reason=result["reason"] or "audit_stop_failed") if plugin is not None: try: plugin.cleanup() result["cleanupOk"] = True except Exception: result.update(exitCode=3, reason="cleanup_failed") if chrome_changed: if previous_chrome is None: os.environ.pop("CHROME_BIN", None) else: os.environ["CHROME_BIN"] = previous_chrome result["passed"] = (result["exitCode"] == 0 and result["cleanupOk"] and result["listUnchanged"] and result["auditVerified"]) result["existingReservationConfirmed"] = result["passed"] and result["confirmedDetailMatched"] print("ITA_RECEIPT_GATE_RESULT=" + json.dumps(result, sort_keys=True), flush=True) return result["exitCode"] def main(argv=None) -> int: parser = argparse.ArgumentParser(description=__doc__) mode = parser.add_mutually_exclusive_group() mode.add_argument("--preflight", action="store_true", help="Local checks only (default)") mode.add_argument("--run", action="store_true", help="Log in and read an existing cancelled sample") parser.add_argument("--non-interactive", action="store_true", help="Require ITA_BOOK_USERNAME/PASSWORD") parser.add_argument("--expect-confirmed", action="store_true", help="Read one existing confirmed receipt matching all three expectations; never submit") parser.add_argument("--expected-date", help="Existing receipt date, YYYY-MM-DD") parser.add_argument("--expected-time", help="Assigned receipt time, HH:mm (not a slot range)") parser.add_argument("--expected-service", help="Exact displayed service name, not a service ID") args = parser.parse_args(argv) return run_receipt_gate(os.environ, execute=args.run, non_interactive=args.non_interactive, expect_confirmed=args.expect_confirmed, expected_date=args.expected_date, expected_time=args.expected_time, expected_service=args.expected_service) if __name__ == "__main__": raise SystemExit(main())